qid int64 46k 74.7M | question stringlengths 54 37.8k | date stringlengths 10 10 | metadata listlengths 3 3 | response_j stringlengths 17 26k | response_k stringlengths 26 26k |
|---|---|---|---|---|---|
4,837,218 | Last night I came across the term called Jython which was kind of new to me so I started reading about it only to add more to my confusion about Python in general. I have never really used Python either. So here is what I am confused about.
1. `Python is implemented in C` - Does that mean that the interpreter was written in C or does the interpreter convert Python source code into C?
2. CPython is nothing but the original Python & the term was just coined to later distinguish it from Jython - true or false?
3. Now that Python is implemented in C (not really sure what that means), but does that mean python can be seamlessly integrated with any C code.
4. Is Jython like a new programming language or does its syntax & other programming constructs look exactly similar to the original python? or is it just python which can be integrated with java code?
5. If none of my above questions answer the difference between Python & Jython, what is it? | 2011/01/29 | [
"https://Stackoverflow.com/questions/4837218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568638/"
] | a) Python is a programming language. Interpreters of Python code are implemented using other programming languages like C (PyPy even using Python itself to implement one, I believe).
b) CPython, aka Classic Python, is the reference implementation and is written in C. Jython is a Python interpreter written in Java.
c) Using C libraries in Python is pretty easy, e.g. using the ctypes module.
d) see b.
e) see a and b. | a) Default and most widely used language implementation is written in c also caled CPython. There is also for instance Python implemented in Python - <http://codespeak.net/pypy/dist/pypy/doc/>
b) CPython is default python implemetation in C. Jython is implemetation in Java.
c) Yes.
d) Jython is implementation of Python language writen in Java.
e) CPython is easly integrated whit C, Jython is easly integrated whit Java. |
4,837,218 | Last night I came across the term called Jython which was kind of new to me so I started reading about it only to add more to my confusion about Python in general. I have never really used Python either. So here is what I am confused about.
1. `Python is implemented in C` - Does that mean that the interpreter was written in C or does the interpreter convert Python source code into C?
2. CPython is nothing but the original Python & the term was just coined to later distinguish it from Jython - true or false?
3. Now that Python is implemented in C (not really sure what that means), but does that mean python can be seamlessly integrated with any C code.
4. Is Jython like a new programming language or does its syntax & other programming constructs look exactly similar to the original python? or is it just python which can be integrated with java code?
5. If none of my above questions answer the difference between Python & Jython, what is it? | 2011/01/29 | [
"https://Stackoverflow.com/questions/4837218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568638/"
] | 1. The former.
2. I suppose yes. Strictly speaking, "Python" refers only to the language (regardless of the implementation) - but unless the distinction important (e.g. when discussing implementations details), it can also refer to implementations. "CPython" is an unambiguous name for the oldest, most widely-used implementation that's the de-facto standard.
3. Well, not quite seamlessly. C code that handles Python objects has to juggle with `PyObject *` and use auxiliary function provided by CPython to convert e.g. a Python integer to a C `int`. Likewise, C code has to be wrapped with functions taking and returning `PyObject *`, exposing functions and metadata to the interpreter, etc. You can also use e.g. `ctypes` for calling native code (although it's often painful), SWIG etc. to automate the wrapping or [Cython](http://cython.org) to write C modules in a Python-C-crossover language.
4. It's another implementation of Python, i.e. the same language. The main difference is that the code runs on the JVM and can thus integrate easily with Java (or Scala or Closure or any other JVM language).
5. Python is a language. Jython is an implementation of that language. Do you ask for the difference between C and GCC? | a) Python is a programming language. Interpreters of Python code are implemented using other programming languages like C (PyPy even using Python itself to implement one, I believe).
b) CPython, aka Classic Python, is the reference implementation and is written in C. Jython is a Python interpreter written in Java.
c) Using C libraries in Python is pretty easy, e.g. using the ctypes module.
d) see b.
e) see a and b. |
4,837,218 | Last night I came across the term called Jython which was kind of new to me so I started reading about it only to add more to my confusion about Python in general. I have never really used Python either. So here is what I am confused about.
1. `Python is implemented in C` - Does that mean that the interpreter was written in C or does the interpreter convert Python source code into C?
2. CPython is nothing but the original Python & the term was just coined to later distinguish it from Jython - true or false?
3. Now that Python is implemented in C (not really sure what that means), but does that mean python can be seamlessly integrated with any C code.
4. Is Jython like a new programming language or does its syntax & other programming constructs look exactly similar to the original python? or is it just python which can be integrated with java code?
5. If none of my above questions answer the difference between Python & Jython, what is it? | 2011/01/29 | [
"https://Stackoverflow.com/questions/4837218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/568638/"
] | 1. The former.
2. I suppose yes. Strictly speaking, "Python" refers only to the language (regardless of the implementation) - but unless the distinction important (e.g. when discussing implementations details), it can also refer to implementations. "CPython" is an unambiguous name for the oldest, most widely-used implementation that's the de-facto standard.
3. Well, not quite seamlessly. C code that handles Python objects has to juggle with `PyObject *` and use auxiliary function provided by CPython to convert e.g. a Python integer to a C `int`. Likewise, C code has to be wrapped with functions taking and returning `PyObject *`, exposing functions and metadata to the interpreter, etc. You can also use e.g. `ctypes` for calling native code (although it's often painful), SWIG etc. to automate the wrapping or [Cython](http://cython.org) to write C modules in a Python-C-crossover language.
4. It's another implementation of Python, i.e. the same language. The main difference is that the code runs on the JVM and can thus integrate easily with Java (or Scala or Closure or any other JVM language).
5. Python is a language. Jython is an implementation of that language. Do you ask for the difference between C and GCC? | a) Default and most widely used language implementation is written in c also caled CPython. There is also for instance Python implemented in Python - <http://codespeak.net/pypy/dist/pypy/doc/>
b) CPython is default python implemetation in C. Jython is implemetation in Java.
c) Yes.
d) Jython is implementation of Python language writen in Java.
e) CPython is easly integrated whit C, Jython is easly integrated whit Java. |
46,431,145 | so im a python beginner and i cant find a way to put a input varible in a random like so,
```html
import time
import random
choice = input('easy (max of 100 number), medium(max of 1000) or hard (max of 5000)? Or custom)')
time.sleep(2)
if choice == 'custom':
cus = input(' max number?')
print ('okey dokey!')
eh = 1
cuss = random.randrange(0, (cus))
easy = random.randint(0, 100)
medium = random.randint(0, 1000)
hard = random.randint (0, 5000)
if choice == 'easy' or 'medium' or 'hard' or cus:
while eh == 1:
esy = int(input('what do you think the number is?)'))
if esy > easy:
time.sleep(2)
print ('too high!')
elif esy == easy:
print (' CORRECT!')
break
elif esy < easy:
print ('TOO low')
```
is there any way i can put a number that someone typed in a random, like in line 9? | 2017/09/26 | [
"https://Stackoverflow.com/questions/46431145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8677673/"
] | There are multiple things wrong with your code. You're using ('s with print, which suggests you're using python3. This means that when you do `cus = input()`, cus is now a string. You probably want to do `cus = int(input())`
Doing `choice == 'easy' or 'medium' or 'hard' or cus` will always be True; I have no idea why people keep doing this in Python, but you need to do `choice == 'easy' or choice == 'medium' or choice == 'hard' or choice == 'cus'`. Of course, a better way to do it is with a dictionary.
```
values = {'easy': 100, 'medium': 1000, 'hard': 5000}
```
And then do
```
value = values.get(choice)
if not value:
value = int(input("Please enter custom value"))
```
And then you can do
`randomvalue = random.randint(1,value)` | Convert your variable `cus` to an int and pass it as you normally would
```
cuss = random.randrange(0, int(cus))
``` |
7,817,926 | I'm trying to use scapy on win32 python2.7
I've manage to compile all the other dependencies expect this one
can some help in the goal of reaching this executable ?
"dnet-1.12.win32-py2.7.exe"
(I promise to update the this question too and the scapy manual,
[Running Scapy on Windows with Python 2.7](https://stackoverflow.com/questions/5447461/running-scapy-on-windows-with-python-v2-7-enthought-python-distribution-7))
**Update:**
I've managed to compile it with mingw32
I'm using vs2005, and I have to make some fixes to libdnet to actually work (look like last time they compiled it on windows it was with vs6.0
I'll try updating scapy manual... (and upload the executables to there) | 2011/10/19 | [
"https://Stackoverflow.com/questions/7817926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459189/"
] | I just called super on the following overridden method of the BaseExpandableListAdapter and since then the notifyDataSetChanged() works.
```
@Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
}
``` | you can try to additionally call invalidateViews() on your ExpandableListView when refreshing. |
7,817,926 | I'm trying to use scapy on win32 python2.7
I've manage to compile all the other dependencies expect this one
can some help in the goal of reaching this executable ?
"dnet-1.12.win32-py2.7.exe"
(I promise to update the this question too and the scapy manual,
[Running Scapy on Windows with Python 2.7](https://stackoverflow.com/questions/5447461/running-scapy-on-windows-with-python-v2-7-enthought-python-distribution-7))
**Update:**
I've managed to compile it with mingw32
I'm using vs2005, and I have to make some fixes to libdnet to actually work (look like last time they compiled it on windows it was with vs6.0
I'll try updating scapy manual... (and upload the executables to there) | 2011/10/19 | [
"https://Stackoverflow.com/questions/7817926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459189/"
] | you can try to additionally call invalidateViews() on your ExpandableListView when refreshing. | You have to wait until the whole viewtree has been drawn and then you can call notifyDataSetChanged()
*"A view tree observer is used to register listeners that can be notified of global changes in the view tree. Such global events include, but are not limited to, layout of the whole tree, beginning of the drawing pass, touch mode change.... A ViewTreeObserver should never be instantiated by applications as it is provided by the views hierarchy. Refer to getViewTreeObserver() for more information."*
<http://developer.android.com/reference/android/view/ViewTreeObserver.html>
```
final View v = convertView;
ViewTreeObserver vto = convertView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
v.getViewTreeObserver().removeOnGlobalLayoutListener(this);
notifyDataSetChanged();
}});
``` |
7,817,926 | I'm trying to use scapy on win32 python2.7
I've manage to compile all the other dependencies expect this one
can some help in the goal of reaching this executable ?
"dnet-1.12.win32-py2.7.exe"
(I promise to update the this question too and the scapy manual,
[Running Scapy on Windows with Python 2.7](https://stackoverflow.com/questions/5447461/running-scapy-on-windows-with-python-v2-7-enthought-python-distribution-7))
**Update:**
I've managed to compile it with mingw32
I'm using vs2005, and I have to make some fixes to libdnet to actually work (look like last time they compiled it on windows it was with vs6.0
I'll try updating scapy manual... (and upload the executables to there) | 2011/10/19 | [
"https://Stackoverflow.com/questions/7817926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459189/"
] | you can try to additionally call invalidateViews() on your ExpandableListView when refreshing. | If you are using Expandable lists of Big Nerd Ranch, please note that traditional `notifyDataSetChanged()` of `RecyclerView.adapter` is not working.
Instead Expandable RecyclerView provides a set of notify methods with the ability to inform the adapter of changes to the list of ParentListItems.
```
// Parent Changes
notifyParentItemInserted(int parentPosition)
notifyParentItemRemoved(int parentPosition)
notifyParentItemChanged(int parentPosition)
notifyParentItemRangeInserted(int parentPositionStart, int itemCount)
// Child Changes
notifyChildItemInserted(int parentPosition, int childPosition)
notifyChildItemRemoved(int parentPosition, int childPosition)
notifyChildItemChanged(int parentPosition, int childPosition)
```
For additional specifics visit <https://bignerdranch.github.io/expandable-recycler-view/> |
7,817,926 | I'm trying to use scapy on win32 python2.7
I've manage to compile all the other dependencies expect this one
can some help in the goal of reaching this executable ?
"dnet-1.12.win32-py2.7.exe"
(I promise to update the this question too and the scapy manual,
[Running Scapy on Windows with Python 2.7](https://stackoverflow.com/questions/5447461/running-scapy-on-windows-with-python-v2-7-enthought-python-distribution-7))
**Update:**
I've managed to compile it with mingw32
I'm using vs2005, and I have to make some fixes to libdnet to actually work (look like last time they compiled it on windows it was with vs6.0
I'll try updating scapy manual... (and upload the executables to there) | 2011/10/19 | [
"https://Stackoverflow.com/questions/7817926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459189/"
] | I just called super on the following overridden method of the BaseExpandableListAdapter and since then the notifyDataSetChanged() works.
```
@Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
}
``` | You have to wait until the whole viewtree has been drawn and then you can call notifyDataSetChanged()
*"A view tree observer is used to register listeners that can be notified of global changes in the view tree. Such global events include, but are not limited to, layout of the whole tree, beginning of the drawing pass, touch mode change.... A ViewTreeObserver should never be instantiated by applications as it is provided by the views hierarchy. Refer to getViewTreeObserver() for more information."*
<http://developer.android.com/reference/android/view/ViewTreeObserver.html>
```
final View v = convertView;
ViewTreeObserver vto = convertView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
v.getViewTreeObserver().removeOnGlobalLayoutListener(this);
notifyDataSetChanged();
}});
``` |
7,817,926 | I'm trying to use scapy on win32 python2.7
I've manage to compile all the other dependencies expect this one
can some help in the goal of reaching this executable ?
"dnet-1.12.win32-py2.7.exe"
(I promise to update the this question too and the scapy manual,
[Running Scapy on Windows with Python 2.7](https://stackoverflow.com/questions/5447461/running-scapy-on-windows-with-python-v2-7-enthought-python-distribution-7))
**Update:**
I've managed to compile it with mingw32
I'm using vs2005, and I have to make some fixes to libdnet to actually work (look like last time they compiled it on windows it was with vs6.0
I'll try updating scapy manual... (and upload the executables to there) | 2011/10/19 | [
"https://Stackoverflow.com/questions/7817926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459189/"
] | I just called super on the following overridden method of the BaseExpandableListAdapter and since then the notifyDataSetChanged() works.
```
@Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
}
``` | If you are using Expandable lists of Big Nerd Ranch, please note that traditional `notifyDataSetChanged()` of `RecyclerView.adapter` is not working.
Instead Expandable RecyclerView provides a set of notify methods with the ability to inform the adapter of changes to the list of ParentListItems.
```
// Parent Changes
notifyParentItemInserted(int parentPosition)
notifyParentItemRemoved(int parentPosition)
notifyParentItemChanged(int parentPosition)
notifyParentItemRangeInserted(int parentPositionStart, int itemCount)
// Child Changes
notifyChildItemInserted(int parentPosition, int childPosition)
notifyChildItemRemoved(int parentPosition, int childPosition)
notifyChildItemChanged(int parentPosition, int childPosition)
```
For additional specifics visit <https://bignerdranch.github.io/expandable-recycler-view/> |
61,038,562 | I'm writing a program where I'm converting a function to prefix and calculate.
```
from pythonds.basic import Stack
def doMath(op, op1, op2):
if op == "*":
return int(op1) * int(op2)
elif op == "/":
return int(op1) / int(op2)
elif op == "+":
return int(op1) + int(op2)
elif op == "-":
return int(op1) + int(op2)
def postfixEval(postfixExpr):
operandStack = Stack()
tokenList = postfixExpr.split()
for token in tokenList:
print(tokenList)
print("this is token: ", token)
if token in "0123456789":
operandStack.push(token)
print("pop: ",operandStack.peek())
elif not operandStack.isEmpty():
operand2 = operandStack.pop()
operand1 = operandStack.pop()
result = doMath(token, operand1, operand2)
print (result)
operandStack.push(result)
return operandStack.pop()
print(postfixEval('7 8 + 3 2 + /'))
print(postfixEval("17 10 + 3 * 9 /"))
```
So when I run the first postfixEval it return 3.0,
but at the second print it returns `IndexError: pop from empty list`
Apparently it's bc of the 2 digit numbers, how could I fix that?
Thanks | 2020/04/05 | [
"https://Stackoverflow.com/questions/61038562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7737188/"
] | When you try:
```
if token in "0123456789":
operandStack.push(token)
```
for `token = 17`, this shall fail since `17` is not in `0123456789`.
So change it to this:
```
try:
if float(token):
operandStack.push(token)
except:
#your code here
```
---
**HOW THIS WORKS:**
When a type of `str` containing digits and numbers are passed, `float()` tries to convert it into float. This is only possible only if it is a number. | Replace `if token in "0123456789"` (checks if `token` is a substring of `"0123456789"`) with `if token.isdigit()` (checks if `token` consists of decimal digits). |
9,816,139 | I've got an old RRD file that was only set up to track 1 year of history. I decided more history would be nice. I did rrdtool resize, and the RRD is now bigger. I've got old backups of this RRD file and I'd like to merge the old data in so that the up-to-date RRD also has the historical data.
I've tried the rrd contrib "merged-rrd.py" but it gives:
```
$ python merged-rrd.py ../temperature-2010-12-06.rrd ../temperature-2011-05-24.rrd merged1.rrd
merging old:../temperature-2010-12-06.rrd to new:../temperature-2011-05-24.rrd. creating merged rrd: merged1.rrd
Traceback (most recent call last):
File "merged-rrd.py", line 149, in <module>
mergeRRD(old_path, new_path, mer_path)
File "merged-rrd.py", line 77, in mergeRRD
odict = getXmlDict(oxml)
File "merged-rrd.py", line 52, in getXmlDict
cf = line.split()[1]
IndexError: list index out of range
```
Also tried "rrd\_merger.pl":
```
$ perl rrd_merger.pl --oldrrd=../temperature-2010-12-06.rrd --newrrd=../temperature-2011-05-24.rrd --mergedrrd=merged1.rrd
Dumping ../temperature-2010-12-06.rrd to XML: /tmp/temperature-2010-12-06.rrd_old_8615.xml
Dumping ../temperature-2011-05-24.rrd to XML: /tmp/temperature-2011-05-24.rrd_new_8615.xml
Parsing ../temperature-2010-12-06.rrd XML......parsing completed
Parsing ../temperature-2011-05-24.rrd XML...
Last Update: 1306217100
Start processing Round Robin DB
Can't call method "text" on an undefined value at rrd_merger.pl line 61.
at rrd_merger.pl line 286
at rrd_merger.pl line 286
```
Is there a tool to combine or merge RRDs that works? | 2012/03/22 | [
"https://Stackoverflow.com/questions/9816139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91238/"
] | I ended up putting together a really simple script that works well enough for my case, by examining the existing python script.
<http://gist.github.com/2166343> | Looking at the XML file generated by rrdtool, there is a simple logic error in the Perl script. The elements AVERAGE and are simple enough but the tag is contained within tag with the text inside.
```
<cf> AVERAGE </cf>
<pdp_per_row> 1 </pdp_per_row> <!-- 300 seconds -->
<params>
<xff> 5.0000000000e-01 </xff>
</params>
```
The parsing just has to be tweaked a bit and when it is working, the fix fed back here (where it is easy to 'Google') and also to the script's author for a fix. |
9,816,139 | I've got an old RRD file that was only set up to track 1 year of history. I decided more history would be nice. I did rrdtool resize, and the RRD is now bigger. I've got old backups of this RRD file and I'd like to merge the old data in so that the up-to-date RRD also has the historical data.
I've tried the rrd contrib "merged-rrd.py" but it gives:
```
$ python merged-rrd.py ../temperature-2010-12-06.rrd ../temperature-2011-05-24.rrd merged1.rrd
merging old:../temperature-2010-12-06.rrd to new:../temperature-2011-05-24.rrd. creating merged rrd: merged1.rrd
Traceback (most recent call last):
File "merged-rrd.py", line 149, in <module>
mergeRRD(old_path, new_path, mer_path)
File "merged-rrd.py", line 77, in mergeRRD
odict = getXmlDict(oxml)
File "merged-rrd.py", line 52, in getXmlDict
cf = line.split()[1]
IndexError: list index out of range
```
Also tried "rrd\_merger.pl":
```
$ perl rrd_merger.pl --oldrrd=../temperature-2010-12-06.rrd --newrrd=../temperature-2011-05-24.rrd --mergedrrd=merged1.rrd
Dumping ../temperature-2010-12-06.rrd to XML: /tmp/temperature-2010-12-06.rrd_old_8615.xml
Dumping ../temperature-2011-05-24.rrd to XML: /tmp/temperature-2011-05-24.rrd_new_8615.xml
Parsing ../temperature-2010-12-06.rrd XML......parsing completed
Parsing ../temperature-2011-05-24.rrd XML...
Last Update: 1306217100
Start processing Round Robin DB
Can't call method "text" on an undefined value at rrd_merger.pl line 61.
at rrd_merger.pl line 286
at rrd_merger.pl line 286
```
Is there a tool to combine or merge RRDs that works? | 2012/03/22 | [
"https://Stackoverflow.com/questions/9816139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91238/"
] | I ended up putting together a really simple script that works well enough for my case, by examining the existing python script.
<http://gist.github.com/2166343> | That fixed rrdtool-merge.pl for me:
```
< my $xff = $new_rra->first_child( 'xff' )->text;
---
> my $xff = $new_rra->first_child_text( 'xff' );
```
From XML::Twig documentation:
```
first_child_text ($optional_condition)
Return the text of the first child of the element, or the first child
matching the $optional_condition If there is no first_child then returns ''. This
avoids getting the child, checking for its existence then getting the text for trivial
cases.
``` |
9,816,139 | I've got an old RRD file that was only set up to track 1 year of history. I decided more history would be nice. I did rrdtool resize, and the RRD is now bigger. I've got old backups of this RRD file and I'd like to merge the old data in so that the up-to-date RRD also has the historical data.
I've tried the rrd contrib "merged-rrd.py" but it gives:
```
$ python merged-rrd.py ../temperature-2010-12-06.rrd ../temperature-2011-05-24.rrd merged1.rrd
merging old:../temperature-2010-12-06.rrd to new:../temperature-2011-05-24.rrd. creating merged rrd: merged1.rrd
Traceback (most recent call last):
File "merged-rrd.py", line 149, in <module>
mergeRRD(old_path, new_path, mer_path)
File "merged-rrd.py", line 77, in mergeRRD
odict = getXmlDict(oxml)
File "merged-rrd.py", line 52, in getXmlDict
cf = line.split()[1]
IndexError: list index out of range
```
Also tried "rrd\_merger.pl":
```
$ perl rrd_merger.pl --oldrrd=../temperature-2010-12-06.rrd --newrrd=../temperature-2011-05-24.rrd --mergedrrd=merged1.rrd
Dumping ../temperature-2010-12-06.rrd to XML: /tmp/temperature-2010-12-06.rrd_old_8615.xml
Dumping ../temperature-2011-05-24.rrd to XML: /tmp/temperature-2011-05-24.rrd_new_8615.xml
Parsing ../temperature-2010-12-06.rrd XML......parsing completed
Parsing ../temperature-2011-05-24.rrd XML...
Last Update: 1306217100
Start processing Round Robin DB
Can't call method "text" on an undefined value at rrd_merger.pl line 61.
at rrd_merger.pl line 286
at rrd_merger.pl line 286
```
Is there a tool to combine or merge RRDs that works? | 2012/03/22 | [
"https://Stackoverflow.com/questions/9816139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91238/"
] | I ended up putting together a really simple script that works well enough for my case, by examining the existing python script.
<http://gist.github.com/2166343> | The rrdmerge.pl utility, included with Routers2 in the /extras directory, can do this. Collect the latest version of Routers2 from <http://www.steveshipway.org/software/rrd/>
This is a utility I wrote for the purpose of merging multiple archived MRTG RRD files which sounds exactly like the situation you are mentioning.
This is probably too late for the OP but will hopefully be useful to later people who come here. It can merge any RRD files, even with different DS, RRA or intervals, and can generate XML or RRD, and will pick the best available data from the component RRD files to make the output.
Example:
```
rrdmerge.pl --rrd --libpath $RRDLIBDIR --output /tmp/merge.rrd --rows 12000 $FROMDIR/file.rrd $ARCHIVE/*.rrd
``` |
9,816,139 | I've got an old RRD file that was only set up to track 1 year of history. I decided more history would be nice. I did rrdtool resize, and the RRD is now bigger. I've got old backups of this RRD file and I'd like to merge the old data in so that the up-to-date RRD also has the historical data.
I've tried the rrd contrib "merged-rrd.py" but it gives:
```
$ python merged-rrd.py ../temperature-2010-12-06.rrd ../temperature-2011-05-24.rrd merged1.rrd
merging old:../temperature-2010-12-06.rrd to new:../temperature-2011-05-24.rrd. creating merged rrd: merged1.rrd
Traceback (most recent call last):
File "merged-rrd.py", line 149, in <module>
mergeRRD(old_path, new_path, mer_path)
File "merged-rrd.py", line 77, in mergeRRD
odict = getXmlDict(oxml)
File "merged-rrd.py", line 52, in getXmlDict
cf = line.split()[1]
IndexError: list index out of range
```
Also tried "rrd\_merger.pl":
```
$ perl rrd_merger.pl --oldrrd=../temperature-2010-12-06.rrd --newrrd=../temperature-2011-05-24.rrd --mergedrrd=merged1.rrd
Dumping ../temperature-2010-12-06.rrd to XML: /tmp/temperature-2010-12-06.rrd_old_8615.xml
Dumping ../temperature-2011-05-24.rrd to XML: /tmp/temperature-2011-05-24.rrd_new_8615.xml
Parsing ../temperature-2010-12-06.rrd XML......parsing completed
Parsing ../temperature-2011-05-24.rrd XML...
Last Update: 1306217100
Start processing Round Robin DB
Can't call method "text" on an undefined value at rrd_merger.pl line 61.
at rrd_merger.pl line 286
at rrd_merger.pl line 286
```
Is there a tool to combine or merge RRDs that works? | 2012/03/22 | [
"https://Stackoverflow.com/questions/9816139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91238/"
] | That fixed rrdtool-merge.pl for me:
```
< my $xff = $new_rra->first_child( 'xff' )->text;
---
> my $xff = $new_rra->first_child_text( 'xff' );
```
From XML::Twig documentation:
```
first_child_text ($optional_condition)
Return the text of the first child of the element, or the first child
matching the $optional_condition If there is no first_child then returns ''. This
avoids getting the child, checking for its existence then getting the text for trivial
cases.
``` | Looking at the XML file generated by rrdtool, there is a simple logic error in the Perl script. The elements AVERAGE and are simple enough but the tag is contained within tag with the text inside.
```
<cf> AVERAGE </cf>
<pdp_per_row> 1 </pdp_per_row> <!-- 300 seconds -->
<params>
<xff> 5.0000000000e-01 </xff>
</params>
```
The parsing just has to be tweaked a bit and when it is working, the fix fed back here (where it is easy to 'Google') and also to the script's author for a fix. |
9,816,139 | I've got an old RRD file that was only set up to track 1 year of history. I decided more history would be nice. I did rrdtool resize, and the RRD is now bigger. I've got old backups of this RRD file and I'd like to merge the old data in so that the up-to-date RRD also has the historical data.
I've tried the rrd contrib "merged-rrd.py" but it gives:
```
$ python merged-rrd.py ../temperature-2010-12-06.rrd ../temperature-2011-05-24.rrd merged1.rrd
merging old:../temperature-2010-12-06.rrd to new:../temperature-2011-05-24.rrd. creating merged rrd: merged1.rrd
Traceback (most recent call last):
File "merged-rrd.py", line 149, in <module>
mergeRRD(old_path, new_path, mer_path)
File "merged-rrd.py", line 77, in mergeRRD
odict = getXmlDict(oxml)
File "merged-rrd.py", line 52, in getXmlDict
cf = line.split()[1]
IndexError: list index out of range
```
Also tried "rrd\_merger.pl":
```
$ perl rrd_merger.pl --oldrrd=../temperature-2010-12-06.rrd --newrrd=../temperature-2011-05-24.rrd --mergedrrd=merged1.rrd
Dumping ../temperature-2010-12-06.rrd to XML: /tmp/temperature-2010-12-06.rrd_old_8615.xml
Dumping ../temperature-2011-05-24.rrd to XML: /tmp/temperature-2011-05-24.rrd_new_8615.xml
Parsing ../temperature-2010-12-06.rrd XML......parsing completed
Parsing ../temperature-2011-05-24.rrd XML...
Last Update: 1306217100
Start processing Round Robin DB
Can't call method "text" on an undefined value at rrd_merger.pl line 61.
at rrd_merger.pl line 286
at rrd_merger.pl line 286
```
Is there a tool to combine or merge RRDs that works? | 2012/03/22 | [
"https://Stackoverflow.com/questions/9816139",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91238/"
] | The rrdmerge.pl utility, included with Routers2 in the /extras directory, can do this. Collect the latest version of Routers2 from <http://www.steveshipway.org/software/rrd/>
This is a utility I wrote for the purpose of merging multiple archived MRTG RRD files which sounds exactly like the situation you are mentioning.
This is probably too late for the OP but will hopefully be useful to later people who come here. It can merge any RRD files, even with different DS, RRA or intervals, and can generate XML or RRD, and will pick the best available data from the component RRD files to make the output.
Example:
```
rrdmerge.pl --rrd --libpath $RRDLIBDIR --output /tmp/merge.rrd --rows 12000 $FROMDIR/file.rrd $ARCHIVE/*.rrd
``` | Looking at the XML file generated by rrdtool, there is a simple logic error in the Perl script. The elements AVERAGE and are simple enough but the tag is contained within tag with the text inside.
```
<cf> AVERAGE </cf>
<pdp_per_row> 1 </pdp_per_row> <!-- 300 seconds -->
<params>
<xff> 5.0000000000e-01 </xff>
</params>
```
The parsing just has to be tweaked a bit and when it is working, the fix fed back here (where it is easy to 'Google') and also to the script's author for a fix. |
65,131,966 | Say I have a collection of scripts organized for convenience in a directory structure like so:
```
root
│ helpers.py
│
├───dir_a
│ data.txt
│ foo.py
│
└───dir_b
data.txt
bar.py
```
`foo.py` and `bar.py` are scripts doing different things, but they both load their distinct `data.txt` the same way. To avoid repeating myself, I wish to put a `load_data()` function in `helpers.py` that can be imported while running scripts in subdirectories `dir_a` and `dir_b`.
I have tried to import helpers in **`dir_a/foo.py`** using a relative import like this:
```
from ..helpers import load_data
foo_data = load_data('data.txt')
# ...rest of code...
```
But directly running **`foo.py`** as a script fails on line 1 with an `ImportError`:
```
Traceback (most recent call last):
File "path/to/file/foo.py", line 1, in <module>
from ..helpers import load_data
ImportError: attempted relative import with no known parent package
```
Is the spirit of what I'm attempting possible in python (i.e. simple and without modifying `sys.path`)? From *Case 3: Importing from Parent Directory* [on this site](https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html), the answer seems to be no, and I need to restructure my collection of scripts to avoid importing one level up.
Bonus question: if not possible, what is the rationale for why not? | 2020/12/03 | [
"https://Stackoverflow.com/questions/65131966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7227829/"
] | I don't think there is a way to have node do what you want. I had a similar where the main project was commonjs but one of the libraries was esm or a library it was using was esm. I don't remember the specific details but it was a royal pain.
The basic work around is to use `esm` to `import` the library giving you issue. It likely that once you do that you will end up with a second layer of issues.
```
// example
const esmImport = require('esm')(module)
const {CookieJar, fetch} = esmImport('node-fetch-cookies')
```
Dynamic import also resolved the issue for me.
```
async init() {
const { CookieJar } = await import('node-fetch-cookies')
this.cookieJar = new CookieJar()
this.cookieJar.addCookie(`username=${this._user}`, this._url.toString())
this.cookieJar.addCookie('hippa=yes', this._url.toString())
}
``` | I had the same issue and I used single quotation for multi-value args like `--exec' to solve it.
```
nodemon --watch 'src/**/*' -e ts,tsx --exec 'ts-node ./src/index.ts'
``` |
8,587,633 | I'm trying to write a python script for BusyBox on ESXi with mail functionality. It runs Python 2.5 with some libraries missing (i.e. the smtplib). I downloaded Python2.5 sources and copied the lib-folder to ESXi. Now I am trying to import the smtplib via "import lib.smtplib" but Python says:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/pysexi/lib/smtplib.py", line 46, in <module>
import email.Utils
File "/pysexi/lib/email/__init__.py", line 115, in <module>
setattr(sys.modules['email'], _name, importer)
KeyError: 'email'
```
I'm stuck. So every help and every thought is appreciated! | 2011/12/21 | [
"https://Stackoverflow.com/questions/8587633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/921051/"
] | Trying to install generic applications on an appliance or custom OS is always fun.
Just a guess, but it may be that the email lib is a compiled C module - i.e. not pure python.
I would try use libraries that are as completely python with no compiled code - I don't know if there are pure python versions of the libraries.
The option is to try to track down what OS version that ESXi is based on and then use the matching python version from that OS. | I don't know anything about BusyBox or ESXi - therefore this may be more of a suggestion than an answer, but you might consider using a email service that supports an HTTP or RESTful API - such as [MailGun](http://documentation.mailgun.net/wrappers.html#python). They have a free plan for up to 200 emails a day, so it might not cost you anything.
Again, this way be more of a suggestion or a plan "B" (if no one can help you with this specific problem) |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.
**Edit:**
It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | Use the IDLE extension called IDLE2HTML.py (search for this).
This lets IDLE print to an HTML file that has color in its style sheet.
Then save the HTML file to a PDF (the color will still be there). | I had the same problem and opened the py file into Visual Studio Code, then simply copied (Ctrl A / Ctrl C) and pasted the text (Ctrl V) into a Microsoft editor such as Word or RTF, or even outlook. The colors stay, including when printing.
Note that in order to avoid the night mode set as a default in VS Code, go to
File->Preferences->Color Theme and choose a day mode which is more suitable for printing. |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.
**Edit:**
It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | IDLE can't do it, but you can do it in an indirect way: Use LaTeX to format your script with the IDLE colors.
The [`listings`](http://www.ctan.org/tex-archive/macros/latex/contrib/listings/) package supports IDLE-like colorizing for python, but it's pretty well hidden: You must know to include a "preference file" that is mentioned in the `listings` manual, but without a description of its features. The following almost-minimal example will turn your script `myscript.py` into color PDF in the IDLE colors.
```latex
\documentclass{article}
\usepackage{listings}
\input{listings-python.prf} % defines the python-idle-code style
\usepackage{textcomp} % Needed for straight quotes
\lstset{
basicstyle=\normalsize\ttfamily, % size of the fonts for the code
language={Python},style={python-idle-code},
showstringspaces=false,
tabsize=4,
upquote=true, % Requires textcomp
}
\oddsidemargin=-0.5cm
\textwidth=7in % This just fits 80 characters at 10pt
\begin{document}
\lstinputlisting{myscript.py}
\end{document}
```
You could also include code snippets in a real LaTeX document.
**Availability:** You'll need at least `listings` version 1.5b (2013/08/26). Users of Texlive 2013 must download it from CTAN (e.g. with the command line texlive manager, `tlmgr`). It is part of TexLive 2016.
Unfortunately there still seems to be a problem with the CTAN version: The preferences file `listings-python.prf` is in the documentation folder for the package, not in `tex/latex/listings` where TeX can find it. You'll need to move it manually for the inclusion to work. | I do this all the time with large amounts of code.
Just install SciTE "https://www.scintilla.org/SciTEDownload.html"
Copy and paste your code and print.
I like to grab some tape and markers stick all the sheets on a wall and put some music on.
Happy coding! |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.
**Edit:**
It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | The easiest way is to open the '.py' file with [Notepad++](https://notepad-plus-plus.org/) and there you can select and modify your settings and preferences (any theme you want for your python codes) to export the python file to a colorful PDF file (using PDF Virtual Printer) or directly print it :-) .
OR
If you are using [VS code](https://visualstudio.microsoft.com/), then simply install ([PrintCode](https://marketplace.visualstudio.com/items?itemName=nobuhito.printcode)) extension and after installing:
1. open **VS Code** and go to **View**
2. Click on **Command Palette**
3. search for " ***PrintCode*** "
It will export the python file as an **HTML** with your default internet browser and there you can directly print it or with a virtual printer, print your python document to a colorful PDF. | I do this all the time with large amounts of code.
Just install SciTE "https://www.scintilla.org/SciTEDownload.html"
Copy and paste your code and print.
I like to grab some tape and markers stick all the sheets on a wall and put some music on.
Happy coding! |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.
**Edit:**
It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | A good and simple solution is to use ***IDLE2HTML***, an extension for IDLE.
The tool allows IDLE to save code from the editor window (or interactive shell) to a HTML file,
with colour included in the CSS format. After this, the file can be printed (as asked for) or its formatted code used with other programs such as word processors.
A reliable website currently to download the Python files and view some instructions is the Python Package Index (PyPI) - the page is <https://pypi.python.org/pypi/IDLE2HTML> or the `pip` module, built-in to newer Python versions, can install the files for you.
An useful advantage of this method is that it gets the colour formatting *from IDLE* instead of taking time analysing the code and using stored colours (which many other solutions do). This means it **uses the actual colour scheme** and works with different IDLE themes such as "IDLE Dark". This should result in less resources and shorter code being used.
Also, the current extension (version 2.0) could probably be **adapted to use a different file format** when saving the data because it has quite simple code.
**Some details about how it works:**
Since the tool is Python code running as an extension, it has access to a special variable provided by IDLE, which contains data about the editor window. The `extend.txt` file of the `idlelib` Python extension (that runs the editor) describes this variable called `editwin`:
>
> An IDLE extension class is instantiated with a single argument,
> `editwin', an EditorWindow instance.
>
>
>
It also includes some other files about extending IDLE such as "config-main.def" and "config-extensions.def". The official Python documentation has more information.
**Installation instructions:**
>
> Copy IDLE2HTML.py to the "idlelib" folder of your python installation.
>
> Append the contents of "config-extensions.txt" to your "config-extensions.def" file (also in the *idlelib* folder) and restart IDLE.
>
>
>
**How to use:**
>
> Select "Save as HTML" from the "Options" menu and specify the filename in the FileDialog window. The HTML file is created immediately.
>
>
>
**A code tweak to work in Python 3.x:**
Currently, the *IDLE2HTML* extension (version 2.0) won't work with Python 3.x until a **small change** is made to the code which I found in a fixed version included with the [IDLEX](http://idlex.sourceforge.net/extensions.html) Python module.
Here is a file comparison, with the original on the left and the fixed IDLEX version on the right of the screenshot image.
[](https://i.stack.imgur.com/bvaJY.png)
Description: if Python version is Python 3.x, use `import tkinter as Tkinter` instead of `import Tkinter` and `import tkinter.filedialog as tkFileDialog` instead of `import tkFileDialog`. The code shown uses `sys.version` from the built-in "sys" module in an if/else block to run the right code. | I do this all the time with large amounts of code.
Just install SciTE "https://www.scintilla.org/SciTEDownload.html"
Copy and paste your code and print.
I like to grab some tape and markers stick all the sheets on a wall and put some music on.
Happy coding! |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.
**Edit:**
It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | A good and simple solution is to use ***IDLE2HTML***, an extension for IDLE.
The tool allows IDLE to save code from the editor window (or interactive shell) to a HTML file,
with colour included in the CSS format. After this, the file can be printed (as asked for) or its formatted code used with other programs such as word processors.
A reliable website currently to download the Python files and view some instructions is the Python Package Index (PyPI) - the page is <https://pypi.python.org/pypi/IDLE2HTML> or the `pip` module, built-in to newer Python versions, can install the files for you.
An useful advantage of this method is that it gets the colour formatting *from IDLE* instead of taking time analysing the code and using stored colours (which many other solutions do). This means it **uses the actual colour scheme** and works with different IDLE themes such as "IDLE Dark". This should result in less resources and shorter code being used.
Also, the current extension (version 2.0) could probably be **adapted to use a different file format** when saving the data because it has quite simple code.
**Some details about how it works:**
Since the tool is Python code running as an extension, it has access to a special variable provided by IDLE, which contains data about the editor window. The `extend.txt` file of the `idlelib` Python extension (that runs the editor) describes this variable called `editwin`:
>
> An IDLE extension class is instantiated with a single argument,
> `editwin', an EditorWindow instance.
>
>
>
It also includes some other files about extending IDLE such as "config-main.def" and "config-extensions.def". The official Python documentation has more information.
**Installation instructions:**
>
> Copy IDLE2HTML.py to the "idlelib" folder of your python installation.
>
> Append the contents of "config-extensions.txt" to your "config-extensions.def" file (also in the *idlelib* folder) and restart IDLE.
>
>
>
**How to use:**
>
> Select "Save as HTML" from the "Options" menu and specify the filename in the FileDialog window. The HTML file is created immediately.
>
>
>
**A code tweak to work in Python 3.x:**
Currently, the *IDLE2HTML* extension (version 2.0) won't work with Python 3.x until a **small change** is made to the code which I found in a fixed version included with the [IDLEX](http://idlex.sourceforge.net/extensions.html) Python module.
Here is a file comparison, with the original on the left and the fixed IDLEX version on the right of the screenshot image.
[](https://i.stack.imgur.com/bvaJY.png)
Description: if Python version is Python 3.x, use `import tkinter as Tkinter` instead of `import Tkinter` and `import tkinter.filedialog as tkFileDialog` instead of `import tkFileDialog`. The code shown uses `sys.version` from the built-in "sys" module in an if/else block to run the right code. | I had the same problem and opened the py file into Visual Studio Code, then simply copied (Ctrl A / Ctrl C) and pasted the text (Ctrl V) into a Microsoft editor such as Word or RTF, or even outlook. The colors stay, including when printing.
Note that in order to avoid the night mode set as a default in VS Code, go to
File->Preferences->Color Theme and choose a day mode which is more suitable for printing. |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.
**Edit:**
It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | The easiest way is to open the '.py' file with [Notepad++](https://notepad-plus-plus.org/) and there you can select and modify your settings and preferences (any theme you want for your python codes) to export the python file to a colorful PDF file (using PDF Virtual Printer) or directly print it :-) .
OR
If you are using [VS code](https://visualstudio.microsoft.com/), then simply install ([PrintCode](https://marketplace.visualstudio.com/items?itemName=nobuhito.printcode)) extension and after installing:
1. open **VS Code** and go to **View**
2. Click on **Command Palette**
3. search for " ***PrintCode*** "
It will export the python file as an **HTML** with your default internet browser and there you can directly print it or with a virtual printer, print your python document to a colorful PDF. | I had the same problem and opened the py file into Visual Studio Code, then simply copied (Ctrl A / Ctrl C) and pasted the text (Ctrl V) into a Microsoft editor such as Word or RTF, or even outlook. The colors stay, including when printing.
Note that in order to avoid the night mode set as a default in VS Code, go to
File->Preferences->Color Theme and choose a day mode which is more suitable for printing. |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.
**Edit:**
It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | IDLE can't do it, but you can do it in an indirect way: Use LaTeX to format your script with the IDLE colors.
The [`listings`](http://www.ctan.org/tex-archive/macros/latex/contrib/listings/) package supports IDLE-like colorizing for python, but it's pretty well hidden: You must know to include a "preference file" that is mentioned in the `listings` manual, but without a description of its features. The following almost-minimal example will turn your script `myscript.py` into color PDF in the IDLE colors.
```latex
\documentclass{article}
\usepackage{listings}
\input{listings-python.prf} % defines the python-idle-code style
\usepackage{textcomp} % Needed for straight quotes
\lstset{
basicstyle=\normalsize\ttfamily, % size of the fonts for the code
language={Python},style={python-idle-code},
showstringspaces=false,
tabsize=4,
upquote=true, % Requires textcomp
}
\oddsidemargin=-0.5cm
\textwidth=7in % This just fits 80 characters at 10pt
\begin{document}
\lstinputlisting{myscript.py}
\end{document}
```
You could also include code snippets in a real LaTeX document.
**Availability:** You'll need at least `listings` version 1.5b (2013/08/26). Users of Texlive 2013 must download it from CTAN (e.g. with the command line texlive manager, `tlmgr`). It is part of TexLive 2016.
Unfortunately there still seems to be a problem with the CTAN version: The preferences file `listings-python.prf` is in the documentation folder for the package, not in `tex/latex/listings` where TeX can find it. You'll need to move it manually for the inclusion to work. | A good and simple solution is to use ***IDLE2HTML***, an extension for IDLE.
The tool allows IDLE to save code from the editor window (or interactive shell) to a HTML file,
with colour included in the CSS format. After this, the file can be printed (as asked for) or its formatted code used with other programs such as word processors.
A reliable website currently to download the Python files and view some instructions is the Python Package Index (PyPI) - the page is <https://pypi.python.org/pypi/IDLE2HTML> or the `pip` module, built-in to newer Python versions, can install the files for you.
An useful advantage of this method is that it gets the colour formatting *from IDLE* instead of taking time analysing the code and using stored colours (which many other solutions do). This means it **uses the actual colour scheme** and works with different IDLE themes such as "IDLE Dark". This should result in less resources and shorter code being used.
Also, the current extension (version 2.0) could probably be **adapted to use a different file format** when saving the data because it has quite simple code.
**Some details about how it works:**
Since the tool is Python code running as an extension, it has access to a special variable provided by IDLE, which contains data about the editor window. The `extend.txt` file of the `idlelib` Python extension (that runs the editor) describes this variable called `editwin`:
>
> An IDLE extension class is instantiated with a single argument,
> `editwin', an EditorWindow instance.
>
>
>
It also includes some other files about extending IDLE such as "config-main.def" and "config-extensions.def". The official Python documentation has more information.
**Installation instructions:**
>
> Copy IDLE2HTML.py to the "idlelib" folder of your python installation.
>
> Append the contents of "config-extensions.txt" to your "config-extensions.def" file (also in the *idlelib* folder) and restart IDLE.
>
>
>
**How to use:**
>
> Select "Save as HTML" from the "Options" menu and specify the filename in the FileDialog window. The HTML file is created immediately.
>
>
>
**A code tweak to work in Python 3.x:**
Currently, the *IDLE2HTML* extension (version 2.0) won't work with Python 3.x until a **small change** is made to the code which I found in a fixed version included with the [IDLEX](http://idlex.sourceforge.net/extensions.html) Python module.
Here is a file comparison, with the original on the left and the fixed IDLEX version on the right of the screenshot image.
[](https://i.stack.imgur.com/bvaJY.png)
Description: if Python version is Python 3.x, use `import tkinter as Tkinter` instead of `import Tkinter` and `import tkinter.filedialog as tkFileDialog` instead of `import tkFileDialog`. The code shown uses `sys.version` from the built-in "sys" module in an if/else block to run the right code. |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.
**Edit:**
It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | IDLE can't do it, but you can do it in an indirect way: Use LaTeX to format your script with the IDLE colors.
The [`listings`](http://www.ctan.org/tex-archive/macros/latex/contrib/listings/) package supports IDLE-like colorizing for python, but it's pretty well hidden: You must know to include a "preference file" that is mentioned in the `listings` manual, but without a description of its features. The following almost-minimal example will turn your script `myscript.py` into color PDF in the IDLE colors.
```latex
\documentclass{article}
\usepackage{listings}
\input{listings-python.prf} % defines the python-idle-code style
\usepackage{textcomp} % Needed for straight quotes
\lstset{
basicstyle=\normalsize\ttfamily, % size of the fonts for the code
language={Python},style={python-idle-code},
showstringspaces=false,
tabsize=4,
upquote=true, % Requires textcomp
}
\oddsidemargin=-0.5cm
\textwidth=7in % This just fits 80 characters at 10pt
\begin{document}
\lstinputlisting{myscript.py}
\end{document}
```
You could also include code snippets in a real LaTeX document.
**Availability:** You'll need at least `listings` version 1.5b (2013/08/26). Users of Texlive 2013 must download it from CTAN (e.g. with the command line texlive manager, `tlmgr`). It is part of TexLive 2016.
Unfortunately there still seems to be a problem with the CTAN version: The preferences file `listings-python.prf` is in the documentation folder for the package, not in `tex/latex/listings` where TeX can find it. You'll need to move it manually for the inclusion to work. | Use the IDLE extension called IDLE2HTML.py (search for this).
This lets IDLE print to an HTML file that has color in its style sheet.
Then save the HTML file to a PDF (the color will still be there). |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.
**Edit:**
It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | IDLE can't do it, but you can do it in an indirect way: Use LaTeX to format your script with the IDLE colors.
The [`listings`](http://www.ctan.org/tex-archive/macros/latex/contrib/listings/) package supports IDLE-like colorizing for python, but it's pretty well hidden: You must know to include a "preference file" that is mentioned in the `listings` manual, but without a description of its features. The following almost-minimal example will turn your script `myscript.py` into color PDF in the IDLE colors.
```latex
\documentclass{article}
\usepackage{listings}
\input{listings-python.prf} % defines the python-idle-code style
\usepackage{textcomp} % Needed for straight quotes
\lstset{
basicstyle=\normalsize\ttfamily, % size of the fonts for the code
language={Python},style={python-idle-code},
showstringspaces=false,
tabsize=4,
upquote=true, % Requires textcomp
}
\oddsidemargin=-0.5cm
\textwidth=7in % This just fits 80 characters at 10pt
\begin{document}
\lstinputlisting{myscript.py}
\end{document}
```
You could also include code snippets in a real LaTeX document.
**Availability:** You'll need at least `listings` version 1.5b (2013/08/26). Users of Texlive 2013 must download it from CTAN (e.g. with the command line texlive manager, `tlmgr`). It is part of TexLive 2016.
Unfortunately there still seems to be a problem with the CTAN version: The preferences file `listings-python.prf` is in the documentation folder for the package, not in `tex/latex/listings` where TeX can find it. You'll need to move it manually for the inclusion to work. | The easiest way is to open the '.py' file with [Notepad++](https://notepad-plus-plus.org/) and there you can select and modify your settings and preferences (any theme you want for your python codes) to export the python file to a colorful PDF file (using PDF Virtual Printer) or directly print it :-) .
OR
If you are using [VS code](https://visualstudio.microsoft.com/), then simply install ([PrintCode](https://marketplace.visualstudio.com/items?itemName=nobuhito.printcode)) extension and after installing:
1. open **VS Code** and go to **View**
2. Click on **Command Palette**
3. search for " ***PrintCode*** "
It will export the python file as an **HTML** with your default internet browser and there you can directly print it or with a virtual printer, print your python document to a colorful PDF. |
16,833,285 | I have searched for an answer to this but the related solutions seem to concern `'print'`ing in the interpreter.
I am wondering if it is possible to print (physically on paper) python code in color from IDLE?
I have gone to: `File > Print Window` in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.
**Edit:**
It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though. | 2013/05/30 | [
"https://Stackoverflow.com/questions/16833285",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1063287/"
] | Use the IDLE extension called IDLE2HTML.py (search for this).
This lets IDLE print to an HTML file that has color in its style sheet.
Then save the HTML file to a PDF (the color will still be there). | I do this all the time with large amounts of code.
Just install SciTE "https://www.scintilla.org/SciTEDownload.html"
Copy and paste your code and print.
I like to grab some tape and markers stick all the sheets on a wall and put some music on.
Happy coding! |
24,520,133 | I'd like to download a series of pdf files from my intranet. I'm able to see the files in my web browser without issue, but when trying to automate the pulling of the file via python, I run into problems. After talking through the proxy set up at my office, I can download files from the internet quite easily with this [answer](https://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python/22776#22776):
```
url = 'http://www.sample.com/fileiwanttodownload.pdf'
user = 'username'
pswd = 'password'
proxy_ip = '12.345.56.78:80'
proxy_url = 'http://' + user + ':' + pswd + '@' + proxy_ip
proxy_support = urllib2.ProxyHandler({"http":proxy_url})
opener = urllib2.build_opener(proxy_support,urllib2.HTTPHandler)
urllib2.install_opener(opener)
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
f.close()
```
but for whatever reason it won't work if the url is pointing to something on my intranet. The following error is returned:
```
Traceback (most recent call last):
File "<ipython-input-13-a055d9eaf05e>", line 1, in <module>
runfile('C:/softwaredev/python/pdfwrite.py', wdir='C:/softwaredev/python')
File "C:\Anaconda\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 585, in runfile
execfile(filename, namespace)
File "C:/softwaredev/python/pdfwrite.py", line 26, in <module>
u = urllib2.urlopen(url)
File "C:\Anaconda\lib\urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "C:\Anaconda\lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Anaconda\lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Anaconda\lib\urllib2.py", line 442, in error
result = self._call_chain(*args)
File "C:\Anaconda\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Anaconda\lib\urllib2.py", line 629, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "C:\Anaconda\lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Anaconda\lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Anaconda\lib\urllib2.py", line 448, in error
return self._call_chain(*args)
File "C:\Anaconda\lib\urllib2.py", line 382, in _call_chain
result = func(*args)
File "C:\Anaconda\lib\urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: Service Unavailable
```
Using `requests.py` in the following code, I can successfully pull down files from the internet, but when trying to pull a pdf from my office intranet, I just get a connection error sent back to me in html. The following code is run:
```
import requests
url = 'www.intranet.sample.com/?layout=attachment&cfapp=26&attachmentid=57142'
proxies = {
"http": "http://12.345.67.89:80",
"https": "http://12.345.67.89:80"
}
local_filename = 'test.pdf'
r = requests.get(url, proxies=proxies, stream=True)
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
print chunk
if chunk:
f.write(chunk)
f.flush()
```
And the html that comes back:
```
Network Error (tcp_error)
A communication error occurred: "No route to host"
The Web Server may be down, too busy, or experiencing other problems preventing it from responding to requests. You may wish to try again at a later time.
For assistance, contact your network support team.
```
Is it possible that there be some network security setting that prevents automated requests outside the web browser environment? | 2014/07/01 | [
"https://Stackoverflow.com/questions/24520133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3746982/"
] | Installing openers into urllib2 doesn't affect requests. You need to use requests' own support for proxies. It should be enough to pass them in the `proxies` argument to `get`, or you can set the `HTTP_PROXY` and `HTTPS_PROXY` environment variables. See <http://docs.python-requests.org/en/latest/user/advanced/#proxies>
```
import requests
proxies = {
"http": "http://10.10.1.10:3128",
"https": "http://10.10.1.10:1080",
}
requests.get("http://example.org", proxies=proxies)
``` | Have you tried not using the proxy to download your files when it's on the intranet?
You could try something like this in python2
```
from urllib2 import urlopen
url = 'http://intranet/myfile.pdf'
with open(local_filename, 'wb') as f:
f.write(urlopen(url).read())
``` |
25,643,943 | I am trying to write a python program in which the user inputs the polynomial and it calculates the derivative. My current code is:
```
print ("Derviatives: ")
k5 = raw.input("Enter 5th degree + coefficent: ")
k4 = raw.input("Enter 4th degree + coefficent: ")
k3 = raw.input("Enter 3rd degree + coefficent: ")
k2 = raw.input("Enter 2nd degree + coefficent: ")
k1 = raw.input("Enter 1st degree + coefficent: ")
k0 = raw.input("Enter constant: ")
int(k5)
int(k4)
int(k3)
int(k2)
int(k1)
int(k0)
print (k5, " ", k4, " ", k3, " ", k2, " ", k1, " ", k0)
1in = raw.input("Correct Y/N?")
if (1in != Y)
k5 = raw.input("Enter 5th degree + coefficent: ")
k4 = raw.input("Enter 4th degree + coefficent: ")
k3 = raw.input("Enter 3rd degree + coefficent: ")
k2 = raw.input("Enter 2nd degree + coefficent: ")
k1 = raw.input("Enter 1st degree + coefficent: ")
k0 = raw.input("Enter constant: ")
else
"""CODE GOES HERE"""
```
I am just a beginning python programmer so I am still a little bit fuzzy on some basic syntax issues. Are there any libraries that I should be importing? | 2014/09/03 | [
"https://Stackoverflow.com/questions/25643943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3953943/"
] | OK, use `raw_input` instead of `raw.input`. It is builtin, as is `int`, so nothing needs importing. When converting to a integer (`int`), you need to assign the result, or nothing will change. You can chain the functions, and use `k5 = int(raw_input("prompt.. "))`. Also, as pointed out by Evert, variable names cannot begin with numbers, so `1in` would have to be changed. This code should work:
```
print("Derviatives: ")
k5 = raw_input("Enter 5th degree + coefficent: ")
k4 = raw_input("Enter 4th degree + coefficent: ")
k3 = raw_input("Enter 3rd degree + coefficent: ")
k2 = raw_input("Enter 2nd degree + coefficent: ")
k1 = raw_input("Enter 1st degree + coefficent: ")
k0 = raw_input("Enter constant: ")
k5 = int(k5)
k4 = int(k4)
k3 = int(k3)
k2 = int(k2)
k1 = int(k1)
k0 = int(k0)
print(k5, " ", k4, " ", k3, " ", k2, " ", k1, " ", k0)
in1 = raw_input("Correct Y/N?")
if in1 != "Y":
k5 = raw_input("Enter 5th degree + coefficent: ")
k4 = raw_input("Enter 4th degree + coefficent: ")
k3 = raw_input("Enter 3rd degree + coefficent: ")
k2 = raw_input("Enter 2nd degree + coefficent: ")
k1 = raw_input("Enter 1st degree + coefficent: ")
k0 = raw_input("Enter constant: ")
else:
"""CODE GOES HERE"""
```
Also, check which version of python you are using. If it is python 3, you need to change `raw_input` to `input`. If you are using python 2, you don't need the brackets on the print statements. E.g. `print("Derviatives: ")` => `print "Derviatives: "`. | I see the following issues with your code:
1. Variable names can't start with a digit: `1in`
2. You have undefined variable `Y`. I suppose you want to compare with a string literal, so write `"Y"` instead.
3. Parentheses aren't needed in python's `if` operators, but a trailing colon is necessary. Same goes for `else`.
4. A list of coefficients would be certainly a better approach than a bunch of variables.
5. It's `raw_input`, not `raw.input`
6. While just doing `int(k5)` would validate the value (raise the exception if string doesn't represent an integer) it won't affect variable, so `k5` would still contain a string.
Guess it wouldn't hurt to show a bit of code, since I'm not doing your task here (implementing the algorithm), but merely displaying language features. So... I'd do it somehow like this:
```
# There are no do...while-style loops in Python, so we'll do it this way
# loop forever, and break when confirmation prompt gets "y"
while True:
k = [] # That's an empty list.
# I'm assuming Python 2.x here. Add parentheses for Python 3.x.
print "Derivatives:"
# This range will work like a list [5, 4, 3, 2, 1].
for n in range(5, 1, -1):
k.append(int(raw_input("Enter {0}th degree + coefficient: ".format(n)))
## Or you could do it this way:
#for num in ["5th", "4th", "3rd", "2nd", "1st"]:
# k.append(int(raw_input("Enter {0} degree + coefficient: ".format(num)))
k.append(int(raw_input("Enter constant: ".format(n)))
# Here's a bit tricky part - a list comprehension.
# Read on those, they're useful.
# We need the comprehension, because our list is full of ints,
# and join experts a list of strings.
print " ".join(str(x) for x in k)
## If you didn't get the previous line - that's fine,
## it's fairly advanced subject. Just do like you're used to:
#print k[0], " ", k[1], " ", k[2], " ", k[3], " ", k[4], " ", k[5]
# Oh, and did you notice 5th coeff. is at k[0]?
# That's because we appended them to the list in reverse order.
# Let's reverse the list in-place, so the constant will be k[0] and so on.
k.reverse()
# You don't always need an intermediate variable for single-use values,
# like when asking for confirmation. Just put raw_input call directly
# in if statement condition - it would work just fine.
#
# And let's be case-insensitive here and accept both "Y" and "y"
if raw_input("Correct [Y/N]? ").lower() == "y":
break
``` |
25,643,943 | I am trying to write a python program in which the user inputs the polynomial and it calculates the derivative. My current code is:
```
print ("Derviatives: ")
k5 = raw.input("Enter 5th degree + coefficent: ")
k4 = raw.input("Enter 4th degree + coefficent: ")
k3 = raw.input("Enter 3rd degree + coefficent: ")
k2 = raw.input("Enter 2nd degree + coefficent: ")
k1 = raw.input("Enter 1st degree + coefficent: ")
k0 = raw.input("Enter constant: ")
int(k5)
int(k4)
int(k3)
int(k2)
int(k1)
int(k0)
print (k5, " ", k4, " ", k3, " ", k2, " ", k1, " ", k0)
1in = raw.input("Correct Y/N?")
if (1in != Y)
k5 = raw.input("Enter 5th degree + coefficent: ")
k4 = raw.input("Enter 4th degree + coefficent: ")
k3 = raw.input("Enter 3rd degree + coefficent: ")
k2 = raw.input("Enter 2nd degree + coefficent: ")
k1 = raw.input("Enter 1st degree + coefficent: ")
k0 = raw.input("Enter constant: ")
else
"""CODE GOES HERE"""
```
I am just a beginning python programmer so I am still a little bit fuzzy on some basic syntax issues. Are there any libraries that I should be importing? | 2014/09/03 | [
"https://Stackoverflow.com/questions/25643943",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3953943/"
] | Use Sympy:
Put these two lines at the top:
```
from sympy import *
import numpy as np
```
And these at the part """CODE GOES HERE"""
```
x = Symbol('x')
y = k5*x**5 + k4*x**4 + k3*x**3 + k2*x**2 + k1*x +constant
yprime = y.diff(x)
yprime
``` | I see the following issues with your code:
1. Variable names can't start with a digit: `1in`
2. You have undefined variable `Y`. I suppose you want to compare with a string literal, so write `"Y"` instead.
3. Parentheses aren't needed in python's `if` operators, but a trailing colon is necessary. Same goes for `else`.
4. A list of coefficients would be certainly a better approach than a bunch of variables.
5. It's `raw_input`, not `raw.input`
6. While just doing `int(k5)` would validate the value (raise the exception if string doesn't represent an integer) it won't affect variable, so `k5` would still contain a string.
Guess it wouldn't hurt to show a bit of code, since I'm not doing your task here (implementing the algorithm), but merely displaying language features. So... I'd do it somehow like this:
```
# There are no do...while-style loops in Python, so we'll do it this way
# loop forever, and break when confirmation prompt gets "y"
while True:
k = [] # That's an empty list.
# I'm assuming Python 2.x here. Add parentheses for Python 3.x.
print "Derivatives:"
# This range will work like a list [5, 4, 3, 2, 1].
for n in range(5, 1, -1):
k.append(int(raw_input("Enter {0}th degree + coefficient: ".format(n)))
## Or you could do it this way:
#for num in ["5th", "4th", "3rd", "2nd", "1st"]:
# k.append(int(raw_input("Enter {0} degree + coefficient: ".format(num)))
k.append(int(raw_input("Enter constant: ".format(n)))
# Here's a bit tricky part - a list comprehension.
# Read on those, they're useful.
# We need the comprehension, because our list is full of ints,
# and join experts a list of strings.
print " ".join(str(x) for x in k)
## If you didn't get the previous line - that's fine,
## it's fairly advanced subject. Just do like you're used to:
#print k[0], " ", k[1], " ", k[2], " ", k[3], " ", k[4], " ", k[5]
# Oh, and did you notice 5th coeff. is at k[0]?
# That's because we appended them to the list in reverse order.
# Let's reverse the list in-place, so the constant will be k[0] and so on.
k.reverse()
# You don't always need an intermediate variable for single-use values,
# like when asking for confirmation. Just put raw_input call directly
# in if statement condition - it would work just fine.
#
# And let's be case-insensitive here and accept both "Y" and "y"
if raw_input("Correct [Y/N]? ").lower() == "y":
break
``` |
52,651,733 | I try to find refresing elements (time minute) on the webpage. My code worked only for simple text earlier. Now I use *Ctrl+Shift+I* and point out my element and *"Copy Xpath"*.
Also, I have Chrome extension *"XPath helper"* and tried to do that with it one. There is more longer XPath, than in my code below. And it doesn't work too.
>
> Error: NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//\*[@id....
>
>
>
And, I also tried to use find by class, by tag, by *CSS* selector.. It only worked by tag and no perfect, on different page.
And I don't even say about print it, sometimes `find_element(By.XPATH,'//*[...).text` work, sometimes not.
I don't understand, why it work on one page and not on second.. I want to work with find elements by *XPath* in flash later.
**UPDATE** Now I retrying code and it work! But still doesn't work on the next webpage.. why it is so changeable? XPath change, when page reload or what? What is the simplest way to get text(refresing) info from flash, opened in chrome browser?
```
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
options = webdriver.ChromeOptions()
options.add_argument('headless')
driver = webdriver.Chrome(r"C:\Users\vishniakov\Desktop\python bj\driver\chromedriver.exe",chrome_options=options)
driver.get("https://www.betfair.com/sport/football/event?eventId=28935432")
print(driver.title)
elem =driver.find_element(By.XPATH,'//*[@id="yui_3_5_0_1_1538670363144_2571"]').text
print(elem)
``` | 2018/10/04 | [
"https://Stackoverflow.com/questions/52651733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10290047/"
] | You should set `Tag` instead of assigning an id to the dynamic created view.
```
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflator=LayoutInflater.from(this.mContext);
View layout=inflator.inflate(R.layout.activity_main, parent, false);
ImageView imageView;
if (convertView == null) {
// if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new ViewGroup.LayoutParams(170, 170));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(4, 4, 4, 4);
} else {
imageView = (ImageView) convertView;
}
// set tag
imageView.setTag(position);
return imageView;
}
```
Later when getting view in `onClick` or `onItemClicked`, you can do something like this-
```
public void onClick(View view) {
Object tag = view.getTag();
if (tag instanceOf Integer) {
int pos = (Integer)tag;
// use position to identify that item.
}
}
```
As you are new to this, I would suggest to use `RecyclerView` if using `Listview`. If still you need to use normal adapter then go with `ViewHolder` pattern. | The position effectively acts as an id. Or I have missed the point? |
43,207,159 | first of all, i´m pretty new to Python. I also searched for a solution, but i guess the usual approach (subprocess.popen) won´t work in my case.
I have to pass arguments to a listener in an already running python script without starting the script over and over again. There is an example how to pass a message to a lcd-screen:
```
function printMsgText(message_text)
local f = io.popen("home/test/show_message.py '" .. message_text .. "'")
end
```
This lua-script above defines the process which gets called everytime a message is recieved. The called process (show\_message.py) looks like that:
```
import sys
from sense_hat import SenseHat
sense = SenseHat()
sense.clear()
sense.show_message(sys.argv[1])
```
I need something similar, except that there is another script running in the backround, so show\_message.py is not the final process but needs to pass the argument/message to another, already running script. My idea was to just let show\_message.py print the message to the console and use sys.argv in the main process aswell but i´m a little afraid that it could get messy.
Is there any easy way to do this?
Kind regards
Edit:
The main script is controlling a stepper-motor. Based on the user input, the motor drives a pre-defined number of steps. The part of the script waiting for the user-input looks like this:
```
while wait:
user_position = input("Where do you wanna go? (0, 1, 2, back): ")
wait = False
# Console output
print("Position: " + str(user_position))
if user_position == "0":
stepper.set_target_position(position_zero)
wait = True
elif user_position == "1":
stepper.set_target_position(position_one
wait = True
elif user_position == "2":
stepper.set_target_position(position_two)
wait = True
elif user_position == "back":
break
```
Now i need to pass the desired position via a web-application which is designed the way i described above (e.g. calling a lua-script every time a variable/argument is passed) and not via the console. | 2017/04/04 | [
"https://Stackoverflow.com/questions/43207159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5607983/"
] | Once a process is running it won't re-evaluate its command line arguments. You need other ways to communicate with it. This is colloquially called *inter-process communication* (IPC), and there are several ways to achieve it. Here are a few:
* Files
* Pipes (on platforms that support them)
* Shared memory
* Socket communication
* Message passing
* RPC
Probably the most approachable way is standard streams (STDIN, STDOUT) as provided by e.g. `subprocess.popen()` which you mentioned. But this requires a parent-child relation between the communicating processes. Maybe you can go this route.
Another way for Python, if you want to avoid parent-child relations, which I have made good experiences with is [Pyro](https://pythonhosted.org/Pyro4/). It was easy to use and worked well, albeit with some performance penalty. It is also a very "infrastructure-ish" way to go about it, both processes have to be coded to use it. | You can use some sort of messaging library that will allow you to communicate between processes. [ZeroMQ](http://www.zeromq.org/bindings:python) is a good option, and has python bindings. |
69,259,654 | When I debug, I often find it useful to print a variable's name and contents.
```python
a = 5
b = 7
print("a: "+str(a)+"\n b: "+str(b))
```
I want to write a function that achieves this. So far, I have the following function:
```python
def dprint(varslist, *varnames):
string = [var+": "+str(varslist[var]) for var in varnames]
print("\n".join(string))
```
An example for its usage is
```python
a = 5
b = 7
dprint(vars(), "a", "b")
```
My question is: is there any way to write `dprint()` such that `vars()` doesn't need to be explicitly passed to it every time it's called? Specifically, is there a way for `dprint()` to access its calling function's `vars()`?
Then, we could rewrite it as
```python
def dprint(*varnames):
varslist = # magic code that gets vars() from calling function
string = [var+": "+str(varslist[var]) for var in varnames]
print("\n".join(string))
``` | 2021/09/20 | [
"https://Stackoverflow.com/questions/69259654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16337951/"
] | Use [`sys._getframe`](https://docs.python.org/3/library/sys.html#sys._getframe):
>
> Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, ValueError is raised. The default for depth is zero, returning the frame at the top of the call stack.
>
>
>
Then use `f_locals` to get local vars of `caller`.
```
import sys
def dprint(*varnames):
caller = sys._getframe(1) # depth=1
for var in varnames:
print(f'{var}: {caller.f_locals.get(var)}')
def foo():
a = 5
b = 7
dprint("a", "b")
foo()
```
Output:
```
a: 5
b: 7
``` | In Python you can debug a program calling the `breakpoint` built-in function. |
3,966,146 | On our production server we need to split 900k images into different dirs and update 400k rows (MySQL with InnoDB engine). I wrote a python script which goes through next steps:
1. Select small chunk of data from db (10 rows)
- Make new dirs
- Copy files to the created dirs and rename it
- Update db (there are some triggers on update which will load server)
- Repeat
My code:
```
import os, shutil
import database # database.py from tornado
LIMIT_START_OFFSET = 0
LIMIT_ROW_COUNT = 10
SRC_PATHS = ('/var/www/site/public/upload/images/',)
DST_PATH = '/var/www/site/public/upload/new_images/'
def main():
offset = LIMIT_START_OFFSET
while True:
db = Connection(DB_HOST, DB_NAME, DB_USER, DB_PASSWD)
db_data = db.query('''
SELECT id AS news_id, image AS src_filename
FROM emd_news
ORDER BY id ASC
LIMIT %s, %s''', offset, LIMIT_ROW_COUNT)
offset = offset + LIMIT_ROW_COUNT
news_images = get_news_images(db_data) # convert data to easy-to-use list
make_dst_dirs(DST_PATH, [i['dst_dirname'] for i in news_images]) # make news dirs
news_to_update = copy_news_images(SRC_PATHS, DST_PATH, news_images) # list of moved files
db.executemany('''
UPDATE emd_news
SET image = %s
WHERE id = %s
LIMIT 1''', [(i['filename'], i['news_id']) for i in news_to_update])
db.close()
if not db_data: break
if __name__ == '__main__':
main()
```
Quite simple task, but I'm a little bit nervous about performance.
How can I make this script more efficient?
UPD:
After all I've used original script without any modifications. It took about 5 hours. And it was fast in the beginning and very slow in the end. | 2010/10/19 | [
"https://Stackoverflow.com/questions/3966146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/228012/"
] | What I recommend.
1. Add an `isProcessed` column to your table.
2. Make your script work on a chunk of, say, 1k rows for the first run (of course select only rows that are not processed).
3. Benchmark it.
4. Adjust the chunk size if needed.
5. Build another script that calls this one at intervals.
Don't forget to add some sleep time in both your scripts!
This will work if your change does not need to be continuous (and I don't think it has to be). If you have to do it all at once you should put your database offline during the time the script runs. | ```
db_data = db.query('''
SELECT id AS news_id, image AS src_filename
FROM emd_news
ORDER BY id ASC
LIMIT %s, %s''', offset, LIMIT_ROW_COUNT)
# Why is there any code here at all? If there's no data, why proceed?
if not db_data: break
``` |
3,966,146 | On our production server we need to split 900k images into different dirs and update 400k rows (MySQL with InnoDB engine). I wrote a python script which goes through next steps:
1. Select small chunk of data from db (10 rows)
- Make new dirs
- Copy files to the created dirs and rename it
- Update db (there are some triggers on update which will load server)
- Repeat
My code:
```
import os, shutil
import database # database.py from tornado
LIMIT_START_OFFSET = 0
LIMIT_ROW_COUNT = 10
SRC_PATHS = ('/var/www/site/public/upload/images/',)
DST_PATH = '/var/www/site/public/upload/new_images/'
def main():
offset = LIMIT_START_OFFSET
while True:
db = Connection(DB_HOST, DB_NAME, DB_USER, DB_PASSWD)
db_data = db.query('''
SELECT id AS news_id, image AS src_filename
FROM emd_news
ORDER BY id ASC
LIMIT %s, %s''', offset, LIMIT_ROW_COUNT)
offset = offset + LIMIT_ROW_COUNT
news_images = get_news_images(db_data) # convert data to easy-to-use list
make_dst_dirs(DST_PATH, [i['dst_dirname'] for i in news_images]) # make news dirs
news_to_update = copy_news_images(SRC_PATHS, DST_PATH, news_images) # list of moved files
db.executemany('''
UPDATE emd_news
SET image = %s
WHERE id = %s
LIMIT 1''', [(i['filename'], i['news_id']) for i in news_to_update])
db.close()
if not db_data: break
if __name__ == '__main__':
main()
```
Quite simple task, but I'm a little bit nervous about performance.
How can I make this script more efficient?
UPD:
After all I've used original script without any modifications. It took about 5 hours. And it was fast in the beginning and very slow in the end. | 2010/10/19 | [
"https://Stackoverflow.com/questions/3966146",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/228012/"
] | i will Add:
Why you create in each loop a new connexion and close it heh !!!
And maybe you can use db.autocommit(False) specially for the UPDATE and do a db.commit() for each 100 rows or something ;
and like Alin Purcaru you should do some benchmark as well.
Hope this can help :) | ```
db_data = db.query('''
SELECT id AS news_id, image AS src_filename
FROM emd_news
ORDER BY id ASC
LIMIT %s, %s''', offset, LIMIT_ROW_COUNT)
# Why is there any code here at all? If there's no data, why proceed?
if not db_data: break
``` |
32,506,956 | I am doing ex47 in Learning Python the Hard W[enter link description here](http://learnpythonthehardway.org/book/ex47.html)ay.
My problem here is that I am unable to import a module `from ex47.game.py import Room` from the other file in the following code:
```
from nose.tools import *
from ex47.game.py import Room
def test_room():
gold = Room( "GoldRoom",
"""This room has gold in it you can grab. There's a
door to the north.""")
assert_equal(gold.name, "GoldRoom")
assert_equal(gold.paths, {})
def test_room_paths():
center = Room("Center", "Test room in the center.")
north = Room("North", "Test room in the north.")
south = Room("South", "Test room in the south.")
center.add_paths({'north': north, 'south':south})
assert_equal(center.go('north'), north)
assert_equal(center.go('south'), south)
def test_map():
start = Room("Start", "You can go west and down a hole.")
west = Room("Trees", "There are trees here, you can go east.")
down = Room("Dungeon", "It's dark down here, you can go up.")
start.add_paths({'west':west, 'down':down})
west.add_paths({'east':start})
down.add_paths({'up':start})
assert_equal(start.go('west'),west)
assert_equal(start.go('west').go('east'),start)
assert_equal(start.go('down').go('up'), start)
```
And I have gotten the following error:
[](https://i.stack.imgur.com/3cwQn.png)
According to the website, this is a common problem and the author suggests to run `export PYTHONPATH=.` on Mac. But as you can see, I have ran it first before running the test also. Am I supposed to specify the pythonpath or this is due to some other problem? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32506956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427176/"
] | I just went through this exercises right now and since I wanted a bit more explanation I've searched on the internet and found this post... hence my late response.. but I hope this helps if someone else encounter this problem.
He is not really clear about the structure of your Directory. So you should have a **ex47** *folder* with the `__init__.py` file and a **game.py** into the **ex47** *main folder*. Then in the *tests folder* you should have **ex47\_tests.py** ...
So then then `from ex47.game import Room` works fine.
`from ex47`(is the package)`.game`(is the .module) `import Room`(is the class inside game.py)
```
ex47/
├── bin/
├── docs/
├── ex47/
│ ├── __init__.py
│ └── game.py
└── tests/
├── __init__.py
├── ex47_game.py
``` | `export PYTHONPATH=.` adds current directory to the list of paths that python will search when looking for a module.
That is, current directory at the time of the search, not the time you enter the line.
But, as you run your programe from `skeleton`, that will make python search for `ex47.game` in the `skeleton` directory.
How to fix it? Well, quick fix: `cd ../..` should bring you to the right place. But it's not very convenient. Better fix: change the `PYTHONPATH` variable to be the actual full path to the root of your project. That way, it won't depend on current directory.
Even better fix, you can make a small runner that sets the appropriate paths automatically before running anything. Assuming you put it at the root of your project, those lines will compute the full path to current script and add it to python search path:
```
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
# do whatever here, for instance run your tests
```
For instance, for running nosetests, you could create a launcher script:
```
#!/usr/bin/env python
import nose, os, sys
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
nose.main()
```
You put it at the root of your project, call it `nosetests.py` and run it instead of `nosetests`
*(As a sidenote, the preferred form of any kind of text on stackoverflow is actual text. This is because it allows other people who may have the same issue to find it through search engines - you can simply copy-paste your text, then use the brackets `{}` icon to make it look right).* |
32,506,956 | I am doing ex47 in Learning Python the Hard W[enter link description here](http://learnpythonthehardway.org/book/ex47.html)ay.
My problem here is that I am unable to import a module `from ex47.game.py import Room` from the other file in the following code:
```
from nose.tools import *
from ex47.game.py import Room
def test_room():
gold = Room( "GoldRoom",
"""This room has gold in it you can grab. There's a
door to the north.""")
assert_equal(gold.name, "GoldRoom")
assert_equal(gold.paths, {})
def test_room_paths():
center = Room("Center", "Test room in the center.")
north = Room("North", "Test room in the north.")
south = Room("South", "Test room in the south.")
center.add_paths({'north': north, 'south':south})
assert_equal(center.go('north'), north)
assert_equal(center.go('south'), south)
def test_map():
start = Room("Start", "You can go west and down a hole.")
west = Room("Trees", "There are trees here, you can go east.")
down = Room("Dungeon", "It's dark down here, you can go up.")
start.add_paths({'west':west, 'down':down})
west.add_paths({'east':start})
down.add_paths({'up':start})
assert_equal(start.go('west'),west)
assert_equal(start.go('west').go('east'),start)
assert_equal(start.go('down').go('up'), start)
```
And I have gotten the following error:
[](https://i.stack.imgur.com/3cwQn.png)
According to the website, this is a common problem and the author suggests to run `export PYTHONPATH=.` on Mac. But as you can see, I have ran it first before running the test also. Am I supposed to specify the pythonpath or this is due to some other problem? | 2015/09/10 | [
"https://Stackoverflow.com/questions/32506956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1427176/"
] | I just went through this exercises right now and since I wanted a bit more explanation I've searched on the internet and found this post... hence my late response.. but I hope this helps if someone else encounter this problem.
He is not really clear about the structure of your Directory. So you should have a **ex47** *folder* with the `__init__.py` file and a **game.py** into the **ex47** *main folder*. Then in the *tests folder* you should have **ex47\_tests.py** ...
So then then `from ex47.game import Room` works fine.
`from ex47`(is the package)`.game`(is the .module) `import Room`(is the class inside game.py)
```
ex47/
├── bin/
├── docs/
├── ex47/
│ ├── __init__.py
│ └── game.py
└── tests/
├── __init__.py
├── ex47_game.py
``` | As far as I know.... when you do import in python, you must not to include .py extension.
```
from ex47.game.py import Room
```
should have coded this instead:
```
from ex47.game import Room
```
where game.py was saved in the folder ex47. I hope this clarify your question. |
71,640,992 | I have a list of headings and subheadings of a document.
```
test_list = ['heading', 'heading','sub-heading', 'sub-heading', 'heading', 'sub-heading', 'sub-sub-heading', 'sub-sub-heading', 'sub-heading', 'sub-heading', 'sub-sub-heading', 'sub-sub-heading','sub-sub-heading', 'heading']
```
I want to assign unique index to each of the heading and the subheading like follows:
```
seg_ids = ['1', '2', '2_1', '2_2', '3', '3_1', '3_1_1', '3_1_2', '3_2', '3_3', '3_3_1', '3_3_2', '3_3_3', '4']
```
This is my code to create this result but it is messy and it is restricted to depth 3. If there is any document with a sub-sub-sub heading the code would become more complicated. Is there any pythonic way to do this?
```
seg_ids = []
for idx, an_ele in enumerate(test_list):
head_id = 0
subh_id = 0
subsubh_id = 0
if an_ele == 'heading' and idx == 0: # if it is the first element
head_id = '1'
seg_ids.append(head_id)
else:
last_seg_ids = seg_ids[idx-1].split('_') # find the depth of the last element
head_id = last_seg_ids[0]
if len(last_seg_ids) == 2:
subh_id = last_seg_ids[1]
elif len(last_seg_ids) == 3:
subh_id = last_seg_ids[1]
subsubh_id = last_seg_ids[2]
if an_ele == 'heading':
head_id= str(int(head_id)+1)
subh_id = 0 # reset sub_heading index
subsubh_id = 0 # reset sub_sub_heading index
elif an_ele == 'sub-heading':
subh_id= str(int(subh_id)+1)
subsubh_id = 0 # reset sub_sub_heading index
elif an_ele == 'sub-sub-heading':
subsubh_id= str(int(subsubh_id)+1)
else:
print('ERROR')
if subsubh_id==0:
if subh_id !=0:
seg_ids.append(head_id+'_'+subh_id)
else:
seg_ids.append(head_id)
if subsubh_id !=0:
seg_ids.append(str(head_id)+'_'+str(subh_id)+'_'+str(subsubh_id))
print(seg_ids)
``` | 2022/03/27 | [
"https://Stackoverflow.com/questions/71640992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9669200/"
] | Those ghosts updates are a known, long standing issue, as evidenced by [this](https://github.com/hashicorp/terraform-provider-aws/issues/18311) still open, 3 year old issue on GH without a solution.
You can try updating your TF, as 0.13 is a very old version. You can also setup [ignore\_changes](https://www.terraform.io/language/meta-arguments/lifecycle#ignore_changes=) and try if this helps. If nothing works, then there is not much you can do about that. Its AWS provider and/or TF internal issue. | I encountered a similar thing when upgrading Aurora mysql from 5.6 to 5.7: `log_output` re-appeared in every plan output.
However, the configured value in the default paramater group changed from 5.6 to 5.7 (from TABLE to FILE). I suspect since there was no change, AWS API returns empty, TF state is not updated, repeat forever.
So: In this case removing the parameter from TF code and leave it to the default was the solution.
```
# plan output example
+ parameter {
+ apply_method = "immediate"
+ name = "log_output"
+ value = "FILE"
}
``` |
70,078,645 | I have written the following python code to read in XYZ data as CSV and then grid to a GTiff format.
When I run the code I am getting no errors.
However, after trying to debug, I added some print statements and noticed that the functions aren't actually being called.
How can I run this script so that it all completes?
```
import sys
from botocore.exceptions import ClientError
import pandas as pd
import numpy as np
import rasterio
from datetime import datetime
from osgeo import gdal
class gdal_toolbox:
## CONSTANTS ##
## API handling Globals ##
gdal_types = [ 'GDT_Unknown','GDT_Byte','GDT_UInt16','GDT_Int16',\
'GDT_UInt32','GDT_Int32','GDT_Float32','GDT_Float64',\
'GDT_CInt16','GDT_CInt32','GDT_CFloat32','GDT_CFloat64',\
'GDT_TypeCount' ]
jobDict = {}
xyz_dict = {}
layerJson = {}
msk = {}
def __init__( self, kwargs ):
self.jobDict = kwargs
if self.jobDict['no_data'] is None:
self.jobDict['no_data'] = -11000
else:
self.jobDict['no_data'] = int(self.jobDict['no_data'])
if self.jobDict['gridAlgorithm'] is None:
self.jobDict['gridAlgorithm'] = 'nearest:radius1=2.25:radius2=2.25:nodata=' + str(self.jobDict['no_data'])
def normalizeToCsv( self ):
MAX_POINTS = 64000000
try:
# Read in ungridded data
self.df = pd.read_csv('C:/Users/......xyz', sep='\s+|,|:|\t',header=None, engine='python')
cnt = self.df.shape[0]
if(cnt > MAX_POINTS):
raise ValueError('Maximum number of points (' + str(cnt) + ' > ' + str(MAX_POINTS) + ') in datasource exceeded')
# convert to named x,y,z columns
print(str(datetime.now()) + ' normalizeToCsv: to_csv (start)')
self.ds = self.df.to_csv(self.csv_buf,sep=',',header=['x','y','z'],index=None)
self.csv_buf.seek(0)
print(str(datetime.now()) + ' normalizeToCsv: to_csv (end)')
dfsize = sys.getsizeof(self.df)
print('df (1) size : ' + str(dfsize))
#return df
except Exception as e:
self.logException(e)
raise
def csvToTiff(self):
try:
x = self.xyz_dict['xAxis'] / self.xyz_dict['xCellSize']
y = self.xyz_dict['yAxis'] / self.xyz_dict['yCellSize']
no_data = str(self.jobDict['no_data'])
if self.jobDict['srs'] is not None:
srs = self.jobDict['srs']
elif self.jobDict['wkt'] is not None:
srs = rasterio.crs.CRS.from_wkt(self.jobDict['wkt'])
option = gdal.GridOptions(format = 'GTIFF', outputType = gdal.GDT_Float32, width = x, height = y, \
outputBounds = [self.xyz_dict['minX'], self.xyz_dict['minY'], self.xyz_dict['maxX'], self.xyz_dict['maxY']], \
outputSRS = srs, algorithm=self.jobDict['gridAlgorithm'])
self.ds_tif = gdal.Grid('C:/Users/Public/......tif', self.ds, options = option)
except Exception as e:
self.logException(e)
raise
``` | 2021/11/23 | [
"https://Stackoverflow.com/questions/70078645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15310475/"
] | Use
```
if __name__ == "__main__":
app = gdal_toolbox(kwargs)
app.run()
```
or
```
if __name__ == "__main__":
gdal_toolbox(kwargs).run()
```
Use thease codes at the end of your script.
And the solution is :
```
class gdal_toolbox:
## CONSTANTS ##
def __init__( self, kwargs ):
print(kwargs)
def normalizeToCsv( self ):
MAX_POINTS = 64000000
print(MAX_POINTS)
def csvToTiff(self):
print("Its the secoend function")
if __name__ == "__main__":
kwargs="Its the keyword arguments"
gdal_toolbox(kwargs)
``` | It seems like you are not executing anything in this piece of code, just defining class and functions within it, right? |
58,822,095 | I have a problem using pyarrow.orc module in Anaconda on Windows 10.
```
import pyarrow.orc as orc
```
throws an exception:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\apps\Anaconda3\envs\ws\lib\site-packages\pyarrow\orc.py", line 23, in <module>
import pyarrow._orc as _orc
ModuleNotFoundError: No module named 'pyarrow._orc'
```
On the other hand:
`import pyarrow`
works without any issues.
```
conda list
# packages in environment at C:\apps\Anaconda3\envs\ws:
#
# Name Version Build Channel
arrow-cpp 0.13.0 py37h49ee12d_0
...
numpy 1.17.3 py37h4ceb530_0
numpy-base 1.17.3 py37hc3f5095_0
...
pip 19.3.1 py37_0
pyarrow 0.13.0 py37ha925a31_0
...
python 3.7.5 h8c8aaf0_0
...
```
I've tried other versions of pyarrow with the same results.
```
conda -V
conda 4.7.12
``` | 2019/11/12 | [
"https://Stackoverflow.com/questions/58822095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12361891/"
] | The ORC reader is not supported at all on Windows and has never been to my knowledge. Apache ORC in C++ is not known to build yet with the Visual Studio C++ compiler. | Bottom line up front,
I had the same error. This was the solution for me:
```
!pip install pyarrow==0.13.0
```
I'm not sure this is limited to Windows 10, I am getting the same error in AWS Sagemaker in the last few days. This was working fine before, on a previous Sagemaker instance.
Using the Conda Packages menu in Jupyter, the conda\_python3 kernel showed it had pyarrow 0.13.0 installed from <https://repo.anaconda.com/pkgs/main/linux-64>, build py36he6710b0\_0.
However a subsequent call to
```
!conda -list
```
Did not show pyarrow as being in the Jupyter conda\_python3 kernel, even after restarting the kernel.
Normally in a Sagemaker [Jupyter notebook] instance, I would use !pip commands because they just seem to work better, and don't have the timeout errors I sometimes find with the Conda Packages menu. (Also I don't need to worry about passing `-y` flags, the installs just happen)
Normally `!pip install pyarrow` was working, but I noticed it was installing **pyarrow 0.15.1 from Nov 1, 2019**.
Perhaps there is an error in that version with loading the \_orc package, or some other conflicting library.
My intuition is that something is wrong with the conda version of pyarrow 0.13.0, and with pyarrow 0.15.1.
In a Jupyter cell I tried this:
```
!pip uninstall pyarrow -y
!pip install pyarrow
from pyarrow import orc
```
Output:
```
Uninstalling pyarrow-0.15.1:
Successfully uninstalled pyarrow-0.15.1
Collecting pyarrow
Downloading https://files.pythonhosted.org/packages/6c/32/ce1926f05679ea5448fd3b98fbd9419d8c7a65f87d1a12ee5fb9577e3a8e/pyarrow-0.15.1-cp36-cp36m-manylinux2010_x86_64.whl (59.2MB)
|████████████████████████████████| 59.2MB 381kB/s eta 0:00:01
Requirement already satisfied: numpy>=1.14 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from pyarrow) (1.14.3)
Requirement already satisfied: six>=1.0.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from pyarrow) (1.11.0)
Installing collected packages: pyarrow
Successfully installed pyarrow-0.15.1
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-6-36378dee5a25> in <module>()
1 get_ipython().system('pip uninstall pyarrow -y')
2 get_ipython().system('pip install pyarrow')
----> 3 from pyarrow import orc
~/anaconda3/envs/python3/lib/python3.6/site-packages/pyarrow/orc.py in <module>()
23 from pyarrow import types
24 from pyarrow.lib import Schema
---> 25 import pyarrow._orc as _orc
26
27
ModuleNotFoundError: No module named 'pyarrow._orc'
```
**Note that when you try to uninstall pyarrow 0.15.1 and install a specific older version, like 0.13.0, you should restart the kernel after uninstalling. There are some incompatible binaries that get left behind.
I did not post that output because it was so long.**
```
pip uninstall pyarrow -y
```
Restart Kernel, then:
```
!pip install pyarrow==0.13.0
from pyarrow import orc
```
Output:
```
Collecting pyarrow==0.13.0
Using cached https://files.pythonhosted.org/packages/ad/25/094b122d828d24b58202712a74e661e36cd551ca62d331e388ff68bae91d/pyarrow-0.13.0-cp36-cp36m-manylinux1_x86_64.whl
Requirement already satisfied: numpy>=1.14 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from pyarrow==0.13.0) (1.14.3)
Requirement already satisfied: six>=1.0.0 in /home/ec2-user/anaconda3/envs/python3/lib/python3.6/site-packages (from pyarrow==0.13.0) (1.11.0)
Installing collected packages: pyarrow
Successfully installed pyarrow-0.13.0
```
There is now no error from the import command, and orc files can be read again. |
58,822,095 | I have a problem using pyarrow.orc module in Anaconda on Windows 10.
```
import pyarrow.orc as orc
```
throws an exception:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\apps\Anaconda3\envs\ws\lib\site-packages\pyarrow\orc.py", line 23, in <module>
import pyarrow._orc as _orc
ModuleNotFoundError: No module named 'pyarrow._orc'
```
On the other hand:
`import pyarrow`
works without any issues.
```
conda list
# packages in environment at C:\apps\Anaconda3\envs\ws:
#
# Name Version Build Channel
arrow-cpp 0.13.0 py37h49ee12d_0
...
numpy 1.17.3 py37h4ceb530_0
numpy-base 1.17.3 py37hc3f5095_0
...
pip 19.3.1 py37_0
pyarrow 0.13.0 py37ha925a31_0
...
python 3.7.5 h8c8aaf0_0
...
```
I've tried other versions of pyarrow with the same results.
```
conda -V
conda 4.7.12
``` | 2019/11/12 | [
"https://Stackoverflow.com/questions/58822095",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12361891/"
] | The ORC reader is not supported at all on Windows and has never been to my knowledge. Apache ORC in C++ is not known to build yet with the Visual Studio C++ compiler. | Below Code solve my issue on windows. Need to install pyorc . It worked well with plain python ,no conda needed. Please refer video <https://www.youtube.com/watch?v=qvV_Frc6zB8> by Alfred Zhong. He nicely explain it.
```
import pyorc
import pandas as pd
data = open('file1.orc','rb')
reader = pyorc.Reader(data)
columns = reader.schema.fields
columns =[col_name for col_idx,col_name in sorted(
[
(reader.schema.find_column_id(c), c) for c in columns
]
)]
df=pd.DataFrame(reader,columns=columns)
df.to_csv('file1.csv')
``` |
67,928,883 | I'm working on this REST application in python `Flask` and a driver called `pymongo`. But if someone knows `mongodb` well he/she maybe able to answer my question.
Suppose Im inserting a new document in a collection say `students`. I want to get the whole inserted document as soon as the document is saved in the collection. Here is what i've tried so far.
```py
res = db.students.insert_one({
"name": args["name"],
"surname": args["surname"],
"student_number": args["student_number"],
"course": args["course"],
"mark": args["mark"]
})
```
If i call:
```
print(res.inserted_id) ## i get the id
```
How can i get something like:
```json
{
"name": "student1",
"surname": "surname1",
"mark": 78,
"course": "ML",
"student_number": 2
}
```
from the `res` object. Because if i print `res` i am getting `<pymongo.results.InsertOneResult object at 0x00000203F96DCA80>` | 2021/06/10 | [
"https://Stackoverflow.com/questions/67928883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12925831/"
] | Put the data to be inserted into a dictionary variable; on insert, the variable will have the `_id` added by pymongo.
```
from pymongo import MongoClient
db = MongoClient()['mydatabase']
doc = {
"name": "name"
}
db.students.insert_one(doc)
print(doc)
```
prints:
```
{'name': 'name', '_id': ObjectId('60ce419c205a661d9f80ba23')}
``` | Unfortunately, the commenters are correct. The PyMongo pattern doesn't specifically allow for what you are asking. You are expected to just use the inserted\_id from the [result](https://pymongo.readthedocs.io/en/stable/api/pymongo/results.html#pymongo.results.InsertOneResult) and if you needed to get the full object from the collection later do a regular [query operation afterwards](https://pymongo.readthedocs.io/en/stable/api/pymongo/collection.html#pymongo.collection.Collection.insert_one) |
52,501,105 | I am trying to connect to MSSQL with help of django-pyodbc. I have installed all the required packages like FreeTDS, unixODBC and django-pyodbc. When I connect using tsql and isql I am able to connect:-
```
>tsql -S mssql -U ********* -P ***********
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
1>
isql -v mssql ********* ***********
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
SQL>
```
But, when I am trying to connect from python it does not work. I am getting below error:-
```
>python
Python 2.7.14 (default, May 16 2018, 06:48:40)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-28)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pyodbc;
>>> print(pyodbc.connect("DSN=GB0015APP09.dir.dbs.com;UID=*********;PWD=*************").cursor().execute("select 1"));
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
pyodbc.Error: ('IM002', '[IM002] [unixODBC][Driver Manager]Data source name not found, and no default driver specified (0) (SQLDriverConnect)')
>>>
```
I have checked all other related answers but nothing is working. Not sure which data source name it is looking for.
Below are all the related configurations:-
```
/root>cat .freetds.conf
[mssql]
host = my_server_name
instance = MSSQL
Port = 1433
tds version =
/root>cat /etc/odbc.ini
[ServerDSN]
Driver = FreeTDS
Description = FreeTDS
Trace = No
Servername = mssql
Server = my_server_name
Port = 1433
Database = my_db_name
/root>cat /etc/odbcinst.ini
[FreeTDS]
Description = FreeTDS
Driver = /usr/lib64/libtdsodbc.so
Setup = /usr/lib64/libtdsS.so
fileusage=1
dontdlclose=1
UsageCount=1
```
I have wasted couple of days trying to resolve this issue, but no luck.
Please help me out.
**EDIT**
```
/root>tsql -C
Compile-time settings (established with the "configure" script)
Version: freetds v0.95.81
freetds.conf directory: /etc
MS db-lib source compatibility: yes
Sybase binary compatibility: yes
Thread safety: yes
iconv library: yes
TDS version: 4.2
iODBC: no
unixodbc: yes
SSPI "trusted" logins: no
Kerberos: yes
OpenSSL: no
GnuTLS: yes
/root>odbcinst -j
unixODBC 2.3.1
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /root/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8
``` | 2018/09/25 | [
"https://Stackoverflow.com/questions/52501105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034743/"
] | This has to do with the current scope that Rankx evaluates de Aggregation.
Try wrapping your aggregation with CALCULATE, and you probably want the SUM not the MAX:
```
Rank Reseller = RANKX(ALL(ResellerSales), CALCULATE(SUM(ResellerSales[SalesAmount])))
```
You can create a Measure like so, and use it on RANKX, since it is a measure it will work without explicitly adding the CALCULATE:
```
Sales Amount = SUM(ResellerSales[SalesAmount])
Rank Reseller = RANKX(ALL(ResellerSales), [Sales Amount])
```
EDIT:
```
Rank Reseller = RANKX(ALL('ResellerSales'[Resellerkey]), [Sales Amount])
```
Try it like this. | To rank the [ReSellerkey] by [SalesAmount] you'd want to do something like this:
```
Rank Sales Amount :=
RANKX(
'Table',
'Table'[SalesAmount],
,
ASC,
Dense
)
``` |
42,301,458 | I have a large netcdf file which is three dimensional. I want to replace for the variable `LU_INDEX` in the netcdf file all the values 10 with 2.
I wrote this python script to do so but it does not seem to work.
```
filelocation = 'D:/dataset.nc'
ncdataset = nc.Dataset(filelocation,'r')
lat = ncdataset.variables['XLAT_M'][0,:,:]
lon = ncdataset.variables['XLONG_M'][0,:,:]
lu_index = ncdataset.variables['LU_INDEX'][0,:,:]
lu_index_new = lu_index
ncdataset.close()
nlat,nlon=lat.shape
for ilat in range(nlat):
for ilon in range(lon):
if lu_index == 10:
lu_index_new[ilat,ilon] = 2
newfilename = 'D:/dataset.new.nc'
copyfile(ncdataset,newfilename)
newfile = nc.Dataset(newfilename,'r+')
newfile.variables['LU_INDEX'][0,:,:] = lu_index_new
newfile.close()
```
I get the error:
```
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```
I am not a very experienced with python, so if there is a more easier way to do this you are very welcome to comment. | 2017/02/17 | [
"https://Stackoverflow.com/questions/42301458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7581459/"
] | You might try [NCO](http://nco.sf.net/nco.html#ncap2)
```
ncap2 -s 'where(LU_INDEX == 10) LU_INDEX=2' in.nc out.nc
``` | I worked it out as follow:
```
import netCDF4 as nc
import numpy as np
pathname = 'D:'
filename = '%s/dataset.nc'%pathname
ncfile = nc.Dataset(filename,'r+')
lu_index = ncfile.variables['LU_INDEX'][:]
I = np.where(lu_index == 10)
lu_index[I] = 2
ncfile.variables['LU_INDEX'][:] = lu_index
filename.close()
print 'conversion complete'
``` |
42,301,458 | I have a large netcdf file which is three dimensional. I want to replace for the variable `LU_INDEX` in the netcdf file all the values 10 with 2.
I wrote this python script to do so but it does not seem to work.
```
filelocation = 'D:/dataset.nc'
ncdataset = nc.Dataset(filelocation,'r')
lat = ncdataset.variables['XLAT_M'][0,:,:]
lon = ncdataset.variables['XLONG_M'][0,:,:]
lu_index = ncdataset.variables['LU_INDEX'][0,:,:]
lu_index_new = lu_index
ncdataset.close()
nlat,nlon=lat.shape
for ilat in range(nlat):
for ilon in range(lon):
if lu_index == 10:
lu_index_new[ilat,ilon] = 2
newfilename = 'D:/dataset.new.nc'
copyfile(ncdataset,newfilename)
newfile = nc.Dataset(newfilename,'r+')
newfile.variables['LU_INDEX'][0,:,:] = lu_index_new
newfile.close()
```
I get the error:
```
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
```
I am not a very experienced with python, so if there is a more easier way to do this you are very welcome to comment. | 2017/02/17 | [
"https://Stackoverflow.com/questions/42301458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7581459/"
] | You might try [NCO](http://nco.sf.net/nco.html#ncap2)
```
ncap2 -s 'where(LU_INDEX == 10) LU_INDEX=2' in.nc out.nc
``` | using np.array might not work for a very large dataset with the following error
"ValueError: array is too big; `arr.size * arr.dtype.itemsize` is larger than the maximum possible size."
CDO can be a nice tool other than NCO and for me, it is much fast.
```
CDO setvals,10,2 in.nc out.nc
```
It is particularly fast when you have to replace values in more than one variables in the same nc file (e.g. replace missing values representation).
One can use "setrtoc" in place of setval for specifying a range. |
25,811,202 | I am trying to execute a shell command and kill it using python **signal** module.
I know signals work only with main thread, so I run the Django development server with,
```
python manage.py runserver --nothreading --noreload
```
and it works fine.
But when i deploy the django application with Apache/mod\_wsgi, it shows the following error:
```
[Fri Sep 12 20:07:00 2014] [error] response = function.call(request, **data)
[Fri Sep 12 20:07:00 2014] [error] File "/Site/cloud/lib/python2.6/site-packages/dajaxice/core/Dajaxice.py", line 18, in call
[Fri Sep 12 20:07:00 2014] [error] return self.function(*args, **kwargs)
[Fri Sep 12 20:07:00 2014] [error] File "/Site/cloud/soc/website/ajax.py", line 83, in execute
[Fri Sep 12 20:07:00 2014] [error] data = scilab_run(code, token, book_id, dependency_exists)
[Fri Sep 12 20:07:00 2014] [error] File "/Site/cloud/soc/website/helpers.py", line 58, in scilab_run
[Fri Sep 12 20:07:00 2014] [error] output = task.run().communicate()[0]
[Fri Sep 12 20:07:00 2014] [error] File "/Site/cloud/soc/website/timeout.py", line 121, in run
[Fri Sep 12 20:07:00 2014] [error] lambda sig,frame : os.killpg(self.pgid,self.timeoutSignal) )
[Fri Sep 12 20:07:00 2014] [error] ValueError: signal only works in main thread
```
Here is my apache virtualhost setting:
```
WSGIDaemonProcess testcloud display-name=scilab_cloud user=apache group=apache threads=1
WSGIProcessGroup testcloud
WSGIScriptAlias / /Site/cloud/soc/soc/wsgi.py
WSGIImportScript /Site/cloud/soc/soc/wsgi.py process-group=testcloud application-group=%{GLOBAL}
```
I also have the below settings outside virtualhost in httpd.conf:
```
WSGIRestrictSignal Off
WSGISocketPrefix /var/run/wsgi
```
[Here is the link](https://gist.github.com/devietti/1526975) to the program which uses **signal** and the one which I use in my django application.
Any help would be appreciated. | 2014/09/12 | [
"https://Stackoverflow.com/questions/25811202",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2102830/"
] | are you running with DEBUG enabled in setting.py ?
If yes try disabling it to see if the issue persists. | I'm not sure that can be done that easily, or at least not with mod\_wsgi. The decision to thread or not to thread is the sum of build and run time options in both apache and mod\_wsgi, which are both set by default, to threading.
I would point you to the docs about that, but I can only post two links, so I think it's better to spend them in proposing a solution:
I had decently good experiences running shell commands from python with [sh](http://amoffat.github.io/sh/index.html), which even has an asynchronous execution module. Maybe you can start your python code running the shell command, and deal with the callback object when needed.
Or, even better, as `sh` asks you to have some cares when handling signals, you could just run it without the asynchronous execution module, but in another process with [multiprocessing.Proces](https://docs.python.org/3.5/library/multiprocessing.html#multiprocessing.Process), which will give you a `Process` object you can just kill with `object.terminate()` |
64,512,500 | Arrays of labels of objects and distances to that objects are given. I want to apply knn to find the label of prediction. I want to use `np.bincount` for that. However, I don't understand how to use this.
See some example
```
labels = [[1,1,2,0,0,3,3,3,5,1,3],
[1,1,2,0,0,3,3,3,5,1,3]]
weights= [[0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,0,1,0,0]]
```
Imagine 10 nearest neighbors for 2 objects are given and their labels and distances are given above. So I want the output as `[5,5]`, because only neighbours with that label have nonzero weight. I am doing the next thing:
```
eps = 1e-5
lab_weight = np.array(list(zip(labels, weights)))
predict = np.apply_along_axis(lambda x: np.bincount(x[0], weights=x[1]).argmax(), 2, lab_weight)
```
I expect that `x` will correspond to `[[1,1,2,0,0,3,3,3,5,1,3], [0,0,0,0,0,0,0,0,1,0,0]]`, but it won't. Other axis parameters are not working too. How can I achieve the goal? I want to use `numpy` functions and avoid python loops. | 2020/10/24 | [
"https://Stackoverflow.com/questions/64512500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13184183/"
] | The next solution gives me desired result:
```
labels = [[1,1,2,0,0,3,3,3,5,1,3],
[1,1,2,0,0,3,3,3,5,1,3]]
weights= [[0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,0,1,0,0]]
length = len(labels[0])
lab_weight = np.hstack((labels, weights))
predict = np.apply_along_axis(lambda x: np.bincount(x[:length], weights=x[length:]).argmax(), 1, lab_weight)
``` | The problem with your code is that you attempt to use your
function to **2-D** slices of your array, whereas *apply\_along\_axis*
applies the given function to **1-D** slices.
So your code generates an exception: *ValueError: object of too small
depth for desired array*.
To apply your function to 2-D slices, use a list comprehension based on
*np.rollaxis* and then create a *Numpy* array from it:
```
result = np.array([ np.bincount(x[0], weights=x[1]).argmax()
for x in np.rollaxis(lab_weight, 2) ])
```
The result, for your array, is:
```
array([1, 1, 2, 0, 0, 3, 3, 3, 5, 1, 3], dtype=int64)
```
To trace, for each interation, the source array, intermediate results
and the final result, run:
```
i = 0
for x in np.rollaxis(lab_weight, 2):
print(f' i: {i}\n{x}'); i += 1
bc = np.bincount(x[0], weights=x[1])
bcm = bc.argmax()
print(bc, bcm)
``` |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.
Let's say I have a program:
```
def foo():
a = 5
my_debug_shell()
print a
foo()
```
my\_debug\_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it. | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | Here is a solution that doesn't require code changes:
```
python -m pdb prog.py <prog_args>
(pdb) b 3
Breakpoint 1 at prog.py:3
(pdb) c
...
(pdb) p a
5
(pdb) a=7
(pdb) ...
```
In short:
* start your program under debugger control
* set a break point at a given line of code
* let the program run up to that point
* you get an interactive prompt that let's you do what you want (type 'help' for all options) | Not sure what the real question is. Python gives you the 'pdb' debugger (google yourself) and in addition you can add logging and debug output as needed. |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.
Let's say I have a program:
```
def foo():
a = 5
my_debug_shell()
print a
foo()
```
my\_debug\_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it. | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | <http://docs.python.org/library/pdb.html>
```
import pdb
pdb.set_trace()
``` | Here is a solution that doesn't require code changes:
```
python -m pdb prog.py <prog_args>
(pdb) b 3
Breakpoint 1 at prog.py:3
(pdb) c
...
(pdb) p a
5
(pdb) a=7
(pdb) ...
```
In short:
* start your program under debugger control
* set a break point at a given line of code
* let the program run up to that point
* you get an interactive prompt that let's you do what you want (type 'help' for all options) |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.
Let's say I have a program:
```
def foo():
a = 5
my_debug_shell()
print a
foo()
```
my\_debug\_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it. | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | Python `3.7` has a new builtin way of setting breakpoints.
```
breakpoint()
```
The implementation of `breakpoint()` will `import pdb` and call `pdb.set_trace()`.
Remember to include the braces `()`, since `breakpoint` is a function, not a keyword. | Not sure what the real question is. Python gives you the 'pdb' debugger (google yourself) and in addition you can add logging and debug output as needed. |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.
Let's say I have a program:
```
def foo():
a = 5
my_debug_shell()
print a
foo()
```
my\_debug\_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it. | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | A *one-line* partial solution is simply to put `1/0` where you want the breakpoint: this will raise an exception, which will be caught by the debugger. Two advantages of this approach are:
* Breakpoints set this way are robust against code modification (no dependence on a particular line number);
* One does not need to `import pdb` in every program to be debugged; one can instead directly insert "breakpoints" where needed.
In order to catch the exception automatically, you can simply do `python -m pdb prog.py…` and then type `c`(ontinue) in order to start the program. When the `1/0` is reached, the program exits, but variables can be inspected as usual with the `pdb` debugger (`p my_var`). Now, this does not allow you to fix things *and keep running* the program. Instead you can try to fix the bug and run the program again.
If you want to use the powerful [IPython](http://ipython.github.com/ipython-doc/stable/html/index.html) shell, `ipython -pdb prog.py…` does the same thing, but leads to IPython's better debugger interface. Alternatively, you can do everything from within the IPython shell:
* In IPython, set up the "debug on exception" mode of IPython (`%pdb`).
* Run the program from IPython with `%run prog.py…`. When an exception occurs, the debugger is automatically activated and you can inspect variables, etc.
The advantage of this latter approach is that (1) the IPython shell is almost a must; and (2) once it is installed, debugging can easily be done through it (instead of directly through the pdb module). The [full documentation](http://ipython.scipy.org/doc/stable/html/interactive/reference.html#running-entire-programs-via-pdb) is available on the IPython pages. | Not sure what the real question is. Python gives you the 'pdb' debugger (google yourself) and in addition you can add logging and debug output as needed. |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.
Let's say I have a program:
```
def foo():
a = 5
my_debug_shell()
print a
foo()
```
my\_debug\_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it. | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | Here is a solution that doesn't require code changes:
```
python -m pdb prog.py <prog_args>
(pdb) b 3
Breakpoint 1 at prog.py:3
(pdb) c
...
(pdb) p a
5
(pdb) a=7
(pdb) ...
```
In short:
* start your program under debugger control
* set a break point at a given line of code
* let the program run up to that point
* you get an interactive prompt that let's you do what you want (type 'help' for all options) | Python `3.7` has a new builtin way of setting breakpoints.
```
breakpoint()
```
The implementation of `breakpoint()` will `import pdb` and call `pdb.set_trace()`.
Remember to include the braces `()`, since `breakpoint` is a function, not a keyword. |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.
Let's say I have a program:
```
def foo():
a = 5
my_debug_shell()
print a
foo()
```
my\_debug\_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it. | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | You can run the program using pdb, and add breakpoints before starting execution.
In reality though, it's usually just as fast to edit the code and put in the set\_trace() call, as another user stated. | Not sure what the real question is. Python gives you the 'pdb' debugger (google yourself) and in addition you can add logging and debug output as needed. |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.
Let's say I have a program:
```
def foo():
a = 5
my_debug_shell()
print a
foo()
```
my\_debug\_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it. | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | <http://docs.python.org/library/pdb.html>
```
import pdb
pdb.set_trace()
``` | A *one-line* partial solution is simply to put `1/0` where you want the breakpoint: this will raise an exception, which will be caught by the debugger. Two advantages of this approach are:
* Breakpoints set this way are robust against code modification (no dependence on a particular line number);
* One does not need to `import pdb` in every program to be debugged; one can instead directly insert "breakpoints" where needed.
In order to catch the exception automatically, you can simply do `python -m pdb prog.py…` and then type `c`(ontinue) in order to start the program. When the `1/0` is reached, the program exits, but variables can be inspected as usual with the `pdb` debugger (`p my_var`). Now, this does not allow you to fix things *and keep running* the program. Instead you can try to fix the bug and run the program again.
If you want to use the powerful [IPython](http://ipython.github.com/ipython-doc/stable/html/index.html) shell, `ipython -pdb prog.py…` does the same thing, but leads to IPython's better debugger interface. Alternatively, you can do everything from within the IPython shell:
* In IPython, set up the "debug on exception" mode of IPython (`%pdb`).
* Run the program from IPython with `%run prog.py…`. When an exception occurs, the debugger is automatically activated and you can inspect variables, etc.
The advantage of this latter approach is that (1) the IPython shell is almost a must; and (2) once it is installed, debugging can easily be done through it (instead of directly through the pdb module). The [full documentation](http://ipython.scipy.org/doc/stable/html/interactive/reference.html#running-entire-programs-via-pdb) is available on the IPython pages. |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.
Let's say I have a program:
```
def foo():
a = 5
my_debug_shell()
print a
foo()
```
my\_debug\_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it. | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | <http://docs.python.org/library/pdb.html>
```
import pdb
pdb.set_trace()
``` | You can run the program using pdb, and add breakpoints before starting execution.
In reality though, it's usually just as fast to edit the code and put in the set\_trace() call, as another user stated. |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.
Let's say I have a program:
```
def foo():
a = 5
my_debug_shell()
print a
foo()
```
my\_debug\_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it. | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | Python `3.7` has a new builtin way of setting breakpoints.
```
breakpoint()
```
The implementation of `breakpoint()` will `import pdb` and call `pdb.set_trace()`.
Remember to include the braces `()`, since `breakpoint` is a function, not a keyword. | You can run the program using pdb, and add breakpoints before starting execution.
In reality though, it's usually just as fast to edit the code and put in the set\_trace() call, as another user stated. |
5,769,382 | I'm not sure if what I'm asking is possible at all, but since python is an interpreter it might be. I'm trying to make changes in an open-source project but because there are no types in python it's difficult to know what the variables have as data and what they do. You can't just look up the documentation on the var's type since you can't be sure what type it is. I want to drop to the terminal so I can quickly examine the types of the variables and what they do by typing help(var) or print(var). I could do this by changing the code and then re-running the program each time but that would be much slower.
Let's say I have a program:
```
def foo():
a = 5
my_debug_shell()
print a
foo()
```
my\_debug\_shell is the function I'm asking about. It would drop me to the '>>>' shell of the python interpreter where I can type help(a), and it would tell me that a is an integer. Then I type 'a=7', and some 'continue' command, and the program goes on to print 7, not 5, because I changed it. | 2011/04/24 | [
"https://Stackoverflow.com/questions/5769382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/492336/"
] | Here is a solution that doesn't require code changes:
```
python -m pdb prog.py <prog_args>
(pdb) b 3
Breakpoint 1 at prog.py:3
(pdb) c
...
(pdb) p a
5
(pdb) a=7
(pdb) ...
```
In short:
* start your program under debugger control
* set a break point at a given line of code
* let the program run up to that point
* you get an interactive prompt that let's you do what you want (type 'help' for all options) | You can run the program using pdb, and add breakpoints before starting execution.
In reality though, it's usually just as fast to edit the code and put in the set\_trace() call, as another user stated. |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, but
```
foo b b
```
would not be | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | I have assumed that the elements of the string can be in any order and appear any number of times. For example, `'a foo'` should match and `'a foo b foo'` should not.
You can do that with a series of alternations employing lookaheads, one for each substring of interest, but it becomes a bit of a dog's breakfast when there are many strings to consider. Let's suppose you wanted to match zero or one `"foo"`'s and/or zero or one `"a"`'s. You could use the following regular expression:
```
^(?:(?!.*\bfoo\b)|(?=(?:(?!\bfoo\b).)*\bfoo\b(?!(.*\bfoo\b))))(?:(?!.*\ba\b)|(?=(?:(?!\ba\b).)*\ba\b(?!(.*\ba\b))))
```
[Start your engine!](https://regex101.com/r/sOBFj4/1)
This matches, for example, `'foofoo'`, `'aa'` and `afooa`. If they are not to be matched remove the word breaks (`\b`).
Notice that this expression begins by asserting the start of the string (`^`) followed by two positive lookaheads, one for `'foo'` and one for `'a'`. To also check for, say, `'c'` one would tack on
```
(?:(?!.*\bc\b)|(?=(?:(?!\bc\b).)*\bc\b(?!(.*\bc\b))))
```
which is the same as
```
(?:(?!.*\ba\b)|(?=(?:(?!\ba\b).)*\ba\b(?!(.*\ba\b))))
```
with `\ba\b` changed to `\bc\b`.
It would be nice to be able to use back-references but I don't see how that could be done.
By hovering over the regular expression in the link an explanation is provided for each element of the expression. (If this is not clear I am referring to the cursor.)
Note that
```
(?!\bfoo\b).
```
matches a character provided it does not begin the word `'foo'`. Therefore
```
(?:(?!\bfoo\b).)*
```
matches a substring that does not contain `'foo'` and does not end with `'f'` followed by `'oo'`.
Would I advocate this approach in practice, as opposed to using simple string methods? Let me ponder that. | If the order of the strings doesn't matter, and you want to make sure every string occurs only once, you can turn the list into a set in Python:
```
my_lst = ['a', 'a', 'b', 'c']
my_set = set(lst)
print(my_set)
# {'a', 'c', 'b'}
``` |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, but
```
foo b b
```
would not be | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | You may use this regex with a capture group and a negative lookahead:
For `Perl`, you can use this variant with [forward referencing](https://www.regular-expressions.info/backref2.html):
```sh
^foo((?!.*\1) [abc])+$
```
[RegEx Demo](https://regex101.com/r/P9Qp9r/2)
**RegEx Details:**
* `^`: Start
* `foo`: Match `foo`
* `(`: Start a capture group #1
+ `(?!.*\1)`: Negative lookahead to assert that we don't match what we have in capture group #1 anywhere in input
+ `[abc]`: Match a space followed by `a` or `b` or `c`
* `)+`: End capture group #1. Repeat this group 1+ times
* `$`: End
As mentioned earlier, this regex is using a feature called **Forward Referencing** which is a back-reference to a group that **appears later in the regex pattern**. JGsoft, .NET, Java, Perl, PCRE, PHP, Delphi, and Ruby allow forward references but Python doesn't.
---
Here is a **work-around of same regex for Python** that doesn't use forward referencing:
```sh
^foo(?!.* ([abc]).*\1)(?: [abc])+$
```
Here we use a negative lookahead before repeated group to check and fail the match if there is any repeat of allowed substrings i.e. `[abc]`.
[RegEx Demo 2](https://regex101.com/r/P9Qp9r/3) | You can assert that there is no match for a second match for a space and a letter at the right:
```
foo(?!(?: [abc])*( [abc])(?: [abc])*\1)(?: [abc])*
```
* `foo` Match literally
* `(?!` Negative lookahead
+ `(?: [abc])*` Match optional repetitions of a space and a b or c
+ `( [abc])` Capture group, use to compare with a backreference for the same
+ `(?: [abc])*` Match again a space and either a b or c
+ `\1` Backreference to group 1
* `)` Close lookahead
* `(?: [abc])*` Match optional repetitions or a space and either a b or c
[Regex demo](https://regex101.com/r/E778Ef/1)
If you don't want to match only foo, you can change the quantifier to 1 or more `(?: [abc])+`
---
A variant in perl reusing the first subpattern using `(?1)` which refers to the capture group `([abc])`
```
^foo ([abc])(?: (?!\1)((?1))(?: (?!\1|\2)(?1))?)?$
```
[Regex demo](https://regex101.com/r/pkLEn9/1) |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, but
```
foo b b
```
would not be | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | You may use this regex with a capture group and a negative lookahead:
For `Perl`, you can use this variant with [forward referencing](https://www.regular-expressions.info/backref2.html):
```sh
^foo((?!.*\1) [abc])+$
```
[RegEx Demo](https://regex101.com/r/P9Qp9r/2)
**RegEx Details:**
* `^`: Start
* `foo`: Match `foo`
* `(`: Start a capture group #1
+ `(?!.*\1)`: Negative lookahead to assert that we don't match what we have in capture group #1 anywhere in input
+ `[abc]`: Match a space followed by `a` or `b` or `c`
* `)+`: End capture group #1. Repeat this group 1+ times
* `$`: End
As mentioned earlier, this regex is using a feature called **Forward Referencing** which is a back-reference to a group that **appears later in the regex pattern**. JGsoft, .NET, Java, Perl, PCRE, PHP, Delphi, and Ruby allow forward references but Python doesn't.
---
Here is a **work-around of same regex for Python** that doesn't use forward referencing:
```sh
^foo(?!.* ([abc]).*\1)(?: [abc])+$
```
Here we use a negative lookahead before repeated group to check and fail the match if there is any repeat of allowed substrings i.e. `[abc]`.
[RegEx Demo 2](https://regex101.com/r/P9Qp9r/3) | Here is a modified version of anubhava's answer, using a [backreference](https://www.regular-expressions.info/backref.html) (which works in Python, and is easier to understand at least for me) instead of a forward reference.
Match using `[abc]` inside a capturing group, then check that the text matched by the capturing group does not appear again anywhere after it:
```
^foo(?:( [abc])(?!.*\1))+$
```
[regex demo](https://regex101.com/r/otEzZP/1)
* `^`: Start
* `foo`: Match `foo`
* `(?:`: Start non-capturing group `(?:( [abc])(?!.*\1))`
+ `( [abc])`: Capturing Group 1, matching a space followed by either `a`, `b`, or `c`
+ `(?!.*\1)`: Negative lookahead, failing to match if the text matched by the first capturing group occurs after zero or more characters matched by `.`
* `)+`: End non-capturing group and match it 1 or more times
* `$`: End |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, but
```
foo b b
```
would not be | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | You can do it using references to previously captured groups.
```regex
foo(?: ([abc]))?(?: (?!\1)([abc]))?(?: (?!\1|\2)([abc]))?$
```
This gets quite long with many options. Such a regex can be generated dynamically, if necessary.
```py
def match_sequence_without_repeats(options, seperator):
def prevent_previous(n):
if n == 0:
return ""
groups = "".join(rf"\{i}" for i in range(1, n + 1))
return f"(?!{groups})"
return "".join(
f"(?:{seperator}{prevent_previous(i)}([{options}]))?"
for i in range(len(options))
)
print(f"foo{match_sequence_without_repeats('abc', ' ')}$")
``` | There is not much to add to the above answers except here is a regex that does not use back or forward references. Instead it uses 3 separate negative lookahead assertions to ensure that the input does not contain 2 occurrences of either `a` or `b` or `c`. The regex also allows for liberal uses of spaces.
```
^foo(?![^a]*a[^a]*a)(?![^b]*b[^b]*b)(?![^c]*c[^c]*c)( +[abc])* *$
```
[See Regex Demo](https://regex101.com/r/6UReEn/1/)
1. `^` - Matches start of string
2. `(?![^a]*a[^a]*a)` - Negative lookahead assertion that what follows does not contain two occurrences of `a`
3. `(?![^b]*b[^b]*b)` - Negative lookahead assertion that what follows does not contain two occurrences of `b`
4. `(?![^c]*c[^c]*c)` - Negative lookahead assertion that what follows does not contain two occurrences of `c`
5. `( +[abc])*` - Matches 0 or more occurrences of: 1 or more spaces followed by an `a` or `b` or `c`
6. `*` - Matches 0 or more occurrences of space
7 `$` - Matches the end of the string
The regex looks "clunky" but is very straightforward. With input `foo a b c` the successful match is done in 35 steps and with input `foo b b` the unsuccessful match is done in 13 steps. Thich compares favorably with the other answers. |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, but
```
foo b b
```
would not be | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | Here is a modified version of anubhava's answer, using a [backreference](https://www.regular-expressions.info/backref.html) (which works in Python, and is easier to understand at least for me) instead of a forward reference.
Match using `[abc]` inside a capturing group, then check that the text matched by the capturing group does not appear again anywhere after it:
```
^foo(?:( [abc])(?!.*\1))+$
```
[regex demo](https://regex101.com/r/otEzZP/1)
* `^`: Start
* `foo`: Match `foo`
* `(?:`: Start non-capturing group `(?:( [abc])(?!.*\1))`
+ `( [abc])`: Capturing Group 1, matching a space followed by either `a`, `b`, or `c`
+ `(?!.*\1)`: Negative lookahead, failing to match if the text matched by the first capturing group occurs after zero or more characters matched by `.`
* `)+`: End non-capturing group and match it 1 or more times
* `$`: End | If the order of the strings doesn't matter, and you want to make sure every string occurs only once, you can turn the list into a set in Python:
```
my_lst = ['a', 'a', 'b', 'c']
my_set = set(lst)
print(my_set)
# {'a', 'c', 'b'}
``` |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, but
```
foo b b
```
would not be | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | If it doesn't have to be a regex:
```py
import collections
# python >=3.10
def is_a_match(sentence):
words = sentence.split()
return (
(len(words) > 0)
and (words[0] == 'foo')
and (collections.Counter(words) <= collections.Counter(['foo', 'a', 'b', 'c']))
)
# python <3.10
def is_a_match(sentence):
words = sentence.split()
return (
(len(words) > 0)
and (words[0] == 'foo')
and not (collections.Counter(words) - collections.Counter(['foo', 'a', 'b', 'c']))
)
# TESTING
#foo a b c True
#foo b c a True
#foo a b True
#foo b True
#foo b b False
```
Or with a set and the walrus operator:
```py
def is_a_match(sentence):
words = sentence.split()
return (
(len(words) > 0)
and (words[0] == 'foo')
and (
(s := set(words[1:])) <= set(['a', 'b', 'c'])
and len(s) == len(words) - 1
)
)
``` | If the order of the strings doesn't matter, and you want to make sure every string occurs only once, you can turn the list into a set in Python:
```
my_lst = ['a', 'a', 'b', 'c']
my_set = set(lst)
print(my_set)
# {'a', 'c', 'b'}
``` |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, but
```
foo b b
```
would not be | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | I have assumed that the elements of the string can be in any order and appear any number of times. For example, `'a foo'` should match and `'a foo b foo'` should not.
You can do that with a series of alternations employing lookaheads, one for each substring of interest, but it becomes a bit of a dog's breakfast when there are many strings to consider. Let's suppose you wanted to match zero or one `"foo"`'s and/or zero or one `"a"`'s. You could use the following regular expression:
```
^(?:(?!.*\bfoo\b)|(?=(?:(?!\bfoo\b).)*\bfoo\b(?!(.*\bfoo\b))))(?:(?!.*\ba\b)|(?=(?:(?!\ba\b).)*\ba\b(?!(.*\ba\b))))
```
[Start your engine!](https://regex101.com/r/sOBFj4/1)
This matches, for example, `'foofoo'`, `'aa'` and `afooa`. If they are not to be matched remove the word breaks (`\b`).
Notice that this expression begins by asserting the start of the string (`^`) followed by two positive lookaheads, one for `'foo'` and one for `'a'`. To also check for, say, `'c'` one would tack on
```
(?:(?!.*\bc\b)|(?=(?:(?!\bc\b).)*\bc\b(?!(.*\bc\b))))
```
which is the same as
```
(?:(?!.*\ba\b)|(?=(?:(?!\ba\b).)*\ba\b(?!(.*\ba\b))))
```
with `\ba\b` changed to `\bc\b`.
It would be nice to be able to use back-references but I don't see how that could be done.
By hovering over the regular expression in the link an explanation is provided for each element of the expression. (If this is not clear I am referring to the cursor.)
Note that
```
(?!\bfoo\b).
```
matches a character provided it does not begin the word `'foo'`. Therefore
```
(?:(?!\bfoo\b).)*
```
matches a substring that does not contain `'foo'` and does not end with `'f'` followed by `'oo'`.
Would I advocate this approach in practice, as opposed to using simple string methods? Let me ponder that. | There is not much to add to the above answers except here is a regex that does not use back or forward references. Instead it uses 3 separate negative lookahead assertions to ensure that the input does not contain 2 occurrences of either `a` or `b` or `c`. The regex also allows for liberal uses of spaces.
```
^foo(?![^a]*a[^a]*a)(?![^b]*b[^b]*b)(?![^c]*c[^c]*c)( +[abc])* *$
```
[See Regex Demo](https://regex101.com/r/6UReEn/1/)
1. `^` - Matches start of string
2. `(?![^a]*a[^a]*a)` - Negative lookahead assertion that what follows does not contain two occurrences of `a`
3. `(?![^b]*b[^b]*b)` - Negative lookahead assertion that what follows does not contain two occurrences of `b`
4. `(?![^c]*c[^c]*c)` - Negative lookahead assertion that what follows does not contain two occurrences of `c`
5. `( +[abc])*` - Matches 0 or more occurrences of: 1 or more spaces followed by an `a` or `b` or `c`
6. `*` - Matches 0 or more occurrences of space
7 `$` - Matches the end of the string
The regex looks "clunky" but is very straightforward. With input `foo a b c` the successful match is done in 35 steps and with input `foo b b` the unsuccessful match is done in 13 steps. Thich compares favorably with the other answers. |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, but
```
foo b b
```
would not be | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | You can assert that there is no match for a second match for a space and a letter at the right:
```
foo(?!(?: [abc])*( [abc])(?: [abc])*\1)(?: [abc])*
```
* `foo` Match literally
* `(?!` Negative lookahead
+ `(?: [abc])*` Match optional repetitions of a space and a b or c
+ `( [abc])` Capture group, use to compare with a backreference for the same
+ `(?: [abc])*` Match again a space and either a b or c
+ `\1` Backreference to group 1
* `)` Close lookahead
* `(?: [abc])*` Match optional repetitions or a space and either a b or c
[Regex demo](https://regex101.com/r/E778Ef/1)
If you don't want to match only foo, you can change the quantifier to 1 or more `(?: [abc])+`
---
A variant in perl reusing the first subpattern using `(?1)` which refers to the capture group `([abc])`
```
^foo ([abc])(?: (?!\1)((?1))(?: (?!\1|\2)(?1))?)?$
```
[Regex demo](https://regex101.com/r/pkLEn9/1) | I have assumed that the elements of the string can be in any order and appear any number of times. For example, `'a foo'` should match and `'a foo b foo'` should not.
You can do that with a series of alternations employing lookaheads, one for each substring of interest, but it becomes a bit of a dog's breakfast when there are many strings to consider. Let's suppose you wanted to match zero or one `"foo"`'s and/or zero or one `"a"`'s. You could use the following regular expression:
```
^(?:(?!.*\bfoo\b)|(?=(?:(?!\bfoo\b).)*\bfoo\b(?!(.*\bfoo\b))))(?:(?!.*\ba\b)|(?=(?:(?!\ba\b).)*\ba\b(?!(.*\ba\b))))
```
[Start your engine!](https://regex101.com/r/sOBFj4/1)
This matches, for example, `'foofoo'`, `'aa'` and `afooa`. If they are not to be matched remove the word breaks (`\b`).
Notice that this expression begins by asserting the start of the string (`^`) followed by two positive lookaheads, one for `'foo'` and one for `'a'`. To also check for, say, `'c'` one would tack on
```
(?:(?!.*\bc\b)|(?=(?:(?!\bc\b).)*\bc\b(?!(.*\bc\b))))
```
which is the same as
```
(?:(?!.*\ba\b)|(?=(?:(?!\ba\b).)*\ba\b(?!(.*\ba\b))))
```
with `\ba\b` changed to `\bc\b`.
It would be nice to be able to use back-references but I don't see how that could be done.
By hovering over the regular expression in the link an explanation is provided for each element of the expression. (If this is not clear I am referring to the cursor.)
Note that
```
(?!\bfoo\b).
```
matches a character provided it does not begin the word `'foo'`. Therefore
```
(?:(?!\bfoo\b).)*
```
matches a substring that does not contain `'foo'` and does not end with `'f'` followed by `'oo'`.
Would I advocate this approach in practice, as opposed to using simple string methods? Let me ponder that. |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, but
```
foo b b
```
would not be | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | You can assert that there is no match for a second match for a space and a letter at the right:
```
foo(?!(?: [abc])*( [abc])(?: [abc])*\1)(?: [abc])*
```
* `foo` Match literally
* `(?!` Negative lookahead
+ `(?: [abc])*` Match optional repetitions of a space and a b or c
+ `( [abc])` Capture group, use to compare with a backreference for the same
+ `(?: [abc])*` Match again a space and either a b or c
+ `\1` Backreference to group 1
* `)` Close lookahead
* `(?: [abc])*` Match optional repetitions or a space and either a b or c
[Regex demo](https://regex101.com/r/E778Ef/1)
If you don't want to match only foo, you can change the quantifier to 1 or more `(?: [abc])+`
---
A variant in perl reusing the first subpattern using `(?1)` which refers to the capture group `([abc])`
```
^foo ([abc])(?: (?!\1)((?1))(?: (?!\1|\2)(?1))?)?$
```
[Regex demo](https://regex101.com/r/pkLEn9/1) | Here is a modified version of anubhava's answer, using a [backreference](https://www.regular-expressions.info/backref.html) (which works in Python, and is easier to understand at least for me) instead of a forward reference.
Match using `[abc]` inside a capturing group, then check that the text matched by the capturing group does not appear again anywhere after it:
```
^foo(?:( [abc])(?!.*\1))+$
```
[regex demo](https://regex101.com/r/otEzZP/1)
* `^`: Start
* `foo`: Match `foo`
* `(?:`: Start non-capturing group `(?:( [abc])(?!.*\1))`
+ `( [abc])`: Capturing Group 1, matching a space followed by either `a`, `b`, or `c`
+ `(?!.*\1)`: Negative lookahead, failing to match if the text matched by the first capturing group occurs after zero or more characters matched by `.`
* `)+`: End non-capturing group and match it 1 or more times
* `$`: End |
69,486,648 | I'm wondering if there's any way in python or perl to build a regex where you can define a set of options can appear at most once in any order. So for example I would like a derivative of `foo(?: [abc])*`, where `a`, `b`, `c` could only appear once. So:
```
foo a b c
foo b c a
foo a b
foo b
```
would all be valid, but
```
foo b b
```
would not be | 2021/10/07 | [
"https://Stackoverflow.com/questions/69486648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8710344/"
] | You may use this regex with a capture group and a negative lookahead:
For `Perl`, you can use this variant with [forward referencing](https://www.regular-expressions.info/backref2.html):
```sh
^foo((?!.*\1) [abc])+$
```
[RegEx Demo](https://regex101.com/r/P9Qp9r/2)
**RegEx Details:**
* `^`: Start
* `foo`: Match `foo`
* `(`: Start a capture group #1
+ `(?!.*\1)`: Negative lookahead to assert that we don't match what we have in capture group #1 anywhere in input
+ `[abc]`: Match a space followed by `a` or `b` or `c`
* `)+`: End capture group #1. Repeat this group 1+ times
* `$`: End
As mentioned earlier, this regex is using a feature called **Forward Referencing** which is a back-reference to a group that **appears later in the regex pattern**. JGsoft, .NET, Java, Perl, PCRE, PHP, Delphi, and Ruby allow forward references but Python doesn't.
---
Here is a **work-around of same regex for Python** that doesn't use forward referencing:
```sh
^foo(?!.* ([abc]).*\1)(?: [abc])+$
```
Here we use a negative lookahead before repeated group to check and fail the match if there is any repeat of allowed substrings i.e. `[abc]`.
[RegEx Demo 2](https://regex101.com/r/P9Qp9r/3) | There is not much to add to the above answers except here is a regex that does not use back or forward references. Instead it uses 3 separate negative lookahead assertions to ensure that the input does not contain 2 occurrences of either `a` or `b` or `c`. The regex also allows for liberal uses of spaces.
```
^foo(?![^a]*a[^a]*a)(?![^b]*b[^b]*b)(?![^c]*c[^c]*c)( +[abc])* *$
```
[See Regex Demo](https://regex101.com/r/6UReEn/1/)
1. `^` - Matches start of string
2. `(?![^a]*a[^a]*a)` - Negative lookahead assertion that what follows does not contain two occurrences of `a`
3. `(?![^b]*b[^b]*b)` - Negative lookahead assertion that what follows does not contain two occurrences of `b`
4. `(?![^c]*c[^c]*c)` - Negative lookahead assertion that what follows does not contain two occurrences of `c`
5. `( +[abc])*` - Matches 0 or more occurrences of: 1 or more spaces followed by an `a` or `b` or `c`
6. `*` - Matches 0 or more occurrences of space
7 `$` - Matches the end of the string
The regex looks "clunky" but is very straightforward. With input `foo a b c` the successful match is done in 35 steps and with input `foo b b` the unsuccessful match is done in 13 steps. Thich compares favorably with the other answers. |
2,313,032 | I am trying to create a regex that matches a US state abbreviations in a string using python.
The abbreviation can be in the format:
```
CA
Ca
```
The string could be:
```
Boulder, CO 80303
Boulder, Co
Boulder CO
...
```
Here is what I have, which obviously doesn't work that well. I'm not very good with regular expressions and google didn't turn up much.
```
pat = re.compile("[A-Za-z]{2}")
st = pat.search(str)
stateAbb = st.group(0)
``` | 2010/02/22 | [
"https://Stackoverflow.com/questions/2313032",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/74474/"
] | A simple and reliable way is to have all the states listed:
```
states = ['IA', 'KS', 'UT', 'VA', 'NC', 'NE', 'SD', 'AL', 'ID', 'FM', 'DE', 'AK', 'CT', 'PR', 'NM', 'MS', 'PW', 'CO', 'NJ', 'FL', 'MN', 'VI', 'NV', 'AZ', 'WI', 'ND', 'PA', 'OK', 'KY', 'RI', 'NH', 'MO', 'ME', 'VT', 'GA', 'GU', 'AS', 'NY', 'CA', 'HI', 'IL', 'TN', 'MA', 'OH', 'MD', 'MI', 'WY', 'WA', 'OR', 'MH', 'SC', 'IN', 'LA', 'MP', 'DC', 'MT', 'AR', 'WV', 'TX']
regex = re.compile(r'\b(' + '|'.join(states) + r')\b', re.IGNORECASE)
```
Use another state list if you want non-US states. | ```
re.search(r'\b[a-z]{2}\b', subject, re.I)
```
it will find double-letter names of towns, though |
42,244,819 | My objective is to insert a key value pair in a YAML file which might be empty.
For example, my `hiera.yaml` (used in puppet) file contains only three hyphens.
Here is my code:
```
#!/usr/bin/python
import ruamel.yaml
import sys
def read_file(f):
with open(f, 'r') as yaml:
return ruamel.yaml.round_trip_load(yaml)
dict = {}
dict['first_name'] = sys.argv[1]
dict['last_name'] = sys.argv[2]
dict['role'] = sys.argv[3]
data = read_file('hiera.yaml')
pos = len(data)
data.insert(pos, sys.argv[1], dict, None)
ruamel.yaml.round_trip_dump(data, open('hiera.yaml', 'w'), block_seq_indent=1)
```
I am running it like:
./alice.py Alice Doe Developer
I get an output like:
```
Traceback (most recent call last):
File "./alice.py", line 16, in <module>
pos = len(data)
TypeError: object of type 'NoneType' has no len()
```
But when my hiera.yaml file is not empty, for example:
```
$ cat hiera.yaml
john:
$./alice.py Alice Doe Developer
$ cat hiera.yaml
john:
alice:
first_name: Alice
last_name: Doe
role: Developer
```
Then it works properly.
Please tell me how to insert a key value pair(in my case a dict) to an empty YAML file. The examples of ruamel.yaml official page use doc string as a sample YAML content and then insert key-value pairs. | 2017/02/15 | [
"https://Stackoverflow.com/questions/42244819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7543970/"
] | If you indeed want to get all the data into a single string you can do it using collect:
```
val rows = df.select("defectDescription").collect().map(_.getString(0)).mkString(" ")
```
You first select the relevant column (so you have just it) and collect it, it would give you an array of rows. the map turns each row to the string (there is just one column - 0). Then mkString would make an overall string of them with a space as the separator.
Note that this would bring the entire dataframe to the driver which might cause memory exceptions. If you need just some of the data you can use take(n) instead of collect to limit the number of rows to n. | ```
val str1 = df.select("defectDescription").collect.mkString(",")
val str = str1.replaceAll("[\\[\\]]","")
```
Another way to do this is as follows:
The 1st line selects the particular columns then collects the subset, collects behaves as:
Collect (Action) - Return all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data.
mkString - mkString method has an overloaded method which allows you to provide a delimiter to separate each element in the collection.
The 2nd line just replaces the additional brackets |
42,244,819 | My objective is to insert a key value pair in a YAML file which might be empty.
For example, my `hiera.yaml` (used in puppet) file contains only three hyphens.
Here is my code:
```
#!/usr/bin/python
import ruamel.yaml
import sys
def read_file(f):
with open(f, 'r') as yaml:
return ruamel.yaml.round_trip_load(yaml)
dict = {}
dict['first_name'] = sys.argv[1]
dict['last_name'] = sys.argv[2]
dict['role'] = sys.argv[3]
data = read_file('hiera.yaml')
pos = len(data)
data.insert(pos, sys.argv[1], dict, None)
ruamel.yaml.round_trip_dump(data, open('hiera.yaml', 'w'), block_seq_indent=1)
```
I am running it like:
./alice.py Alice Doe Developer
I get an output like:
```
Traceback (most recent call last):
File "./alice.py", line 16, in <module>
pos = len(data)
TypeError: object of type 'NoneType' has no len()
```
But when my hiera.yaml file is not empty, for example:
```
$ cat hiera.yaml
john:
$./alice.py Alice Doe Developer
$ cat hiera.yaml
john:
alice:
first_name: Alice
last_name: Doe
role: Developer
```
Then it works properly.
Please tell me how to insert a key value pair(in my case a dict) to an empty YAML file. The examples of ruamel.yaml official page use doc string as a sample YAML content and then insert key-value pairs. | 2017/02/15 | [
"https://Stackoverflow.com/questions/42244819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7543970/"
] | If you indeed want to get all the data into a single string you can do it using collect:
```
val rows = df.select("defectDescription").collect().map(_.getString(0)).mkString(" ")
```
You first select the relevant column (so you have just it) and collect it, it would give you an array of rows. the map turns each row to the string (there is just one column - 0). Then mkString would make an overall string of them with a space as the separator.
Note that this would bring the entire dataframe to the driver which might cause memory exceptions. If you need just some of the data you can use take(n) instead of collect to limit the number of rows to n. | ```
df.createTempView(viewName="table")
val res=spark.sqlContext.sql(sqlText="select defectDescription from table").collectAsList.toString.replace("[", "").replace("]", "")
```
Initially create a temporary view of the dataframe, then convert into a list, and then string- Finally remove the brackets as per the required output. |
42,244,819 | My objective is to insert a key value pair in a YAML file which might be empty.
For example, my `hiera.yaml` (used in puppet) file contains only three hyphens.
Here is my code:
```
#!/usr/bin/python
import ruamel.yaml
import sys
def read_file(f):
with open(f, 'r') as yaml:
return ruamel.yaml.round_trip_load(yaml)
dict = {}
dict['first_name'] = sys.argv[1]
dict['last_name'] = sys.argv[2]
dict['role'] = sys.argv[3]
data = read_file('hiera.yaml')
pos = len(data)
data.insert(pos, sys.argv[1], dict, None)
ruamel.yaml.round_trip_dump(data, open('hiera.yaml', 'w'), block_seq_indent=1)
```
I am running it like:
./alice.py Alice Doe Developer
I get an output like:
```
Traceback (most recent call last):
File "./alice.py", line 16, in <module>
pos = len(data)
TypeError: object of type 'NoneType' has no len()
```
But when my hiera.yaml file is not empty, for example:
```
$ cat hiera.yaml
john:
$./alice.py Alice Doe Developer
$ cat hiera.yaml
john:
alice:
first_name: Alice
last_name: Doe
role: Developer
```
Then it works properly.
Please tell me how to insert a key value pair(in my case a dict) to an empty YAML file. The examples of ruamel.yaml official page use doc string as a sample YAML content and then insert key-value pairs. | 2017/02/15 | [
"https://Stackoverflow.com/questions/42244819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7543970/"
] | If you indeed want to get all the data into a single string you can do it using collect:
```
val rows = df.select("defectDescription").collect().map(_.getString(0)).mkString(" ")
```
You first select the relevant column (so you have just it) and collect it, it would give you an array of rows. the map turns each row to the string (there is just one column - 0). Then mkString would make an overall string of them with a space as the separator.
Note that this would bring the entire dataframe to the driver which might cause memory exceptions. If you need just some of the data you can use take(n) instead of collect to limit the number of rows to n. | Let's leverage parallel computing by not prematurely `collect`ing the data while there is associative processing to be done:
```
def str(r: Row) = r.getString(0)
def cat(r0: Row, r1: Row) = Row(s"${str(r0)} ${str(r1)}")
str(df.select("defectDescription").reduce(cat))
```
This allows parallel concatenations to be done on all executors before concatenating their results in the driver. |
42,244,819 | My objective is to insert a key value pair in a YAML file which might be empty.
For example, my `hiera.yaml` (used in puppet) file contains only three hyphens.
Here is my code:
```
#!/usr/bin/python
import ruamel.yaml
import sys
def read_file(f):
with open(f, 'r') as yaml:
return ruamel.yaml.round_trip_load(yaml)
dict = {}
dict['first_name'] = sys.argv[1]
dict['last_name'] = sys.argv[2]
dict['role'] = sys.argv[3]
data = read_file('hiera.yaml')
pos = len(data)
data.insert(pos, sys.argv[1], dict, None)
ruamel.yaml.round_trip_dump(data, open('hiera.yaml', 'w'), block_seq_indent=1)
```
I am running it like:
./alice.py Alice Doe Developer
I get an output like:
```
Traceback (most recent call last):
File "./alice.py", line 16, in <module>
pos = len(data)
TypeError: object of type 'NoneType' has no len()
```
But when my hiera.yaml file is not empty, for example:
```
$ cat hiera.yaml
john:
$./alice.py Alice Doe Developer
$ cat hiera.yaml
john:
alice:
first_name: Alice
last_name: Doe
role: Developer
```
Then it works properly.
Please tell me how to insert a key value pair(in my case a dict) to an empty YAML file. The examples of ruamel.yaml official page use doc string as a sample YAML content and then insert key-value pairs. | 2017/02/15 | [
"https://Stackoverflow.com/questions/42244819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7543970/"
] | ```
val str1 = df.select("defectDescription").collect.mkString(",")
val str = str1.replaceAll("[\\[\\]]","")
```
Another way to do this is as follows:
The 1st line selects the particular columns then collects the subset, collects behaves as:
Collect (Action) - Return all the elements of the dataset as an array at the driver program. This is usually useful after a filter or other operation that returns a sufficiently small subset of the data.
mkString - mkString method has an overloaded method which allows you to provide a delimiter to separate each element in the collection.
The 2nd line just replaces the additional brackets | Let's leverage parallel computing by not prematurely `collect`ing the data while there is associative processing to be done:
```
def str(r: Row) = r.getString(0)
def cat(r0: Row, r1: Row) = Row(s"${str(r0)} ${str(r1)}")
str(df.select("defectDescription").reduce(cat))
```
This allows parallel concatenations to be done on all executors before concatenating their results in the driver. |
42,244,819 | My objective is to insert a key value pair in a YAML file which might be empty.
For example, my `hiera.yaml` (used in puppet) file contains only three hyphens.
Here is my code:
```
#!/usr/bin/python
import ruamel.yaml
import sys
def read_file(f):
with open(f, 'r') as yaml:
return ruamel.yaml.round_trip_load(yaml)
dict = {}
dict['first_name'] = sys.argv[1]
dict['last_name'] = sys.argv[2]
dict['role'] = sys.argv[3]
data = read_file('hiera.yaml')
pos = len(data)
data.insert(pos, sys.argv[1], dict, None)
ruamel.yaml.round_trip_dump(data, open('hiera.yaml', 'w'), block_seq_indent=1)
```
I am running it like:
./alice.py Alice Doe Developer
I get an output like:
```
Traceback (most recent call last):
File "./alice.py", line 16, in <module>
pos = len(data)
TypeError: object of type 'NoneType' has no len()
```
But when my hiera.yaml file is not empty, for example:
```
$ cat hiera.yaml
john:
$./alice.py Alice Doe Developer
$ cat hiera.yaml
john:
alice:
first_name: Alice
last_name: Doe
role: Developer
```
Then it works properly.
Please tell me how to insert a key value pair(in my case a dict) to an empty YAML file. The examples of ruamel.yaml official page use doc string as a sample YAML content and then insert key-value pairs. | 2017/02/15 | [
"https://Stackoverflow.com/questions/42244819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7543970/"
] | ```
df.createTempView(viewName="table")
val res=spark.sqlContext.sql(sqlText="select defectDescription from table").collectAsList.toString.replace("[", "").replace("]", "")
```
Initially create a temporary view of the dataframe, then convert into a list, and then string- Finally remove the brackets as per the required output. | Let's leverage parallel computing by not prematurely `collect`ing the data while there is associative processing to be done:
```
def str(r: Row) = r.getString(0)
def cat(r0: Row, r1: Row) = Row(s"${str(r0)} ${str(r1)}")
str(df.select("defectDescription").reduce(cat))
```
This allows parallel concatenations to be done on all executors before concatenating their results in the driver. |
60,311,694 | I'm taking a look at some parser combinator libraries in Python ([Parsy](https://parsy.readthedocs.io/en/latest/index.html) to be more precise) and I'm currently faced with the following problem, simplified with a minimally working example below:
```py
text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TEXT HERE SHOULD
BE CAPTURED STOP CCCCCCCCCC CCCCCC
'''
start, stop = r"STARTS?", r"STOPS?"
s = section(text, start, stop)
print(s)
```
which should output:
```
THE TEXT HERE SHOULD
BE CAPTURED
```
The current solution I'm working is by doing a regex lookahead, it works fine, but my original problem involves combining many of these little regexes, which can get messy and a problem for others to maintain later.
```py
from typing import Pattern, TypeVar
import re
# A Generic type declaration.
T = TypeVar("T")
def first(text: str, pattern: str, default: T, flags=0) -> T:
"""
Given a `text`, a regex `pattern` and a `default` value, return the first match
in `text`. Otherwise return a `default` value if no match is found.
"""
match = re.findall(pattern, text, flags=flags)
return match[0] if len(match) > 0 else default
def section(text: str, begin: str, end: str) -> str:
"""
Given a `text` and two `start` and `stop` regexes, return the captured group
found in the interval. Otherwise, return an empty string if no match is found.
"""
return first(text, fr"{begin}([\s\S]*?)(?={end})", default="")
```
Parser Combinators seem to be perfect for situations like these, but I'm unable to reproduce the same behavior as the working solution, any hints would be welcome:
```
# A Simpler example with hardcoded stuff
from parsy import regex, seq, string
text = '''
AAAAAAAAAA AAAAAAAA AAAAAAAAAAAAAA
BBBBBBB START THE TEXT HERE SHOULD
BE CAPTURED STOP CCCCCCCCCC CCCCCC
'''
start = regex(r"STARTS?")
middle = regex(r"[\s\S]*").optional()
stop = regex(r"STOPS?")
eol = string("\n")
# Work fine
start.parse("START")
middle.parse("")
stop.parse("STOP")
section = seq(
start,
middle,
stop
)
# Simpler case, breaks
section.parse("START AAA STOP")
```
Gives:
```
---------------------------------------------------------------------------
ParseError Traceback (most recent call last)
<ipython-input-260-fdec112e1648> in <module>
24 )
25 # Simpler case, breaks
---> 26 section.parse("START AAA STOP")
~/.venv/lib/python3.8/site-packages/parsy/__init__.py in parse(self, stream)
88 def parse(self, stream):
89 """Parse a string or list of tokens and return the result or raise a ParseError."""
---> 90 (result, _) = (self << eof).parse_partial(stream)
91 return result
92
~/.venv/lib/python3.8/site-packages/parsy/__init__.py in parse_partial(self, stream)
102 return (result.value, stream[result.index:])
103 else:
--> 104 raise ParseError(result.expected, stream, result.furthest)
105
106 def bind(self, bind_fn):
ParseError: expected 'STOPS?' at 0:14
``` | 2020/02/20 | [
"https://Stackoverflow.com/questions/60311694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4614840/"
] | There was an issue related to the routing in the application. I had a parser inside the controller that was used for directing correct routes between a route "aluno" with first Param.
Once I had taken the route with no params and put it first at the controller, there was no need anymore for the parser, and the issue was gone. Hope this answer helps more people if they get the same problem. | Please check your method result type of controller
Change this:
```
@Contoller()
export class MyController {
// ...
async myMethod() {
return {}
}
}
```
to:
```
@Contoller()
export class MyController {
// ...
async myMethod():Promise<any> {
return {}
}
}
``` |
27,708,882 | I have two Anaconda installations on my computer. The first one is based on Python 2.7 and the other is based on Python 3.4. The default Python version is the 3.4 though. What is more, I can start Python 3.4 either by typing **/home/eualin/.bin/anaconda3/bin/python** or just **python**. I can do the same but for Python 2.7 by typing **/home/eualin/.bin/anaconda2/bin/python**. My problem is that I don't know how to install new libraries under certain environments (either under Python 2.7 or Python 3.4). For example, when I do pip install seaborn the library gets installed under Python 3.4 by default when in fact I want to install it under Python 2.7. Any ideas?
**EDIT**
This is what I am doing so far: the ~/.bashrc file contains the following two blocks, of which only one is enabled at any given time.
```
# added by Anaconda 2.1.0 installer
export PATH="/home/eualin/.bin/anaconda2/bin:$PATH"
# added by Anaconda3 2.1.0 installer
#export PATH="/home/eualin/.bin/anaconda3/bin:$PATH"
```
Depending of which version I want to work, I open the fie, comment the opposite block and do `source ~/.bashrc` Then, I install the libraries I want to use one by one. But, is this the recommended way? | 2014/12/30 | [
"https://Stackoverflow.com/questions/27708882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706838/"
] | You don't need multiple `anaconda` distributions for different python versions. I would suggest keeping only one.
`conda` basically lets you create environments for your different needs.
`conda create -n myenv python=3.3` creates a new environment named `myenv`, which works with a python3.3 interpreter.
`source activate myenv` switches to the newly created environment. This basically sets the `PATH` such that `pip`, `conda`, `python` and other binaries point to the correct environment and interpreter.
`conda install pip` is the first thing you may want to do. Afterwards you can use `pip` and `conda` to install the packages you need.
After activating your environment `pip install <mypackage>` will point to the right version of `pip` so no need to worry too much.
You may want to create environments for different python versions or different sets of packages. Of course you can easily switch between those environments using `source activate <environment name>`.
For more examples and details you may want to have a look at the [docs](http://conda.pydata.org/docs/). | Using virtualenv is your best option as @Dettorer has mentioned.
I found this method of installing and using virtualenv the most useful.
Check it out:
[Proper way to install virtualenv](https://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python) |
27,708,882 | I have two Anaconda installations on my computer. The first one is based on Python 2.7 and the other is based on Python 3.4. The default Python version is the 3.4 though. What is more, I can start Python 3.4 either by typing **/home/eualin/.bin/anaconda3/bin/python** or just **python**. I can do the same but for Python 2.7 by typing **/home/eualin/.bin/anaconda2/bin/python**. My problem is that I don't know how to install new libraries under certain environments (either under Python 2.7 or Python 3.4). For example, when I do pip install seaborn the library gets installed under Python 3.4 by default when in fact I want to install it under Python 2.7. Any ideas?
**EDIT**
This is what I am doing so far: the ~/.bashrc file contains the following two blocks, of which only one is enabled at any given time.
```
# added by Anaconda 2.1.0 installer
export PATH="/home/eualin/.bin/anaconda2/bin:$PATH"
# added by Anaconda3 2.1.0 installer
#export PATH="/home/eualin/.bin/anaconda3/bin:$PATH"
```
Depending of which version I want to work, I open the fie, comment the opposite block and do `source ~/.bashrc` Then, I install the libraries I want to use one by one. But, is this the recommended way? | 2014/12/30 | [
"https://Stackoverflow.com/questions/27708882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706838/"
] | You don't need multiple `anaconda` distributions for different python versions. I would suggest keeping only one.
`conda` basically lets you create environments for your different needs.
`conda create -n myenv python=3.3` creates a new environment named `myenv`, which works with a python3.3 interpreter.
`source activate myenv` switches to the newly created environment. This basically sets the `PATH` such that `pip`, `conda`, `python` and other binaries point to the correct environment and interpreter.
`conda install pip` is the first thing you may want to do. Afterwards you can use `pip` and `conda` to install the packages you need.
After activating your environment `pip install <mypackage>` will point to the right version of `pip` so no need to worry too much.
You may want to create environments for different python versions or different sets of packages. Of course you can easily switch between those environments using `source activate <environment name>`.
For more examples and details you may want to have a look at the [docs](http://conda.pydata.org/docs/). | Virtualenv seems like the obvious answer here, but I do want to suggest an alternative that we've been using to great effect lately: [Fig](http://www.fig.sh/) - this is particularly effective since we use Docker in production as well, but I imagine that using Fig as a replacement for virtualenv would be quite effective regardless of your production environment. |
27,708,882 | I have two Anaconda installations on my computer. The first one is based on Python 2.7 and the other is based on Python 3.4. The default Python version is the 3.4 though. What is more, I can start Python 3.4 either by typing **/home/eualin/.bin/anaconda3/bin/python** or just **python**. I can do the same but for Python 2.7 by typing **/home/eualin/.bin/anaconda2/bin/python**. My problem is that I don't know how to install new libraries under certain environments (either under Python 2.7 or Python 3.4). For example, when I do pip install seaborn the library gets installed under Python 3.4 by default when in fact I want to install it under Python 2.7. Any ideas?
**EDIT**
This is what I am doing so far: the ~/.bashrc file contains the following two blocks, of which only one is enabled at any given time.
```
# added by Anaconda 2.1.0 installer
export PATH="/home/eualin/.bin/anaconda2/bin:$PATH"
# added by Anaconda3 2.1.0 installer
#export PATH="/home/eualin/.bin/anaconda3/bin:$PATH"
```
Depending of which version I want to work, I open the fie, comment the opposite block and do `source ~/.bashrc` Then, I install the libraries I want to use one by one. But, is this the recommended way? | 2014/12/30 | [
"https://Stackoverflow.com/questions/27708882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/706838/"
] | Virtualenv seems like the obvious answer here, but I do want to suggest an alternative that we've been using to great effect lately: [Fig](http://www.fig.sh/) - this is particularly effective since we use Docker in production as well, but I imagine that using Fig as a replacement for virtualenv would be quite effective regardless of your production environment. | Using virtualenv is your best option as @Dettorer has mentioned.
I found this method of installing and using virtualenv the most useful.
Check it out:
[Proper way to install virtualenv](https://stackoverflow.com/questions/4324558/whats-the-proper-way-to-install-pip-virtualenv-and-distribute-for-python) |
18,730,612 | I want to run both a websocket and a flash policy file server on port 80 using Tornado. The reason for not wanting to run a server on the default port 843 is that it's often closed in corporate networks. Is it possible to do this and if so, how should I do this?
I tried the following structure, which does not seem to work: the websocket connection works, but the policy file request is not routed to the `TCPHandler`.
```
#!/usr/bin/python
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.gen
from tornado.options import define, options
from tornado.tcpserver import TCPServer
define("port", default=80, help="run on the given port", type=int)
class FlashPolicyServer(TCPServer):
def handle_stream(self, stream, address):
self._stream = stream
self._read_line()
def _read_line(self):
self._stream.read_until('\n', self._handle_read)
def _handle_read(self, data):
policyFile = ""
self._stream.write(policyFile)
self._read_line()
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
pass
def on_message(self, message):
pass
def on_close(self):
pass
def main():
tornado.options.parse_command_line()
mainLoop = tornado.ioloop.IOLoop.instance()
app = tornado.web.Application(
handlers=[
(r"/websocket", WebSocketHandler),
(r"/", FlashPolicyServer)
], main_loop=mainLoop
)
httpServer = tornado.httpserver.HTTPServer(app)
httpServer.listen(options.port)
mainLoop.start()
if __name__ == "__main__":
main()
```
Any ideas? If this is not possible, would another idea be to serve the policy file via port 443? | 2013/09/10 | [
"https://Stackoverflow.com/questions/18730612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2259361/"
] | the new formula become L= P / [(1+c)^n-1]/[c(1+c)^n]
let me work this out for you. To add L to the other side you have to multiple by 1/L. so now the left side of the equation is P/L. to get rid of the P you have to multiple 1/P. now leaving the L alone makes the L into a ratio of 1/L. To get rid of the one you have to reverse the equationon the right side. so you get the new formula above. | Your monthly payment isn't being calculated correctly in the code that isn't working properly. If you look at it, you'll see that you're not factoring in your debts whatsoever.
I'm not sure exactly how you're choosing to calculate the monthly payment, but my guess is you need to subtract your debts from your income and then do your ceiling math, maybe something like this:
```
var debt_ceiling = (income - debts) * .92;
var monthly_payment = (debt_ceiling * .28).toFixed(2);
```
Or something like that... but in there is your error, I think. |
18,730,612 | I want to run both a websocket and a flash policy file server on port 80 using Tornado. The reason for not wanting to run a server on the default port 843 is that it's often closed in corporate networks. Is it possible to do this and if so, how should I do this?
I tried the following structure, which does not seem to work: the websocket connection works, but the policy file request is not routed to the `TCPHandler`.
```
#!/usr/bin/python
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.gen
from tornado.options import define, options
from tornado.tcpserver import TCPServer
define("port", default=80, help="run on the given port", type=int)
class FlashPolicyServer(TCPServer):
def handle_stream(self, stream, address):
self._stream = stream
self._read_line()
def _read_line(self):
self._stream.read_until('\n', self._handle_read)
def _handle_read(self, data):
policyFile = ""
self._stream.write(policyFile)
self._read_line()
class WebSocketHandler(tornado.websocket.WebSocketHandler):
def open(self):
pass
def on_message(self, message):
pass
def on_close(self):
pass
def main():
tornado.options.parse_command_line()
mainLoop = tornado.ioloop.IOLoop.instance()
app = tornado.web.Application(
handlers=[
(r"/websocket", WebSocketHandler),
(r"/", FlashPolicyServer)
], main_loop=mainLoop
)
httpServer = tornado.httpserver.HTTPServer(app)
httpServer.listen(options.port)
mainLoop.start()
if __name__ == "__main__":
main()
```
Any ideas? If this is not possible, would another idea be to serve the policy file via port 443? | 2013/09/10 | [
"https://Stackoverflow.com/questions/18730612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2259361/"
] | the new formula become L= P / [(1+c)^n-1]/[c(1+c)^n]
let me work this out for you. To add L to the other side you have to multiple by 1/L. so now the left side of the equation is P/L. to get rid of the P you have to multiple 1/P. now leaving the L alone makes the L into a ratio of 1/L. To get rid of the one you have to reverse the equationon the right side. so you get the new formula above. | Semi-Solved:
The issue was with my formula and a colleague and I figured out the major problem. When I converted the original formula (which I didn't outline in very good detail here), I didn't perform the proper algebraic method of reversing what was done to one side of the equation on the other side. Basically, the fraction bit of the original formula needed to be flipped and multiplied. So here's the new formula, solving for L rather than P:
>
> L = P[(1 + c)^n -1]/[c(1 + c)^n]
>
>
> And the original with the carrots to signify "raised to the power of n": P = L[c(1 + c)^n]/[(1 + c)^n - 1]
>
>
>
Still having an issue though, which I added to my original question. |
25,514,378 | This sample python program:
```
document='''<p>This is <i>something</i>, it happens
in <b>real</b> life</p>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(document)
print(soup.prettify())
```
produces the following output:
```
<html>
<body>
<p>
This is
<i>
something
</i>
, it happens
in
<b>
real
</b>
life
</p>
</body>
</html>
```
That's wrong, because it adds whitespace before and after each opening and closing tag and, for example, there should be no space between `</i>` and `,`. I would like it to:
1. Not add whitespace where there are none (even around block-level tags they could be problematic, if they are styled with `display:inline` in CSS.)
2. Collapse all whitespace in a single space, except optionally for line wrapping.
Something like this:
```
<html>
<body>
<p>This is
<i>something</i>,
it happens in
<b>real</b> life</p>
</body>
</html>
```
Is this possible with `BeautifulSoup`? Any other recommended HTML parser that can deal with this? | 2014/08/26 | [
"https://Stackoverflow.com/questions/25514378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538701/"
] | Beautiful Soup's `.prettify()` method is defined as outputting each tag on its own line (<http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.html#pretty-printing>). If you want something else you'll need to make it yourself by walking the parse tree. | As previous comments and thebjorn stated, BeautifulSoup's definition of pretty html is with each tag on it's own line, however, to deal with some of your problems with the spacing of , and such, you can collapse it first like so:
```
from bs4 import BeautifulSoup
document = """<p>This is <i>something</i>, it happens
in <b>real</b> life</p>"""
document_stripped = " ".join(l.strip() for l in document.split("\n"))
soup = BeautifulSoup(document_stripped).prettify()
print(soup)
```
Which outputs this:
```
<html>
<body>
<p>
This is
<i>
something
</i>
, it happens in
<b>
real
</b>
life
</p>
</body>
</html>
``` |
25,514,378 | This sample python program:
```
document='''<p>This is <i>something</i>, it happens
in <b>real</b> life</p>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(document)
print(soup.prettify())
```
produces the following output:
```
<html>
<body>
<p>
This is
<i>
something
</i>
, it happens
in
<b>
real
</b>
life
</p>
</body>
</html>
```
That's wrong, because it adds whitespace before and after each opening and closing tag and, for example, there should be no space between `</i>` and `,`. I would like it to:
1. Not add whitespace where there are none (even around block-level tags they could be problematic, if they are styled with `display:inline` in CSS.)
2. Collapse all whitespace in a single space, except optionally for line wrapping.
Something like this:
```
<html>
<body>
<p>This is
<i>something</i>,
it happens in
<b>real</b> life</p>
</body>
</html>
```
Is this possible with `BeautifulSoup`? Any other recommended HTML parser that can deal with this? | 2014/08/26 | [
"https://Stackoverflow.com/questions/25514378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1538701/"
] | Because of the habit of `.prettify` to put each tag in it's own line, it is not suitable for production code; it is only usable for debugging output, IMO. Just convert your soup to a string, using the `str` builtin function.
What you want is a change of the string contents in your tree; you could create a function to find all elements which contain sequences of two or more whitespace characters (using a pre-compiled regular expression), and then replace their contents.
BTW, you can have Python avoid the insertion of insignificant whitespace if you write your example like so:
```
document = ('<p>This is <i>something</i>, it happens '
'in <b>real</b> life</p>')
```
This way you have two literals which are implicitly concatinated. | As previous comments and thebjorn stated, BeautifulSoup's definition of pretty html is with each tag on it's own line, however, to deal with some of your problems with the spacing of , and such, you can collapse it first like so:
```
from bs4 import BeautifulSoup
document = """<p>This is <i>something</i>, it happens
in <b>real</b> life</p>"""
document_stripped = " ".join(l.strip() for l in document.split("\n"))
soup = BeautifulSoup(document_stripped).prettify()
print(soup)
```
Which outputs this:
```
<html>
<body>
<p>
This is
<i>
something
</i>
, it happens in
<b>
real
</b>
life
</p>
</body>
</html>
``` |
14,281,469 | So I've got these huge text files that are filled with a single comma delimited record per line. I need a way to process the files line by line, removing lines that meet certain criteria. Some of the removals are easy, such as one of the fields is less than a certain length. The hardest criteria is that these lines all have timestamps. Many records are identical except for their timestamps and I have to remove all records but one that are identical and within 15 seconds of one another.
So I'm wondering if some others can come up with the best approach for this. I did come up with a small program in Java that accomplishes the task, using JodaTime for the timestamp stuff which makes it really easy. However, the initial way I coded the program was running into OutofMemory Heap Space errors. I refactored the code a bit and it seemed ok for the most part but I do still believe it has some memory issues as once in awhile the program just seems to get hung up. That and it just seems to take way too long. I'm not sure if this is a memory leak issue, a poor coding issue, or something else entirely. And yes I tried increasing the Heap Size significantly but still was having issues.
I will say that the program needs to be in either Perl or Java. I might be able to make a python script work too but I'm not overly familiar with python. As I said, the timestamp stuff is easiest (to me) in Java because of the JodaTime library. I'm not sure how I'd accomplish the timestamp stuff in Perl. But I'm up for learning and using whatever would work best.
I will also add the files being read in vary tremendously in size but some big ones are around 100Mb with something like 1.3 million records.
My code essentially reads in all the records and puts them into a Hashmap with the keys being a specific subset of the data from a record that similar records would share. So a subset of the record not including the timestamps which would be different. This way you'd end up with some number of records with identical data but that occurred at different times. (So completely identical minus the timestamps).
The value of each key then, is a Set of all records that have the same subset of data. Then I simply iterate through the Hashmap, taking each set and iterating through it. I take the first record and compare its times to all the rest to see if they're within 15 seconds. If so the record is removed. Once that set is finished it's written out to a file until all the records have been gone through. Hopefully that makes sense.
This works but clearly the way I'm doing it is too memory intensive. Anyone have any ideas on a better way to do it? Or, a way I can do this in Perl would actually be good because trying to insert the Java program into the current implementation has caused a number of other headaches. Though perhaps that's just because of my memory issues and poor coding.
Finally, I'm not asking someone to write the program for me. Pseudo code is fine. Though if you have ideas for Perl I could use more specifics. The main thing I'm not sure how to do in Perl is the time comparison stuff. I've looked a little into Perl libraries but haven't seen anything like JodaTime (though I haven't looked much). Any thoughts or suggestions are appreciated. Thank you. | 2013/01/11 | [
"https://Stackoverflow.com/questions/14281469",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/947756/"
] | Reading all the rows in is not ideal, because you need to store the whole lot in memory.
Instead you could read line by line, writing out the records that you want to keep as you go. You could keep a cache of the rows you've hit previously, bounded to be within 15 seconds of the current program. In very rough pseudo-code, for every line you'd read:
```
var line = ReadLine()
DiscardAnythingInCacheOlderThan(line.Date().Minus(15 seconds);
if (!cache.ContainsSomethingMatchingCriteria()) {
// it's a line we want to keep
WriteLine(line);
}
UpdateCache(line); // make sure we store this line so we don't write it out again.
```
As pointed out, this assumes that the lines are in time stamp order. If they aren't, then I'd just use UNIX `sort` to make it so they are, as that'll quite merrily handle extremely large files. | You might read the file and output just the line numbers to be deleted (to be sorted and used in a separate pass.) Your hash map could then contain just the minimum data needed plus the line number. This could save a lot of memory if the data needed is small compared to the line size. |
32,054,066 | I'm using the [`websockets`](https://github.com/aaugustin/websockets) library to create a websocket server in Python 3.4. Here's a simple echo server:
```python
import asyncio
import websockets
@asyncio.coroutine
def connection_handler(websocket, path):
while True:
msg = yield from websocket.recv()
if msg is None: # connection lost
break
yield from websocket.send(msg)
start_server = websockets.serve(connection_handler, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
```
Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that? I mean, because `connection_handler` is constantly waiting for incoming messages, the server can only take action *after* it has received a message from the client, right? What am I missing here?
Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? [Tornado](http://www.tornadoweb.org/en/stable/websocket.html)? | 2015/08/17 | [
"https://Stackoverflow.com/questions/32054066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1668646/"
] | **TL;DR** Use [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future) to run several coroutines concurrently.
---
>
> Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? Tornado?
>
>
>
No, you don't need any other framework for this. The whole idea the asynchronous application vs synchronous is that it doesn't block, while waiting for result. It doesn't matter how it is implemented, using coroutines or callbacks.
>
> I mean, because connection\_handler is constantly waiting for incoming messages, the server can only take action after it has received a message from the client, right? What am I missing here?
>
>
>
In synchronous application you will write something like `msg = websocket.recv()`, which would block whole application until you receive message (as you described). But in the asynchronous application it's completely different.
When you do `msg = yield from websocket.recv()` you say something like: suspend execution of `connection_handler()` until `websocket.recv()` will produce something. Using `yield from` inside coroutine returns control back to the event loop, so some other code can be executed, while we're waiting for result of `websocket.recv()`. Please, refer to [documentation](https://docs.python.org/3/library/asyncio-task.html#coroutines) to better understand how coroutines work.
>
> Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that?
>
>
>
You can use [`asyncio.async()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.async) to run as many coroutines as you want, before executing blocking call for [starting event loop](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_forever).
```
import asyncio
import websockets
# here we'll store all active connections to use for sending periodic messages
connections = []
@asyncio.coroutine
def connection_handler(connection, path):
connections.append(connection) # add connection to pool
while True:
msg = yield from connection.recv()
if msg is None: # connection lost
connections.remove(connection) # remove connection from pool, when client disconnects
break
else:
print('< {}'.format(msg))
yield from connection.send(msg)
print('> {}'.format(msg))
@asyncio.coroutine
def send_periodically():
while True:
yield from asyncio.sleep(5) # switch to other code and continue execution in 5 seconds
for connection in connections:
print('> Periodic event happened.')
yield from connection.send('Periodic event happened.') # send message to each connected client
start_server = websockets.serve(connection_handler, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.async(send_periodically()) # before blocking call we schedule our coroutine for sending periodic messages
asyncio.get_event_loop().run_forever()
```
Here is an example client implementation. It asks you to enter name, receives it back from the echo server, waits for two more messages from server (which are our periodic messages) and closes connection.
```
import asyncio
import websockets
@asyncio.coroutine
def hello():
connection = yield from websockets.connect('ws://localhost:8000/')
name = input("What's your name? ")
yield from connection.send(name)
print("> {}".format(name))
for _ in range(3):
msg = yield from connection.recv()
print("< {}".format(msg))
yield from connection.close()
asyncio.get_event_loop().run_until_complete(hello())
```
Important points:
1. In Python 3.4.4 `asyncio.async()` was renamed to [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future).
2. There are special methods for scheduling [delayed calls](https://docs.python.org/3/library/asyncio-eventloop.html#delayed-calls), but they don't work with coroutines. | Same issue, can hardly got solution until I saw the perfect sample here: <http://websockets.readthedocs.io/en/stable/intro.html#both>
```
done, pending = await asyncio.wait(
[listener_task, producer_task],
return_when=asyncio.FIRST_COMPLETED) # Important
```
So, I can handle multi coroutine tasks such as heartbeat and redis subscribe. |
32,054,066 | I'm using the [`websockets`](https://github.com/aaugustin/websockets) library to create a websocket server in Python 3.4. Here's a simple echo server:
```python
import asyncio
import websockets
@asyncio.coroutine
def connection_handler(websocket, path):
while True:
msg = yield from websocket.recv()
if msg is None: # connection lost
break
yield from websocket.send(msg)
start_server = websockets.serve(connection_handler, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
```
Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that? I mean, because `connection_handler` is constantly waiting for incoming messages, the server can only take action *after* it has received a message from the client, right? What am I missing here?
Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? [Tornado](http://www.tornadoweb.org/en/stable/websocket.html)? | 2015/08/17 | [
"https://Stackoverflow.com/questions/32054066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1668646/"
] | **TL;DR** Use [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future) to run several coroutines concurrently.
---
>
> Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? Tornado?
>
>
>
No, you don't need any other framework for this. The whole idea the asynchronous application vs synchronous is that it doesn't block, while waiting for result. It doesn't matter how it is implemented, using coroutines or callbacks.
>
> I mean, because connection\_handler is constantly waiting for incoming messages, the server can only take action after it has received a message from the client, right? What am I missing here?
>
>
>
In synchronous application you will write something like `msg = websocket.recv()`, which would block whole application until you receive message (as you described). But in the asynchronous application it's completely different.
When you do `msg = yield from websocket.recv()` you say something like: suspend execution of `connection_handler()` until `websocket.recv()` will produce something. Using `yield from` inside coroutine returns control back to the event loop, so some other code can be executed, while we're waiting for result of `websocket.recv()`. Please, refer to [documentation](https://docs.python.org/3/library/asyncio-task.html#coroutines) to better understand how coroutines work.
>
> Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that?
>
>
>
You can use [`asyncio.async()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.async) to run as many coroutines as you want, before executing blocking call for [starting event loop](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_forever).
```
import asyncio
import websockets
# here we'll store all active connections to use for sending periodic messages
connections = []
@asyncio.coroutine
def connection_handler(connection, path):
connections.append(connection) # add connection to pool
while True:
msg = yield from connection.recv()
if msg is None: # connection lost
connections.remove(connection) # remove connection from pool, when client disconnects
break
else:
print('< {}'.format(msg))
yield from connection.send(msg)
print('> {}'.format(msg))
@asyncio.coroutine
def send_periodically():
while True:
yield from asyncio.sleep(5) # switch to other code and continue execution in 5 seconds
for connection in connections:
print('> Periodic event happened.')
yield from connection.send('Periodic event happened.') # send message to each connected client
start_server = websockets.serve(connection_handler, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.async(send_periodically()) # before blocking call we schedule our coroutine for sending periodic messages
asyncio.get_event_loop().run_forever()
```
Here is an example client implementation. It asks you to enter name, receives it back from the echo server, waits for two more messages from server (which are our periodic messages) and closes connection.
```
import asyncio
import websockets
@asyncio.coroutine
def hello():
connection = yield from websockets.connect('ws://localhost:8000/')
name = input("What's your name? ")
yield from connection.send(name)
print("> {}".format(name))
for _ in range(3):
msg = yield from connection.recv()
print("< {}".format(msg))
yield from connection.close()
asyncio.get_event_loop().run_until_complete(hello())
```
Important points:
1. In Python 3.4.4 `asyncio.async()` was renamed to [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future).
2. There are special methods for scheduling [delayed calls](https://docs.python.org/3/library/asyncio-eventloop.html#delayed-calls), but they don't work with coroutines. | I'm surprised `gather` isn't mentioned.
From the [Python documentation](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather):
```
import asyncio
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({number}) = {f}")
async def main():
# Schedule three calls *concurrently*:
await asyncio.gather(
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
)
asyncio.run(main())
# Expected output:
#
# Task A: Compute factorial(2)...
# Task B: Compute factorial(2)...
# Task C: Compute factorial(2)...
# Task A: factorial(2) = 2
# Task B: Compute factorial(3)...
# Task C: Compute factorial(3)...
# Task B: factorial(3) = 6
# Task C: Compute factorial(4)...
# Task C: factorial(4) = 24
``` |
32,054,066 | I'm using the [`websockets`](https://github.com/aaugustin/websockets) library to create a websocket server in Python 3.4. Here's a simple echo server:
```python
import asyncio
import websockets
@asyncio.coroutine
def connection_handler(websocket, path):
while True:
msg = yield from websocket.recv()
if msg is None: # connection lost
break
yield from websocket.send(msg)
start_server = websockets.serve(connection_handler, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
```
Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that? I mean, because `connection_handler` is constantly waiting for incoming messages, the server can only take action *after* it has received a message from the client, right? What am I missing here?
Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? [Tornado](http://www.tornadoweb.org/en/stable/websocket.html)? | 2015/08/17 | [
"https://Stackoverflow.com/questions/32054066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1668646/"
] | **TL;DR** Use [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future) to run several coroutines concurrently.
---
>
> Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? Tornado?
>
>
>
No, you don't need any other framework for this. The whole idea the asynchronous application vs synchronous is that it doesn't block, while waiting for result. It doesn't matter how it is implemented, using coroutines or callbacks.
>
> I mean, because connection\_handler is constantly waiting for incoming messages, the server can only take action after it has received a message from the client, right? What am I missing here?
>
>
>
In synchronous application you will write something like `msg = websocket.recv()`, which would block whole application until you receive message (as you described). But in the asynchronous application it's completely different.
When you do `msg = yield from websocket.recv()` you say something like: suspend execution of `connection_handler()` until `websocket.recv()` will produce something. Using `yield from` inside coroutine returns control back to the event loop, so some other code can be executed, while we're waiting for result of `websocket.recv()`. Please, refer to [documentation](https://docs.python.org/3/library/asyncio-task.html#coroutines) to better understand how coroutines work.
>
> Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that?
>
>
>
You can use [`asyncio.async()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.async) to run as many coroutines as you want, before executing blocking call for [starting event loop](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.BaseEventLoop.run_forever).
```
import asyncio
import websockets
# here we'll store all active connections to use for sending periodic messages
connections = []
@asyncio.coroutine
def connection_handler(connection, path):
connections.append(connection) # add connection to pool
while True:
msg = yield from connection.recv()
if msg is None: # connection lost
connections.remove(connection) # remove connection from pool, when client disconnects
break
else:
print('< {}'.format(msg))
yield from connection.send(msg)
print('> {}'.format(msg))
@asyncio.coroutine
def send_periodically():
while True:
yield from asyncio.sleep(5) # switch to other code and continue execution in 5 seconds
for connection in connections:
print('> Periodic event happened.')
yield from connection.send('Periodic event happened.') # send message to each connected client
start_server = websockets.serve(connection_handler, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.async(send_periodically()) # before blocking call we schedule our coroutine for sending periodic messages
asyncio.get_event_loop().run_forever()
```
Here is an example client implementation. It asks you to enter name, receives it back from the echo server, waits for two more messages from server (which are our periodic messages) and closes connection.
```
import asyncio
import websockets
@asyncio.coroutine
def hello():
connection = yield from websockets.connect('ws://localhost:8000/')
name = input("What's your name? ")
yield from connection.send(name)
print("> {}".format(name))
for _ in range(3):
msg = yield from connection.recv()
print("< {}".format(msg))
yield from connection.close()
asyncio.get_event_loop().run_until_complete(hello())
```
Important points:
1. In Python 3.4.4 `asyncio.async()` was renamed to [`asyncio.ensure_future()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.ensure_future).
2. There are special methods for scheduling [delayed calls](https://docs.python.org/3/library/asyncio-eventloop.html#delayed-calls), but they don't work with coroutines. | If you are using *Python 3.7 and later* you can use `asyncio.gather()` and `asyncio.run()` as follows:
```py
import asyncio
async def coro1():
for i in range(1, 6):
print(i)
await asyncio.sleep(0) # switches task every one iteration.
async def coro2():
for i in range(1, 6):
print(i * 10)
await asyncio.sleep(0) # switches task every one iteration.
async def main():
await asyncio.gather(
coro1(),
coro2(),
)
asyncio.run(main())
## Or instead of defining the main async function:
futures = [coro1(), coro2()]
await asyncio.gather(*futures)
```
Otherwise, if you are using *Python 3.6 or 3.5* do as follows for the same result which you should handle the loop as well:
```py
import asyncio
async def coro1():
for i in range(1, 6):
print(i)
await asyncio.sleep(0) # switches task every one iteration.
async def coro2():
for i in range(1, 6):
print(i * 10)
await asyncio.sleep(0) # switches task every one iteration.
loop = asyncio.get_event_loop()
futures = [
asyncio.ensure_future(coro1()),
asyncio.ensure_future(coro2())
]
loop.run_until_complete(asyncio.gather(*futures))
loop.close()
```
Out:
```
1
10
2
20
3
30
4
40
5
50
```
---
[UPDATE]:
With new syntax in *Python 3.11* you don't need `.gather()`:
```py
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(coro1())
tg.create_task(coro2())
asyncio.run(main())
``` |
32,054,066 | I'm using the [`websockets`](https://github.com/aaugustin/websockets) library to create a websocket server in Python 3.4. Here's a simple echo server:
```python
import asyncio
import websockets
@asyncio.coroutine
def connection_handler(websocket, path):
while True:
msg = yield from websocket.recv()
if msg is None: # connection lost
break
yield from websocket.send(msg)
start_server = websockets.serve(connection_handler, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
```
Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that? I mean, because `connection_handler` is constantly waiting for incoming messages, the server can only take action *after* it has received a message from the client, right? What am I missing here?
Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? [Tornado](http://www.tornadoweb.org/en/stable/websocket.html)? | 2015/08/17 | [
"https://Stackoverflow.com/questions/32054066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1668646/"
] | I'm surprised `gather` isn't mentioned.
From the [Python documentation](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather):
```
import asyncio
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({number}) = {f}")
async def main():
# Schedule three calls *concurrently*:
await asyncio.gather(
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
)
asyncio.run(main())
# Expected output:
#
# Task A: Compute factorial(2)...
# Task B: Compute factorial(2)...
# Task C: Compute factorial(2)...
# Task A: factorial(2) = 2
# Task B: Compute factorial(3)...
# Task C: Compute factorial(3)...
# Task B: factorial(3) = 6
# Task C: Compute factorial(4)...
# Task C: factorial(4) = 24
``` | Same issue, can hardly got solution until I saw the perfect sample here: <http://websockets.readthedocs.io/en/stable/intro.html#both>
```
done, pending = await asyncio.wait(
[listener_task, producer_task],
return_when=asyncio.FIRST_COMPLETED) # Important
```
So, I can handle multi coroutine tasks such as heartbeat and redis subscribe. |
32,054,066 | I'm using the [`websockets`](https://github.com/aaugustin/websockets) library to create a websocket server in Python 3.4. Here's a simple echo server:
```python
import asyncio
import websockets
@asyncio.coroutine
def connection_handler(websocket, path):
while True:
msg = yield from websocket.recv()
if msg is None: # connection lost
break
yield from websocket.send(msg)
start_server = websockets.serve(connection_handler, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
```
Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that? I mean, because `connection_handler` is constantly waiting for incoming messages, the server can only take action *after* it has received a message from the client, right? What am I missing here?
Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? [Tornado](http://www.tornadoweb.org/en/stable/websocket.html)? | 2015/08/17 | [
"https://Stackoverflow.com/questions/32054066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1668646/"
] | Same issue, can hardly got solution until I saw the perfect sample here: <http://websockets.readthedocs.io/en/stable/intro.html#both>
```
done, pending = await asyncio.wait(
[listener_task, producer_task],
return_when=asyncio.FIRST_COMPLETED) # Important
```
So, I can handle multi coroutine tasks such as heartbeat and redis subscribe. | If you are using *Python 3.7 and later* you can use `asyncio.gather()` and `asyncio.run()` as follows:
```py
import asyncio
async def coro1():
for i in range(1, 6):
print(i)
await asyncio.sleep(0) # switches task every one iteration.
async def coro2():
for i in range(1, 6):
print(i * 10)
await asyncio.sleep(0) # switches task every one iteration.
async def main():
await asyncio.gather(
coro1(),
coro2(),
)
asyncio.run(main())
## Or instead of defining the main async function:
futures = [coro1(), coro2()]
await asyncio.gather(*futures)
```
Otherwise, if you are using *Python 3.6 or 3.5* do as follows for the same result which you should handle the loop as well:
```py
import asyncio
async def coro1():
for i in range(1, 6):
print(i)
await asyncio.sleep(0) # switches task every one iteration.
async def coro2():
for i in range(1, 6):
print(i * 10)
await asyncio.sleep(0) # switches task every one iteration.
loop = asyncio.get_event_loop()
futures = [
asyncio.ensure_future(coro1()),
asyncio.ensure_future(coro2())
]
loop.run_until_complete(asyncio.gather(*futures))
loop.close()
```
Out:
```
1
10
2
20
3
30
4
40
5
50
```
---
[UPDATE]:
With new syntax in *Python 3.11* you don't need `.gather()`:
```py
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(coro1())
tg.create_task(coro2())
asyncio.run(main())
``` |
32,054,066 | I'm using the [`websockets`](https://github.com/aaugustin/websockets) library to create a websocket server in Python 3.4. Here's a simple echo server:
```python
import asyncio
import websockets
@asyncio.coroutine
def connection_handler(websocket, path):
while True:
msg = yield from websocket.recv()
if msg is None: # connection lost
break
yield from websocket.send(msg)
start_server = websockets.serve(connection_handler, 'localhost', 8000)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
```
Let's say we – additionally – wanted to send a message to the client whenever some event happens. For simplicity, let's send a message periodically every 60 seconds. How would we do that? I mean, because `connection_handler` is constantly waiting for incoming messages, the server can only take action *after* it has received a message from the client, right? What am I missing here?
Maybe this scenario requires a framework based on events/callbacks rather than one based on coroutines? [Tornado](http://www.tornadoweb.org/en/stable/websocket.html)? | 2015/08/17 | [
"https://Stackoverflow.com/questions/32054066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1668646/"
] | I'm surprised `gather` isn't mentioned.
From the [Python documentation](https://docs.python.org/3/library/asyncio-task.html#asyncio.gather):
```
import asyncio
async def factorial(name, number):
f = 1
for i in range(2, number + 1):
print(f"Task {name}: Compute factorial({i})...")
await asyncio.sleep(1)
f *= i
print(f"Task {name}: factorial({number}) = {f}")
async def main():
# Schedule three calls *concurrently*:
await asyncio.gather(
factorial("A", 2),
factorial("B", 3),
factorial("C", 4),
)
asyncio.run(main())
# Expected output:
#
# Task A: Compute factorial(2)...
# Task B: Compute factorial(2)...
# Task C: Compute factorial(2)...
# Task A: factorial(2) = 2
# Task B: Compute factorial(3)...
# Task C: Compute factorial(3)...
# Task B: factorial(3) = 6
# Task C: Compute factorial(4)...
# Task C: factorial(4) = 24
``` | If you are using *Python 3.7 and later* you can use `asyncio.gather()` and `asyncio.run()` as follows:
```py
import asyncio
async def coro1():
for i in range(1, 6):
print(i)
await asyncio.sleep(0) # switches task every one iteration.
async def coro2():
for i in range(1, 6):
print(i * 10)
await asyncio.sleep(0) # switches task every one iteration.
async def main():
await asyncio.gather(
coro1(),
coro2(),
)
asyncio.run(main())
## Or instead of defining the main async function:
futures = [coro1(), coro2()]
await asyncio.gather(*futures)
```
Otherwise, if you are using *Python 3.6 or 3.5* do as follows for the same result which you should handle the loop as well:
```py
import asyncio
async def coro1():
for i in range(1, 6):
print(i)
await asyncio.sleep(0) # switches task every one iteration.
async def coro2():
for i in range(1, 6):
print(i * 10)
await asyncio.sleep(0) # switches task every one iteration.
loop = asyncio.get_event_loop()
futures = [
asyncio.ensure_future(coro1()),
asyncio.ensure_future(coro2())
]
loop.run_until_complete(asyncio.gather(*futures))
loop.close()
```
Out:
```
1
10
2
20
3
30
4
40
5
50
```
---
[UPDATE]:
With new syntax in *Python 3.11* you don't need `.gather()`:
```py
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(coro1())
tg.create_task(coro2())
asyncio.run(main())
``` |
27,812,789 | I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
But when I debug this function:
```
def popall(self):
objs = self.curstack
self.curstack = []
return objs
```
It looks like some kind of copy is taking place. After this function runs obis is full of things and **`self.curstack`** is empty…
So some copy is going on. Is it deep or shallow? | 2015/01/07 | [
"https://Stackoverflow.com/questions/27812789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444342/"
] | It doesn't copy anything. It's just that assigning to `self.curstack` does not modify whatever `self.curstack` used to refer to. It just makes `self.curstack` refer to something else.
Think of it this way. `self.curstack` points to some stuff. With `objs = self.curstack` you make `objs` point to that same stuff. With `self.curstack = []`, you make `self.curstack` point to an empty list. This doesn't remove any of the stuff that `self.curstack` used to point at; that stuff is still there and `objs` is still pointing at it.
[This article](http://foobarnbaz.com/2012/07/08/understanding-python-variables/) explains it using a nice analogy of label tags. | Python uses references everywhere. So your code works like this:
```
objs = self.curstack
```
Now `objs` points to whatever `curstack` was.
```
self.curstack = []
```
Now `curstack` points to an empty list. `objs` is unchanged, and points to the old `curstack`.
```
return objs
```
You return `objs`, which is the old `curstack`. |
27,812,789 | I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
But when I debug this function:
```
def popall(self):
objs = self.curstack
self.curstack = []
return objs
```
It looks like some kind of copy is taking place. After this function runs obis is full of things and **`self.curstack`** is empty…
So some copy is going on. Is it deep or shallow? | 2015/01/07 | [
"https://Stackoverflow.com/questions/27812789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444342/"
] | It doesn't copy anything. It's just that assigning to `self.curstack` does not modify whatever `self.curstack` used to refer to. It just makes `self.curstack` refer to something else.
Think of it this way. `self.curstack` points to some stuff. With `objs = self.curstack` you make `objs` point to that same stuff. With `self.curstack = []`, you make `self.curstack` point to an empty list. This doesn't remove any of the stuff that `self.curstack` used to point at; that stuff is still there and `objs` is still pointing at it.
[This article](http://foobarnbaz.com/2012/07/08/understanding-python-variables/) explains it using a nice analogy of label tags. | Let's demonstrate what's really going on (using `id` which shows the location of the memory)
```
a = [1,2,3]
print id(a)
b = a
print id(b)
a = 4
print id(a)
print a
print b
```
>
> 4339130240
>
>
> 4339130240
>
>
> 4298163184
>
>
> 4
>
>
> [1, 2, 3]
>
>
>
So `a` and `b` initially point to the same place in memory, but then `a` points somewhere new. But now, let's try
```
a = [1,2,3]
print id(a)
b = a
print id(b)
a[0] = 4
print id(a)
print a
print b
```
>
> 4339098040
>
>
> 4339098040
>
>
> 4339098040
>
>
> [4, 2, 3]
>
>
> [4, 2, 3]
>
>
>
So `b` isn't a fresh new copy of `a`. It is the same object as `a` (when it's defined). If you then do `a=4`, you're telling python, let's forget what `a` used to point to and assign a new meaning to it. *4 does not appear in the spot in memory that `a` used to refer to*. Instead `a` now refers to a new place in memory. `b` still refers to what `a` initially referred to.
If we don't reassign `a`, but instead we change one of the things within the object that `a` points to, then checking `b` shows that the corresponding change happens to `b`. |
27,812,789 | I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
But when I debug this function:
```
def popall(self):
objs = self.curstack
self.curstack = []
return objs
```
It looks like some kind of copy is taking place. After this function runs obis is full of things and **`self.curstack`** is empty…
So some copy is going on. Is it deep or shallow? | 2015/01/07 | [
"https://Stackoverflow.com/questions/27812789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444342/"
] | It doesn't copy anything. It's just that assigning to `self.curstack` does not modify whatever `self.curstack` used to refer to. It just makes `self.curstack` refer to something else.
Think of it this way. `self.curstack` points to some stuff. With `objs = self.curstack` you make `objs` point to that same stuff. With `self.curstack = []`, you make `self.curstack` point to an empty list. This doesn't remove any of the stuff that `self.curstack` used to point at; that stuff is still there and `objs` is still pointing at it.
[This article](http://foobarnbaz.com/2012/07/08/understanding-python-variables/) explains it using a nice analogy of label tags. | As mentioned in all the answers that `self.curstack` doesn't modify it just refer to something. In you case it is referring to an empty list `[]`.
You can actually see the how objects are referring using [**swampy**](http://www.greenteapress.com/thinkpython/swampy/)
```
from swampy.Lumpy import Lumpy
class ref_test:
def __init__(self, curstack):
self.curstack = curstack
def popall(self):
lampy = Lumpy()
objs = self.curstack
self.curstack = []
print id(self.curstack), id(objs)
lampy.object_diagram()
return objs
o = ref_test([1,2,3,4])
res = o.popall()
print res
```

As you can see `self.curstack` is pointing to an empty list and `objs` is still holding up the old values of `self.curstack`.
You can use [**id**](https://docs.python.org/2/library/functions.html#id) function to check “identity” of an object. Which is not unique in our case for `self.curstack` and `objs`
```
164711692 163838732
``` |
27,812,789 | I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
But when I debug this function:
```
def popall(self):
objs = self.curstack
self.curstack = []
return objs
```
It looks like some kind of copy is taking place. After this function runs obis is full of things and **`self.curstack`** is empty…
So some copy is going on. Is it deep or shallow? | 2015/01/07 | [
"https://Stackoverflow.com/questions/27812789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444342/"
] | It doesn't copy anything. It's just that assigning to `self.curstack` does not modify whatever `self.curstack` used to refer to. It just makes `self.curstack` refer to something else.
Think of it this way. `self.curstack` points to some stuff. With `objs = self.curstack` you make `objs` point to that same stuff. With `self.curstack = []`, you make `self.curstack` point to an empty list. This doesn't remove any of the stuff that `self.curstack` used to point at; that stuff is still there and `objs` is still pointing at it.
[This article](http://foobarnbaz.com/2012/07/08/understanding-python-variables/) explains it using a nice analogy of label tags. | In Python, there are two spaces, the namespace and the object space.
Names are just labels you assign to objects, which live in the object space. Objects have values and types; names are just there for our convenience; so that we may access things in the object space.
This is different than other languages like C where the variable is more like a box in which you can put a certain type of thing.
In Python, names can point to any object of any type - they are just aliases.
When you assign a name to an object, like this:
```
a = 1
```
`a` is just a label that points to the object `1` that has a type (int) and a value. If you next do this:
```
b = 1
```
Now you have two names `a` and `b` pointing to the same object - they are not "copies", but just two labels to the same object.
When you do this:
```
a = 'hello'
```
Now `a` is pointing to a new object, but `b` is still pointing to the old object (`1`).
Eventually, when no names are pointing to objects, Python does automatic garbage collection to keep the object space optimized. |
27,812,789 | I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
But when I debug this function:
```
def popall(self):
objs = self.curstack
self.curstack = []
return objs
```
It looks like some kind of copy is taking place. After this function runs obis is full of things and **`self.curstack`** is empty…
So some copy is going on. Is it deep or shallow? | 2015/01/07 | [
"https://Stackoverflow.com/questions/27812789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444342/"
] | Python uses references everywhere. So your code works like this:
```
objs = self.curstack
```
Now `objs` points to whatever `curstack` was.
```
self.curstack = []
```
Now `curstack` points to an empty list. `objs` is unchanged, and points to the old `curstack`.
```
return objs
```
You return `objs`, which is the old `curstack`. | Let's demonstrate what's really going on (using `id` which shows the location of the memory)
```
a = [1,2,3]
print id(a)
b = a
print id(b)
a = 4
print id(a)
print a
print b
```
>
> 4339130240
>
>
> 4339130240
>
>
> 4298163184
>
>
> 4
>
>
> [1, 2, 3]
>
>
>
So `a` and `b` initially point to the same place in memory, but then `a` points somewhere new. But now, let's try
```
a = [1,2,3]
print id(a)
b = a
print id(b)
a[0] = 4
print id(a)
print a
print b
```
>
> 4339098040
>
>
> 4339098040
>
>
> 4339098040
>
>
> [4, 2, 3]
>
>
> [4, 2, 3]
>
>
>
So `b` isn't a fresh new copy of `a`. It is the same object as `a` (when it's defined). If you then do `a=4`, you're telling python, let's forget what `a` used to point to and assign a new meaning to it. *4 does not appear in the spot in memory that `a` used to refer to*. Instead `a` now refers to a new place in memory. `b` still refers to what `a` initially referred to.
If we don't reassign `a`, but instead we change one of the things within the object that `a` points to, then checking `b` shows that the corresponding change happens to `b`. |
27,812,789 | I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
But when I debug this function:
```
def popall(self):
objs = self.curstack
self.curstack = []
return objs
```
It looks like some kind of copy is taking place. After this function runs obis is full of things and **`self.curstack`** is empty…
So some copy is going on. Is it deep or shallow? | 2015/01/07 | [
"https://Stackoverflow.com/questions/27812789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444342/"
] | Python uses references everywhere. So your code works like this:
```
objs = self.curstack
```
Now `objs` points to whatever `curstack` was.
```
self.curstack = []
```
Now `curstack` points to an empty list. `objs` is unchanged, and points to the old `curstack`.
```
return objs
```
You return `objs`, which is the old `curstack`. | In Python, there are two spaces, the namespace and the object space.
Names are just labels you assign to objects, which live in the object space. Objects have values and types; names are just there for our convenience; so that we may access things in the object space.
This is different than other languages like C where the variable is more like a box in which you can put a certain type of thing.
In Python, names can point to any object of any type - they are just aliases.
When you assign a name to an object, like this:
```
a = 1
```
`a` is just a label that points to the object `1` that has a type (int) and a value. If you next do this:
```
b = 1
```
Now you have two names `a` and `b` pointing to the same object - they are not "copies", but just two labels to the same object.
When you do this:
```
a = 'hello'
```
Now `a` is pointing to a new object, but `b` is still pointing to the old object (`1`).
Eventually, when no names are pointing to objects, Python does automatic garbage collection to keep the object space optimized. |
27,812,789 | I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
But when I debug this function:
```
def popall(self):
objs = self.curstack
self.curstack = []
return objs
```
It looks like some kind of copy is taking place. After this function runs obis is full of things and **`self.curstack`** is empty…
So some copy is going on. Is it deep or shallow? | 2015/01/07 | [
"https://Stackoverflow.com/questions/27812789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444342/"
] | As mentioned in all the answers that `self.curstack` doesn't modify it just refer to something. In you case it is referring to an empty list `[]`.
You can actually see the how objects are referring using [**swampy**](http://www.greenteapress.com/thinkpython/swampy/)
```
from swampy.Lumpy import Lumpy
class ref_test:
def __init__(self, curstack):
self.curstack = curstack
def popall(self):
lampy = Lumpy()
objs = self.curstack
self.curstack = []
print id(self.curstack), id(objs)
lampy.object_diagram()
return objs
o = ref_test([1,2,3,4])
res = o.popall()
print res
```

As you can see `self.curstack` is pointing to an empty list and `objs` is still holding up the old values of `self.curstack`.
You can use [**id**](https://docs.python.org/2/library/functions.html#id) function to check “identity” of an object. Which is not unique in our case for `self.curstack` and `objs`
```
164711692 163838732
``` | Let's demonstrate what's really going on (using `id` which shows the location of the memory)
```
a = [1,2,3]
print id(a)
b = a
print id(b)
a = 4
print id(a)
print a
print b
```
>
> 4339130240
>
>
> 4339130240
>
>
> 4298163184
>
>
> 4
>
>
> [1, 2, 3]
>
>
>
So `a` and `b` initially point to the same place in memory, but then `a` points somewhere new. But now, let's try
```
a = [1,2,3]
print id(a)
b = a
print id(b)
a[0] = 4
print id(a)
print a
print b
```
>
> 4339098040
>
>
> 4339098040
>
>
> 4339098040
>
>
> [4, 2, 3]
>
>
> [4, 2, 3]
>
>
>
So `b` isn't a fresh new copy of `a`. It is the same object as `a` (when it's defined). If you then do `a=4`, you're telling python, let's forget what `a` used to point to and assign a new meaning to it. *4 does not appear in the spot in memory that `a` used to refer to*. Instead `a` now refers to a new place in memory. `b` still refers to what `a` initially referred to.
If we don't reassign `a`, but instead we change one of the things within the object that `a` points to, then checking `b` shows that the corresponding change happens to `b`. |
27,812,789 | I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
But when I debug this function:
```
def popall(self):
objs = self.curstack
self.curstack = []
return objs
```
It looks like some kind of copy is taking place. After this function runs obis is full of things and **`self.curstack`** is empty…
So some copy is going on. Is it deep or shallow? | 2015/01/07 | [
"https://Stackoverflow.com/questions/27812789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444342/"
] | In Python, there are two spaces, the namespace and the object space.
Names are just labels you assign to objects, which live in the object space. Objects have values and types; names are just there for our convenience; so that we may access things in the object space.
This is different than other languages like C where the variable is more like a box in which you can put a certain type of thing.
In Python, names can point to any object of any type - they are just aliases.
When you assign a name to an object, like this:
```
a = 1
```
`a` is just a label that points to the object `1` that has a type (int) and a value. If you next do this:
```
b = 1
```
Now you have two names `a` and `b` pointing to the same object - they are not "copies", but just two labels to the same object.
When you do this:
```
a = 'hello'
```
Now `a` is pointing to a new object, but `b` is still pointing to the old object (`1`).
Eventually, when no names are pointing to objects, Python does automatic garbage collection to keep the object space optimized. | Let's demonstrate what's really going on (using `id` which shows the location of the memory)
```
a = [1,2,3]
print id(a)
b = a
print id(b)
a = 4
print id(a)
print a
print b
```
>
> 4339130240
>
>
> 4339130240
>
>
> 4298163184
>
>
> 4
>
>
> [1, 2, 3]
>
>
>
So `a` and `b` initially point to the same place in memory, but then `a` points somewhere new. But now, let's try
```
a = [1,2,3]
print id(a)
b = a
print id(b)
a[0] = 4
print id(a)
print a
print b
```
>
> 4339098040
>
>
> 4339098040
>
>
> 4339098040
>
>
> [4, 2, 3]
>
>
> [4, 2, 3]
>
>
>
So `b` isn't a fresh new copy of `a`. It is the same object as `a` (when it's defined). If you then do `a=4`, you're telling python, let's forget what `a` used to point to and assign a new meaning to it. *4 does not appear in the spot in memory that `a` used to refer to*. Instead `a` now refers to a new place in memory. `b` still refers to what `a` initially referred to.
If we don't reassign `a`, but instead we change one of the things within the object that `a` points to, then checking `b` shows that the corresponding change happens to `b`. |
27,812,789 | I read that the assign in python does not copy it works like it does in c where it assigns a pointer to an object.
But when I debug this function:
```
def popall(self):
objs = self.curstack
self.curstack = []
return objs
```
It looks like some kind of copy is taking place. After this function runs obis is full of things and **`self.curstack`** is empty…
So some copy is going on. Is it deep or shallow? | 2015/01/07 | [
"https://Stackoverflow.com/questions/27812789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2444342/"
] | As mentioned in all the answers that `self.curstack` doesn't modify it just refer to something. In you case it is referring to an empty list `[]`.
You can actually see the how objects are referring using [**swampy**](http://www.greenteapress.com/thinkpython/swampy/)
```
from swampy.Lumpy import Lumpy
class ref_test:
def __init__(self, curstack):
self.curstack = curstack
def popall(self):
lampy = Lumpy()
objs = self.curstack
self.curstack = []
print id(self.curstack), id(objs)
lampy.object_diagram()
return objs
o = ref_test([1,2,3,4])
res = o.popall()
print res
```

As you can see `self.curstack` is pointing to an empty list and `objs` is still holding up the old values of `self.curstack`.
You can use [**id**](https://docs.python.org/2/library/functions.html#id) function to check “identity” of an object. Which is not unique in our case for `self.curstack` and `objs`
```
164711692 163838732
``` | In Python, there are two spaces, the namespace and the object space.
Names are just labels you assign to objects, which live in the object space. Objects have values and types; names are just there for our convenience; so that we may access things in the object space.
This is different than other languages like C where the variable is more like a box in which you can put a certain type of thing.
In Python, names can point to any object of any type - they are just aliases.
When you assign a name to an object, like this:
```
a = 1
```
`a` is just a label that points to the object `1` that has a type (int) and a value. If you next do this:
```
b = 1
```
Now you have two names `a` and `b` pointing to the same object - they are not "copies", but just two labels to the same object.
When you do this:
```
a = 'hello'
```
Now `a` is pointing to a new object, but `b` is still pointing to the old object (`1`).
Eventually, when no names are pointing to objects, Python does automatic garbage collection to keep the object space optimized. |
56,526,857 | I am developing a software in which I have an OpenGL window. I am creating the GUI of the software using `PyQt5` and for the opengGL Window I am using `QOpengGLWidget` and for object selection, I am using [**Stencil** **Buffer**](https://en.wikibooks.org/wiki/OpenGL_Programming/Object_selection) and reading **STENCIL\_INDEX** as the following function on `mousePressEvent(self, event)`:
`id = glReadPixels(event.x(), self.height - event.y() - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT)`
but this is not working when I am using with Qt5 GUI and showing following error:
```
Traceback (most recent call last):
File "/home/akv26/Desktop/internProject/Main/opengl.py", line 92, in mousePressEvent
val = glReadPixels(event.x(), self.height - event.y() - 1, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT)
File "/home/akv26/.local/lib/python3.7/site-packages/OpenGL/GL/images.py", line 371, in glReadPixels
imageData
File "/home/akv26/.local/lib/python3.7/site-packages/OpenGL/platform/baseplatform.py", line 402, in __call__
return self( *args, **named )
File "/home/akv26/.local/lib/python3.7/site-packages/OpenGL/error.py", line 232, in glCheckError
baseOperation = baseOperation,
OpenGL.error.GLError: GLError(
err = 1282,
description = b'invalid operation',
baseOperation = glReadPixels,
cArguments = (
183,
228,
1,
1,
GL_DEPTH_COMPONENT,
GL_FLOAT,
array([[0.]], dtype=float32),
)
)
Aborted (core dumped)
```
and here is the code for my custom `QOpenGLWidget`:
```
import sys
from PyQt5.QtWidgets import QOpenGLWidget
from PyQt5.QtCore import QSize, Qt
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from math import *
class MyGLWidget(QOpenGLWidget):
def initializeGL(self):
glutInit()
glClearColor(1.0, 0.5, 0.2, 0.5)
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glEnable(GL_COLOR_MATERIAL)
glEnable(GL_LIGHT0)
glEnable(GL_LIGHT1)
glEnable(GL_NORMALIZE)
glShadeModel(GL_SMOOTH)
def resizeGL(self, w, h):
self.height=h
if h==0:
h=1
ratio = w * 1.0 / h
# Use the Projection Matrix
glMatrixMode(GL_PROJECTION)
# Reset Matrix
glLoadIdentity()
# Set the viewport to be the entire window
glViewport(0, 0, w, h)
# Set the correct perspective.
gluPerspective(45.0, ratio, 0.1, 100.0)
# Get Back to the Modelview
glMatrixMode(GL_MODELVIEW)
def paintGL(self):
glClearStencil(0)
glClear(GL_STENCIL_BUFFER_BIT)
glEnable(GL_STENCIL_TEST)
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)
ambientColor = [0.2,0.2,0.2,1.0]
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor)
lightColor0 = [0.5,0.5,0.5,1.0]
lightPos0 = [0, 0, -10.0, 1.0]
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0)
glLightfv(GL_LIGHT0, GL_POSITION, lightPos0)
lightColor1 = [0.5, 0.2, 0.2, 1.0]
lightPos1 = [-1.0, 0.5, 0.5, 0.0]
glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1)
glLightfv(GL_LIGHT1, GL_POSITION, lightPos1)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
gluLookAt(-5, 5, -5, 0, 0, 0, 0.0, 1.0, 0.0)
self.drawSome()
def drawSome(self):
glStencilFunc(GL_ALWAYS, 1, -1)
glBegin(GL_QUADS)
glColor3f(0.0, 0.5, 0.0)
glNormal3f(0,0,-1)
glVertex3f(-1,-1,0)
glVertex3f(-1,1,0)
glVertex3f(1,1,0)
glVertex3f(1,-1,0)
glEnd()
glTranslatef(0,0,0)
glColor3f(0.5,0,0)
glStencilFunc(GL_ALWAYS, 2, -1)
glutSolidCube(1.0)
def mousePressEvent(self, event):
id = glReadPixels(event.x(), self.height - event.y() - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT)
print(id)
```
and the same is working properly when I am using this with GLUT window as following:
```
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from math import *
import numpy as np
window_width=0
window_height=0
def changeSize(w, h):
global window_height, window_width
window_width=w
window_height=h
# Prevent a divide by zero, when window is too short
# (you cant make a window of zero width).
if h==0:
h=1
ratio = w * 1.0 / h
# Use the Projection Matrix
glMatrixMode(GL_PROJECTION)
# Reset Matrix
glLoadIdentity()
# Set the viewport to be the entire window
glViewport(0, 0, w, h)
# Set the correct perspective.
gluPerspective(45.0, ratio, 0.1, 100.0)
# Get Back to the Modelview
glMatrixMode(GL_MODELVIEW)
def drawSome():
glStencilFunc(GL_ALWAYS, 1, -1)
glBegin(GL_QUADS)
glColor3f(0.0, 0.5, 0.0)
glNormal3f(0,0,-1)
glVertex3f(-1,-1,0)
glVertex3f(-1,1,0)
glVertex3f(1,1,0)
glVertex3f(1,-1,0)
glEnd()
glTranslatef(0,0,0)
glColor3f(0.5,0,0)
glStencilFunc(GL_ALWAYS, 2, -1)
glutSolidCube(1.0)
def renderScene():
glClearStencil(0)
glClear(GL_STENCIL_BUFFER_BIT)
glEnable(GL_STENCIL_TEST)
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)
ambientColor = [0.2,0.2,0.2,1.0]
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor)
lightColor0 = [0.5,0.5,0.5,1.0] #Color
lightPos0 = [0, 0, -10.0, 1.0]
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0)
glLightfv(GL_LIGHT0, GL_POSITION, lightPos0)
lightColor1 = [0.5, 0.2, 0.2, 1.0]
lightPos1 = [-1.0, 0.5, 0.5, 0.0]
glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1)
glLightfv(GL_LIGHT1, GL_POSITION, lightPos1)
# Clear Color and Depth Buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
# Reset transformations
glLoadIdentity()
# Set the camera
# gluLookAt(x, 1.0, z, x+lx, 1.0, z+lz, 0.0, 1.0, 0.0)
gluLookAt(-5, 5, -5, 0, 0, 0, 0.0, 1.0, 0.0)
drawSome()
glutSwapBuffers()
def mouse(button, state, x, y):
global window_height
id = glReadPixels(x, window_height - y - 1, 1, 1, GL_STENCIL_INDEX, GL_UNSIGNED_INT)
print(id[0][0])
if __name__ == '__main__':
glutInit()
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA)
# glutInitWindowPosition(100,100)
glutInitWindowSize(320,320)
glutCreateWindow("Lighthouse3D - GLUT Tutorial")
glClearColor(1.0, 0.5, 0.2, 0.5)
# register callbacks
glutDisplayFunc(renderScene)
glutReshapeFunc(changeSize)
glutMouseFunc(mouse)
# glutTimerFunc(0, Timer, 0)
# here are the new entries
glutIgnoreKeyRepeat(1)
# OpenGL init
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glEnable(GL_COLOR_MATERIAL)
glEnable(GL_LIGHT0)
glEnable(GL_LIGHT1)
glEnable(GL_NORMALIZE)
glShadeModel(GL_SMOOTH)
glutMainLoop()
```
**How to resolve the problem with QT5 GUI ?** | 2019/06/10 | [
"https://Stackoverflow.com/questions/56526857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | `strip()` does not respect count or order when it removes characters from the end of your string. The argument you passed it, `"-Vaccines"`, contains an "a", so it will remove the "a" from "Rivera". It does not matter that it already removed an "a" from "Vaccines" and it does not matter that it doesn't come between a V and a c.
Consider another example:
```
>>> "abcXqrqqqrrrqrqrqrqrqqrr".strip("qr")
'abcX'
```
Many `q`s and `r`s are removed here, even though the argument to `strip` contains only one of each.
In general, `strip` is not suitable for removing a static number of characters from the end of a string. One possible alternative is to use regex, which can match a literal character sequence that appears at the end of a string:
```
>>> import re
>>> ac = "Pearl Rivera-Vaccines"
>>> re.sub("-Vaccines$", "", ac)
'Pearl Rivera'
```
---
In his answer, Tom Karzes observes that this approach doesn't readily work on strings that contain characters that have special meanings in a regex. For instance,
```
>>> import re
>>> s = "foo^bar"
>>> re.sub("^bar$", "", s)
'foo^bar'
```
`^` has a special meaning in regex, so the pattern `"^bar$"` fails to match the end of the string `s`. If the string you want to match contains special characters, you should escape it, either manually or with an `re.escape` call.
```
>>> import re
>>> s = "foo^bar"
>>> re.sub(r"\^bar$", "", s)
'foo'
>>> re.sub(re.escape("^bar") + "$", "", s)
'foo'
``` | The problem is that the argument to `strip` isn't used the way you think it is. The argument isn't treated as a sequence of characters, but rather as a set of characters. Any character in the argument string is removed. For example:
```
"abaca".strip("ac")
```
Produces:
```
'b'
```
since all instances of `"a"` and `"b"` have been removed.
If you just want to remove a suffix from a string, you can do something like:
```
ac = "Pearl Rivera-Vaccines"
s = "-Vaccines"
b = ac
if b.endswith(s):
b = b[:-len(s)]
```
This will result in `b` having the value:
```
'Pearl Rivera'
```
Note that this will be faster than using the `re` module. It will also be more flexible, since it will work with any non-empty string (whereas creating a regular expression will require escaping certain characters). |
64,211,267 | I want to install package MetaTrader5 on my Linux [Fedora], but this package is supported only for Windows.
**And my question is:** Is it possible to install Windows Python packages on Linux? and after installation import in my python file?
**My Solution**
1. install `wine` (learn more about [wine](https://www.winehq.org/))
2. download [python for windows](https://www.python.org/downloads/windows/), than install with `wine <path to .exe>`
3. `wine pip install MetaTrader5` or another windows only library
4. (example) create virtual enviroment `wine venv <name project>` and select
5. than import library to file, install package [3] in your virtual enviroment and you can you use it.
6. run with `wine python <file.py>` | 2020/10/05 | [
"https://Stackoverflow.com/questions/64211267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13033299/"
] | you can install `wine` to deal with the windows installer files in your fedora.
as per the doc, you can run the following comands one by one to install wine:
`sudo dnf clean all && sudo dnf update`
`dnf config-manager --add-repo https://dl.winehq.org/wine-builds/fedora/32/winehq.repo`
`sudo dnf install winehq-stable`
after that, to confirm the installation: run `wine --version` , this should be executed without any error.
lastly, dowmload the `mt5setup.exe` and open it with `wine`.
also, have a look at this answer: <https://stackoverflow.com/a/44031808/10918344>
hope you find it helpful | Yes it possible to use Wine.
Its simply to do with **CrossOver**, its more stable.
Meta Trader compiled for the Wine.
Ive use this thing. Work correctly Meta Trader and Meta editor. |
41,883,254 | I am trying to process a form in django/python using the following code.
---
home.html:
```html
<form action="{% url 'home:submit' %}" method='post'>
```
---
views.py:
```py
def submit(request):
a = request.POST(['initial'])
return render(request, 'home/home.html', {
'error_message': "returned"
})
```
---
urls.py:
```py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^submit/$', views.submit, name='submit')
]
```
when I try to run it in a browser I get the error:
`NoReverseMatch at /home/ u'home' is not a registered namespace`
and another error message indicating a problem with the form. | 2017/01/26 | [
"https://Stackoverflow.com/questions/41883254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7169431/"
] | In your main project, open url.py first. Then check, there should be app\_name declared at first. If it is not, declare it.
For example, my app name is user info which is declared in url.py
```
app_name = "userinfo"
urlpatterns = [
url(r'home/', views.home, name='home'),
url(r'register/', views.registration, name='register')
]
``` | Maybe someone will find this suggestion helpful.
Go to your applications `urls.py` and type this before the urlpatterns:
```
app_name = 'Your app name'
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.