Rectangle 27 10

You have three options here, but maybe you don't need any of them, since Matlab used 'copy-on-write', i.e. variables are only copied if you modify them.

  • As @gnovice mentions, you can use a nested function. Variables used inside the nested function are shared between the nested function and the enclosing function. Nested functions are somewhat tricky to debug, and a bit more complicated to write/understand.
  • You can store your images as properties of a handle object, which is passed by reference.
  • You can write code differently in order to not use a recursive function, since Matlab isn't the best language for using those. If you have access to the image processing toolbox, you may be able to use functions like blockproc, or im2col to rewrite the function.

Finally, if you want to stay with your current scheme, I strongly suggest using persistent variables instead of globals.

matlab - How to modify an array in function? - Stack Overflow

matlab pass-by-reference pass-by-value
Rectangle 27 2

Python does not support globals shared between several modules: this is a feature. Code that implicitly modifies variables used far away is confusing and unmaintainable. The real solution is to encapsulate all state within a class and pass its instance to anything that has to modify it. This can make code clearer, more maintainable, more testable, more modular, and more expendable.

scope - how to have global variables among different modules in Python...

python scope global-variables
Rectangle 27 47

You need to use the global statement so that you are modifying the global variable counter, instead of a local variable:

counter = 0

def increment():
  global counter
  counter += 1

increment()

If the enclosing scope that counter is defined in is not the global scope, on Python 3.x you could use the nonlocal statement. In the same situation on Python 2.x you would have no way to reassign to the nonlocal name counter, so you would need to make counter mutable and modify it:

counter = [0]

def increment():
  counter[0] += 1

increment()
print counter[0]  # prints '1'

global variables - UnboundLocalError in Python - Stack Overflow

python global-variables scope
Rectangle 27 44

You need to use the global statement so that you are modifying the global variable counter, instead of a local variable:

counter = 0

def increment():
  global counter
  counter += 1

increment()

If the enclosing scope that counter is defined in is not the global scope, on Python 3.x you could use the nonlocal statement. In the same situation on Python 2.x you would have no way to reassign to the nonlocal name counter, so you would need to make counter mutable and modify it:

counter = [0]

def increment():
  counter[0] += 1

increment()
print counter[0]  # prints '1'

global variables - UnboundLocalError in Python - Stack Overflow

python global-variables scope
Rectangle 27 573

Static variables represent global state. That's hard to reason about and hard to test: if I create a new instance of an object, I can reason about its new state within tests. If I use code which is using static variables, it could be in any state - and anything could be modifying it.

I could go on for quite a while, but the bigger concept to think about is that the tighter the scope of something, the easier it is to reason about. We're good at thinking about small things, but it's hard to reason about the state of a million line system if there's no modularity. This applies to all sorts of things, by the way - not just static variables.

That lately seems to be an argument, whether code testable or not. It's a rather flawed reasoning. The argument should be 'good design', and usually good design is testable. But not the other way around: "I can't test it therefor it must be bad design." Don't get me wrong though, I agree with your post in general.

@M Platvoet: I would say that given a choice between two otherwise equally valid designs, the testable one is superior. Being testable certainly doesn't equate to being well designed, but I've rarely come across untestable good designs, and I think they're sufficiently rare that I have no problem in making testability a general purpose contributing indicator towards good design.

@M Platvoet - Testability affects both maintainability and reliability, and I would consider those major factors in the quality of design. They're not the only factors, surely, but IMHO the cost of any given code is a combination of machine cycles, developer cycles, and user cycles. Testability hits two of those three.

@M Platvoet - Testability also tends to affect reusability, since a decoupled class is generally easier to reuse.

M Platvoet - I don't agree with your first comment here. I think if something can't be tested, then it IS bad design; because if I can't test it, I can't know that it works. Would you buy a car if the salesperson told you "The design of this model prevents it from being tested, so I don't know if it actually runs"? Testability is so crucial for software (as well as cars), that competent design DEMANDS that it be included.

