I'm trying to print how many time a substring occurs. When I try to print this I get the error- Counter is undefined.     s = str(&quot;eewd&quot;)     substring = &quot;e&quot;     def count_substring(s,substring):         len1 = len(s)         len2 = len(substring)         i =0         counter = 0         while(i &lt; len1):             if(s[i] == substring[0]):                 if(s[i:i+len2] == substring):                     counter += 1             i += 1              return counter  if __name__ == &quot;__main__&quot;:        print(counter)  Also is     if __name__ == &quot;__main__&quot;: needed in python 3?
2152
What exactly are the Python scoping rules?  If I have some code:  code1 class Foo:    code2    def spam.....       code3       for code4..:        code5        x()   Where is x found?  Some possible choices include the list below:   In the enclosing source file In the class namespace In the function definition In the for loop index variable Inside the for loop   Also there is the context during execution, when the function spam is passed somewhere else. And maybe  pass a bit differently?  There must be a simple reference or algorithm somewhere.  It's a confusing world for intermediate Python programmers.
107813
I'm looking at the following code snippet:  my @ret = &lt;someMethod&gt; return (undef) if( $DB_ERROR ); return (undef) unless ($#ret &gt;= 0);   Does $# just give you a count of elements in a array?
10915
I'm pretty new to coding and I want to get an opinion on my coding. I am learning Python and I made a really simple heads and tails guessing game.  import random import time import easygui import sys while True:     rand = random.choice(["Heads", "Tails"])     firstguess = raw_input("Guess Heads or Tails: ")     if firstguess == rand:         print "Wow you win"     else:         print "That is wrong you suck so bad lol."     time.sleep(2)     answer = easygui.buttonbox("Play again?", choices=["Yes","No"])     if answer == "Yes":         easygui.msgbox("Ok")     else:         break  easygui.msgbox("Ok, see you later!") sys.exit(0)
26189
I have a bunch of log files. I need to find out how many times a string occurs in all files.  grep -c string *   returns  ... file1:1 file2:0 file3:0 ...   Using a pipe I was able to get only files that have one or more occurrences:  grep -c string * | grep -v :0  ... file4:5 file5:1 file6:2 ...   How can I get only the combined count? (If it returns file4:5, file5:1, file6:2, I want to get back 8.)
4791
Say i have this PHP code:  $FooBar = "a string";   i then need a function like this:  print_var_name($FooBar);   which prints:  FooBar   Any Ideas how to achieve this? Is this even possible in PHP?
4188
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:  flist = []  for i in xrange(3):     def func(x): return x * i     flist.append(func)  for f in flist:     print f(2)   Note that this example mindfully avoids lambda. It prints "4 4 4", which is surprising. I'd expect "0 2 4".   This equivalent Perl code does it right:  my @flist = ();  foreach my $i (0 .. 2) {     push(@flist, sub {$i * $_[0]}); }  foreach my $f (@flist) {     print $f-&gt;(2), "\n"; }   "0 2 4" is printed.  Can you please explain the difference ?    Update:   The problem is not with i being global. This displays the same behavior:  flist = []  def outer():     for i in xrange(3):         def inner(x): return x * i         flist.append(inner)  outer() #~ print i   # commented because it causes an error  for f in flist:     print f(2)   As the commented line shows, i is unknown at that point. Still, it prints "4 4 4".
85902
I found the following behavior at least weird:  def errors():     try:         ErrorErrorError     finally:         return 10  print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined   The exception disappears when you use return inside a finally clause. Is that a bug? Is that documented anywhere?  But the real question (and the answer I will mark as correct) is: What is the python developers' reason to allow that odd behavior?
107901
The \show command is extremely useful for figuring out what's going on with a particular macro.  Similarly, using \the can tell me the value of a counter.  I'd like to know if there's something similar for lengths and skips.  At the moment, I end up doing something like \rule{1pt}{\unknownlength} but that's a fairly crude method.
6643
I am doing something where I realised I wanted to count how many /s I could find in a string, and then it struck me, that there were several ways to do it, but couldn't decide on what the best (or easiest) was.  At the moment I'm going with something like:  string source = "/once/upon/a/time/"; int count = source.Length - source.Replace("/", "").Length;   But I don't like it at all, any takers?  I don't really want to dig out RegEx for this, do I?  I know my string is going to have the term I'm searching for, so you can assume that...  Of course for strings where length > 1,  string haystack = "/once/upon/a/time"; string needle = "/"; int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;
4728
I can output the value of a counter in a LaTeX document via:  \setcounter{mycounter}{1} \arabic{mycounter}   Which inserts a 1. But how do I format the output by, for example, adding a leading zero if mycounter is less than 10 in a way similar to what  lets you do by specifying %02d as your format string?
30755
How can I check if a string ends with a particular character in JavaScript?  Example: I have a string   var str = "mystring#";   I want to know if that string is ending with #. How can I check it?   Is there a endsWith() method in JavaScript? One solution I have is take the length of the string and get the last character and check it.   Is this the best way or there is any other way?
7206
I know that python has a len() function that is used to determine the size of a string, but I was wondering why it's not a method of the string object.  Update  Ok, I realized I was embarrassingly mistaken. __len__() is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see __len__ as the name instead of just len.
15003
Can you add new statements (like print, raise, with) to Python's syntax?  Say, to allow..  mystatement "Something"   Or,  new_if True:     print "example"   Not so much if you should, but rather if it's possible (short of modifying the python interpreters code)
37330
I am trying to get a number by counting how many points are in a shapefile. And this works, except I then am running into trouble using that number somewhere else. Eventually, I'll be using that count in some math (field calculator), but while debugging I'm running into an error that will end up causing me trouble later on.   This code:  TotalPoints = arcpy.GetCount_management(Path_Pts) arcpy.AddMessage("&gt;&gt;&gt;&gt; PROCESS: COUNT PATH POINTS {" + TotalPoints + "}")   gives this error:  TypeError: cannot concatenate 'str' and 'Result' objects   I tried casting it as a int, which it ALSO doesn't like:  TypeError: int() argument must be a string or a number, not 'Result'   So I've got a 'Result' object and need to turn it into a number.   How can I do that -- or is using the ArcPy function unnecessary or overly complicated here?
24750
I've just encountered a weird problem, I'm trying to printf an integer variable, but I forgot to specify the variable name, i.e.  printf("%d");   instead of  printf("%d", integerName);   Surprisingly the program compiles, there is output and it is not random. In fact, it happens to be the very integer I wanted to print in the first place, which happens to be m-1.  The errorneous printf statement will consistently output m-1 for as long as the program keeps running... In other words, it's behaving exactly as if the statement reads  printf("%d", m-1);   Anybody knows the reason behind this behaviour? I'm using g++ without any command line options.  #include &lt;iostream&gt; #define maxN 100 #define ON 1 #define OFF 0  using namespace std;  void clearArray(int* array, int n); int fillArray(int* array, int m, int n);  int main() {     int n = -1, i, m;     int array[maxN];     int found;      scanf("%d", &amp;n);      while(n!=0)     {         found=0;         m = 1;         while(found!=1)         {             if(m != 2 &amp;&amp; m != 3 &amp;&amp; m != 4 &amp;&amp; m != 6 &amp;&amp; m != 12)             {                 clearArray(array, n);                 if(fillArray(array, m, n) == 0)                 {                     found = 1;                 }             }             m++;         }          printf("%d\n");          scanf("%d", &amp;n);     }      return 0; }  void clearArray(int* array, int n) {     for(int i = 1; i &lt;= n; i++)         array[i] = ON; }  int fillArray(int* array, int m, int n) {     int i = 1, j, offCounter = 0, incrementCounter;      while(offCounter != n)     {         if(*(array+i)==ON)          {             *(array+i) = OFF;             offCounter++;                }         else          {             j = 0;             while((*array+i+j)==OFF)             {                 j++;             }             *(array+i+j) = OFF;             offCounter++;                    }         if(*(array+13) == OFF &amp;&amp; offCounter != n) return 1;         if(offCounter ==n) break;          incrementCounter = 0;                while(incrementCounter != m)         {             i++;             if(i &gt; n) i = 1;             if(*(array+i) == ON) incrementCounter++;          }            }      return 0; }
84232
Alright, I think we all agree that what happens with the following code is undefined, depending on what is passed,  void deleteForMe(int* pointer) {      delete[] pointer; }   The pointer could be all sorts of different things, and so performing an unconditional delete[] on it is undefined. However, let's assume that we are indeed passing an array pointer,  int main() {      int* arr = new int[5];      deleteForMe(arr);      return 0; }   My question is, in this case where the pointer is an array, who is it that knows this? I mean, from the language/compiler's point of view, it has no idea whether or not arr is an array pointer versus a pointer to a single int. Heck, it doesn't even know whether arr was dynamically created. Yet, if I do the following instead,  int main() {      int* num = new int(1);      deleteForMe(num);      return 0; }   The OS is smart enough to only delete one int and not go on some type of 'killing spree' by deleting the rest of the memory beyond that point (contrast that with strlen and a non-\0-terminated string -- it will keep going until it hits 0).  So whose job is it to remember these things? Does the OS keep some type of record in the background? (I mean, I realise that I started this post by saying that what happens is undefined, but the fact is, the 'killing spree' scenario doesn't happen, so therefore in the practical world someone is remembering.)
32406
Technically, any odd number of backslashes, as described in .  &gt;&gt;&gt; r'\'   File "&lt;stdin&gt;", line 1     r'\'        ^ SyntaxError: EOL while scanning string literal &gt;&gt;&gt; r'\\' '\\\\' &gt;&gt;&gt; r'\\\'   File "&lt;stdin&gt;", line 1     r'\\\'          ^ SyntaxError: EOL while scanning string literal   It seems like the parser could just treat backslashes in raw strings as regular characters (isn't that what raw strings are all about?), but I'm probably missing something obvious.