FAQ Database Discussion Community


losing data when leaving scope

javascript,ajax,scope
I'm programming something in javascript and at one point I make an ajax call I store the data in an object literal but when I leave the scope I lose the data (even in my object literal) I don't understand what is happening here var menusView = { menusRep: null,...

Puppet conditional assignment and += operator

string,variables,scope,puppet
In puppet, I want to write a file with a string based on configuration in nodes.pp. nodes.pp defines the $sslClientCertConfig variable, which has a loadBalancerIp property. I want to create a configuration string, we'll call it $config, without repeating the string code. The configuration string should be either A: if...

How to save counter of entries in str and show it in Text field?

python,tkinter,scope,counter
Using such example i want to count number of entries. And represent string with number of entries in Text field. Like, for example: 1: number of entries(1) 21: number of entries(2) ... Where should i put my counter variable? import random from tkinter import * class MyApp(Frame): def __init__(self, master):...

calling the parent controller function in Ext.Ajax.request

extjs,view,controller,scope
I have a login Page which authenticates the user.On correct username and password it should hide the loginview and display the next view.When I call the function to do the same it gives an error saying "Uncaught TypeError: this.functionname is not a function.Here is my code for the same: startMain...

Variable scoping in Swift with tasks

ios,swift,scope
I've got all of this code inside of a function in my view controller: self.activityIndicator.startAnimating() let url = NSURL(string: "http://www.google.com") var request = NSMutableURLRequest(URL: url!) request.HTTPMethod = "PUT" var err: NSError? request.HTTPBody = NSJSONSerialization.dataWithJSONObject(["notes": self.textView.text], options: nil, error: &err) request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.addValue("application/json", forHTTPHeaderField: "Accept") var s = NSString(data:...

Global variables, Jquery

javascript,jquery,variables,scope
I have the following code oss = $("#us"); mainLogo = $("#mainLogo"); container = $(".container"); $(document).ready(function(){ oss.hide(); oss.fadeIn(1000); mainLogo.hide(); mainLogo.fadeIn(1000); container.find("#images").hide(); container.find("#images").slideDown(); }) $(oss).click(function(){ container.fadeOut(); }) The problem I have is that I can't seem to access the variables outside. I've tried window.varName, just writing var infront etc. But the compiler...

Laravel Eloquent: access method parameter within chunk Closure

php,laravel,static,scope,eloquent
I need to pass an anonymous function to a static method on an Eloquent model and have that static method call the closure within a chunk closure. The goal is code similar to the following: class MyModel extends Eloquent { // ... table stuff public static function doSomething (Closure $thing)...

Having trouble using user input between functions

python,function,scope
I'm trying to learn Python and I'm really struggling with getting my code into self-contained functions. Here is an example: def get_inputs(): sales_amount = float(input("Enter total sales amount: ")) def calculate_discount(sales_amount): discount_amount = sales_amount * 2 return discount_amount def output(): print ( discount_amount ) def main(): get_inputs() calculate_discount(sales_amount) output() main()...

Javascript variable is set in one function, but undefined in another function

javascript,jquery,namespaces,scope
I have the following Javascript, eventManager: { $musicGenres : null, // $musicGenres is the selector for a div-container of inputs musicGenres : [], // Functions handle : function(selectors) { selectors = (typeof selectors === 'undefined') ? { 'musicGenres' : '#musicGenres' } : selectors; // selectors default values... this.$musicGenres = $(selectors['musicGenres']);...

Scope in javascript acting weird

javascript,function,scope,pass-by-reference
Object are passed with their reference in javascript. Meaning change in that object from any where should be reflected. In this case, the expected output was {} for console.log(a) function change(a,b) { a.x = 'added'; a = b;//assigning a as {} to b } a={} b={} change(a,b); console.log(a); //expected {}...

Score Incrementing in Javascript (Variable Scope Issues, probabbly?)

javascript,scope
As a complete beginner to programming I was following the JavaScript courses at CodeAcademy. I've completed the rock-paper-scissors assignmennt and now I want to add a score system to my game. What I decided to do was creating two global variables called userScore and computerScore. The game function would then...

AngularJS directive: scope

angularjs,scope,directive
I have the example below: HTML: <body ng-controller="MainCtrl"> <p>Hello {{name}}!</p> <p>Result is {{result}}!</p> <output-content data="name"></output-content> </body> JavaScript: var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope) { $scope.name = 'World'; $scope.result = "no"; $scope.changeLabel = function() { $scope.result = 'yes'; } }); app.directive('outputContent', function() { return { restrict: 'E', replace: true, templateUrl:...

Javascript Variable not passing through ocanvas function and for loop

javascript,scope,ocanvas
I'm having an issue with a variable not being passed through an ocanvas function. it appears that the variable is changing inside the function but isn't making it outside the function. here is my code: sonicSpeed2 = 0; sonicState2 = 0; canvas.bind("keypress", function () { var keys = canvas.keyboard.getKeysDown(); var...

Usage of 'nonlocal' keyword in python

python,python-3.x,scope
Below program asks for nonlocal keyword with UnboundLocalError: local variable 'balance' referenced before assignment >>> def make_withdraw(balance): """Return a withdraw function with a starting balance.""" def withdraw(amount): if amount > balance: return 'Insufficient funds' balance = balance - amount return balance return withdraw >>> withdraw = make_withdraw(101) >>> withdraw(25) But,...

bash: piping output from a loop seems to change the scope within the loop - why?

bash,loops,scope,pipe
I've noticed that variable scope within a bash for loop seems to change if I pipe the output of the loop. For example, here g remains changed after the loop: $ g=bing; for f in foo; do g=fing; echo g in loop: $g; done; echo g after $g; g in...

AngularJS call function from click

javascript,html,angularjs,scope
I can't for the life of me figure out why I can't call this function in my controller. On clicking an accordion-group attribute I get this error: Uncaught ReferenceError: getConversationsForUser is not defined Here is the html: <ui-view id="smtConvoCard" layout="column" layout-fill layout-padding> <div layout="row" flex layout-align="center center"> <md-card flex-gt-sm="90" onresize="resize()"...

Function is undefined in JS object

javascript,scope
I create object var myObj = new functon () {...}. In that object i add functions like : var myObj = new function () { this.func1 = function() { func2(); } this.func2 = function() { ... } } As you can see in func1 I try to call func2 but...

JavaScript function parameter and scope

javascript,function,scope
I have done some tests with codes listed below: function foo(x) { alert(y); } var y = 'I am defined outside foo definition'; foo(); The above code gives me an alert 'I am defined outside foo definition'. Then another test: function bar(x) { alert(x); } var x = 'I am...

import to all package member files (package scope)

scala,import,scope,package
I have multiple class files in one package/directory. Similar to this: File 1: package model import same.library class File1Class {}[...] File 2: package model import same.library class File2Class {}[...] etc... Being part of package model already allows each member to access all package model-defined classes, so I was wondering if...

how to access $loader variable from within a class?

php,symfony2,scope
app/config/routing.php This is how it should be done $collection = new RouteCollection(); $collection->addCollection( // second argument is the type, which is required to enable // the annotation reader for this resource $loader->import("@AppBundle/Controller/", "annotation") ); return $this->collection; I need to create a more complex routing system for a company, and need...

Testing a controller not using $scope using karma

angularjs,unit-testing,scope,karma-jasmine,controllers
I followed the instructions on docs.angularjs.org to test a controller with karma and it's perfectly working. However I was wondering if it's possible to test a controller which is not using $scope? Testing this controller is ok: angular.module('starter.controllers') .controller('PasswordController', function PasswordController($scope) { $scope.password = ''; $scope.grade = function() { var...

How exactly works the Javascript variable scope? [duplicate]

javascript,variables,scope
This question already has an answer here: What is the scope of variables in JavaScript? 13 answers I am pretty new in JavaScript and I have some doubts related to the variable scope. So I tryed to do this example: function outer() { alert("INTO outer()"); var val1 = 1;...

compiling regexes within a frequently-called function

python,regex,function,scope
Let's say I have a function which searches for multiple patterns in a string using regexes: import re def get_patterns(string): """ Takes a string and returns found groups of numeric and alphabetic characters. """ re_digits = re.compile("(\d+)") re_alpha = re.compile("(?i)([A-Z]+)") digits = re_digits.findall(string) alpha = re_alpha.findall(string) return digits, alpha get_patterns("99...

Scala scope, initialization

java,scala,scope,initialization
Imagine the following Java Class: class Test { private Button b; private Table t; public Test() { setupButton(); setupTable(); } private void setupButton() { b = ... b.doAwesomeStuff(); // ... more stuff going on } private void setupTable() { t = ... t.attach(b); // Works, because b is in (class)...

C programming - Confusion regarding curly braces

c,scope
The following code is for replacing multiple consecutive spaces into 1 space. Although I manage to do it, I am confused in the use of curly braces. This one is actually running fine: #include <stdio.h> #include <stdlib.h> int main() { int ch, lastch; lastch = 'a'; while((ch = getchar())!= EOF)...

Using a variable outside of it's scope

swift,scope
I wish to access a variable outside of it's scope. (A snippet of the relevant code is posted). Within the @IBAction ,the sphereNode.runAction(moveUp) is not recognised. I cannot simply declare sphereNode global as it is dependant upon the sphereGeometry declaration. override func viewDidLoad() { super.viewDidLoad() //Added our first shape =...

Assign function argument to global variable of the same name

actionscript-3,variables,scope
Is it possible to set a global variable from within a function that takes that same variable name as an argument? var a:int = 0; function test(a:int) { a *global* = a *local*; } test(1); trace(a) // traces 0 but I'd like it to trace 1 (The reason why I'd...

Scope of global variables in a java class and their behavior in methods of the same class

java,scope
I am new to programming and Java and I have some confusion regarding the behavior of global variables in methods of the same class. In an exercise question provided by the course I am taking, I am asked what is the value of variable b after executing inc(b). int b;...

PHP dependency property scope

php,oop,dependency-injection,scope
In the following class, I have two properties, $session and $client and these are properties into which dependencies are injected. In the class, they are declared as public but is this the correct scope for properties containing dependencies? What is best practice for PHP in this regard, public, protected or...

Angularjs - Custom directive cannot access controller scope

angularjs,scope,code-injection,directive
I am building a single page app with Angular JS. The problem is the custom directive mySlider cannot access the scope of the controllers I assign to the template. Is there a way to solve this problem? Here are my files index.html <script src="js/dishesapp.js"></script> <div ng-view></div> partials/dishestemplate.html <div my-slider></div> directives/slider.html...

Where to store a variable when needed in the next run?

c,variables,scope
I'm changing a program written in C. For these changes I need a counter (variable int). When the run stops, I need the value of this counter in the following run of the program. (even if the pc is restarted in between). What is the best way to store this...

Block scope, function scope and local scope in Javascript

javascript,scope,var,let
Is block scope sometimes the same as function scope? I know function scope is for everything inside a function, but don't get what exactly a block scope is. For Javascript, is it currently recommended to use let / const instead of var for future maintenance? (This was from Airbnb...

Javscript oop function reference not yet declared

javascript,oop,scope
I'm here yet again to solve another Javascript enigma. Consider this code: starmap = function(game){ this.PI2 = Math.PI * 2; this.renderer = { ... } this.star = function (...) { console.log(this.map); ... } this.map = { ... } } starmap.prototype = { preload: function(){}, create : function(){ this.map.initialize('starmap'); }, update:...

Access declared variables via `this` in non-global scopes

javascript,scope
var x = 16; console.log(this["x"]); // 16 I'm ok with this, but: (function () { var y = 16; console.log(this["y"]); // undefined }()); Why we cant access variables via this ?! I know it's possibe when we assign values, for example: (function () { x = 16; // will assigned...

Optimization - For statement and variable declarations

javascript,loops,scope
Here is a quotation from MDN about 'for' statement : An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same...

EaselJS keyboard input issue

javascript,variables,scope,easeljs
I'm having a problem with easelJS, I have a function that listens for keyboard input but it does not update the variables according to the keys i hit. I placed a console.log inside the different cases and it logs fine but for some reason it does update variables. I think...

Python: How to make variables consistent throughout different functions?

python,variables,input,scope
I'm still starting out how to program in Python, and I'm just wondering how to make a variable consistent throughout different functions. For example, a function that I've made modified a variable. Then, I've used that variable again in another function. How can I make the modified variable appear in...

how in angularjs we can achieve the object update which is based on some other objects?

javascript,angularjs,scope
I am trying to update values of variables b and c with an add method (simply incrementing their value) but a (the sum of the two) is not reflecting this operation. I understand we can use a $scope.$watch function to update them, but I have an application with many objects...

arrays with the same names in different functions

javascript,arrays,scope
I have two arrays named the same thing in two separate functions. I assumed the arrays would be local to each function, but some of the values from the first function are messing up the values in the other function. When I change the name of the array in the...

How to keep scope within an XHR request?

javascript,routing,scope,xmlhttprequest
So I am building a Javascript router and building a route like this: route('/user/{name}', 'page', function() { this.text = 'User: ' + this.name; }); The scope of the function is the current route, so I can manipulate the current route here (this.text is what the view is looking for). Now...

Can I modularize my javascript code like this?

javascript,performance,scope
I really don't like all of my javascript code ending up in just one file, I tried using libraries like require.js to help me modularize but they end up getting a little complex for me. So I was wondering if I can do something like this. Context : Say I...

Variable scope in S3 generics

r,scope,r-s3
I have the following snippet: y <- 1 g <- function(x) { y <- 2 UseMethod("g") } g.numeric <- function(x) y g(10) # [1] 2 I do not understand, why it is possible to have access to y in g.numeric <- function(x) y. To my understanding y's scope is just...

Variable scope incorrectly set-up in Node.JS

node.js,scope
The following is a MCVE of my try at BattleShip in NodeJS. Grid.set calls Grid.place which calls Grid.place.methodPlace which tries to call Grid.cells and fails. This is not the way to access such a variable, since this.cells is not in scope. What is the correct way of accessing this variable?...

Cannot access different object inside another in Javascript, it gives ReferenceError: abc is not defined

javascript,jquery,object,scope
The below code has two scope of objects, where the first one has a function and the second one has another function. Both the functions gets called separately at the time of page loading. But Cross object method cannot be called. I cannot understand how to make a function available...

Directive scope variable

javascript,angularjs,scope,angularjs-scope
I am using a directive for three consecutive time in html page, the scope variable i am passing to different at every time but it is taking all the scope variable from the third directive ?, for example first time, <my-dir is-active=true></my-dir> sec time, <my-dir is-active="true"></my-dir> third time, <my-dir is-Active="true"...

accessing a variable from outside a function and returning the variable. In a module pattern

javascript,function,module,scope
I'm learning about how to split up different functionalities into different section so I could have loose coupling. i have two object 1.'addition' and 2. 'subtraction'. I don't think that info matters for this Q. what i want to do is that when amount = 3 in the index.html file...

srand() + rand() with local scope

c++,c++11,random,scope,thread-safety
I have a function that calls srand and rand like this: void foo() { int seed = some_operation(); std::srand(seed); int value = std::rand(); // Do something with random value } However, I don't want to change the global state of rand. Whats the easiest way to get a random number...

Populating a julia dictionary with an array of symbols

scope,metaprogramming,julia-lang
I'm getting stuck on some basics of scope in Julia expressions. Can someone help tell me what is going wrong inside the for loop below? Inside the lopp the first expression works and the second does not, though both work with variables from the global scope. x = 1 glob_obj...

Multiple Scope value in Binding (Specflow)

scope,automated-tests,specflow,feature-selection,feature-file
I have a method which runs Before a feature like so, [BeforeFeature, Scope(Feature = "Feature1"] Method() { } I want the same method to be ran for another feature file that i've wiritten i.e. Feature2 How do i combine this "Feature2" in the scope Binding? I tried this [BeforeFeature, Scope(Feature...

Reload controllers after scope change (AngularJS)

javascript,angularjs,view,routes,scope
so I have this controller for swapping languages app.controller("langCtrl",['$scope','$route',function($scope,$route){ this.swap_lang = function(){ if(lang == "tr"){ lang = "en"; }else{ lang = "tr"; } console.log(lang); this.lang = lang; //$route.reload(); //$scope.$apply(); }; }]); And this one below is supposed to be responsible for bringing up menus (JSON files with short language codes)...

Using callbacks instead of promises in AngularJS results in different behavior in unit tests. Why?

angularjs,callback,scope,synchronization,promise
I'm testing a $resource. If I have code like this: $resource.do(stuff).$promise.then(function(data){ console.log(1); }); console.log(2); I get the print out: 2 1 But if I have code like this: var callback = function(data){ console.log(1); } $resource.do(stuff,callback); console.log(2); I get the print out: 1 2 Why? I have found that with the...

Java ee session scope attributes for drop down lists

jsp,session,java-ee,scope
I'm trying to gain some performance on my application that search members in groups in ldap. My page shows 5 drop down lists which countains groups from different domains (around 150+ in each). I noticed that my application spend most of the time loading those drop down lists and little...

Why aren't the references to the private var's not being updated?

javascript,class,scope,closures
The add method isn't working like intended. When I have 2 time object t (all 0's), and t2 (1 minute). When I add t2 to t, t doesn't change BUT when I call my toString method on t it gives me the expected value. Here is what I mean if...

ServiceNow Javascript passing variables from GlideAjax functions

javascript,ajax,validation,scope,servicenow
I am using ServiceNow. I need to validate a form onSubmit. I am using GlideAjax with a script include to validate data. How can I pass variables from the Ajax function calendarDate(response) to other functions within the Client Script? When the glide ajax function returns an error message, I want...

cxf request scoped bean not working in unit test (soap)

web-services,unit-testing,soap,scope,cxf
CXF soap application, using following versions: springBootVersion = 1.2.3.RELEASE springVersion = '4.1.6.RELEASE' cxfVersion = '3.1.0' junitVersion = '4.12' I have a spring bean with a request scope: @Component @Scope( value=WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS ) public class RequestScopedClass which I fetch dynamically from ApplicationContext in my CXF endpoint implementation: @Component @WebService(endpointInterface...

Namespace scope in C#

c#,namespaces,scope
Does the name of namespace also define the scope in the class? For example, I have namespace that is named by solution by default. Lets say in Program.cs name of namespace is "MySolution". in the next file interface that I have created, name of namespace is "Interfaces" When I go...

Python - Why is my list not being modified outside the scope of this method? How do I modify my code so that it is?

python,list,filter,scope
I have the following method: def instances(candidate, candidates): count = candidates.count(candidate) # Removing candidate from candidates. # list(filter(candidate.__ne__, candidates)) return {candidate: count} Its intended purpose is to find how many instances of a certain element are in a list, delete those instances from the list, and return a Key:Value pair...

How to change value of variable from a different .py file in Python

python,scope
From a file foo.py, I want to change the value of a variable which's placed in a different file, let's say bar.py. I've tried to do it importing the variable, but it seems that it's imported not as reference. Just examples: bar.py: age = 18 foo.py: from bar import age...

A method of telling if object supports a method

ruby,file,scope
I am trying to write some file handling code that opens a file, obtains data about the file, then closes the file. My first encountered problem is that if I use the File.open(...) do |fd| var = fd.size end method of opening a file which ensures that is closed at...

JavaScript scoping and function declaration

javascript,scope
I'm trying to understand why inside the test() function, var g = f is not var g = f(). The output for alert(test(true)) is ['local', 'local'] vs ['global'] for alert(test(false)), so var g = f must be a declaration setting g equal to the outer f() function. function f() {...

const variable not hoisted for immediately invoked function

javascript,scope,const,ecmascript-6,hoisting
I was playing around new ECMASCRIPT-6 const key word. I did not understand one particular behaviour of the keyword. Lets say I have two functions First case (function(){ console.log(_t); const _t=10; })(); and Second case function t(){ console.log(_y); const _y=11; } t(); For the first case the output is (didn't...

exists and sapply: why are these functions different?

r,scope,sapply
Why are the two functions fn and gn below different? I don't think they should be, but I must be missing something. vars <- letters[1:10] a <- b <- 1 fn <- function (d) { sapply( vars, exists ) } gn <- function (d) { sapply( vars, function (x) {...

Is there a lazy functional (immutable) language where functions have intermediate variables+return?

scope,functional-programming,lazy-evaluation
I apologize if this has an obvious answer. I would like to find a lazy functional programming language where the following pseudo code makes sense: let f = function(x) { let y = x*x // The variables y and z let z = y*2 // are local return z }...

Variable isConnected is not changed

javascript,mysql,scope,mocha,chai
isConnected is supposed to be a variable to test if the database connection is successfull or not. Now in my DatabaseTest class I want to assert this isConnected variable. isConnected is declared in the database object, so it should be accessable via database.isConnected. But the value is not changed in...

Creating and returning object from function: can this avoid garbage collection?

javascript,object,scope,garbage-collection,return-by-reference
If I have a function that creates an object, do some stuff and than returns it. If it's true that objects are passed by reference, does this mean that the function that creates the object (or the function's scope chain) will not be available for garbage collection? Example code: function...

How to scope only the tags a user has used

ruby-on-rails,ruby-on-rails-4,scope,tags
I am writing a Rails 4.2 app with models user, notecard, tag and tagging (for the m-2-m relationship). A tag can have multiple notecards and a notecard can have multiple tags. A card belongs to a user and a tag DOESN'T belong to a user. How can I scope the...

AngularJS Set Value to $scope from Nested Function

javascript,angularjs,scope,angularjs-scope,closures
I'm trying to get a value from a function inside a function: Controller $scope.vm = {}; function myFunc(){ $scope.vm.hello = 'Hello'; function myFunction(){ $scope.vm.world = 'world'; } } myFunc(); View <p>{{vm.hello}} {{vm.world}}</p> Here's my Plunk. How can I get this to display "Hello world"?...

Proper way to have two functions access a single function's environment?

r,scope
Based on the answer provided in1088639, I set up a pair of functions which both access the same sub-function's environment. This example works, but I wanted to see if I'd missed some cleaner way to "connect" both top-level functions to the internal environment. ( Back story: I wanted to write...

Python global variable/scope confusion [duplicate]

python,scope,global-variables,jes
This question already has an answer here: Python scope [duplicate] 4 answers I've started teaching myself python, and have noticed something strange to do with global variables and scope. When I run this: x = 2 y = 3 z=17 def add_nums(): y = 6 return z+y The result...

DataContext scope during binding

wpf,data-binding,user-controls,scope
I have a View A that has a UserControl U containing its own UserControl UChild. When I set the DataContext of A, will UChild get the DataContext of A using direct binding to its grandparent's property i.e. { Binding PropertyFromA } within UChild? I am trying to achieve this but...

Angular updating $scope variable after ajax is not reflecting in UI

javascript,ajax,angularjs,scope,angular-http
I cannot seem to figure out the issue here. On an ajax success response I set a value in the current controller that is not reflecting in the UI. The general answer I have found is to run with the Angular ajax functions and/or apply $apply or $digest to the...

'using' scope in C# and sharpdx

c#,scope,using,sharpdx
The question is more C# related, but I started learining sharpdx recently and I came up on two ways to initialize resources. First stores the resource (Texture2D in this example) as a global variable. Then in code assigns the value to it and passes it to sharpdx's method (and down...

Local variable scope in Java vs Python [duplicate]

java,python,scope
This question already has an answer here: Short Description of Python Scoping Rules 6 answers What's the scope of a Python variable declared in an if statement? 7 answers When I try to access the local variable jimFound outside of the block it was declared in the first Java...

Java inheritance and Scope of variable

java,inheritance,scope
The Program is: class A { int i = 10; } class B extends A { int j = 20; } class C extends B { int k = 30; } class D extends C { int m = 40; } public class asg2 { public static void main(String[] args)...

Why is it a bad idea to use the same field for loop control variables in different methods of a class?

java,for-loop,scope
Question from a practice final for Intro to Java Class: Why is it a bad idea to use the same field for loop control variables in different methods of a class? A. Because if a method is called from the body of the loop, it may reset the value of...

Accessing outer variable inside eventListener [duplicate]

javascript,scope,eventlistener
This question already has an answer here: JavaScript closure inside loops – simple practical example 25 answers In case of: var allBusiness = ["one", "two", "three", "four"] for (var i = 0; i < allBusiness.length; i++) { document.getElementById(allBusiness[i]).addEventListener("click", function () { console.log(allBusiness); }); } This one logs ["one", "two",...

Variable scope behavior c language

c,scope
Code snippet: void function(void) { while(1) { int i = 0; i += 1; if(i == 500) break; } } The variable i is stored in stack every time when restart the loop ? What is the memory structure when running this code ? What is the behavior of this...

Why is my custom php.ini file not loaded site wide while placed in /public_hml? [duplicate]

php,configuration,scope,ini,public-html
This question already has an answer here: Custom php.ini per-directory (for testing sites) 2 answers I created a custom php.ini ... it's located in /public_html. Shouldn't it be valid and used for the whole site and directories under public_html ? It seems not to be loaded e.g. in /public_html/cms/usr...

Understanding Javascript Scope Trouble

javascript,node.js,scope
I have the following code in my Node.js project: var response; if (theInput == 1) { models.User.find({ usersNumber: usersNumber, active: true }, function (err, user_data) { response = "Number is 1"; }); } else if (theInput == 2) { response = "Number is 2"; } else { response = "Number...

Python: Unable to import global variable initialized in setUp method from init file

python,scope,global-variables,python-unittest
I have a package with testing modules and inside the init file I have a setUp method with some operations. These operations are executed correctly before any unit test in the package's modules run. Inside the setUp method I'd like to initialize a global variable and then access it from...

Why are these global variables when they have namespace scope?

c++,namespaces,scope,global-variables,forward-declaration
In the following code, this is calling the variables in the globals.cpp namespace actual global variables. globals.h #ifndef GLOBALS_H_ #define GLOBALS_H_ namespace Constants { // forward declarations only extern const double pi; extern const double avogadro; extern const double my_gravity; } #endif globals.cpp namespace Constants { // actual global variables...

in ActiveRecord::Relation, is it preferable to scope by parent in the model or set @parent in the controller

ruby-on-rails-4,activerecord,model-view-controller,scope,parent-child
I have a class which belongs to another. course.rb class Course < ActiveRecord::Base belongs_to :school I currently use a before_action to set the parent instance in the controller. courses_controller.rb class CoursesController < ApplicationController #returns @school. only: [methods] avoids trying to set @school when no school param expected before_action :set_school, only:...

Java variable scope - copying bitmaps?

java,bitmap,scope,recycle
I'm trying to better understand how Java variable scope works and what exactly happens to the underlying data when we do something like the following in a method: this.variable = variable What exactly does this line do? Here is my actual problem: I'm loading Bitmaps to apply as textures in...

How do I see the list of all variables in scope along with their values in Javascript using the Developer Tools on Google Chrome?

javascript,google-chrome,scope,developer-tools
I tried using the following and it does give me a list of variables in scope. I also need to see their values on the console. Is it possible? for(var b in window) { if (window.hasOwnProperty(b)) console.log(b); } ...

Create a new context for an function [closed]

javascript,scope
Lets say I have an ajax call like this: $.ajax({ ... success : someFn }) On the code review, they asked about what environment does someFn have access to? They were more worried about, what all variables, scopes does someFn have access to and how I'm going to manage the...

What is the scope of public variable in different methods of a same class in Console C#

c#,variables,scope
I have a class named Data that is used to retrieve a user's data class Data { public string firstName; public string lastName; public void getdata() { firstName = "ABC"; lastName = "XYZ"; } public static XDocument GetDataToXml() { var objget = new Data(); objget.getdata(); XDocument doc = new XDocument(...

Understanding Python Closures

python,python-2.7,scope,closures
I always thought that Python 2.7 functions refer to the scope they were defined in. Consider the following code. Why is the second output not "calculating: sin"? Is there any way to modify the code so it is working as expected? import math mymath = dict() for fun in ["sin",...

How does function scope work in JavaScript?

javascript,scope
I am having some trouble understanding function scope in JavaScript: function Person() { var _firstName; var _lastName; } personOne = new Person(); personOne._firstName = "Fred"; alert(personOne._firstName); This outputs "Fred", but I thought the variables of the Person function would only be accessible inside the function. Why does it work?...

Assign and use of a variable in the same subshell

bash,scope,subshell
I was doing something very simple like: v=5 echo "$v" and expected it to print 5. However, it does not. The value that was just set is not available for the next command. I recently learnt that "In most shells, each command of a pipeline is executed in a separate...

Returning a pointer which is a locally declared wchar_t

c,static,scope,return
I've read a lot of questions about returning pointers in C, but am still confused with the issue of scope. The following code works because of the call to malloc, and one possible output might end up being Wide string: StackOverflow. #include <stdlib.h> #include <string.h> #include <stdio.h> #include <wchar.h> static...

LPTSTR Losing Scope, work around not working (C++)

c++,scope,setter,lptstr
EDIT: Solution was to replace LPTSTR to wstring. When Windows API required LPTSTR the wstring is casted with .c_str() My problem is, a variable (LPTSTR) is going out of scope and I can't fix it. I'll explain... In my code I am trying to save the name of an Image...

Problems with Flash 8 (AS2), Timelines, and Variable Scopes

flash,variables,scope,actionscript-2
Okay, so trying to not post 5 pages of information, I'll start with the following: In a movie clip, I have 3 keyframes. I'm trying to edit a textbox on each frame, but I've found previously that only the text box in the current frame is accessible. In an attempt...

How javascript retains the outer function's execution context when an inner function is returned?

javascript,scope,executioncontext,scope-chain
I'm reading these two blogs: execution context and scope chain published by David Shariff diving depth into javascript's execution context and scope chain concept. One thing not clear to me after reading the above blogs is how javascript prevents a parent function's execution context being garbage collected? Let's look at...

Multiple requires of same module seem to affect scope of each successive require

node.js,module,scope
I created the following 3 files: base.js var base = {}; base.one = 1; base.two = 2; base.three = 3; base.bar = function(){ console.log( this.three ); }; a.js var base = require('./base'); base.three = 6; module.exports = base; b.js var base = require('./base'); module.exports = base; test.js var test_modules =...

How to limit the scope of a variable to the function when declared in an If statement

vb.net,scope
I need to limit the scope of a variable to the function it resides with however I need to declare it within an if statement as it's type will change depending. I'm working within VB.NET Public Function CourseDataTable() If RadioCourses.Checked Then Dim SearchBy As New classSearchCourses ElseIf RadioAttendees.Checked Then Dim...

Unexpected behavior of Python's variable scope [duplicate]

python,function,variables,scope
This question already has an answer here: UnboundLocalError in Python 8 answers I'm a bit confused as to how Python's variable scope system works. Say I have situation like this: a = 10 def test(): print(a) Then everything works just as I expect. Python first looks for a local...

Javascript - Calling A Variable From Outside Of If/Else Block Returns Undefined

javascript,node.js,scope,global-variables
I thought this is how you make a variable inside a if/else block global (Case 3). connection.query(sql, function (err,rows){ //Handle Errors if(err){ //Log The Error & Die } //If Successful - Log Results For Now (Change To Export Results) else { //console.log(rows); foo = rows; } }); console.log(foo); // Out:...

Why is fileinput.input object not lost when going out-of-scope?

python,scope
In the following code I would expect than python is freeing fileinput.input when I'm returning in the middle my loop as it is going out-of-scope. However, when calling again my function fileinput tells me raise RuntimeError, "input() already active" Here is my code: def func(inplace): for line in fileinput.input(sys.argv[1], inplace=inplace):...

Cannot change the value of a global variable

ios,swift,scope
I just wrote some Swift code for accessing Riot API, with Alamofire and SwiftyJSON. I wrote a function func getIDbyName(SummName: String) -> String to get the summoner id. As you can see from the code below, I am assigning the id to self.SummID. After executing the function, I am able...

refer to a variable which is not in scope

javascript,jquery,extjs,scope
I have a structure like this : { .... initComponent : function () { .... this.appCombo = Ext.create('Ext.form.field.ComboBox', { .... listeners : { // Use 'data' here } } }, load : function () { var data = .... } } I wish to use the data where I have...