java - Why are static variables considered evil? - Stack Overflow

java static
Rectangle 27 7

Hi if you write anything in a "" (string) then it will be treated as a String. You should modify your code like below:

text =  "Test Message"
message = client.messages.create(
    body= text,
    to="+12125551234",
    from_="+15105551234",
)
print message.sid
text
body

I felt so dumb how i missed this simple logic, Code is working Fine Now. Thanks Ankitha :)

variables - Twillio Restclient in python - Stack Overflow

python variables sms twilio
Rectangle 27 569

Static variables represent global state. That's hard to reason about and hard to test: if I create a new instance of an object, I can reason about its new state within tests. If I use code which is using static variables, it could be in any state - and anything could be modifying it.

I could go on for quite a while, but the bigger concept to think about is that the tighter the scope of something, the easier it is to reason about. We're good at thinking about small things, but it's hard to reason about the state of a million line system if there's no modularity. This applies to all sorts of things, by the way - not just static variables.

That lately seems to be an argument, whether code testable or not. It's a rather flawed reasoning. The argument should be 'good design', and usually good design is testable. But not the other way around: "I can't test it therefor it must be bad design." Don't get me wrong though, I agree with your post in general.

@M Platvoet: I would say that given a choice between two otherwise equally valid designs, the testable one is superior. Being testable certainly doesn't equate to being well designed, but I've rarely come across untestable good designs, and I think they're sufficiently rare that I have no problem in making testability a general purpose contributing indicator towards good design.

@M Platvoet - Testability affects both maintainability and reliability, and I would consider those major factors in the quality of design. They're not the only factors, surely, but IMHO the cost of any given code is a combination of machine cycles, developer cycles, and user cycles. Testability hits two of those three.

@M Platvoet - Testability also tends to affect reusability, since a decoupled class is generally easier to reuse.

M Platvoet - I don't agree with your first comment here. I think if something can't be tested, then it IS bad design; because if I can't test it, I can't know that it works. Would you buy a car if the salesperson told you "The design of this model prevents it from being tested, so I don't know if it actually runs"? Testability is so crucial for software (as well as cars), that competent design DEMANDS that it be included.

java - Why are static variables considered evil? - Stack Overflow

java static
Rectangle 27 194

By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.

To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition.

<?php
function add_some_extra(&$string)
{
    $string .= 'and something extra.';
}

$str = 'This is a string, ';
add_some_extra($str);
echo $str;    // outputs 'This is a string, and something extra.'
?>

I also had this doubt ( newbie ) - so just to be clear , this would be the same as $str = add_some_extra($str); if I was not using the reference , right ? then what is the real added value of that ?

@Obmerk If you were not using the ampersand to signify by reference, it would not be equivalent. Notice how the function has no return statement, so $str would be assigned null, in your case.

if you do it this way @ObmerkKronen then you'll have to return the value and catch it through your code too. The initial variable will remain the same otherwise.

I'm wondering if pass by reference has some performance benefits or not? I'm passing a large array & by default it is pass by value. So, if I use call by reference then, will there be some performance wise benefit??? (keeping the array values unchanged during the whole process)

the real benefit is that you can manipulate/return muliple values. You are also able to pass variables by reference and still let the function return something.

Are PHP Variables passed by value or by reference? - Stack Overflow

php variables pass-by-reference pass-by-value
Rectangle 27 2

Terminal sessions use the shell. You only should modify shell environment variables, there is no need to reconfigure GUI programs.

Also, I don't suppose the .plist offers a way to extend a preexisting variable.

~/.profile
export PATH=$PATH:~XXXX/Qt/5.4/clang_64/bin

If Qt offers a more canonical method of installation, that would probably be preferable, though.

If you literally just want the command qmake to work, without really installing anything, just do

sudo ln -s ~/Qt/5.4/clang_64/bin/qmake /usr/local/bin

@CroCo It's applied every time you launch a shell. Until you change .profile again to remove it.

ln: /usr/local/bin: No such file or directory
/opt/local/bin

osx - how to set environment variables in Yosemite - Stack Overflow

osx environment-variables osx-yosemite
Rectangle 27 5

Like shellcheck would helpfully have pointed out, you're modifying ac_reg_ids in a subshell.

ac_reg_ids="-1" #Starting value
while read ac_reg_id; do
    echo "$ac_reg_id" 
    ac_reg_ids="$ac_reg_ids, $ac_reg_id"
done < <( mysql whatever )  # Redirect from process substution, avoiding pipeline
echo "ac_reg_ids: $ac_reg_ids"

I'll see if it does the trick. Thanks for pointing out that website, didn't know about it yet. Could you give more information about how "< <" works? I'm pretty new with bash.

There is no < <. There is < which redirects from a file as I'm sure you already know, and there's <(cmd) which expands to a filename which when read produces the output from cmd. Any variation on this, such as << (cmd), <<(cmd) or < < cmd is invalid.

string - Bash variable concatenation fails inside loop - Stack Overflo...

string bash variables concatenation
Rectangle 27 5

Like shellcheck would helpfully have pointed out, you're modifying ac_reg_ids in a subshell.

ac_reg_ids="-1" #Starting value
while read ac_reg_id; do
    echo "$ac_reg_id" 
    ac_reg_ids="$ac_reg_ids, $ac_reg_id"
done < <( mysql whatever )  # Redirect from process substution, avoiding pipeline
echo "ac_reg_ids: $ac_reg_ids"

I'll see if it does the trick. Thanks for pointing out that website, didn't know about it yet. Could you give more information about how "< <" works? I'm pretty new with bash.

There is no < <. There is < which redirects from a file as I'm sure you already know, and there's <(cmd) which expands to a filename which when read produces the output from cmd. Any variation on this, such as << (cmd), <<(cmd) or < < cmd is invalid.

string - Bash variable concatenation fails inside loop - Stack Overflo...

string bash variables concatenation
Rectangle 27 9

You can use reflection to get the values of private fields. For example:

Field field = YourClass.class.getDeclaredField("language");
field.setAccessible(true); //override the access restriction of it being private
field.get(yourObject);

If there's spring on your classpath, you can use its ReflectionUtils / ReflectionTestUtils.

It is sometimes argued that private fields should not be verified, and only the public state of the object is the point of unit-testing. From that perspective it may be better to expose a getter, or even better - thrown an exception.

If the object is in invalid state if the fields are not set, then it should be the responsibility of the object itself to enforce its validity, by throwing an exception.

Thanks, in the end I decided to throw an exception from my init method if the values were not correct.

java - How to test void method that only modifies private class member...

java unit-testing
Rectangle 27 9

I want to assert that the language, country and credits fields have been set after calling init

Some philosophy: why do you care whether they are set correctly? If the answer is "so the class then behaves correctly", then you can test that they have been set correctlty by testing that expected subsequent behaviour. If however setting them incorrectly has no effect they are redundant and you should remove them.

Another poster has suggested using reflection to access the private fields. I advise against this; anything marked private should be an implementation detail of the class, and therefore should not be directly tested. You should instead test the published API of your class. You then have the freedom to refactor it easilly by changing implementation (private) details.

There is another method in the same class that needs these fields to be set, however since the method call that relies on these fields is mocked it won't be reporting an error. In this case is it better to catch the fields as they are being set in the init method?

If no error would be reported, the fields have no effect, so I would recommend removing them Or, rather, defer adding them until you work on that method.

Under normal circumstances there would be an error reported, but under a test situation those external dependencies need to be mocked - hence no error would be thrown from the mock - but the fields are actually required. Setting the field values only in the method they are used in would make sense, but the values they are set from (props) are only available to the init method.

You are saying that it is hard to test your class. This suggests the design of your class is faulty, and you need to adjust the published interface of the class to make it easier to test.

java - How to test void method that only modifies private class member...

java unit-testing
Rectangle 27 134

You must use the __block specifier when you modify a variable inside a block, so the code you gave should look like this instead:

__block NSString *textString;
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 
                                                 (unsigned long)NULL), ^(void) {
      textString = [self getTextString];
});

Blocks capture the state of the variables referenced inside their bodies, so the captured variable must be declared mutable. And mutability is exactly what you need considering that you're essentially setting this thing.

__block

But this solution is still useless -- the block is executed once asynchronously. So even if it could assign to the local variable testString, who can use it? The only thing I can think of if there's another block in this scope that also uses textString, which can be executed later.

Without surrounding context, or code that isn't basically pseudo-code, how did you come to that determination? For all you know, the OP could have omitted dispatch_group logic, or perhaps some surrounding KVO will/didChangeValueForKey: calls in the block. Point is: you missed the point of the question.

To assign a value for a Global variable __block works fine as mentioned above. This means, we can modify the value of textString inside the block. At the same time, accessing "self" inside the block will create a retain cycle. So try using weak instance of self inside the block (create weak self like this __weak typeof(self) wkSelf = self)

ios - Unable to access global variables in dispatch_async : "Variable ...

ios objective-c multithreading objective-c-blocks grand-central-dispatch
Rectangle 27 133

You must use the __block specifier when you modify a variable inside a block, so the code you gave should look like this instead:

__block NSString *textString;
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 
                                                 (unsigned long)NULL), ^(void) {
      textString = [self getTextString];
});

Blocks capture the state of the variables referenced inside their bodies, so the captured variable must be declared mutable. And mutability is exactly what you need considering that you're essentially setting this thing.

__block

But this solution is still useless -- the block is executed once asynchronously. So even if it could assign to the local variable testString, who can use it? The only thing I can think of if there's another block in this scope that also uses textString, which can be executed later.

Without surrounding context, or code that isn't basically pseudo-code, how did you come to that determination? For all you know, the OP could have omitted dispatch_group logic, or perhaps some surrounding KVO will/didChangeValueForKey: calls in the block. Point is: you missed the point of the question.

To assign a value for a Global variable __block works fine as mentioned above. This means, we can modify the value of textString inside the block. At the same time, accessing "self" inside the block will create a retain cycle. So try using weak instance of self inside the block (create weak self like this __weak typeof(self) wkSelf = self)

ios - Unable to access global variables in dispatch_async : "Variable ...

ios objective-c multithreading objective-c-blocks grand-central-dispatch
Rectangle 27 292

There is no "pass by reference" available in JavaScript. You can pass an object (which is to say, you can pass-by-value a reference to an object) and then have a function modify the object contents:

function alterObject(obj) {
  obj.foo = "goodbye";
}

var myObj = { foo: "hello world" };

alterObject(myObj);

alert(myObj.foo); // "goodbye" instead of "hello world"

Now, in your case, you're not passing anything anyway, as far as I can tell. You can iterate over the properties of an array with a numeric index and modify each cell of the array, if you want.

It's important to note that "pass-by-reference" is a very specific term. It does not mean simply that it's possible to pass a reference to a modifiable object. Instead, it means that it's possible to pass a simple variable in such a way as to allow a function to modify that value in the calling context. So:

function swap(a, b) {
   var tmp = a;
   a = b;
   b = tmp; //assign tmp to b
 }

 var x = 1, y = 2;
 swap(x, y);

 alert("x is " + x + " y is " + y); // "x is 1 y is 2"

In a language like C++, it's possible to do that because that language does (sort-of) have pass-by-reference.

edit this recently (March 2015) blew up on Reddit again over a blog post similar to mine mentioned below, though in this case about Java. It occurred to me while reading the back-and-forth in the Reddit comments that a big part of the confusion stems from the unfortunate collision involving the word "reference". The terminology "pass by reference" and "pass by value" predates the concept of having "objects" to work with in programming languages. It's really not about objects at all; it's about function parameters, and specifically how function parameters are "connected" (or not) to the calling environment. In particular, note that in a true pass-by-reference language one that does involve objects one would still have the ability to modify object contents, and it would look pretty much exactly like it does in JavaScript. However, one would also be able to modify the object reference in the calling environment, and that's the key thing that you can't do in JavaScript. A pass-by-reference language would pass not the reference itself, but a reference to the reference.

edit here is a blog post on the topic. (Note the comment to that post that explains that C++ doesn't really have pass-by-reference. That is true. What C++ does have, however, is the ability to create references to plain variables, either explicitly at the point of function invocation to create a pointer, or implicitly when calling functions whose argument type signature calls for that to be done. Those are the key things JavaScript doesn't support.)

You can pass a reference to an object or an array which allows you to change the original object or array which I believe is what the OP is actually asking about.

Well, the OP used the terminology but the actual code doesn't seem to involve any "passing" at all :-) I'm not really sure what he trying to do.

You can't do that in JavaScript because you cannot create a reference to a variable; you can't create a "pointer", in other words. You can keep your variables in object containers, however, because you can effectively use property names as pointers. (Not exactly the same thing of course, but it would work.)

Passing a reference by value is not the same as passing by reference, though it may appear so in some scenarios such as this.

Your blogger is wrong about C++, which does pass-by-reference, and his post makes no sense. It's irrelevant that you can't change the value of a reference after initialisation; that's got nothing to do with 'pass by reference'. His statement that 'The "pass by reference" semantic can be traced back through C#' should have rung an alarm bell.

Pass Variables by Reference in Javascript - Stack Overflow

javascript variables pass-by-reference
Rectangle 27 287

There is no "pass by reference" available in JavaScript. You can pass an object (which is to say, you can pass-by-value a reference to an object) and then have a function modify the object contents:

function alterObject(obj) {
  obj.foo = "goodbye";
}

var myObj = { foo: "hello world" };

alterObject(myObj);

alert(myObj.foo); // "goodbye" instead of "hello world"

Now, in your case, you're not passing anything anyway, as far as I can tell. You can iterate over the properties of an array with a numeric index and modify each cell of the array, if you want.

It's important to note that "pass-by-reference" is a very specific term. It does not mean simply that it's possible to pass a reference to a modifiable object. Instead, it means that it's possible to pass a simple variable in such a way as to allow a function to modify that value in the calling context. So:

function swap(a, b) {
   var tmp = a;
   a = b;
   b = tmp; //assign tmp to b
 }

 var x = 1, y = 2;
 swap(x, y);

 alert("x is " + x + " y is " + y); // "x is 1 y is 2"

In a language like C++, it's possible to do that because that language does (sort-of) have pass-by-reference.

edit this recently (March 2015) blew up on Reddit again over a blog post similar to mine mentioned below, though in this case about Java. It occurred to me while reading the back-and-forth in the Reddit comments that a big part of the confusion stems from the unfortunate collision involving the word "reference". The terminology "pass by reference" and "pass by value" predates the concept of having "objects" to work with in programming languages. It's really not about objects at all; it's about function parameters, and specifically how function parameters are "connected" (or not) to the calling environment. In particular, note that in a true pass-by-reference language one that does involve objects one would still have the ability to modify object contents, and it would look pretty much exactly like it does in JavaScript. However, one would also be able to modify the object reference in the calling environment, and that's the key thing that you can't do in JavaScript. A pass-by-reference language would pass not the reference itself, but a reference to the reference.

edit here is a blog post on the topic. (Note the comment to that post that explains that C++ doesn't really have pass-by-reference. That is true. What C++ does have, however, is the ability to create references to plain variables, either explicitly at the point of function invocation to create a pointer, or implicitly when calling functions whose argument type signature calls for that to be done. Those are the key things JavaScript doesn't support.)

I wouldn't say "there is no pass by reference". Some types of variables are always passed by reference. There is no control over pass by reference vs. pass by value, but there is pass by reference.

You can pass a reference to an object or an array which allows you to change the original object or array which I believe is what the OP is actually asking about.

Well, the OP used the terminology but the actual code doesn't seem to involve any "passing" at all :-) I'm not really sure what he trying to do.

You can't do that in JavaScript because you cannot create a reference to a variable; you can't create a "pointer", in other words. You can keep your variables in object containers, however, because you can effectively use property names as pointers. (Not exactly the same thing of course, but it would work.)

Passing a reference by value is not the same as passing by reference, though it may appear so in some scenarios such as this.

Pass Variables by Reference in Javascript - Stack Overflow

javascript variables pass-by-reference
Rectangle 27 287

There is no "pass by reference" available in JavaScript. You can pass an object (which is to say, you can pass-by-value a reference to an object) and then have a function modify the object contents:

function alterObject(obj) {
  obj.foo = "goodbye";
}

var myObj = { foo: "hello world" };

alterObject(myObj);

alert(myObj.foo); // "goodbye" instead of "hello world"

Now, in your case, you're not passing anything anyway, as far as I can tell. You can iterate over the properties of an array with a numeric index and modify each cell of the array, if you want.

It's important to note that "pass-by-reference" is a very specific term. It does not mean simply that it's possible to pass a reference to a modifiable object. Instead, it means that it's possible to pass a simple variable in such a way as to allow a function to modify that value in the calling context. So:

function swap(a, b) {
   var tmp = a;
   a = b;
   b = tmp; //assign tmp to b
 }

 var x = 1, y = 2;
 swap(x, y);

 alert("x is " + x + " y is " + y); // "x is 1 y is 2"

In a language like C++, it's possible to do that because that language does (sort-of) have pass-by-reference.

edit this recently (March 2015) blew up on Reddit again over a blog post similar to mine mentioned below, though in this case about Java. It occurred to me while reading the back-and-forth in the Reddit comments that a big part of the confusion stems from the unfortunate collision involving the word "reference". The terminology "pass by reference" and "pass by value" predates the concept of having "objects" to work with in programming languages. It's really not about objects at all; it's about function parameters, and specifically how function parameters are "connected" (or not) to the calling environment. In particular, note that in a true pass-by-reference language one that does involve objects one would still have the ability to modify object contents, and it would look pretty much exactly like it does in JavaScript. However, one would also be able to modify the object reference in the calling environment, and that's the key thing that you can't do in JavaScript. A pass-by-reference language would pass not the reference itself, but a reference to the reference.

edit here is a blog post on the topic. (Note the comment to that post that explains that C++ doesn't really have pass-by-reference. That is true. What C++ does have, however, is the ability to create references to plain variables, either explicitly at the point of function invocation to create a pointer, or implicitly when calling functions whose argument type signature calls for that to be done. Those are the key things JavaScript doesn't support.)

I wouldn't say "there is no pass by reference". Some types of variables are always passed by reference. There is no control over pass by reference vs. pass by value, but there is pass by reference.

You can pass a reference to an object or an array which allows you to change the original object or array which I believe is what the OP is actually asking about.

Well, the OP used the terminology but the actual code doesn't seem to involve any "passing" at all :-) I'm not really sure what he trying to do.

You can't do that in JavaScript because you cannot create a reference to a variable; you can't create a "pointer", in other words. You can keep your variables in object containers, however, because you can effectively use property names as pointers. (Not exactly the same thing of course, but it would work.)

Passing a reference by value is not the same as passing by reference, though it may appear so in some scenarios such as this.

Pass Variables by Reference in Javascript - Stack Overflow

javascript variables pass-by-reference