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
|
|---|---|---|---|---|---|
30,114,579
|
I am running ubuntu 12.04 and running programs through the terminal. I have a file that compiles and runs without any issues when I am in the current directory. Example below,
```
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$ pwd
/home/david/Documents/BudgetAutomation/BillList
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$ python3.4 bill.py
./otherlisted.txt
./monthlisted.txt
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$
```
Now when I go back one directory and try running the same piece of code, I get an error message, `ValueError: need more than 1 value to unpack`. Below is what happens when I run the sample code one folder back and then the sample code below that.
```
david@block-ubuntu:~/Documents/BudgetAutomation$ python3.4 /home/david/Documents/BudgetAutomation/BillList/bill.py
Traceback (most recent call last):
File "/home/david/Documents/BudgetAutomation/BillList/bill.py", line 22, in <module>
bill_no, bill_name, trash = line.split('|', 2)
ValueError: need more than 1 value to unpack
```
The code, `bill.py`, below. This program reads two text files from the folder that it is located in and parses the lines into variables.
```
#!/usr/bin/env python
import glob
# gather all txt files in directory
arr = glob.glob('./*.txt')
arrlen = int(len(arr))
# create array to store list of bill numbers and names
list_num = []
list_name = []
# for loop that parses lines into appropriate variables
for i in range(arrlen):
with open(arr[i]) as input:
w = 0 ## iterative variable for arrays
for line in input:
list_num.append(1) ## initialize arrays
list_name.append(1)
# split line into variables.. trash is rest of line that has no use
bill_no, bill_name, trash = line.split('|', 2)
# stores values in array
list_num[w] = bill_no
list_name[w] = bill_name
w += 1
```
What is going on here? Am I not running the compile and run command in the terminal correctly? Another note to know is that I eventually call this code from another file and it will not run the for loop, I am assuming since it doesn't run unless its called from its own folder/directory?
|
2015/05/08
|
[
"https://Stackoverflow.com/questions/30114579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4362951/"
] |
Your problem starts in line 5:
```
arr = glob.glob('./*.txt')
```
You are telling glob to look in the local directory for all .txt files. Since you are one directory up you do not have these files.
You are getting a ValueError because the line variable is empty.
As it is written you will need to run it from that directory.
Edit:
The way I see it you have three separate options.
1. You could simply run script with the full path (assuming it is executable)
~/Documents/BudgetAutomation/BillList/bill.py
2. You could put the full path into the file (although not very Pythonic)
arr = glob.glob('/home/[username]/Documents/BudgetAutomation/BillList/\*.txt')
3. You could use [sys.argv](https://docs.python.org/3/library/sys.html?highlight=sys.argv#sys.argv) to pass the path in the file. This would be my personal preferred way. Use os.path.join to put the correct slashes.
arr = glob.glob(os.path.join(sys.argv[1](https://docs.python.org/3/library/sys.html?highlight=sys.argv#sys.argv), '\*.txt'))
|
You must use absolute path `arr = glob.glob('./*.txt')` here.
Do something like `arr = glob.glob('/home/abc/stack_overflow/*.txt')`
If possible use below code
```
dir_name = "your directory name" # /home/abc/stack_overflow
[file for file in os.listdir(dir_name) if file.endswith('txt')]
```
This will provide you with list of files that you want to `glob` with
|
30,114,579
|
I am running ubuntu 12.04 and running programs through the terminal. I have a file that compiles and runs without any issues when I am in the current directory. Example below,
```
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$ pwd
/home/david/Documents/BudgetAutomation/BillList
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$ python3.4 bill.py
./otherlisted.txt
./monthlisted.txt
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$
```
Now when I go back one directory and try running the same piece of code, I get an error message, `ValueError: need more than 1 value to unpack`. Below is what happens when I run the sample code one folder back and then the sample code below that.
```
david@block-ubuntu:~/Documents/BudgetAutomation$ python3.4 /home/david/Documents/BudgetAutomation/BillList/bill.py
Traceback (most recent call last):
File "/home/david/Documents/BudgetAutomation/BillList/bill.py", line 22, in <module>
bill_no, bill_name, trash = line.split('|', 2)
ValueError: need more than 1 value to unpack
```
The code, `bill.py`, below. This program reads two text files from the folder that it is located in and parses the lines into variables.
```
#!/usr/bin/env python
import glob
# gather all txt files in directory
arr = glob.glob('./*.txt')
arrlen = int(len(arr))
# create array to store list of bill numbers and names
list_num = []
list_name = []
# for loop that parses lines into appropriate variables
for i in range(arrlen):
with open(arr[i]) as input:
w = 0 ## iterative variable for arrays
for line in input:
list_num.append(1) ## initialize arrays
list_name.append(1)
# split line into variables.. trash is rest of line that has no use
bill_no, bill_name, trash = line.split('|', 2)
# stores values in array
list_num[w] = bill_no
list_name[w] = bill_name
w += 1
```
What is going on here? Am I not running the compile and run command in the terminal correctly? Another note to know is that I eventually call this code from another file and it will not run the for loop, I am assuming since it doesn't run unless its called from its own folder/directory?
|
2015/05/08
|
[
"https://Stackoverflow.com/questions/30114579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4362951/"
] |
As [eomer explains](https://stackoverflow.com/a/30114648/908494), the problem is that `'./*.txt'` is a relative path—relative to the current working directory. If you're not running from the directory that all those `*.txt` files are in, you won't find anything.
If the `*.txt` files are supposed to be *in the same directory as the script*, use *the same directory as the script*, not *the current working directory*.
The standard way of doing that is to put code like this at the top of your script:
```
import os
import sys
scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))
```
* [`argv[0]`](https://docs.python.org/3/library/sys.html#sys.argv) gets the path to the script itself. So, if you ran the script as `python BillList/bill.py`, this will be `'BillList/bill.py'`.\*
* [`dirname`](https://docs.python.org/3/library/os.path.html#os.path.dirname) just takes a path to a file, and gives you the path to the directory the file was in. So, in this case, `BillList`.
* [`abspath`](https://docs.python.org/3/library/os.path.html#os.path.abspath) normalizes and absolutizes the path.\*\* So, you'll get `/home/david/Documents/BudgetAutomation/BillList/`. And that's the directory the `*.txt` files are in.
Then, instead of this:
```
glob.glob('./*.txt')
```
… you do this:
```
glob.glob(os.path.join(scriptdir, '*.txt'))
```
---
\* Actually, on some platforms you will get an absolute path here, rather than relative, meaning the later `abspath` is unnecessary. But for portability, it's worth doing. A bigger problem is that in some cases you will get just `bill.py`, with no path. There used to be cases where it was worth checking for that and trying `__file__` instead, but as far as I know that isn't true on any modern platform—and there are cases where `__file__` is wrong but `argv[0]` is right.
\*\* For a relative path, it absolutizes it relative to the current working directory. That's why it's important to do this at the top of the script—in case someone does an `os.chdir` later.
|
Your problem starts in line 5:
```
arr = glob.glob('./*.txt')
```
You are telling glob to look in the local directory for all .txt files. Since you are one directory up you do not have these files.
You are getting a ValueError because the line variable is empty.
As it is written you will need to run it from that directory.
Edit:
The way I see it you have three separate options.
1. You could simply run script with the full path (assuming it is executable)
~/Documents/BudgetAutomation/BillList/bill.py
2. You could put the full path into the file (although not very Pythonic)
arr = glob.glob('/home/[username]/Documents/BudgetAutomation/BillList/\*.txt')
3. You could use [sys.argv](https://docs.python.org/3/library/sys.html?highlight=sys.argv#sys.argv) to pass the path in the file. This would be my personal preferred way. Use os.path.join to put the correct slashes.
arr = glob.glob(os.path.join(sys.argv[1](https://docs.python.org/3/library/sys.html?highlight=sys.argv#sys.argv), '\*.txt'))
|
30,114,579
|
I am running ubuntu 12.04 and running programs through the terminal. I have a file that compiles and runs without any issues when I am in the current directory. Example below,
```
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$ pwd
/home/david/Documents/BudgetAutomation/BillList
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$ python3.4 bill.py
./otherlisted.txt
./monthlisted.txt
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$
```
Now when I go back one directory and try running the same piece of code, I get an error message, `ValueError: need more than 1 value to unpack`. Below is what happens when I run the sample code one folder back and then the sample code below that.
```
david@block-ubuntu:~/Documents/BudgetAutomation$ python3.4 /home/david/Documents/BudgetAutomation/BillList/bill.py
Traceback (most recent call last):
File "/home/david/Documents/BudgetAutomation/BillList/bill.py", line 22, in <module>
bill_no, bill_name, trash = line.split('|', 2)
ValueError: need more than 1 value to unpack
```
The code, `bill.py`, below. This program reads two text files from the folder that it is located in and parses the lines into variables.
```
#!/usr/bin/env python
import glob
# gather all txt files in directory
arr = glob.glob('./*.txt')
arrlen = int(len(arr))
# create array to store list of bill numbers and names
list_num = []
list_name = []
# for loop that parses lines into appropriate variables
for i in range(arrlen):
with open(arr[i]) as input:
w = 0 ## iterative variable for arrays
for line in input:
list_num.append(1) ## initialize arrays
list_name.append(1)
# split line into variables.. trash is rest of line that has no use
bill_no, bill_name, trash = line.split('|', 2)
# stores values in array
list_num[w] = bill_no
list_name[w] = bill_name
w += 1
```
What is going on here? Am I not running the compile and run command in the terminal correctly? Another note to know is that I eventually call this code from another file and it will not run the for loop, I am assuming since it doesn't run unless its called from its own folder/directory?
|
2015/05/08
|
[
"https://Stackoverflow.com/questions/30114579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4362951/"
] |
As [eomer explains](https://stackoverflow.com/a/30114648/908494), the problem is that `'./*.txt'` is a relative path—relative to the current working directory. If you're not running from the directory that all those `*.txt` files are in, you won't find anything.
If the `*.txt` files are supposed to be *in the same directory as the script*, use *the same directory as the script*, not *the current working directory*.
The standard way of doing that is to put code like this at the top of your script:
```
import os
import sys
scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))
```
* [`argv[0]`](https://docs.python.org/3/library/sys.html#sys.argv) gets the path to the script itself. So, if you ran the script as `python BillList/bill.py`, this will be `'BillList/bill.py'`.\*
* [`dirname`](https://docs.python.org/3/library/os.path.html#os.path.dirname) just takes a path to a file, and gives you the path to the directory the file was in. So, in this case, `BillList`.
* [`abspath`](https://docs.python.org/3/library/os.path.html#os.path.abspath) normalizes and absolutizes the path.\*\* So, you'll get `/home/david/Documents/BudgetAutomation/BillList/`. And that's the directory the `*.txt` files are in.
Then, instead of this:
```
glob.glob('./*.txt')
```
… you do this:
```
glob.glob(os.path.join(scriptdir, '*.txt'))
```
---
\* Actually, on some platforms you will get an absolute path here, rather than relative, meaning the later `abspath` is unnecessary. But for portability, it's worth doing. A bigger problem is that in some cases you will get just `bill.py`, with no path. There used to be cases where it was worth checking for that and trying `__file__` instead, but as far as I know that isn't true on any modern platform—and there are cases where `__file__` is wrong but `argv[0]` is right.
\*\* For a relative path, it absolutizes it relative to the current working directory. That's why it's important to do this at the top of the script—in case someone does an `os.chdir` later.
|
You don't need to create that range object to iterate over the glob result. You can just do it like this:
```
for file_path in arr:
with open(file_path) as text_file:
#...code below...
```
The reason of why that exception is raised, I guess, is there exist text files contain content not conforming with your need. You read a line from that file, which is something may be like "foo|bar", then the splitting result of it is ["foo", "bar"].
If you want to avoid this exception, you could just catch it:
```
try:
bill_no, bill_name, trash = line.split('|', 2)
except ValueError:
# You can do something more meaningful but just "pass"
pass
```
|
30,114,579
|
I am running ubuntu 12.04 and running programs through the terminal. I have a file that compiles and runs without any issues when I am in the current directory. Example below,
```
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$ pwd
/home/david/Documents/BudgetAutomation/BillList
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$ python3.4 bill.py
./otherlisted.txt
./monthlisted.txt
david@block-ubuntu:~/Documents/BudgetAutomation/BillList$
```
Now when I go back one directory and try running the same piece of code, I get an error message, `ValueError: need more than 1 value to unpack`. Below is what happens when I run the sample code one folder back and then the sample code below that.
```
david@block-ubuntu:~/Documents/BudgetAutomation$ python3.4 /home/david/Documents/BudgetAutomation/BillList/bill.py
Traceback (most recent call last):
File "/home/david/Documents/BudgetAutomation/BillList/bill.py", line 22, in <module>
bill_no, bill_name, trash = line.split('|', 2)
ValueError: need more than 1 value to unpack
```
The code, `bill.py`, below. This program reads two text files from the folder that it is located in and parses the lines into variables.
```
#!/usr/bin/env python
import glob
# gather all txt files in directory
arr = glob.glob('./*.txt')
arrlen = int(len(arr))
# create array to store list of bill numbers and names
list_num = []
list_name = []
# for loop that parses lines into appropriate variables
for i in range(arrlen):
with open(arr[i]) as input:
w = 0 ## iterative variable for arrays
for line in input:
list_num.append(1) ## initialize arrays
list_name.append(1)
# split line into variables.. trash is rest of line that has no use
bill_no, bill_name, trash = line.split('|', 2)
# stores values in array
list_num[w] = bill_no
list_name[w] = bill_name
w += 1
```
What is going on here? Am I not running the compile and run command in the terminal correctly? Another note to know is that I eventually call this code from another file and it will not run the for loop, I am assuming since it doesn't run unless its called from its own folder/directory?
|
2015/05/08
|
[
"https://Stackoverflow.com/questions/30114579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4362951/"
] |
As [eomer explains](https://stackoverflow.com/a/30114648/908494), the problem is that `'./*.txt'` is a relative path—relative to the current working directory. If you're not running from the directory that all those `*.txt` files are in, you won't find anything.
If the `*.txt` files are supposed to be *in the same directory as the script*, use *the same directory as the script*, not *the current working directory*.
The standard way of doing that is to put code like this at the top of your script:
```
import os
import sys
scriptdir = os.path.abspath(os.path.dirname(sys.argv[0]))
```
* [`argv[0]`](https://docs.python.org/3/library/sys.html#sys.argv) gets the path to the script itself. So, if you ran the script as `python BillList/bill.py`, this will be `'BillList/bill.py'`.\*
* [`dirname`](https://docs.python.org/3/library/os.path.html#os.path.dirname) just takes a path to a file, and gives you the path to the directory the file was in. So, in this case, `BillList`.
* [`abspath`](https://docs.python.org/3/library/os.path.html#os.path.abspath) normalizes and absolutizes the path.\*\* So, you'll get `/home/david/Documents/BudgetAutomation/BillList/`. And that's the directory the `*.txt` files are in.
Then, instead of this:
```
glob.glob('./*.txt')
```
… you do this:
```
glob.glob(os.path.join(scriptdir, '*.txt'))
```
---
\* Actually, on some platforms you will get an absolute path here, rather than relative, meaning the later `abspath` is unnecessary. But for portability, it's worth doing. A bigger problem is that in some cases you will get just `bill.py`, with no path. There used to be cases where it was worth checking for that and trying `__file__` instead, but as far as I know that isn't true on any modern platform—and there are cases where `__file__` is wrong but `argv[0]` is right.
\*\* For a relative path, it absolutizes it relative to the current working directory. That's why it's important to do this at the top of the script—in case someone does an `os.chdir` later.
|
You must use absolute path `arr = glob.glob('./*.txt')` here.
Do something like `arr = glob.glob('/home/abc/stack_overflow/*.txt')`
If possible use below code
```
dir_name = "your directory name" # /home/abc/stack_overflow
[file for file in os.listdir(dir_name) if file.endswith('txt')]
```
This will provide you with list of files that you want to `glob` with
|
14,965,542
|
I have a huge file from which I need data for specific entries. File structure is:
```
>Entry1.1
#size=1688
704 1 1 1 4
979 2 2 2 0
1220 1 1 1 4
1309 1 1 1 4
1316 1 1 1 4
1372 1 1 1 4
1374 1 1 1 4
1576 1 1 1 4
>Entry2.1
#size=6251
6110 3 1.5 0 2
6129 2 2 2 2
6136 1 1 1 4
6142 3 3 3 2
6143 4 4 4 1
6150 1 1 1 4
6152 1 1 1 4
>Entry3.2
#size=1777
AND SO ON-----------
```
What I have to achieve is that I need to extract all the lines (complete record) for certain entries. For e.x. I need record for Entry1.1 than I can use name of entry '>Entry1.1' till next '>' as markers in REGEX to extract lines in between. But I do not know how to build such complex REGEX expressions. Once I have such expression the I will put it a FOR loop:
```
For entry in entrylist:
GET record from big_file
DO some processing
WRITE in result file
```
What could be the REGEX to perform such extraction of record for specific entries? Is there any more pythonic way to achieve this? I would appreciate your help on this.
AK
|
2013/02/19
|
[
"https://Stackoverflow.com/questions/14965542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031842/"
] |
With regex
```
import re
ss = '''
>Entry1.1
#size=1688
704 1 1 1 4
979 2 2 2 0
1220 1 1 1 4
1309 1 1 1 4
1316 1 1 1 4
1372 1 1 1 4
1374 1 1 1 4
1576 1 1 1 4
>Entry2.1
#size=6251
6110 3 1.5 0 2
6129 2 2 2 2
6136 1 1 1 4
6142 3 3 3 2
6143 4 4 4 1
6150 1 1 1 4
6152 1 1 1 4
>Entry3.2
#size=1777
AND SO ON-----------
'''
patbase = '(>Entry *%s(?![^\n]+?\d).+?)(?=>|(?:\s*\Z))'
while True:
x = raw_input('What entry do you want ? : ')
found = re.findall(patbase % x, ss, re.DOTALL)
if found:
print 'found ==',found
for each_entry in found:
print '\n%s\n' % each_entry
else:
print '\n ** There is no such an entry **\n'
```
Explanation of `'(>Entry *%s(?![^\n]+?\d).+?)(?=>|(?:\s*\Z))'` :
1)
==
`%s` receives the reference of entry: 1.1 , 2 , 2.1 etc
2)
==
The portion `(?![^\n]+?\d)` is to do a verification.
`(?![^\n]+?\d)` is a negative look-ahead assertion that says that what is after `%s` must not be `[^\n]+?\d` that is to say any characters `[^\n]+?` before a digit `\d`
I write `[^\n]` to mean "any character except a newline `\n`".
I am obliged to write this instead of simply `.+?` because I put the flag `re.DOTALL` and the pattern portion `.+?` would be acting until the end of the entry.
However, I only want to verify that after the entered reference (represented by %s in the pattern), there won't be supplementary digits before the end OF THE LINE, entered by error
All that is because if there is an Entry2.1 but no Entry2 , and the user enters only 2 because he wants Entry2 and no other, the regex would detect the presence of the Entry2.1 and would yield it, though the user would really like Entry2 in fact.
3)
==
At the end of `'(>Entry *%s(?![^\n]+?\d).+?)` , the part `.+?` will catch the complete block of the Entry, because the dot represents any character, comprised a newline `\n`
It's for this aim that I put the flag `re.DOTALL`in order to make the following pattern portion `.+?` capable to pass the newlines until the end of the entry.
4)
==
I want the matching to stop at the end of the Entry desired, not inside the next one, so that the group defined by the parenthesises in `(>Entry *%s(?![^\n]+?\d).+?)` will catch exactly what we want
Hence, I put at the end a positive look-ahaed assertion `(?=>|(?:\s*\Z))` that says that the character before which the running ungreedy `.+?` must stop to match is either `>` (beginning of the next Entry) or the end of the string `\Z`.
As it is possible that the end of the last Entry wouldn't exactly be the end of the entire string, I put `\s*` that means "possible whitespaces before the very end".
So `\s*\Z` means "there can be whitespaces before to bump into the end of the string"
Whitespaces are a `blank` , `\f`, `\n`, `\r`, `\t`, `\v`
|
Not entirely sure what you're asking. Does this get you any closer? It will put all your entries as dictionary keys and a list of all its entries. Assuming it is formatted like I believe it is. Does it have duplicate entries? Here's what I've got:
```
entries = {}
key = ''
for entry in open('entries.txt'):
if entry.startswith('>Entry'):
key = entry[1:].strip() # removes > and newline
entries[key] = []
else:
entries[key].append(entry)
```
|
14,965,542
|
I have a huge file from which I need data for specific entries. File structure is:
```
>Entry1.1
#size=1688
704 1 1 1 4
979 2 2 2 0
1220 1 1 1 4
1309 1 1 1 4
1316 1 1 1 4
1372 1 1 1 4
1374 1 1 1 4
1576 1 1 1 4
>Entry2.1
#size=6251
6110 3 1.5 0 2
6129 2 2 2 2
6136 1 1 1 4
6142 3 3 3 2
6143 4 4 4 1
6150 1 1 1 4
6152 1 1 1 4
>Entry3.2
#size=1777
AND SO ON-----------
```
What I have to achieve is that I need to extract all the lines (complete record) for certain entries. For e.x. I need record for Entry1.1 than I can use name of entry '>Entry1.1' till next '>' as markers in REGEX to extract lines in between. But I do not know how to build such complex REGEX expressions. Once I have such expression the I will put it a FOR loop:
```
For entry in entrylist:
GET record from big_file
DO some processing
WRITE in result file
```
What could be the REGEX to perform such extraction of record for specific entries? Is there any more pythonic way to achieve this? I would appreciate your help on this.
AK
|
2013/02/19
|
[
"https://Stackoverflow.com/questions/14965542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031842/"
] |
I'm no good with regexes, so I try to look for non-regex solutions whenever I can. In Python, the natural place to store iteration logic is in a generator, and so I'd use something like this (no-itertools-required version):
```
def group_by_marker(seq, marker):
group = []
# advance past negatives at start
for line in seq:
if marker(line):
group = [line]
break
for line in seq:
# found a new group start; yield what we've got
# and start over
if marker(line) and group:
yield group
group = []
group.append(line)
# might have extra bits left..
if group:
yield group
```
In your example case, we get:
```
>>> with open("entry0.dat") as fp:
... marker = lambda line: line.startswith(">Entry")
... for group in group_by_marker(fp, marker):
... print(repr(group[0]), len(group))
...
'>Entry1.1\n' 10
'>Entry2.1\n' 9
'>Entry3.2\n' 4
```
One advantage to this approach is that we never have to keep more than one group in memory, so it's handy for really large files. It's not nearly as fast as a regex, although if the file is 1 GB you're probably I/O bound anyhow.
|
Not entirely sure what you're asking. Does this get you any closer? It will put all your entries as dictionary keys and a list of all its entries. Assuming it is formatted like I believe it is. Does it have duplicate entries? Here's what I've got:
```
entries = {}
key = ''
for entry in open('entries.txt'):
if entry.startswith('>Entry'):
key = entry[1:].strip() # removes > and newline
entries[key] = []
else:
entries[key].append(entry)
```
|
14,965,542
|
I have a huge file from which I need data for specific entries. File structure is:
```
>Entry1.1
#size=1688
704 1 1 1 4
979 2 2 2 0
1220 1 1 1 4
1309 1 1 1 4
1316 1 1 1 4
1372 1 1 1 4
1374 1 1 1 4
1576 1 1 1 4
>Entry2.1
#size=6251
6110 3 1.5 0 2
6129 2 2 2 2
6136 1 1 1 4
6142 3 3 3 2
6143 4 4 4 1
6150 1 1 1 4
6152 1 1 1 4
>Entry3.2
#size=1777
AND SO ON-----------
```
What I have to achieve is that I need to extract all the lines (complete record) for certain entries. For e.x. I need record for Entry1.1 than I can use name of entry '>Entry1.1' till next '>' as markers in REGEX to extract lines in between. But I do not know how to build such complex REGEX expressions. Once I have such expression the I will put it a FOR loop:
```
For entry in entrylist:
GET record from big_file
DO some processing
WRITE in result file
```
What could be the REGEX to perform such extraction of record for specific entries? Is there any more pythonic way to achieve this? I would appreciate your help on this.
AK
|
2013/02/19
|
[
"https://Stackoverflow.com/questions/14965542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031842/"
] |
With regex
```
import re
ss = '''
>Entry1.1
#size=1688
704 1 1 1 4
979 2 2 2 0
1220 1 1 1 4
1309 1 1 1 4
1316 1 1 1 4
1372 1 1 1 4
1374 1 1 1 4
1576 1 1 1 4
>Entry2.1
#size=6251
6110 3 1.5 0 2
6129 2 2 2 2
6136 1 1 1 4
6142 3 3 3 2
6143 4 4 4 1
6150 1 1 1 4
6152 1 1 1 4
>Entry3.2
#size=1777
AND SO ON-----------
'''
patbase = '(>Entry *%s(?![^\n]+?\d).+?)(?=>|(?:\s*\Z))'
while True:
x = raw_input('What entry do you want ? : ')
found = re.findall(patbase % x, ss, re.DOTALL)
if found:
print 'found ==',found
for each_entry in found:
print '\n%s\n' % each_entry
else:
print '\n ** There is no such an entry **\n'
```
Explanation of `'(>Entry *%s(?![^\n]+?\d).+?)(?=>|(?:\s*\Z))'` :
1)
==
`%s` receives the reference of entry: 1.1 , 2 , 2.1 etc
2)
==
The portion `(?![^\n]+?\d)` is to do a verification.
`(?![^\n]+?\d)` is a negative look-ahead assertion that says that what is after `%s` must not be `[^\n]+?\d` that is to say any characters `[^\n]+?` before a digit `\d`
I write `[^\n]` to mean "any character except a newline `\n`".
I am obliged to write this instead of simply `.+?` because I put the flag `re.DOTALL` and the pattern portion `.+?` would be acting until the end of the entry.
However, I only want to verify that after the entered reference (represented by %s in the pattern), there won't be supplementary digits before the end OF THE LINE, entered by error
All that is because if there is an Entry2.1 but no Entry2 , and the user enters only 2 because he wants Entry2 and no other, the regex would detect the presence of the Entry2.1 and would yield it, though the user would really like Entry2 in fact.
3)
==
At the end of `'(>Entry *%s(?![^\n]+?\d).+?)` , the part `.+?` will catch the complete block of the Entry, because the dot represents any character, comprised a newline `\n`
It's for this aim that I put the flag `re.DOTALL`in order to make the following pattern portion `.+?` capable to pass the newlines until the end of the entry.
4)
==
I want the matching to stop at the end of the Entry desired, not inside the next one, so that the group defined by the parenthesises in `(>Entry *%s(?![^\n]+?\d).+?)` will catch exactly what we want
Hence, I put at the end a positive look-ahaed assertion `(?=>|(?:\s*\Z))` that says that the character before which the running ungreedy `.+?` must stop to match is either `>` (beginning of the next Entry) or the end of the string `\Z`.
As it is possible that the end of the last Entry wouldn't exactly be the end of the entire string, I put `\s*` that means "possible whitespaces before the very end".
So `\s*\Z` means "there can be whitespaces before to bump into the end of the string"
Whitespaces are a `blank` , `\f`, `\n`, `\r`, `\t`, `\v`
|
I'm no good with regexes, so I try to look for non-regex solutions whenever I can. In Python, the natural place to store iteration logic is in a generator, and so I'd use something like this (no-itertools-required version):
```
def group_by_marker(seq, marker):
group = []
# advance past negatives at start
for line in seq:
if marker(line):
group = [line]
break
for line in seq:
# found a new group start; yield what we've got
# and start over
if marker(line) and group:
yield group
group = []
group.append(line)
# might have extra bits left..
if group:
yield group
```
In your example case, we get:
```
>>> with open("entry0.dat") as fp:
... marker = lambda line: line.startswith(">Entry")
... for group in group_by_marker(fp, marker):
... print(repr(group[0]), len(group))
...
'>Entry1.1\n' 10
'>Entry2.1\n' 9
'>Entry3.2\n' 4
```
One advantage to this approach is that we never have to keep more than one group in memory, so it's handy for really large files. It's not nearly as fast as a regex, although if the file is 1 GB you're probably I/O bound anyhow.
|
5,086,419
|
I wrote the following script in python to convert datetime from any given timezone to EST.
```
from datetime import datetime, timedelta
from pytz import timezone
import pytz
utc = pytz.utc
# Converts char representation of int to numeric representation '121'->121, '-1729'->-1729
def toInt(ch):
ret = 0
minus = False
if ch[0] == '-':
ch = ch[1:]
minus = True
for c in ch:
ret = ret*10 + ord(c) - 48
if minus:
ret *= -1
return ret
# Converts given datetime in tzone to EST. dt = 'yyyymmdd' and tm = 'hh:mm:ss'
def convert2EST(dt, tm, tzone):
y = toInt(dt[0:4])
m = toInt(dt[4:6])
d = toInt(dt[6:8])
hh = toInt(tm[0:2])
mm = toInt(tm[3:5])
ss = toInt(tm[6:8])
# EST timezone and given timezone
est_tz = timezone('US/Eastern')
given_tz = timezone(tzone)
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
# Initialize given datetime and convert it to local/given timezone
local = datetime(y, m, d, hh, mm, ss)
local_dt = given_tz.localize(local)
est_dt = est_tz.normalize(local_dt.astimezone(est_tz))
dt = est_dt.strftime(fmt)
print dt
return dt
```
When I call this method with
convert2EST('20110220', '11:00:00', 'America/Sao\_Paulo')
output is '2011-02-20 08:00:00 EST-0500' but DST in Brazil ended on 20th Feb and correct answer should be '2011-02-20 09:00:00 EST-0500'.
From some experimentation I figured out that according to pytz Brazil's DST ends on 27th Feb which is incorrect.
Does pytz contains wrong data or I am missing something. Any help or comments will be much appreciated.
|
2011/02/23
|
[
"https://Stackoverflow.com/questions/5086419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/629424/"
] |
Firstly slightly less insane implementation:
```
import datetime
import pytz
EST = pytz.timezone('US/Eastern')
def convert2EST(date, time, tzone):
dt = datetime.datetime.strptime(date+time, '%Y%m%d%H:%M:%S')
tz = pytz.timezone(tzone)
dt = tz.localize(dt)
return dt.astimezone(EST)
```
Now, we try to call it:
```
>>> print convert2EST('20110220', '11:00:00', 'America/Sao_Paulo')
2011-02-20 09:00:00-05:00
```
As we see, we get the correct answer.
Update: I got it!
Brazil changed it's daylight savings in 2008. It's unclear what it was before that, but likely your data is old.
This is probably not pytz fault as pytz is able to use your operating systems database. You probably need to update your operating system. This is (I guess) the reason I got the correct answer even with a pytz from 2005, it used the (updated) data from my OS.
|
Seems like you have answered your own question. If pytz says DST ends on 27 Feb in Brazil, it's wrong. DST in Brazil ends on the [third Sunday of February](http://translate.google.com/translate?js=n&prev=_t&hl=en&ie=UTF-8&layout=2&eotf=1&sl=pt&tl=en&u=http%3A%2F%2Fpcdsh01.on.br%2FDecHV.html), unless that Sunday falls during Carnival; it does not this year, so DST is not delayed.
That said, you seem to be rolling your own converter unnecessarily. You should look at the [`time`](http://docs.python.org/library/time.html) module, which eases conversions between gmt and local time, among other things.
|
30,368,275
|
I have file test.robot with test cases.
How can i get the list of this test cases without activating the tests, from command line or python?
|
2015/05/21
|
[
"https://Stackoverflow.com/questions/30368275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923721/"
] |
You can check out [testdoc tool](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-data-documentation-tool-testdoc). Like explained in the doc, "The created documentation is in HTML format and it includes name, documentation and other metadata of each test suite and test case".
|
**For v3.2 and up:**
In RobotFramework 3.2 [the parsing APIs have been rewritten](https://github.com/robotframework/robotframework/blob/master/doc/releasenotes/rf-3.2.rst#parsing-apis-have-been-rewritten), so the answer from Bryan Oakley won't work on these versions anymore.
The proper code that is compatible with both pre-3.2 and post-3.2 versions is the following:
```
from robot.running import TestSuiteBuilder
from robot.model import SuiteVisitor
class TestCasesFinder(SuiteVisitor):
def __init__(self):
self.tests = []
def visit_test(self, test):
self.tests.append(test)
builder = TestSuiteBuilder()
testsuite = builder.build('testsuite/')
finder = TestCasesFinder()
testsuite.visit(finder)
print(*finder.tests)
```
Further reading:
* [Visitor model](https://robot-framework.readthedocs.io/en/latest/autodoc/robot.model.html#module-robot.model.visitor)
* [`TestSuiteBuilder` class reference](https://robot-framework.readthedocs.io/en/latest/autodoc/robot.running.builder.html#robot.running.builder.builders.TestSuiteBuilder)
|
30,368,275
|
I have file test.robot with test cases.
How can i get the list of this test cases without activating the tests, from command line or python?
|
2015/05/21
|
[
"https://Stackoverflow.com/questions/30368275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4923721/"
] |
Robot test suites are easy to parse with the robot parser:
```
from robot.parsing.model import TestData
suite = TestData(parent=None, source=path_to_test_suite)
for testcase in suite.testcase_table:
print(testcase.name)
```
|
**For v3.2 and up:**
In RobotFramework 3.2 [the parsing APIs have been rewritten](https://github.com/robotframework/robotframework/blob/master/doc/releasenotes/rf-3.2.rst#parsing-apis-have-been-rewritten), so the answer from Bryan Oakley won't work on these versions anymore.
The proper code that is compatible with both pre-3.2 and post-3.2 versions is the following:
```
from robot.running import TestSuiteBuilder
from robot.model import SuiteVisitor
class TestCasesFinder(SuiteVisitor):
def __init__(self):
self.tests = []
def visit_test(self, test):
self.tests.append(test)
builder = TestSuiteBuilder()
testsuite = builder.build('testsuite/')
finder = TestCasesFinder()
testsuite.visit(finder)
print(*finder.tests)
```
Further reading:
* [Visitor model](https://robot-framework.readthedocs.io/en/latest/autodoc/robot.model.html#module-robot.model.visitor)
* [`TestSuiteBuilder` class reference](https://robot-framework.readthedocs.io/en/latest/autodoc/robot.running.builder.html#robot.running.builder.builders.TestSuiteBuilder)
|
50,254,723
|
I updated the python version from 3.6.4 to 3.6.5 today. This is because, in the process of distributing to Heroku, it recommends version 3.6.5. Therefore, the following power shell contents were confirmed.
```
Writing objects: 100% (35/35), 11.68 KiB | 0 bytes/s, done.
Total 35 (delta 3), reused 0 (delta 0)
remote: Compressing source files... done.
remote: -----> Python app detected
remote: ! The latest version of Python 3 is python-3.6.5 (you are using ÿþpython-3.6.5, which is unsupported).
remote: ! We recommend upgrading by specifying the latest version (python-3.6.5).
remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes
remote: -----> Installing ÿþpython-3.6.5
remote: ! Requested runtime (ÿþpython-3.6.5) is not available for this stack (heroku-16).
remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support
remote: ! Push rejected, failed to compile Python app.
remote:
remote: ! Push failed
remote:
remote: ! Push rejected to XXXXXXXX.
remote:
To https://git.heroku.com/XXXXXXXX.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/XXXXXXXX.git
```
After changing my `runtime.txt` file to UTF-8, I now get the following error:
```
Writing objects: 100% (35/35), 11.68 KiB | 0 bytes/s, done.
Total 35 (delta 3), reused 0 (delta 0)
remote: Compressing source files... done.
remote: -----> Python app detected
remote: ! The latest version of Python 3 is python-3.6.5 (you are using python-3.6.5, which is unsupported).
remote: ! We recommend upgrading by specifying the latest version (python-3.6.5).
remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes
remote: -----> Installing python-3.6.5
remote: ! Requested runtime (python-3.6.5) is not available for this stack (heroku-16).
remote: ! Aborting. More info: https://devcenter.heroku.com/articles/python-support
remote: ! Push rejected, failed to compile Python app.
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to XXXXXXXX.
remote:
To https://git.heroku.com/XXXXXXXX.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/XXXXXXXX.git
```
Why is `python-3.6.5` being rejected? Isn't that exactly what Heroku says is the default version?
|
2018/05/09
|
[
"https://Stackoverflow.com/questions/50254723",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9556991/"
] |
Heroku believes that your `runtime.txt` contains some extra characters:
```
ÿþpython-3.6.5
```
This is probably [byte-order mark for a file encoded as UTF-16 in little-endian order](https://en.wikipedia.org/wiki/Byte_order_mark#UTF-16). Make sure you're using a sane encoding for that file (and others). UTF-8 is a good choice in virtually all situations.
|
You're trying to install `ÿþpython-3.6.5` not `python-3.6.5` as the console output suggests. Remove `ÿþ` and it should work as expected.
|
65,030,618
|
TLDR
====
One of my models contains data that could either be a charfield, textfield, or boolfield based on a choice made in a separate model that it is connected to through a foreignkey. What's the most efficient way to model this in Django?
My problem
==========
I'm putting together a Django app that outputs a python {'key': 'value'} dictionary in a somewhat lengthy two-step process. In the first step, users design a custom 'Template' that contains a collection of 'TemplateEntries'. In pseudo-code:
```
Template MODEL
foreign key: User
description = textfield
name = charfield
TemplateEntry MODEL
foreign key: Template
key = charfield
value_type = charfield(choices='CharField', 'TextField', 'BoolField')
description = textfield
order = positivesmallintegerfield (So users can re-arrange the order of TemplateEntries when creating the Template)
```
EXAMPLE TEMPLATE FORM #1
1. [Description] | [Key] | Field Type: [Choice between **Char Field**, Text Field, Bool Field]
2. [Description] | [Key] | Field Type: [Choice between **Char Field**, Text Field, Bool Field]
3. [Description] | [Key] | Field Type: [Choice between Char Field, Text Field, **Bool Field**]
4. [Description] | [Key] | Field Type: [Choice between **Char Field**, Text Field, Bool Field]
5. [Description] | [Key] | Field Type: [Choice between Char Field, **Text Field**, Bool Field]
In the second step, the same or different user is presented with a form based off of the Template and with the appropriate field for each of the values. In pseudocode:
```
EntrySet MODEL
foreignkey: User
foreignkey: Template
name = charfield
Entry MODEL
foreignkey: EntrySet
foreignkey: TemplateEntry
value = ??
```
EXAMPLE ENTRYSET FORM FOR TEMPLATE #1
(the description for what entry represents is carried over from TemplateEntry)
1. [Char Field]
2. [Char Field]
3. True/False (Bool Field)
4. [Char Field]
5. [----------------Text Field-----------------]
Finally, the dictionary is created by combining the key field from each TemplateEntry in Template with the value field from each Entry in EntrySet.
The problem I'm having is that I don't know how to model the 'value' field in the entry model, since it could take the form of a charfield, textfield, or boolfield. My current approach is to break it up into three different fields: value\_short = charfield, value\_long = textfield, value\_bool = boolfield and to iterate through each of them when creating the dictionary, only taking the value of whichever field has content. However, this seems inefficient and would result in errors if more than one of them contained a value. Any suggestions on how to fix this issue or improve my model would be appreciated!
|
2020/11/27
|
[
"https://Stackoverflow.com/questions/65030618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14621609/"
] |
If your database supports [jsonfield](https://docs.djangoproject.com/en/3.1/ref/contrib/postgres/fields/#jsonfield) and you want to keep it as a single field, you can use it.
If it doesn't, first of all, if I'm not skipping something, you can use both textfield and charfield as textfield instead of separating them. Other than that, the best option is to leave these fields with the options `null=True,blank=True`. Then, add data to the relevant field according to its type and return whichever is not null to the user. And if you need to nullify the previous value when the data type changes, I recommend you do it in view or form or in pre\_save signal.
|
I feel that `contenttypes` will be useful for you, and help you to prevent reinventing the wheel:
<https://docs.djangoproject.com/en/3.1/ref/contrib/contenttypes/>
|
2,030,970
|
I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:
[](https://i.stack.imgur.com/FUL1M.png)
But I'm looking for something like this:
[](https://i.stack.imgur.com/ASwJl.png)
Example Code:
```
from matplotlib import pyplot as plt
import random
foo = lambda : random.gauss(0.0,1.0)
x = [foo() for i in xrange(5000)]
y = [foo() for i in xrange(5000)]
pairs = zip(x,y)
#using hexbin I supply the x,y series and it does the binning for me
hexfig = plt.figure()
hexplt = hexfig.add_subplot(1,1,1)
hexplt.hexbin(x, y, gridsize = 20)
#to use imshow I have to bin the data myself
def histBin(pairsData,xbins,ybins=None):
if (ybins == None): ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = min(xdata),max(xdata)
xwidth = xmax-xmin
ymin,ymax = min(ydata),max(ydata)
ywidth = ymax-ymin
def xbin(xval):
xbin = int(xbins*(xval-xmin)/xwidth)
return max(min(xbin,xbins-1),0)
def ybin(yval):
ybin = int(ybins*(yval-ymin)/ywidth)
return max(min(ybin,ybins-1),0)
hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)]
for x,y in pairsData:
hist[ybin(y)][xbin(x)] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
#plot using imshow
imdata,extent = histBin(pairs,20)
imfig = plt.figure()
implt = imfig.add_subplot(1,1,1)
implt.imshow(imdata,extent = extent, interpolation = 'nearest')
plt.draw()
plt.show()
```
It seems like there should already be a way to do this without writing my own "binning" method and using imshow.
|
2010/01/08
|
[
"https://Stackoverflow.com/questions/2030970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43665/"
] |
Numpy has a function called [histogram2d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html), whose docstring also shows you how to visualize it using Matplotlib. Add `interpolation=nearest` to the imshow call to disable the interpolation.
|
Is `matplotlib.pyplot.hist` what you're looking for?
```
>>> help(matplotlib.pyplot.hist)
Help on function hist in module matplotlib.pyplot:
hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, botto
m=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=Fa
lse, hold=None, **kwargs)
call signature::
hist(x, bins=10, range=None, normed=False, cumulative=False,
bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False, **kwargs)
Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
[*patches0*, *patches1*,...]) if the input contains multiple
data.
```
|
2,030,970
|
I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:
[](https://i.stack.imgur.com/FUL1M.png)
But I'm looking for something like this:
[](https://i.stack.imgur.com/ASwJl.png)
Example Code:
```
from matplotlib import pyplot as plt
import random
foo = lambda : random.gauss(0.0,1.0)
x = [foo() for i in xrange(5000)]
y = [foo() for i in xrange(5000)]
pairs = zip(x,y)
#using hexbin I supply the x,y series and it does the binning for me
hexfig = plt.figure()
hexplt = hexfig.add_subplot(1,1,1)
hexplt.hexbin(x, y, gridsize = 20)
#to use imshow I have to bin the data myself
def histBin(pairsData,xbins,ybins=None):
if (ybins == None): ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = min(xdata),max(xdata)
xwidth = xmax-xmin
ymin,ymax = min(ydata),max(ydata)
ywidth = ymax-ymin
def xbin(xval):
xbin = int(xbins*(xval-xmin)/xwidth)
return max(min(xbin,xbins-1),0)
def ybin(yval):
ybin = int(ybins*(yval-ymin)/ywidth)
return max(min(ybin,ybins-1),0)
hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)]
for x,y in pairsData:
hist[ybin(y)][xbin(x)] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
#plot using imshow
imdata,extent = histBin(pairs,20)
imfig = plt.figure()
implt = imfig.add_subplot(1,1,1)
implt.imshow(imdata,extent = extent, interpolation = 'nearest')
plt.draw()
plt.show()
```
It seems like there should already be a way to do this without writing my own "binning" method and using imshow.
|
2010/01/08
|
[
"https://Stackoverflow.com/questions/2030970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43665/"
] |
I just submitted a pull request for this <https://github.com/matplotlib/matplotlib/pull/805> . Hopefully, it will be accepted.
|
Is `matplotlib.pyplot.hist` what you're looking for?
```
>>> help(matplotlib.pyplot.hist)
Help on function hist in module matplotlib.pyplot:
hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, botto
m=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=Fa
lse, hold=None, **kwargs)
call signature::
hist(x, bins=10, range=None, normed=False, cumulative=False,
bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False, **kwargs)
Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
[*patches0*, *patches1*,...]) if the input contains multiple
data.
```
|
2,030,970
|
I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:
[](https://i.stack.imgur.com/FUL1M.png)
But I'm looking for something like this:
[](https://i.stack.imgur.com/ASwJl.png)
Example Code:
```
from matplotlib import pyplot as plt
import random
foo = lambda : random.gauss(0.0,1.0)
x = [foo() for i in xrange(5000)]
y = [foo() for i in xrange(5000)]
pairs = zip(x,y)
#using hexbin I supply the x,y series and it does the binning for me
hexfig = plt.figure()
hexplt = hexfig.add_subplot(1,1,1)
hexplt.hexbin(x, y, gridsize = 20)
#to use imshow I have to bin the data myself
def histBin(pairsData,xbins,ybins=None):
if (ybins == None): ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = min(xdata),max(xdata)
xwidth = xmax-xmin
ymin,ymax = min(ydata),max(ydata)
ywidth = ymax-ymin
def xbin(xval):
xbin = int(xbins*(xval-xmin)/xwidth)
return max(min(xbin,xbins-1),0)
def ybin(yval):
ybin = int(ybins*(yval-ymin)/ywidth)
return max(min(ybin,ybins-1),0)
hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)]
for x,y in pairsData:
hist[ybin(y)][xbin(x)] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
#plot using imshow
imdata,extent = histBin(pairs,20)
imfig = plt.figure()
implt = imfig.add_subplot(1,1,1)
implt.imshow(imdata,extent = extent, interpolation = 'nearest')
plt.draw()
plt.show()
```
It seems like there should already be a way to do this without writing my own "binning" method and using imshow.
|
2010/01/08
|
[
"https://Stackoverflow.com/questions/2030970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43665/"
] |
I realize that there is a patch submitted to matplotlib, but I adopted the code from the other example to acommodate a few needs that I had.
now the histogram is plotted from the lower left corner, as in conventional math (not computing)
also, values outside the binning range are ignored and I use a 2d numpy array for the twodimensional array
I changed the data input from pairs to two 1D arrays since this is how data is supplied to scatter(x,y) and alike functions
```
def histBin(x,y,x_range=(0.0,1.0),y_range=(0.0,1.0),xbins=10,ybins=None):
""" Helper function to do 2D histogram binning
x, y are lists / 2D arrays
x_range and yrange define the range of the plot similar to the hist(range=...)
xbins,ybins are the number of bins within this range.
"""
pairsData = zip(x,y)
if (ybins == None):
ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = x_range
xmin = float(xmin)
xmax = float(xmax)
xwidth = xmax-xmin
ymin,ymax = y_range
ymin = float(ymin)
ymax = float(ymax)
ywidth = ymax-ymin
def xbin(xval):
return floor(xbins*(xval-xmin)/xwidth) if xmin <= xval < xmax else xbins-1 if xval ==xmax else None
def ybin(yval):
return floor(ybins*(yval-ymin)/ywidth) if ymin <= yval < ymax else ybins-1 if yval ==ymax else None
hist = numpy.zeros((xbins,ybins))
for x,y in pairsData:
i_x,i_y = xbin(x),ybin(ymax-y)
if i_x is not None and i_y is not None:
hist[i_y,i_x] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
```
|
Is `matplotlib.pyplot.hist` what you're looking for?
```
>>> help(matplotlib.pyplot.hist)
Help on function hist in module matplotlib.pyplot:
hist(x, bins=10, range=None, normed=False, weights=None, cumulative=False, botto
m=None, histtype='bar', align='mid', orientation='vertical', rwidth=None, log=Fa
lse, hold=None, **kwargs)
call signature::
hist(x, bins=10, range=None, normed=False, cumulative=False,
bottom=None, histtype='bar', align='mid',
orientation='vertical', rwidth=None, log=False, **kwargs)
Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
[*patches0*, *patches1*,...]) if the input contains multiple
data.
```
|
2,030,970
|
I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:
[](https://i.stack.imgur.com/FUL1M.png)
But I'm looking for something like this:
[](https://i.stack.imgur.com/ASwJl.png)
Example Code:
```
from matplotlib import pyplot as plt
import random
foo = lambda : random.gauss(0.0,1.0)
x = [foo() for i in xrange(5000)]
y = [foo() for i in xrange(5000)]
pairs = zip(x,y)
#using hexbin I supply the x,y series and it does the binning for me
hexfig = plt.figure()
hexplt = hexfig.add_subplot(1,1,1)
hexplt.hexbin(x, y, gridsize = 20)
#to use imshow I have to bin the data myself
def histBin(pairsData,xbins,ybins=None):
if (ybins == None): ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = min(xdata),max(xdata)
xwidth = xmax-xmin
ymin,ymax = min(ydata),max(ydata)
ywidth = ymax-ymin
def xbin(xval):
xbin = int(xbins*(xval-xmin)/xwidth)
return max(min(xbin,xbins-1),0)
def ybin(yval):
ybin = int(ybins*(yval-ymin)/ywidth)
return max(min(ybin,ybins-1),0)
hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)]
for x,y in pairsData:
hist[ybin(y)][xbin(x)] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
#plot using imshow
imdata,extent = histBin(pairs,20)
imfig = plt.figure()
implt = imfig.add_subplot(1,1,1)
implt.imshow(imdata,extent = extent, interpolation = 'nearest')
plt.draw()
plt.show()
```
It seems like there should already be a way to do this without writing my own "binning" method and using imshow.
|
2010/01/08
|
[
"https://Stackoverflow.com/questions/2030970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43665/"
] |
Numpy has a function called [histogram2d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html), whose docstring also shows you how to visualize it using Matplotlib. Add `interpolation=nearest` to the imshow call to disable the interpolation.
|
Use `xlim` and `ylim` to set the limits of the plot. `xlim(-3, 3)` and `ylim(-3, 3)` should do it.
|
2,030,970
|
I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:
[](https://i.stack.imgur.com/FUL1M.png)
But I'm looking for something like this:
[](https://i.stack.imgur.com/ASwJl.png)
Example Code:
```
from matplotlib import pyplot as plt
import random
foo = lambda : random.gauss(0.0,1.0)
x = [foo() for i in xrange(5000)]
y = [foo() for i in xrange(5000)]
pairs = zip(x,y)
#using hexbin I supply the x,y series and it does the binning for me
hexfig = plt.figure()
hexplt = hexfig.add_subplot(1,1,1)
hexplt.hexbin(x, y, gridsize = 20)
#to use imshow I have to bin the data myself
def histBin(pairsData,xbins,ybins=None):
if (ybins == None): ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = min(xdata),max(xdata)
xwidth = xmax-xmin
ymin,ymax = min(ydata),max(ydata)
ywidth = ymax-ymin
def xbin(xval):
xbin = int(xbins*(xval-xmin)/xwidth)
return max(min(xbin,xbins-1),0)
def ybin(yval):
ybin = int(ybins*(yval-ymin)/ywidth)
return max(min(ybin,ybins-1),0)
hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)]
for x,y in pairsData:
hist[ybin(y)][xbin(x)] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
#plot using imshow
imdata,extent = histBin(pairs,20)
imfig = plt.figure()
implt = imfig.add_subplot(1,1,1)
implt.imshow(imdata,extent = extent, interpolation = 'nearest')
plt.draw()
plt.show()
```
It seems like there should already be a way to do this without writing my own "binning" method and using imshow.
|
2010/01/08
|
[
"https://Stackoverflow.com/questions/2030970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43665/"
] |
Numpy has a function called [histogram2d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html), whose docstring also shows you how to visualize it using Matplotlib. Add `interpolation=nearest` to the imshow call to disable the interpolation.
|
I just submitted a pull request for this <https://github.com/matplotlib/matplotlib/pull/805> . Hopefully, it will be accepted.
|
2,030,970
|
I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:
[](https://i.stack.imgur.com/FUL1M.png)
But I'm looking for something like this:
[](https://i.stack.imgur.com/ASwJl.png)
Example Code:
```
from matplotlib import pyplot as plt
import random
foo = lambda : random.gauss(0.0,1.0)
x = [foo() for i in xrange(5000)]
y = [foo() for i in xrange(5000)]
pairs = zip(x,y)
#using hexbin I supply the x,y series and it does the binning for me
hexfig = plt.figure()
hexplt = hexfig.add_subplot(1,1,1)
hexplt.hexbin(x, y, gridsize = 20)
#to use imshow I have to bin the data myself
def histBin(pairsData,xbins,ybins=None):
if (ybins == None): ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = min(xdata),max(xdata)
xwidth = xmax-xmin
ymin,ymax = min(ydata),max(ydata)
ywidth = ymax-ymin
def xbin(xval):
xbin = int(xbins*(xval-xmin)/xwidth)
return max(min(xbin,xbins-1),0)
def ybin(yval):
ybin = int(ybins*(yval-ymin)/ywidth)
return max(min(ybin,ybins-1),0)
hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)]
for x,y in pairsData:
hist[ybin(y)][xbin(x)] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
#plot using imshow
imdata,extent = histBin(pairs,20)
imfig = plt.figure()
implt = imfig.add_subplot(1,1,1)
implt.imshow(imdata,extent = extent, interpolation = 'nearest')
plt.draw()
plt.show()
```
It seems like there should already be a way to do this without writing my own "binning" method and using imshow.
|
2010/01/08
|
[
"https://Stackoverflow.com/questions/2030970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43665/"
] |
Numpy has a function called [histogram2d](http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html), whose docstring also shows you how to visualize it using Matplotlib. Add `interpolation=nearest` to the imshow call to disable the interpolation.
|
I realize that there is a patch submitted to matplotlib, but I adopted the code from the other example to acommodate a few needs that I had.
now the histogram is plotted from the lower left corner, as in conventional math (not computing)
also, values outside the binning range are ignored and I use a 2d numpy array for the twodimensional array
I changed the data input from pairs to two 1D arrays since this is how data is supplied to scatter(x,y) and alike functions
```
def histBin(x,y,x_range=(0.0,1.0),y_range=(0.0,1.0),xbins=10,ybins=None):
""" Helper function to do 2D histogram binning
x, y are lists / 2D arrays
x_range and yrange define the range of the plot similar to the hist(range=...)
xbins,ybins are the number of bins within this range.
"""
pairsData = zip(x,y)
if (ybins == None):
ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = x_range
xmin = float(xmin)
xmax = float(xmax)
xwidth = xmax-xmin
ymin,ymax = y_range
ymin = float(ymin)
ymax = float(ymax)
ywidth = ymax-ymin
def xbin(xval):
return floor(xbins*(xval-xmin)/xwidth) if xmin <= xval < xmax else xbins-1 if xval ==xmax else None
def ybin(yval):
return floor(ybins*(yval-ymin)/ywidth) if ymin <= yval < ymax else ybins-1 if yval ==ymax else None
hist = numpy.zeros((xbins,ybins))
for x,y in pairsData:
i_x,i_y = xbin(x),ybin(ymax-y)
if i_x is not None and i_y is not None:
hist[i_y,i_x] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
```
|
2,030,970
|
I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:
[](https://i.stack.imgur.com/FUL1M.png)
But I'm looking for something like this:
[](https://i.stack.imgur.com/ASwJl.png)
Example Code:
```
from matplotlib import pyplot as plt
import random
foo = lambda : random.gauss(0.0,1.0)
x = [foo() for i in xrange(5000)]
y = [foo() for i in xrange(5000)]
pairs = zip(x,y)
#using hexbin I supply the x,y series and it does the binning for me
hexfig = plt.figure()
hexplt = hexfig.add_subplot(1,1,1)
hexplt.hexbin(x, y, gridsize = 20)
#to use imshow I have to bin the data myself
def histBin(pairsData,xbins,ybins=None):
if (ybins == None): ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = min(xdata),max(xdata)
xwidth = xmax-xmin
ymin,ymax = min(ydata),max(ydata)
ywidth = ymax-ymin
def xbin(xval):
xbin = int(xbins*(xval-xmin)/xwidth)
return max(min(xbin,xbins-1),0)
def ybin(yval):
ybin = int(ybins*(yval-ymin)/ywidth)
return max(min(ybin,ybins-1),0)
hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)]
for x,y in pairsData:
hist[ybin(y)][xbin(x)] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
#plot using imshow
imdata,extent = histBin(pairs,20)
imfig = plt.figure()
implt = imfig.add_subplot(1,1,1)
implt.imshow(imdata,extent = extent, interpolation = 'nearest')
plt.draw()
plt.show()
```
It seems like there should already be a way to do this without writing my own "binning" method and using imshow.
|
2010/01/08
|
[
"https://Stackoverflow.com/questions/2030970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43665/"
] |
I just submitted a pull request for this <https://github.com/matplotlib/matplotlib/pull/805> . Hopefully, it will be accepted.
|
Use `xlim` and `ylim` to set the limits of the plot. `xlim(-3, 3)` and `ylim(-3, 3)` should do it.
|
2,030,970
|
I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:
[](https://i.stack.imgur.com/FUL1M.png)
But I'm looking for something like this:
[](https://i.stack.imgur.com/ASwJl.png)
Example Code:
```
from matplotlib import pyplot as plt
import random
foo = lambda : random.gauss(0.0,1.0)
x = [foo() for i in xrange(5000)]
y = [foo() for i in xrange(5000)]
pairs = zip(x,y)
#using hexbin I supply the x,y series and it does the binning for me
hexfig = plt.figure()
hexplt = hexfig.add_subplot(1,1,1)
hexplt.hexbin(x, y, gridsize = 20)
#to use imshow I have to bin the data myself
def histBin(pairsData,xbins,ybins=None):
if (ybins == None): ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = min(xdata),max(xdata)
xwidth = xmax-xmin
ymin,ymax = min(ydata),max(ydata)
ywidth = ymax-ymin
def xbin(xval):
xbin = int(xbins*(xval-xmin)/xwidth)
return max(min(xbin,xbins-1),0)
def ybin(yval):
ybin = int(ybins*(yval-ymin)/ywidth)
return max(min(ybin,ybins-1),0)
hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)]
for x,y in pairsData:
hist[ybin(y)][xbin(x)] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
#plot using imshow
imdata,extent = histBin(pairs,20)
imfig = plt.figure()
implt = imfig.add_subplot(1,1,1)
implt.imshow(imdata,extent = extent, interpolation = 'nearest')
plt.draw()
plt.show()
```
It seems like there should already be a way to do this without writing my own "binning" method and using imshow.
|
2010/01/08
|
[
"https://Stackoverflow.com/questions/2030970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43665/"
] |
I realize that there is a patch submitted to matplotlib, but I adopted the code from the other example to acommodate a few needs that I had.
now the histogram is plotted from the lower left corner, as in conventional math (not computing)
also, values outside the binning range are ignored and I use a 2d numpy array for the twodimensional array
I changed the data input from pairs to two 1D arrays since this is how data is supplied to scatter(x,y) and alike functions
```
def histBin(x,y,x_range=(0.0,1.0),y_range=(0.0,1.0),xbins=10,ybins=None):
""" Helper function to do 2D histogram binning
x, y are lists / 2D arrays
x_range and yrange define the range of the plot similar to the hist(range=...)
xbins,ybins are the number of bins within this range.
"""
pairsData = zip(x,y)
if (ybins == None):
ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = x_range
xmin = float(xmin)
xmax = float(xmax)
xwidth = xmax-xmin
ymin,ymax = y_range
ymin = float(ymin)
ymax = float(ymax)
ywidth = ymax-ymin
def xbin(xval):
return floor(xbins*(xval-xmin)/xwidth) if xmin <= xval < xmax else xbins-1 if xval ==xmax else None
def ybin(yval):
return floor(ybins*(yval-ymin)/ywidth) if ymin <= yval < ymax else ybins-1 if yval ==ymax else None
hist = numpy.zeros((xbins,ybins))
for x,y in pairsData:
i_x,i_y = xbin(x),ybin(ymax-y)
if i_x is not None and i_y is not None:
hist[i_y,i_x] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
```
|
Use `xlim` and `ylim` to set the limits of the plot. `xlim(-3, 3)` and `ylim(-3, 3)` should do it.
|
2,030,970
|
I've got a series of (x,y) values that I want to plot a 2d histogram of using python's matplotlib. Using hexbin, I get something like this:
[](https://i.stack.imgur.com/FUL1M.png)
But I'm looking for something like this:
[](https://i.stack.imgur.com/ASwJl.png)
Example Code:
```
from matplotlib import pyplot as plt
import random
foo = lambda : random.gauss(0.0,1.0)
x = [foo() for i in xrange(5000)]
y = [foo() for i in xrange(5000)]
pairs = zip(x,y)
#using hexbin I supply the x,y series and it does the binning for me
hexfig = plt.figure()
hexplt = hexfig.add_subplot(1,1,1)
hexplt.hexbin(x, y, gridsize = 20)
#to use imshow I have to bin the data myself
def histBin(pairsData,xbins,ybins=None):
if (ybins == None): ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = min(xdata),max(xdata)
xwidth = xmax-xmin
ymin,ymax = min(ydata),max(ydata)
ywidth = ymax-ymin
def xbin(xval):
xbin = int(xbins*(xval-xmin)/xwidth)
return max(min(xbin,xbins-1),0)
def ybin(yval):
ybin = int(ybins*(yval-ymin)/ywidth)
return max(min(ybin,ybins-1),0)
hist = [[0 for x in xrange(xbins)] for y in xrange(ybins)]
for x,y in pairsData:
hist[ybin(y)][xbin(x)] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
#plot using imshow
imdata,extent = histBin(pairs,20)
imfig = plt.figure()
implt = imfig.add_subplot(1,1,1)
implt.imshow(imdata,extent = extent, interpolation = 'nearest')
plt.draw()
plt.show()
```
It seems like there should already be a way to do this without writing my own "binning" method and using imshow.
|
2010/01/08
|
[
"https://Stackoverflow.com/questions/2030970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/43665/"
] |
I realize that there is a patch submitted to matplotlib, but I adopted the code from the other example to acommodate a few needs that I had.
now the histogram is plotted from the lower left corner, as in conventional math (not computing)
also, values outside the binning range are ignored and I use a 2d numpy array for the twodimensional array
I changed the data input from pairs to two 1D arrays since this is how data is supplied to scatter(x,y) and alike functions
```
def histBin(x,y,x_range=(0.0,1.0),y_range=(0.0,1.0),xbins=10,ybins=None):
""" Helper function to do 2D histogram binning
x, y are lists / 2D arrays
x_range and yrange define the range of the plot similar to the hist(range=...)
xbins,ybins are the number of bins within this range.
"""
pairsData = zip(x,y)
if (ybins == None):
ybins = xbins
xdata, ydata = zip(*pairsData)
xmin,xmax = x_range
xmin = float(xmin)
xmax = float(xmax)
xwidth = xmax-xmin
ymin,ymax = y_range
ymin = float(ymin)
ymax = float(ymax)
ywidth = ymax-ymin
def xbin(xval):
return floor(xbins*(xval-xmin)/xwidth) if xmin <= xval < xmax else xbins-1 if xval ==xmax else None
def ybin(yval):
return floor(ybins*(yval-ymin)/ywidth) if ymin <= yval < ymax else ybins-1 if yval ==ymax else None
hist = numpy.zeros((xbins,ybins))
for x,y in pairsData:
i_x,i_y = xbin(x),ybin(ymax-y)
if i_x is not None and i_y is not None:
hist[i_y,i_x] += 1
extent = (xmin,xmax,ymin,ymax)
return hist,extent
```
|
I just submitted a pull request for this <https://github.com/matplotlib/matplotlib/pull/805> . Hopefully, it will be accepted.
|
5,518,927
|
I need to crawl a list of several thousand hosts and find at least two files rooted there that are larger than some value, given as an argument. Can any popular (python based?) tool possibly help?
|
2011/04/01
|
[
"https://Stackoverflow.com/questions/5518927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/649805/"
] |
Here is an example of how you can get the filesize of an file on a HTTP server.
```
import urllib2
def sizeofURLResource(url):
"""
Return the size of an resource at 'url' in bytes
"""
info = urllib2.urlopen(url).info()
return info.getheaders("Content-Length")[0]
```
There is also an library for building web scrapers here: <http://dev.scrapy.org/> but I don't know much about it(just googled honestly).
|
Here is how I did it. See the code below.
```
import urllib2
url = 'http://www.ueseo.org'
r = urllib2.urlopen(url)
print len(r.read())
```
|
57,915,312
|
I am not sure how exactly to ask this question so please forgive my ignorance.
I am running a function from many files. And after importing df I get the outcome into a csv file.
```
df=pd.read_csv("C:\Users\filename.csv ")
years = 5
days = 365
out_put, productivity= timeresult.input_data.outbuild(df, year, days)
productivity.to_csv("Jan.csv")
```
However, this looks painfully to do for many CSV I am working with. So I managed to put all the csv file names into a big folder. And imported the csv files names into a list.
```
filelist=["C:\Users\jan.csv", "C:\Users\feb.csv", "C:\Users\mar.csv"]
```
Would there be a way to have python loop all the list in the function and take the place of df and then send each file to a csv.
I tried this but failed
```
filelist = []
for x in filelist:
out_put, productivity= timeresult.input_data.outbuild(x, year, days)
filelist.append(productivity)
```
My goal was to have it run every cvs file name in the list and then create csv for each file.
|
2019/09/12
|
[
"https://Stackoverflow.com/questions/57915312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12016027/"
] |
If I understand your problem correctly, this code is for you:
```
years = 5
days = 365
filelist = ["C:\Users\jan.csv", "C:\Users\feb.csv", "C:\Users\mar.csv"]
for filepath in filelist:
df = pd.read_csv(filepath)
out_put, productivity= timeresult.input_data.outbuild(df, year, days)
df.index.name = filepath.split('\\')[-1].split('.')[0]
productivity.to_csv(filepath)
```
An example of the dataframe obtained could be the following:
From `jan.csv`:
```
costPrice currencyCode endDateValid
jan
0 83.56 GBP 2011-05-01
1 99.56 EUR 2017-05-01
```
From `feb.csv`:
```
costPrice currencyCode endDateValid
feb
0 93.89 EUR 2014-02-01
1 59.56 EUR 2012-07-01
```
**Tips**: If you want to get the list of names of all *.csv* files in the *"C:\Users\"* folder:
```
import glob
filelist = glob.glob("C:\Users\*.csv")
```
|
You were so close, you used the location instead of the file. Use this code:
```
filelist=["C:\Users\jan.csv", "C:\Users\feb.csv", "C:\Users\mar.csv"]
for location in filelist:
df = pd.read_csv(location)
out_put, productivity= timeresult.input_data.outbuild(df, year, days)
filelist.append(productivity)
```
|
57,915,312
|
I am not sure how exactly to ask this question so please forgive my ignorance.
I am running a function from many files. And after importing df I get the outcome into a csv file.
```
df=pd.read_csv("C:\Users\filename.csv ")
years = 5
days = 365
out_put, productivity= timeresult.input_data.outbuild(df, year, days)
productivity.to_csv("Jan.csv")
```
However, this looks painfully to do for many CSV I am working with. So I managed to put all the csv file names into a big folder. And imported the csv files names into a list.
```
filelist=["C:\Users\jan.csv", "C:\Users\feb.csv", "C:\Users\mar.csv"]
```
Would there be a way to have python loop all the list in the function and take the place of df and then send each file to a csv.
I tried this but failed
```
filelist = []
for x in filelist:
out_put, productivity= timeresult.input_data.outbuild(x, year, days)
filelist.append(productivity)
```
My goal was to have it run every cvs file name in the list and then create csv for each file.
|
2019/09/12
|
[
"https://Stackoverflow.com/questions/57915312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12016027/"
] |
If I understand your problem correctly, this code is for you:
```
years = 5
days = 365
filelist = ["C:\Users\jan.csv", "C:\Users\feb.csv", "C:\Users\mar.csv"]
for filepath in filelist:
df = pd.read_csv(filepath)
out_put, productivity= timeresult.input_data.outbuild(df, year, days)
df.index.name = filepath.split('\\')[-1].split('.')[0]
productivity.to_csv(filepath)
```
An example of the dataframe obtained could be the following:
From `jan.csv`:
```
costPrice currencyCode endDateValid
jan
0 83.56 GBP 2011-05-01
1 99.56 EUR 2017-05-01
```
From `feb.csv`:
```
costPrice currencyCode endDateValid
feb
0 93.89 EUR 2014-02-01
1 59.56 EUR 2012-07-01
```
**Tips**: If you want to get the list of names of all *.csv* files in the *"C:\Users\"* folder:
```
import glob
filelist = glob.glob("C:\Users\*.csv")
```
|
### To get a single, combined dataframe:
### Create the dataframe with all `files`
```py
from pathlib import Path
import pandas as pd
p = Path(r'"C:\Users\name\Documents') # set your path, don't end the path with "\"
files = p.glob('*.csv') # find your files
df = pd.concat([pd.read_csv(file) for file in files])
```
### Apply to a function:
* This depends whether `timeresult.input_data.outbuild` accepts a dataframe.
```py
out_put, productivity = timeresult.input_data.outbuild(df, year, days)
```
### Just running the files through the function:
* using `files` from above
* it's unclear whether `timeresult` takes a file or a dataframe
```py
for file in files:
out_put, productivity = timeresult.input_data.outbuild(file, year, days)
productivity.to_csv(file.name)
```
* If the function doesn't work with `pathlib` objects, replace `file` with `str(file)` in the function call
|
56,438,069
|
I have images in a sub-folder. Let's the folder `images`
I have a python program which will take image arguments from the folder one by one, the images are named in sequential order (1.jpg , 2.jpg, 3.jpg and so on).
The call to the program is : `python prog.py 1.jpg`
What will be a shell script to automate this ?
Please ask for any additional information.
|
2019/06/04
|
[
"https://Stackoverflow.com/questions/56438069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6916919/"
] |
Try this from the folder that contains images/:
`for i in images/*.jpg; do
python prog.py $i
done`
|
```
cd IMG_DIR
for item in [0-9]*.jpg
do
python prog.py $item
echo "Item processed : $item"
done
```
You can also pass image dir as a shellscript argument
|
56,438,069
|
I have images in a sub-folder. Let's the folder `images`
I have a python program which will take image arguments from the folder one by one, the images are named in sequential order (1.jpg , 2.jpg, 3.jpg and so on).
The call to the program is : `python prog.py 1.jpg`
What will be a shell script to automate this ?
Please ask for any additional information.
|
2019/06/04
|
[
"https://Stackoverflow.com/questions/56438069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6916919/"
] |
Try this from the folder that contains images/:
`for i in images/*.jpg; do
python prog.py $i
done`
|
You could do them all in parallel very simply with **GNU Parallel** like this:
```
parallel python prog.py ::: images/*.jpg
```
Or, if your Python writes to the current directory:
```
cd images
parallel python prog.py ::: *.jpg
```
|
37,023,460
|
I'm transitioning from discretization of a continuous state space to function approximation. My action and state space(3D) are both continuous. My problem suffers majorly from errors due to aliasing and nearly no convergene after training for a long time. Also I just cannot figure out how to choose the right step size for discretization.
Reading Sutton & Barto helped me understand the power of tile coding i.e having the state space described by multiple offested tilings overlapping each other. Given a continuous query/state, it is discribed by N basis functions, each corresponding to a single block/square of the criss-cross tilings it belongs to.
1) How is the performance different from going for a highly discretized state space?
2) Can anyone please point me to a working example of tile coding in python? I am learning too many things at the same time and getting super confused! (Q learning, discretization dilemma, tile coding, function approximation and handling the problem itself)
There doesn't seem to be any exhaustive Python coding tutorials for continuous problems in RL.
|
2016/05/04
|
[
"https://Stackoverflow.com/questions/37023460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4284161/"
] |
As the Simon's comment describes, a key difference between a highly discretized state space and a function approximator using tile coding, it's the hability of tile coding to generalize the values learned from one state to other similar states (i.e., tiles can overlap). In the case of a highly discretized state space, you need to visit all (and they can be a lot) the states to obtain a good representation of the value function (or Q function).
Regarding the second question, in this [link](http://incompleteideas.net/rlai.cs.ualberta.ca/RLAI/RLtoolkit/tiles.html#Python_Versions_) you can find an implementation of tile coding (in C, C++, Lisp and Python) written by Rich Sutton and other members of his laboratory.
|
Adding to Pablo's answer -
Tile coding (as a special case of coarse coding) can be compared to simple state aggregation. A simple state aggregation is, for example, a grid. Tile coding would be a stack of grids on top of each other, each shifted a bit from the previous.
The benefits are two fold - it allows you to have **better discrimination** (more fine grained control, less bias) **without loss of generalization** (less variance).
This is because with tile coding **you cover more states, with less features**.
A grid is similar to one-hot-encoding. A 3x3 grid is equivalent to a 9-Dimension 1-hot-encoding vector - and covers 10 states in total - either an object is in one of the 9 grid blocks, or is in none of them.
[](https://i.stack.imgur.com/Lo1y7.png)
So the middle point could be represented by (0,0,0,0,1,0,0,0,0).
How about you take 4 - 1x1 boxes, and just shift them a little bit 0.5 box (so that they cover 2x2 area of the grid each).
[](https://i.stack.imgur.com/KKZnv.png)
Now you cover 10 states with only 4 dimensions, or 4 inputs: red box, green box, blue box, and purple box.
Now the same middle point could be represented by (1,1,1,1).
This means you can generalize better. Before - gradient descent would only affect that middle point parameters. Now, since a point is influenced by a combination of few features - all of these features parameters will be affected. Which also allows for faster learning (as Pablo mentions).
Coursera offers (a paid) [specialization](https://www.coursera.org/specializations/reinforcement-learning?) which has exercises you need to implement in Python. Specifically Course 3 week 3 let's you work with tiles. They are using an **updated** (compared to Pablo's answer) [Sutton's implementation of the code](http://incompleteideas.net/tiles/tiles3.html), which is more simplified and uses python 3. Since the code can be quite cryptic at first, here is [my comments on it](https://github.com/MaverickMeerkat/Reinforcement-Learning/blob/master/Tile%20Coding.ipynb).
|
1,480,431
|
I need to:
1. Open a video file
2. Iterate over the frames of the file as images
3. Do some analysis in this image frame of the video
4. Draw in this image of the video
5. Create a new video with these changes
OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst?
Thank you!
|
2009/09/26
|
[
"https://Stackoverflow.com/questions/1480431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179372/"
] |
Do you mean opencv can't connect to your webcam or can't read video files recorded by it?
Have you tried saving the video in an other format?
OpenCV is probably the best supported python image processing tool
|
Just build a C/C++ wrapper for your webcam and then use SWIG or SIP to access these functions from Python. Then use OpenCV in Python that's the best open sourced computer vision library in the wild.
If you worry for performance and you work under Linux, you could download free versions of Intel Performance Primitives (IPP) that could be loaded at runtime with zero effort from OpenCV. For certain algorithms you could get a 200% boost of performances, plus automatic multicore support for most of time consuming functions.
|
1,480,431
|
I need to:
1. Open a video file
2. Iterate over the frames of the file as images
3. Do some analysis in this image frame of the video
4. Draw in this image of the video
5. Create a new video with these changes
OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst?
Thank you!
|
2009/09/26
|
[
"https://Stackoverflow.com/questions/1480431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179372/"
] |
Do you mean opencv can't connect to your webcam or can't read video files recorded by it?
Have you tried saving the video in an other format?
OpenCV is probably the best supported python image processing tool
|
I'm going through this myself. It's only a couple of lines in MATLAB using mmreader, but I've already blown two work days trying to figure out how to pull frames from a video file into numpy. If you have enough disk space, and it doesn't have to be real time, you can use:
```
mplayer -noconsolecontrols -vo png blah.mov
```
and then pull the .png files into numpy using:
```
pylab.imread('blah0000001.png')
```
I know this is incomplete, but it may still help you. Good luck!
|
1,480,431
|
I need to:
1. Open a video file
2. Iterate over the frames of the file as images
3. Do some analysis in this image frame of the video
4. Draw in this image of the video
5. Create a new video with these changes
OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst?
Thank you!
|
2009/09/26
|
[
"https://Stackoverflow.com/questions/1480431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179372/"
] |
Do you mean opencv can't connect to your webcam or can't read video files recorded by it?
Have you tried saving the video in an other format?
OpenCV is probably the best supported python image processing tool
|
I used this script to convert a movie to a numpy array + binary store:
```
"""
Takes a MPEG movie and produces a numpy record file with a numpy array.
"""
import os
filename = 'walking'
if not(os.path.isfile(filename + '.npy')): # do nothing if files exists
N_frame = 42 # number of frames we want to store
os.system('ffmpeg -i WALK.MOV.qt -f image2 foo-%03d.png')
# convert them to numpy
from numpy import zeros, save, mean
from pylab import imread
n_x, n_y, n_rgb = imread('foo-001.png').shape
mov = zeros((n_y, n_x, N_frame))
for i_frame in range(N_frame):
name = 'foo-%03d.png' % (i_frame +1)
mov[:n_y,:n_x,i_frame] = flipud(mean(imread(name), axis=2)).T
os.system('rm -f foo-*.png')
save(filename + '.npy', mov)
```
note that depending on your conventions you may not want to flip the image. you may then load it using :
```
load('walking.npy')
```
|
1,480,431
|
I need to:
1. Open a video file
2. Iterate over the frames of the file as images
3. Do some analysis in this image frame of the video
4. Draw in this image of the video
5. Create a new video with these changes
OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst?
Thank you!
|
2009/09/26
|
[
"https://Stackoverflow.com/questions/1480431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179372/"
] |
I'm going through this myself. It's only a couple of lines in MATLAB using mmreader, but I've already blown two work days trying to figure out how to pull frames from a video file into numpy. If you have enough disk space, and it doesn't have to be real time, you can use:
```
mplayer -noconsolecontrols -vo png blah.mov
```
and then pull the .png files into numpy using:
```
pylab.imread('blah0000001.png')
```
I know this is incomplete, but it may still help you. Good luck!
|
Just build a C/C++ wrapper for your webcam and then use SWIG or SIP to access these functions from Python. Then use OpenCV in Python that's the best open sourced computer vision library in the wild.
If you worry for performance and you work under Linux, you could download free versions of Intel Performance Primitives (IPP) that could be loaded at runtime with zero effort from OpenCV. For certain algorithms you could get a 200% boost of performances, plus automatic multicore support for most of time consuming functions.
|
1,480,431
|
I need to:
1. Open a video file
2. Iterate over the frames of the file as images
3. Do some analysis in this image frame of the video
4. Draw in this image of the video
5. Create a new video with these changes
OpenCV isn't working for my webcam, but python-gst is working. Is this possible using python-gst?
Thank you!
|
2009/09/26
|
[
"https://Stackoverflow.com/questions/1480431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/179372/"
] |
I used this script to convert a movie to a numpy array + binary store:
```
"""
Takes a MPEG movie and produces a numpy record file with a numpy array.
"""
import os
filename = 'walking'
if not(os.path.isfile(filename + '.npy')): # do nothing if files exists
N_frame = 42 # number of frames we want to store
os.system('ffmpeg -i WALK.MOV.qt -f image2 foo-%03d.png')
# convert them to numpy
from numpy import zeros, save, mean
from pylab import imread
n_x, n_y, n_rgb = imread('foo-001.png').shape
mov = zeros((n_y, n_x, N_frame))
for i_frame in range(N_frame):
name = 'foo-%03d.png' % (i_frame +1)
mov[:n_y,:n_x,i_frame] = flipud(mean(imread(name), axis=2)).T
os.system('rm -f foo-*.png')
save(filename + '.npy', mov)
```
note that depending on your conventions you may not want to flip the image. you may then load it using :
```
load('walking.npy')
```
|
Just build a C/C++ wrapper for your webcam and then use SWIG or SIP to access these functions from Python. Then use OpenCV in Python that's the best open sourced computer vision library in the wild.
If you worry for performance and you work under Linux, you could download free versions of Intel Performance Primitives (IPP) that could be loaded at runtime with zero effort from OpenCV. For certain algorithms you could get a 200% boost of performances, plus automatic multicore support for most of time consuming functions.
|
8,099,925
|
I want to check what is the password I stored in the DB for the user named as 'user'.
Here is what I have done.
```
user@ubuntu:~/Documents/Django/django_bookmarks$ python manage.py shell
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> user = User.objects.get(id=1)
>>> user.username, user.password
(u'user', u'sha1$6934a$f92c73726c0bd5d4821013ad4161578a2114090f')
>>>
>>> import hashlib
>>> hexhash = hashlib.sha1("password")
>>> hexhash
<sha1 HASH object @ 0x99c18c0>
>>> hexhash.digest
<built-in method digest of _hashlib.HASH object at 0x99c18c0>
```
I remember that I have used 'password' for the password of user but I cannot verify it.
Question> How can I find out what the password for the user is?
Thank you
|
2011/11/11
|
[
"https://Stackoverflow.com/questions/8099925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391104/"
] |
You can check the user's password with `check_password`: <https://docs.djangoproject.com/en/1.3/topics/auth/#django.contrib.auth.models.User.check_password>
```
from django.contrib.auth.models import User
user = User.objects.get(id=1)
user.check_password('password') # Returns True or False
```
|
django has been hashed your passwd, this is a function that only works in a way.
You can try to search the sha1 on a [hash database](http://www.hash-database.net/), but they are not guaranty to found it.
You should search for 'f92c73726c0bd5d4821013ad4161578a2114090f'. Hash function is sha1 and key used to hash is '6934a'
|
8,099,925
|
I want to check what is the password I stored in the DB for the user named as 'user'.
Here is what I have done.
```
user@ubuntu:~/Documents/Django/django_bookmarks$ python manage.py shell
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> user = User.objects.get(id=1)
>>> user.username, user.password
(u'user', u'sha1$6934a$f92c73726c0bd5d4821013ad4161578a2114090f')
>>>
>>> import hashlib
>>> hexhash = hashlib.sha1("password")
>>> hexhash
<sha1 HASH object @ 0x99c18c0>
>>> hexhash.digest
<built-in method digest of _hashlib.HASH object at 0x99c18c0>
```
I remember that I have used 'password' for the password of user but I cannot verify it.
Question> How can I find out what the password for the user is?
Thank you
|
2011/11/11
|
[
"https://Stackoverflow.com/questions/8099925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391104/"
] |
You can check the user's password with `check_password`: <https://docs.djangoproject.com/en/1.3/topics/auth/#django.contrib.auth.models.User.check_password>
```
from django.contrib.auth.models import User
user = User.objects.get(id=1)
user.check_password('password') # Returns True or False
```
|
You can not get the actual password that you have set. set\_password method converts original password into sha1 code.
You can only check your password, either this is correct or not.
also check this link
<https://docs.djangoproject.com/en/1.3/topics/auth/#django.contrib.auth.models.User.check_password>
|
8,099,925
|
I want to check what is the password I stored in the DB for the user named as 'user'.
Here is what I have done.
```
user@ubuntu:~/Documents/Django/django_bookmarks$ python manage.py shell
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:05:24)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from django.contrib.auth.models import User
>>> user = User.objects.get(id=1)
>>> user.username, user.password
(u'user', u'sha1$6934a$f92c73726c0bd5d4821013ad4161578a2114090f')
>>>
>>> import hashlib
>>> hexhash = hashlib.sha1("password")
>>> hexhash
<sha1 HASH object @ 0x99c18c0>
>>> hexhash.digest
<built-in method digest of _hashlib.HASH object at 0x99c18c0>
```
I remember that I have used 'password' for the password of user but I cannot verify it.
Question> How can I find out what the password for the user is?
Thank you
|
2011/11/11
|
[
"https://Stackoverflow.com/questions/8099925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391104/"
] |
django has been hashed your passwd, this is a function that only works in a way.
You can try to search the sha1 on a [hash database](http://www.hash-database.net/), but they are not guaranty to found it.
You should search for 'f92c73726c0bd5d4821013ad4161578a2114090f'. Hash function is sha1 and key used to hash is '6934a'
|
You can not get the actual password that you have set. set\_password method converts original password into sha1 code.
You can only check your password, either this is correct or not.
also check this link
<https://docs.djangoproject.com/en/1.3/topics/auth/#django.contrib.auth.models.User.check_password>
|
35,104,897
|
First of all a disclaimer: I am using python and anaconda and jupyter all for the first time, so it might be something basic.
I pasted the following code into a new Jupyter note from this url:
<https://github.com/t0pep0/btc-e.api.python/blob/master/btceapi.py>
After filling in my own API and secret API key, I tried to get this running:
```
getInfo()
```
But I ran into this error:
```
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-14-c63c8cc1259c> in <module>()
96
97
---> 98 getInfo()
NameError: name 'getInfo' is not defined
```
I checked the following solutions:
* Defining the function first and then running it, this example works
fine in Jupyter.
[function is not defined error in Python](https://stackoverflow.com/questions/5986860/function-is-not-defined-error-in-python)
* Defining the class first and then running the function, this example
also works fine in Jupyter.
[Python NameError: name is not defined](https://stackoverflow.com/questions/14804084/python-nameerror-name-is-not-defined)
But since the class and function are both defined in the correct order in the script I copied, there must be something else going on.
|
2016/01/30
|
[
"https://Stackoverflow.com/questions/35104897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3022427/"
] |
`getInfo` is a class method. So you need to instanciate an `api` object before calling it. You could try something like this.
```
myApi = api()
myApi.getInfo()
```
|
Some general comments, as Hakens answer is your problem.
Don't copy this script into a cell in the notebook like this (I believe this is what you are doing) You can either manually install to site packages (there doesn't appear to be a setup script for this module), or have the file in the same directory as the notebook. Then you can run
```
from btcapi import api
```
and proceed with Haken's answer (with appropriate arguments to the **init** method)
|
17,417,918
|
What's the most efficient way to get the integer part and fractional part of a python (python 3) `Decimal`?
This is what I have right now:
```
from decimal import *
>>> divmod(Decimal('1.0000000000000003')*7,Decimal(1))
(Decimal('7'), Decimal('2.1E-15'))
```
Any suggestions are welcome.
|
2013/07/02
|
[
"https://Stackoverflow.com/questions/17417918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1115577/"
] |
You can use the `Window > Reset Windows` menu item. This will reset the IDE's GUI back to the default state.
|
Use the `Help>About` menu to find the `User Directory`. Then navigate to it and delete directory `config>Windows2Local`. Restart the IDE and you will have the default windows settings. (The deleted dir will be recreated by netbeans)
|
28,029,672
|
I want to be able to create a JSON object so that I can access it like this.
```
education.schools.UNCC.graduation
```
Currently, my JSON is like this:
```
var education = {
"schools": [
"UNCC": {
"graduation": 2015,
"city": "Charlotte, NC",
"major": ["CS", "Spanish"]
},
"UNC-CH": {
"graduation": 2012,
"city": "Chapel Hill, NC"
"major": ["Sociology", "Film"]
}
],
"online": {
"website": "Udacity",
"courses": ["python", "java", "data science"]
}
};
```
When I go to Lint my JSON, I get an error message.
I know I can reformat my object to access it like this (below), but I don't want to do it this way. I want to be able to call the school name, and not use an index number.
```
education.schools[1].graduation
```
|
2015/01/19
|
[
"https://Stackoverflow.com/questions/28029672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3558010/"
] |
Objects have named keys. Arrays are a list of members.
Replace the value of `"schools"` with an object. Change `[]` to `{}`.
|
This is your JSON corrected.
Your JSON is invalid.
```
{
"schools": [
{
"UNCC": {
"graduation": "2015",
"city": [
"CS",
"Spanish"
],
"major": [
"CS",
"Spanish"
]
}
},
{
"UNC-CH": {
"graduation": "2012",
"city": [
"Chapel Hill",
"NC"
],
"major": [
"Sociology",
"Film"
]
}
}
],
"online": {
"website": "Udacity",
"courses": [
"python",
"java",
"data science"
]
}
}
```
**Explanation**:
1. "city": "Chapel Hill, NC" -> this is a array with 2 values "*Chapel* *Hill*" and "*HC*", like you do with major and courses.
2. The Schools array, you need to use this sintaxe to construct a array [{
<http://adobe.github.io/Spry/samples/data_region/JSONDataSetSample.html>
|
1,809,874
|
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're not allowed access to underscore variables in templates. **Great!**
You *can* test `field.field.widget.input_type` but this only works for text/password `<input ../>` types. I need more resolution that that.
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across `ModelForm`s and standard `Form`s (something that wouldn't be true if I wrote an intermediary Form class).
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
|
2009/11/27
|
[
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
Following the answer from Oli and rinti: I used this one and I think it is a bit simpler:
template code: `{{ field|fieldtype }}`
filter code:
```
from django import template
register = template.Library()
@register.filter('fieldtype')
def fieldtype(field):
return field.field.widget.__class__.__name__
```
|
You can make every view that manages forms inherit from a custom generic view where you load into the context the metadata that you need in the templates. The generic form view should include something like this:
```
class CustomUpdateView(UpdateView):
...
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
...
for f, value in context["form"].fields.items():
context["form"].fields[f].type = self.model._meta.get_field(f).get_internal_type()
...
return context
```
In the template you can access these custom properties through field.field:
```
{% if field.field.type == 'BooleanField' %}
<div class="custom-control custom-checkbox">
...
</div>
{% endif %}
```
By using the debugger of PyCharm or Visual Studio Code you can see all the available metadata, if you need something else besides the field type.
|
1,809,874
|
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're not allowed access to underscore variables in templates. **Great!**
You *can* test `field.field.widget.input_type` but this only works for text/password `<input ../>` types. I need more resolution that that.
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across `ModelForm`s and standard `Form`s (something that wouldn't be true if I wrote an intermediary Form class).
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
|
2009/11/27
|
[
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
Following up on the accepted answer - the enhanced `if tag` in Django 1.2 allows you to use filters in `if tag` comparisons. So you could now do your custom html/logic in the template like so:
```
<ul>
{% for field in form.fields %}
<li>
{% if field.field.widget|klass == "Textarea" %}
<!-- do something special for Textarea -->
<h2>Text Areas are Special </h2>
{% else %}
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
{% endif %}
</li>
{% endfor %}
</ul>
```
|
You can make every view that manages forms inherit from a custom generic view where you load into the context the metadata that you need in the templates. The generic form view should include something like this:
```
class CustomUpdateView(UpdateView):
...
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
...
for f, value in context["form"].fields.items():
context["form"].fields[f].type = self.model._meta.get_field(f).get_internal_type()
...
return context
```
In the template you can access these custom properties through field.field:
```
{% if field.field.type == 'BooleanField' %}
<div class="custom-control custom-checkbox">
...
</div>
{% endif %}
```
By using the debugger of PyCharm or Visual Studio Code you can see all the available metadata, if you need something else besides the field type.
|
1,809,874
|
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're not allowed access to underscore variables in templates. **Great!**
You *can* test `field.field.widget.input_type` but this only works for text/password `<input ../>` types. I need more resolution that that.
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across `ModelForm`s and standard `Form`s (something that wouldn't be true if I wrote an intermediary Form class).
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
|
2009/11/27
|
[
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
Making a template tag might work? Something like `field.field.widget|widget_type`
Edit from Oli: Good point! I just wrote a filter:
```
from django import template
register = template.Library()
@register.filter('klass')
def klass(ob):
return ob.__class__.__name__
```
And now `{{ object|klass }}` renders correctly. Now I've just got to figure out how to use that inside a template's `if` statement.
Edit from Oli #2: I needed to use the result of that in an if statetement in-template, so I just shifted all that logic into the templatetag. Magic. Thanks for poking me in the right direction.
|
For anyone here whose purpose is to customise widget style according to its type, based on @oli answer great idea, I decided to set the mapping directly in the template filter, and return the corresponding classes directly. This avoids messing with `{% if %}` statements in the template.
```py
from django import template
register = template.Library()
BASIC_INPUT = "border border-indigo-300 px-2.5 py-1.5 rounded-md focus:outline-none"
mapping = {
"Select": BASIC_INPUT,
"TextInput": BASIC_INPUT,
"EmailInput": BASIC_INPUT,
"RegionalPhoneNumberWidget": BASIC_INPUT,
"ModelSelect2": "", # let the default markup
}
@register.filter("get_field_classes")
def get_field_classes(field):
widget_class_name = field.field.widget.__class__.__name__
try:
return mapping[widget_class_name]
except KeyError:
raise ValueError(f"Classes related to {widget_class_name} are not defined yet")
```
Then in your default form template (e.g: `django/forms/default.html`), when browsing fields, with the help of [django-widget-tweaks](https://pypi.org/project/django-widget-tweaks/) package:
```html
{% load widget_tweaks %}
{% load get_field_classes %}
{% for field in form.visible_fields %}
{# .... #}
<div>
{% with field_classes=field|get_field_classes %}
{{ field|add_class:field_classes }}
{% endwith %}
</div>
{% endfor %}
```
|
1,809,874
|
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're not allowed access to underscore variables in templates. **Great!**
You *can* test `field.field.widget.input_type` but this only works for text/password `<input ../>` types. I need more resolution that that.
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across `ModelForm`s and standard `Form`s (something that wouldn't be true if I wrote an intermediary Form class).
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
|
2009/11/27
|
[
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
Following up on the accepted answer - the enhanced `if tag` in Django 1.2 allows you to use filters in `if tag` comparisons. So you could now do your custom html/logic in the template like so:
```
<ul>
{% for field in form.fields %}
<li>
{% if field.field.widget|klass == "Textarea" %}
<!-- do something special for Textarea -->
<h2>Text Areas are Special </h2>
{% else %}
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
{% endif %}
</li>
{% endfor %}
</ul>
```
|
For anyone here whose purpose is to customise widget style according to its type, based on @oli answer great idea, I decided to set the mapping directly in the template filter, and return the corresponding classes directly. This avoids messing with `{% if %}` statements in the template.
```py
from django import template
register = template.Library()
BASIC_INPUT = "border border-indigo-300 px-2.5 py-1.5 rounded-md focus:outline-none"
mapping = {
"Select": BASIC_INPUT,
"TextInput": BASIC_INPUT,
"EmailInput": BASIC_INPUT,
"RegionalPhoneNumberWidget": BASIC_INPUT,
"ModelSelect2": "", # let the default markup
}
@register.filter("get_field_classes")
def get_field_classes(field):
widget_class_name = field.field.widget.__class__.__name__
try:
return mapping[widget_class_name]
except KeyError:
raise ValueError(f"Classes related to {widget_class_name} are not defined yet")
```
Then in your default form template (e.g: `django/forms/default.html`), when browsing fields, with the help of [django-widget-tweaks](https://pypi.org/project/django-widget-tweaks/) package:
```html
{% load widget_tweaks %}
{% load get_field_classes %}
{% for field in form.visible_fields %}
{# .... #}
<div>
{% with field_classes=field|get_field_classes %}
{{ field|add_class:field_classes }}
{% endwith %}
</div>
{% endfor %}
```
|
1,809,874
|
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're not allowed access to underscore variables in templates. **Great!**
You *can* test `field.field.widget.input_type` but this only works for text/password `<input ../>` types. I need more resolution that that.
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across `ModelForm`s and standard `Form`s (something that wouldn't be true if I wrote an intermediary Form class).
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
|
2009/11/27
|
[
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
Following up on the accepted answer - the enhanced `if tag` in Django 1.2 allows you to use filters in `if tag` comparisons. So you could now do your custom html/logic in the template like so:
```
<ul>
{% for field in form.fields %}
<li>
{% if field.field.widget|klass == "Textarea" %}
<!-- do something special for Textarea -->
<h2>Text Areas are Special </h2>
{% else %}
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
{% endif %}
</li>
{% endfor %}
</ul>
```
|
Perhaps worth pointing out to contemporary readers that [`django-widget-tweaks`](https://github.com/jazzband/django-widget-tweaks) provides `field_type` and `widget_type` template filters for this purpose, returning the respective class names in lowercase. In the example below I also show the output of the `input_type` property on the field widget (since Django 1.11), which may also be useful.
`forms.py`:
```
class ContactForm(forms.Form):
name = forms.CharField(
max_length=150,
required=True,
label='Your name'
)
```
`template.html`:
```
{% load widget_tweaks %}
{% for field in form.visible_fields %}
{{ field.label }}
{{ field.field.widget.input_type }}
{{ field|field_type }}
{{ field|widget_type }})
{% endfor %}
```
**Result:**
```
Your name
text
charfield
textinput
```
Between these various options you should be able to find the right property to target for just about any use-case. If you need to capture the output of one of these filters for use in `if` statements, you can use the [`with`](https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#with) template tag.
|
1,809,874
|
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're not allowed access to underscore variables in templates. **Great!**
You *can* test `field.field.widget.input_type` but this only works for text/password `<input ../>` types. I need more resolution that that.
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across `ModelForm`s and standard `Form`s (something that wouldn't be true if I wrote an intermediary Form class).
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
|
2009/11/27
|
[
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
Making a template tag might work? Something like `field.field.widget|widget_type`
Edit from Oli: Good point! I just wrote a filter:
```
from django import template
register = template.Library()
@register.filter('klass')
def klass(ob):
return ob.__class__.__name__
```
And now `{{ object|klass }}` renders correctly. Now I've just got to figure out how to use that inside a template's `if` statement.
Edit from Oli #2: I needed to use the result of that in an if statetement in-template, so I just shifted all that logic into the templatetag. Magic. Thanks for poking me in the right direction.
|
Following the answer from Oli and rinti: I used this one and I think it is a bit simpler:
template code: `{{ field|fieldtype }}`
filter code:
```
from django import template
register = template.Library()
@register.filter('fieldtype')
def fieldtype(field):
return field.field.widget.__class__.__name__
```
|
1,809,874
|
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're not allowed access to underscore variables in templates. **Great!**
You *can* test `field.field.widget.input_type` but this only works for text/password `<input ../>` types. I need more resolution that that.
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across `ModelForm`s and standard `Form`s (something that wouldn't be true if I wrote an intermediary Form class).
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
|
2009/11/27
|
[
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
Following the answer from Oli and rinti: I used this one and I think it is a bit simpler:
template code: `{{ field|fieldtype }}`
filter code:
```
from django import template
register = template.Library()
@register.filter('fieldtype')
def fieldtype(field):
return field.field.widget.__class__.__name__
```
|
For anyone here whose purpose is to customise widget style according to its type, based on @oli answer great idea, I decided to set the mapping directly in the template filter, and return the corresponding classes directly. This avoids messing with `{% if %}` statements in the template.
```py
from django import template
register = template.Library()
BASIC_INPUT = "border border-indigo-300 px-2.5 py-1.5 rounded-md focus:outline-none"
mapping = {
"Select": BASIC_INPUT,
"TextInput": BASIC_INPUT,
"EmailInput": BASIC_INPUT,
"RegionalPhoneNumberWidget": BASIC_INPUT,
"ModelSelect2": "", # let the default markup
}
@register.filter("get_field_classes")
def get_field_classes(field):
widget_class_name = field.field.widget.__class__.__name__
try:
return mapping[widget_class_name]
except KeyError:
raise ValueError(f"Classes related to {widget_class_name} are not defined yet")
```
Then in your default form template (e.g: `django/forms/default.html`), when browsing fields, with the help of [django-widget-tweaks](https://pypi.org/project/django-widget-tweaks/) package:
```html
{% load widget_tweaks %}
{% load get_field_classes %}
{% for field in form.visible_fields %}
{# .... #}
<div>
{% with field_classes=field|get_field_classes %}
{{ field|add_class:field_classes }}
{% endwith %}
</div>
{% endfor %}
```
|
1,809,874
|
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're not allowed access to underscore variables in templates. **Great!**
You *can* test `field.field.widget.input_type` but this only works for text/password `<input ../>` types. I need more resolution that that.
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across `ModelForm`s and standard `Form`s (something that wouldn't be true if I wrote an intermediary Form class).
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
|
2009/11/27
|
[
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
As of Django 1.11, you can just use `widget.input_type`. Example:
```
{% for field in form.visible_fields %}
<input type="{{ field.field.widget.input_type }}"
id="{{ field.id_for_label }}"
name="{{ field.html_name }}"
placeholder="{{ field.label }}"
maxlength="{{ field.field.max_length }}" />
{% endfor %}
```
|
Perhaps worth pointing out to contemporary readers that [`django-widget-tweaks`](https://github.com/jazzband/django-widget-tweaks) provides `field_type` and `widget_type` template filters for this purpose, returning the respective class names in lowercase. In the example below I also show the output of the `input_type` property on the field widget (since Django 1.11), which may also be useful.
`forms.py`:
```
class ContactForm(forms.Form):
name = forms.CharField(
max_length=150,
required=True,
label='Your name'
)
```
`template.html`:
```
{% load widget_tweaks %}
{% for field in form.visible_fields %}
{{ field.label }}
{{ field.field.widget.input_type }}
{{ field|field_type }}
{{ field|widget_type }})
{% endfor %}
```
**Result:**
```
Your name
text
charfield
textinput
```
Between these various options you should be able to find the right property to target for just about any use-case. If you need to capture the output of one of these filters for use in `if` statements, you can use the [`with`](https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#with) template tag.
|
1,809,874
|
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're not allowed access to underscore variables in templates. **Great!**
You *can* test `field.field.widget.input_type` but this only works for text/password `<input ../>` types. I need more resolution that that.
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across `ModelForm`s and standard `Form`s (something that wouldn't be true if I wrote an intermediary Form class).
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
|
2009/11/27
|
[
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
As of Django 1.11, you can just use `widget.input_type`. Example:
```
{% for field in form.visible_fields %}
<input type="{{ field.field.widget.input_type }}"
id="{{ field.id_for_label }}"
name="{{ field.html_name }}"
placeholder="{{ field.label }}"
maxlength="{{ field.field.max_length }}" />
{% endfor %}
```
|
You can make every view that manages forms inherit from a custom generic view where you load into the context the metadata that you need in the templates. The generic form view should include something like this:
```
class CustomUpdateView(UpdateView):
...
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
...
for f, value in context["form"].fields.items():
context["form"].fields[f].type = self.model._meta.get_field(f).get_internal_type()
...
return context
```
In the template you can access these custom properties through field.field:
```
{% if field.field.type == 'BooleanField' %}
<div class="custom-control custom-checkbox">
...
</div>
{% endif %}
```
By using the debugger of PyCharm or Visual Studio Code you can see all the available metadata, if you need something else besides the field type.
|
1,809,874
|
I'm iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to know the widget type. Its class name or something similar. In standard python, this is easy! `field.field.widget.__class__.__name__`
Unfortunately, you're not allowed access to underscore variables in templates. **Great!**
You *can* test `field.field.widget.input_type` but this only works for text/password `<input ../>` types. I need more resolution that that.
To me, however difficult it might look, it makes most sense to do this at template level. I've outsourced the bit of code that handles HTML for fields to a separate template that gets included in the field-loop. This means it is consistent across `ModelForm`s and standard `Form`s (something that wouldn't be true if I wrote an intermediary Form class).
If you can see a universal approach that doesn't require me to edit 20-odd forms, let me know too!
|
2009/11/27
|
[
"https://Stackoverflow.com/questions/1809874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12870/"
] |
Making a template tag might work? Something like `field.field.widget|widget_type`
Edit from Oli: Good point! I just wrote a filter:
```
from django import template
register = template.Library()
@register.filter('klass')
def klass(ob):
return ob.__class__.__name__
```
And now `{{ object|klass }}` renders correctly. Now I've just got to figure out how to use that inside a template's `if` statement.
Edit from Oli #2: I needed to use the result of that in an if statetement in-template, so I just shifted all that logic into the templatetag. Magic. Thanks for poking me in the right direction.
|
Perhaps worth pointing out to contemporary readers that [`django-widget-tweaks`](https://github.com/jazzband/django-widget-tweaks) provides `field_type` and `widget_type` template filters for this purpose, returning the respective class names in lowercase. In the example below I also show the output of the `input_type` property on the field widget (since Django 1.11), which may also be useful.
`forms.py`:
```
class ContactForm(forms.Form):
name = forms.CharField(
max_length=150,
required=True,
label='Your name'
)
```
`template.html`:
```
{% load widget_tweaks %}
{% for field in form.visible_fields %}
{{ field.label }}
{{ field.field.widget.input_type }}
{{ field|field_type }}
{{ field|widget_type }})
{% endfor %}
```
**Result:**
```
Your name
text
charfield
textinput
```
Between these various options you should be able to find the right property to target for just about any use-case. If you need to capture the output of one of these filters for use in `if` statements, you can use the [`with`](https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#with) template tag.
|
51,804,600
|
I am a little confused about a piece of python code in using dict:
```
>>> S = "ababcbacadefegdehijhklij"
>>> lindex = {c: i for i, c in enumerate(S)}
>>> lindex
{'a': 8, 'c': 7, 'b': 5, 'e': 15, 'd': 14, 'g': 13, 'f': 11, 'i': 22, 'h': 19, 'k': 20, 'j': 23, 'l': 21}
```
How to understand it the "{c: i for i, c in enumerate(S)}" ? Could anyone give me some explanations?
|
2018/08/11
|
[
"https://Stackoverflow.com/questions/51804600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6654375/"
] |
First question
--------------
Polymorphism can be achieved in Java in two ways:
* Through *class inheritance*: `class A extends B`
* Through *interface implementation*: `class A implements C`.
In the later case, to properly implement A's behaviour, it can be done though *composition*, making A delegate over some other class/es which do the tasks specified in Interface C.
Example: Let's suppose we have already some class imeplementing interface C:
```
class X implements C
{
public String getName() {...}
public int getAge() {...}
}
```
How can we create a new class implementing C with the same behaviour of X? Like this:
```
class A implements C
{
private C x=new X();
public String getName() {return x.getName();}
public int getAge() {return x.getAge();}
}
```
Second question
---------------
No, polymorphism is not method overloading and/or method overriding (in fact, overloading has nothing to do with Object Oriented Design):
* Method *overloading* consists on creating a new method with the same name that some other (maybe inherited) method in the same class but with a different signature (=parameter numbers or types). Adding new methods is OK, but that is not the aim of polymorphism.
* Method *overriding* consists on setting a new body to an inherited method, so that this new body will be executed in the current class instead of the inherited method's body. This is a advantage of polymorphism, still is not the base of it either.
Polymorphism, in brief, is the ability of a class to be *used* as different classes/interfaces.
|
There is book answer, if one remember about all the firemans are fireman but some are drivers, chiefs etc. There you need polymorphism. There is things you can do with classes and it's a general idea in OOP as language constraints. Overriding is just what you can do with classes. Also permissions and local and/or global scopes. There is default constructor for any class. There is namespace scope, program, class etc.
*All Classes and methods are functions but not all functions are methods*
You can override class but not method. Those are static or volatile. Cos method can only return the value. So overriding the method has no sense. I hope this will turn you, if nothing, toward how it was meant to be. Inheritance is mechanism how polymorphism works.
My apologies for unintentional mistakes during too much data.
|
51,804,600
|
I am a little confused about a piece of python code in using dict:
```
>>> S = "ababcbacadefegdehijhklij"
>>> lindex = {c: i for i, c in enumerate(S)}
>>> lindex
{'a': 8, 'c': 7, 'b': 5, 'e': 15, 'd': 14, 'g': 13, 'f': 11, 'i': 22, 'h': 19, 'k': 20, 'j': 23, 'l': 21}
```
How to understand it the "{c: i for i, c in enumerate(S)}" ? Could anyone give me some explanations?
|
2018/08/11
|
[
"https://Stackoverflow.com/questions/51804600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6654375/"
] |
First question
--------------
Polymorphism can be achieved in Java in two ways:
* Through *class inheritance*: `class A extends B`
* Through *interface implementation*: `class A implements C`.
In the later case, to properly implement A's behaviour, it can be done though *composition*, making A delegate over some other class/es which do the tasks specified in Interface C.
Example: Let's suppose we have already some class imeplementing interface C:
```
class X implements C
{
public String getName() {...}
public int getAge() {...}
}
```
How can we create a new class implementing C with the same behaviour of X? Like this:
```
class A implements C
{
private C x=new X();
public String getName() {return x.getName();}
public int getAge() {return x.getAge();}
}
```
Second question
---------------
No, polymorphism is not method overloading and/or method overriding (in fact, overloading has nothing to do with Object Oriented Design):
* Method *overloading* consists on creating a new method with the same name that some other (maybe inherited) method in the same class but with a different signature (=parameter numbers or types). Adding new methods is OK, but that is not the aim of polymorphism.
* Method *overriding* consists on setting a new body to an inherited method, so that this new body will be executed in the current class instead of the inherited method's body. This is a advantage of polymorphism, still is not the base of it either.
Polymorphism, in brief, is the ability of a class to be *used* as different classes/interfaces.
|
No, not really. Polymorphism and composition or aggregation (composition is a more rigid form of aggregation wherein the composed objects' lifetimes are tied together) are different ways of reusing classes.
Composition involves aggregating multiple objects to form a single entity. Polymorphism involves multiple objects that share analogous behavior.
For example, a Car object might be *composed* of two Axle objects, a Chassis object, four Wheel objects (which themselves may be composed of a Rim, a Tire, six LugNuts and so on). When you instantiate a Car, your Car constructor would instantiate all the parts that go along with it. That's composition. (Aggregation would use all the same part objects but not necessarily instantiate them in its constructor.)
A Car object might also not be useful on its own, but rather as a blueprint for numerous more specialized *implementations* of cars, such as SportsCar, SUVCar, SedanCar, and the like. In this case, the Car object might define a Car *interface* that would define common behaviors such as Steer, HitTheGas and Brake, but leave the implementations of those behaviors to the implementing classes. Then, a consumer of a Car object can declare an object of type Car, instantiate it as any of the implementing classes such as SportsCar, call the methods defined in the Car interface, and get the behavior implemented in the instantiated class. That's polymorphism.
For a decent tutorial on both, with some comparisons, have a look at [this](http://www.ntu.edu.sg/home/ehchua/programming/java/j3b_oopinheritancepolymorphism.html). Keep in mind that the UML diagrams have an inaccuracy: while the examples do indeed describe composition as opposed to aggregation, the related UML class diagrams have white diamonds where they should be black. UML class diagram syntax uses a white diamond for class associations that are aggregations and a black one for those that are compositions.
Also, [this post](https://softwareengineering.stackexchange.com/questions/134097/why-should-i-prefer-composition-over-inheritance) has some good information, in particular tdammers's answer halfway down the page.
|
51,804,600
|
I am a little confused about a piece of python code in using dict:
```
>>> S = "ababcbacadefegdehijhklij"
>>> lindex = {c: i for i, c in enumerate(S)}
>>> lindex
{'a': 8, 'c': 7, 'b': 5, 'e': 15, 'd': 14, 'g': 13, 'f': 11, 'i': 22, 'h': 19, 'k': 20, 'j': 23, 'l': 21}
```
How to understand it the "{c: i for i, c in enumerate(S)}" ? Could anyone give me some explanations?
|
2018/08/11
|
[
"https://Stackoverflow.com/questions/51804600",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6654375/"
] |
No, not really. Polymorphism and composition or aggregation (composition is a more rigid form of aggregation wherein the composed objects' lifetimes are tied together) are different ways of reusing classes.
Composition involves aggregating multiple objects to form a single entity. Polymorphism involves multiple objects that share analogous behavior.
For example, a Car object might be *composed* of two Axle objects, a Chassis object, four Wheel objects (which themselves may be composed of a Rim, a Tire, six LugNuts and so on). When you instantiate a Car, your Car constructor would instantiate all the parts that go along with it. That's composition. (Aggregation would use all the same part objects but not necessarily instantiate them in its constructor.)
A Car object might also not be useful on its own, but rather as a blueprint for numerous more specialized *implementations* of cars, such as SportsCar, SUVCar, SedanCar, and the like. In this case, the Car object might define a Car *interface* that would define common behaviors such as Steer, HitTheGas and Brake, but leave the implementations of those behaviors to the implementing classes. Then, a consumer of a Car object can declare an object of type Car, instantiate it as any of the implementing classes such as SportsCar, call the methods defined in the Car interface, and get the behavior implemented in the instantiated class. That's polymorphism.
For a decent tutorial on both, with some comparisons, have a look at [this](http://www.ntu.edu.sg/home/ehchua/programming/java/j3b_oopinheritancepolymorphism.html). Keep in mind that the UML diagrams have an inaccuracy: while the examples do indeed describe composition as opposed to aggregation, the related UML class diagrams have white diamonds where they should be black. UML class diagram syntax uses a white diamond for class associations that are aggregations and a black one for those that are compositions.
Also, [this post](https://softwareengineering.stackexchange.com/questions/134097/why-should-i-prefer-composition-over-inheritance) has some good information, in particular tdammers's answer halfway down the page.
|
There is book answer, if one remember about all the firemans are fireman but some are drivers, chiefs etc. There you need polymorphism. There is things you can do with classes and it's a general idea in OOP as language constraints. Overriding is just what you can do with classes. Also permissions and local and/or global scopes. There is default constructor for any class. There is namespace scope, program, class etc.
*All Classes and methods are functions but not all functions are methods*
You can override class but not method. Those are static or volatile. Cos method can only return the value. So overriding the method has no sense. I hope this will turn you, if nothing, toward how it was meant to be. Inheritance is mechanism how polymorphism works.
My apologies for unintentional mistakes during too much data.
|
63,592,741
|
When trying to update a dictionary with a tuple, I encountered the error:
`>>> dict1.update(("stat",10))`
`ValueError: dictionary update sequence element #0 has length 4; 2 is required`
When in reality this shouldn't be happening. From the python docs,
>
> update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two).
>
>
>
This makes no sense, since the tuple i supplied clearly has length 2.
`>>> len(("stat",10))`
`2`
What is going on? Is this a bug that isn't resolved yet? Running Python 3.8.0.
Or was this due to the fact that my dictionary is empty? Tried this with other strings and values, same problem.
|
2020/08/26
|
[
"https://Stackoverflow.com/questions/63592741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14168419/"
] |
The documentation said you need an ***iterable*** of key value pairs. A single tuple is not an iterable of key value pairs, either a list or tuple of tuples will do.
```py
dict1.update([("stat", 10)])
```
|
The documentation says "or an iterable of key/value pairs (as tuples or other iterables of length two)".
Therefore you need to pass it a tuple of tuples that have length 2
Try this:
```
dict1.update((("stat",10),))
```
Or you can pass multiple key/value pairs as followings:
```
dict1.update((("stat",10), ('foo', 'bar'), ('buzz', 'fizz')))
```
|
63,592,741
|
When trying to update a dictionary with a tuple, I encountered the error:
`>>> dict1.update(("stat",10))`
`ValueError: dictionary update sequence element #0 has length 4; 2 is required`
When in reality this shouldn't be happening. From the python docs,
>
> update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two).
>
>
>
This makes no sense, since the tuple i supplied clearly has length 2.
`>>> len(("stat",10))`
`2`
What is going on? Is this a bug that isn't resolved yet? Running Python 3.8.0.
Or was this due to the fact that my dictionary is empty? Tried this with other strings and values, same problem.
|
2020/08/26
|
[
"https://Stackoverflow.com/questions/63592741",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14168419/"
] |
The documentation said you need an ***iterable*** of key value pairs. A single tuple is not an iterable of key value pairs, either a list or tuple of tuples will do.
```py
dict1.update([("stat", 10)])
```
|
Add a , to the tuple end `dict1.update((("stat",10),))`
Or pass a list `dict1.update([("stat",10)])`
|
4,701,383
|
what i'm trying to do is write a quadratic equation solver but when the solution should be `-1`, as in `quadratic(2, 4, 2)` it returns `1`
what am i doing wrong?
```
#!/usr/bin/python
import math
def quadratic(a, b, c):
#a = raw_input("What\'s your `a` value?\t")
#b = raw_input("What\'s your `b` value?\t")
#c = raw_input("What\'s your `c` value?\t")
a, b, c = float(a), float(b), float(c)
disc = (b*b)-(4*a*c)
print "Discriminant is:\n" + str(disc)
if disc >= 0:
root = math.sqrt(disc)
top1 = b + root
top2 = b - root
sol1 = top1/(2*a)
sol2 = top2/(2*a)
if sol1 != sol2:
print "Solution 1:\n" + str(sol1) + "\nSolution 2:\n" + str(sol2)
if sol1 == sol2:
print "One solution:\n" + str(sol1)
else:
print "No solution!"
```
EDIT: it returns the following...
```
>>> import mathmodules
>>> mathmodules.quadratic(2, 4, 2)
Discriminant is:
0.0
One solution:
1.0
```
|
2011/01/15
|
[
"https://Stackoverflow.com/questions/4701383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569183/"
] |
Unless the formula has changed since I went to school (one can never be too sure), it's `(-b +- sqrt(b^2-4ac)) / 2a`, you have `b` in your code.
[edit] May I suggest a refactor?
```
def quadratic(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant < 0:
return []
elif discriminant == 0:
return [-b / (2*a)]
else:
root = math.sqrt(discriminant)
return [(-b + root) / (2*a), (-b - root) / (2*a)]
print quadratic(2, 3, 2) # []
print quadratic(2, 4, 2) # [-1]
print quadratic(2, 5, 2) # [-0.5, -2.0]
```
|
The solution to the quadratic is
```
x = (-b +/- sqrt(b^2 - 4ac))/2a
```
but what you have coded up is
```
x = (b +/- sqrt(b^2 - 4ac))/2a
```
So that's why you get the sign error.
|
4,701,383
|
what i'm trying to do is write a quadratic equation solver but when the solution should be `-1`, as in `quadratic(2, 4, 2)` it returns `1`
what am i doing wrong?
```
#!/usr/bin/python
import math
def quadratic(a, b, c):
#a = raw_input("What\'s your `a` value?\t")
#b = raw_input("What\'s your `b` value?\t")
#c = raw_input("What\'s your `c` value?\t")
a, b, c = float(a), float(b), float(c)
disc = (b*b)-(4*a*c)
print "Discriminant is:\n" + str(disc)
if disc >= 0:
root = math.sqrt(disc)
top1 = b + root
top2 = b - root
sol1 = top1/(2*a)
sol2 = top2/(2*a)
if sol1 != sol2:
print "Solution 1:\n" + str(sol1) + "\nSolution 2:\n" + str(sol2)
if sol1 == sol2:
print "One solution:\n" + str(sol1)
else:
print "No solution!"
```
EDIT: it returns the following...
```
>>> import mathmodules
>>> mathmodules.quadratic(2, 4, 2)
Discriminant is:
0.0
One solution:
1.0
```
|
2011/01/15
|
[
"https://Stackoverflow.com/questions/4701383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569183/"
] |
Unless the formula has changed since I went to school (one can never be too sure), it's `(-b +- sqrt(b^2-4ac)) / 2a`, you have `b` in your code.
[edit] May I suggest a refactor?
```
def quadratic(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant < 0:
return []
elif discriminant == 0:
return [-b / (2*a)]
else:
root = math.sqrt(discriminant)
return [(-b + root) / (2*a), (-b - root) / (2*a)]
print quadratic(2, 3, 2) # []
print quadratic(2, 4, 2) # [-1]
print quadratic(2, 5, 2) # [-0.5, -2.0]
```
|
```
top1 = b + root
top2 = b - root
```
Should be:
```
top1 = -b + root
top2 = -b - root
```
|
4,701,383
|
what i'm trying to do is write a quadratic equation solver but when the solution should be `-1`, as in `quadratic(2, 4, 2)` it returns `1`
what am i doing wrong?
```
#!/usr/bin/python
import math
def quadratic(a, b, c):
#a = raw_input("What\'s your `a` value?\t")
#b = raw_input("What\'s your `b` value?\t")
#c = raw_input("What\'s your `c` value?\t")
a, b, c = float(a), float(b), float(c)
disc = (b*b)-(4*a*c)
print "Discriminant is:\n" + str(disc)
if disc >= 0:
root = math.sqrt(disc)
top1 = b + root
top2 = b - root
sol1 = top1/(2*a)
sol2 = top2/(2*a)
if sol1 != sol2:
print "Solution 1:\n" + str(sol1) + "\nSolution 2:\n" + str(sol2)
if sol1 == sol2:
print "One solution:\n" + str(sol1)
else:
print "No solution!"
```
EDIT: it returns the following...
```
>>> import mathmodules
>>> mathmodules.quadratic(2, 4, 2)
Discriminant is:
0.0
One solution:
1.0
```
|
2011/01/15
|
[
"https://Stackoverflow.com/questions/4701383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569183/"
] |
Unless the formula has changed since I went to school (one can never be too sure), it's `(-b +- sqrt(b^2-4ac)) / 2a`, you have `b` in your code.
[edit] May I suggest a refactor?
```
def quadratic(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant < 0:
return []
elif discriminant == 0:
return [-b / (2*a)]
else:
root = math.sqrt(discriminant)
return [(-b + root) / (2*a), (-b - root) / (2*a)]
print quadratic(2, 3, 2) # []
print quadratic(2, 4, 2) # [-1]
print quadratic(2, 5, 2) # [-0.5, -2.0]
```
|
The signs of `top1` and `top2` are wrong, see <http://en.wikipedia.org/wiki/Quadratic_equation>
|
4,701,383
|
what i'm trying to do is write a quadratic equation solver but when the solution should be `-1`, as in `quadratic(2, 4, 2)` it returns `1`
what am i doing wrong?
```
#!/usr/bin/python
import math
def quadratic(a, b, c):
#a = raw_input("What\'s your `a` value?\t")
#b = raw_input("What\'s your `b` value?\t")
#c = raw_input("What\'s your `c` value?\t")
a, b, c = float(a), float(b), float(c)
disc = (b*b)-(4*a*c)
print "Discriminant is:\n" + str(disc)
if disc >= 0:
root = math.sqrt(disc)
top1 = b + root
top2 = b - root
sol1 = top1/(2*a)
sol2 = top2/(2*a)
if sol1 != sol2:
print "Solution 1:\n" + str(sol1) + "\nSolution 2:\n" + str(sol2)
if sol1 == sol2:
print "One solution:\n" + str(sol1)
else:
print "No solution!"
```
EDIT: it returns the following...
```
>>> import mathmodules
>>> mathmodules.quadratic(2, 4, 2)
Discriminant is:
0.0
One solution:
1.0
```
|
2011/01/15
|
[
"https://Stackoverflow.com/questions/4701383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569183/"
] |
The solution to the quadratic is
```
x = (-b +/- sqrt(b^2 - 4ac))/2a
```
but what you have coded up is
```
x = (b +/- sqrt(b^2 - 4ac))/2a
```
So that's why you get the sign error.
|
```
top1 = b + root
top2 = b - root
```
Should be:
```
top1 = -b + root
top2 = -b - root
```
|
4,701,383
|
what i'm trying to do is write a quadratic equation solver but when the solution should be `-1`, as in `quadratic(2, 4, 2)` it returns `1`
what am i doing wrong?
```
#!/usr/bin/python
import math
def quadratic(a, b, c):
#a = raw_input("What\'s your `a` value?\t")
#b = raw_input("What\'s your `b` value?\t")
#c = raw_input("What\'s your `c` value?\t")
a, b, c = float(a), float(b), float(c)
disc = (b*b)-(4*a*c)
print "Discriminant is:\n" + str(disc)
if disc >= 0:
root = math.sqrt(disc)
top1 = b + root
top2 = b - root
sol1 = top1/(2*a)
sol2 = top2/(2*a)
if sol1 != sol2:
print "Solution 1:\n" + str(sol1) + "\nSolution 2:\n" + str(sol2)
if sol1 == sol2:
print "One solution:\n" + str(sol1)
else:
print "No solution!"
```
EDIT: it returns the following...
```
>>> import mathmodules
>>> mathmodules.quadratic(2, 4, 2)
Discriminant is:
0.0
One solution:
1.0
```
|
2011/01/15
|
[
"https://Stackoverflow.com/questions/4701383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569183/"
] |
The solution to the quadratic is
```
x = (-b +/- sqrt(b^2 - 4ac))/2a
```
but what you have coded up is
```
x = (b +/- sqrt(b^2 - 4ac))/2a
```
So that's why you get the sign error.
|
The signs of `top1` and `top2` are wrong, see <http://en.wikipedia.org/wiki/Quadratic_equation>
|
4,701,383
|
what i'm trying to do is write a quadratic equation solver but when the solution should be `-1`, as in `quadratic(2, 4, 2)` it returns `1`
what am i doing wrong?
```
#!/usr/bin/python
import math
def quadratic(a, b, c):
#a = raw_input("What\'s your `a` value?\t")
#b = raw_input("What\'s your `b` value?\t")
#c = raw_input("What\'s your `c` value?\t")
a, b, c = float(a), float(b), float(c)
disc = (b*b)-(4*a*c)
print "Discriminant is:\n" + str(disc)
if disc >= 0:
root = math.sqrt(disc)
top1 = b + root
top2 = b - root
sol1 = top1/(2*a)
sol2 = top2/(2*a)
if sol1 != sol2:
print "Solution 1:\n" + str(sol1) + "\nSolution 2:\n" + str(sol2)
if sol1 == sol2:
print "One solution:\n" + str(sol1)
else:
print "No solution!"
```
EDIT: it returns the following...
```
>>> import mathmodules
>>> mathmodules.quadratic(2, 4, 2)
Discriminant is:
0.0
One solution:
1.0
```
|
2011/01/15
|
[
"https://Stackoverflow.com/questions/4701383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/569183/"
] |
The signs of `top1` and `top2` are wrong, see <http://en.wikipedia.org/wiki/Quadratic_equation>
|
```
top1 = b + root
top2 = b - root
```
Should be:
```
top1 = -b + root
top2 = -b - root
```
|
70,088,798
|
I am making a python PyQt5 CSV comparison tool project and the user can add conditions for querying the pandas dataframe one by one before they are executed.
At the moment I have a nested list of conditions with each element containing the field, operation (==,!=,>,<), and value for comparison as strings. With just one condition I can use .query as it takes a string condition:
```
data.query('{} {} {}'.format(field,operation,value))
```
But as far as I can tell the formatting for multiple queries would use loc similar to this:
```
data.loc[(data.query('{} {} {}'.format(field[0],operation[0],value[0]))) & (data.query('{} {} {}'.format(field[1],operation[1],value[1]))) & ...]
```
Firstly I wanted to make sure my understanding of the loc function was correct (do I need a primary key at the end maybe?).
And secondly, how would I represent this multiple condition query with an unknown number of conditions set?
Thanks
|
2021/11/23
|
[
"https://Stackoverflow.com/questions/70088798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13696214/"
] |
Would this work?
```
conds = [
f'{f} {o} {v}' for f, o, v in zip(field, operation, value)
]
data.query(' and '.join(conds))
```
|
**Warning**: Not tested, more like a comment but put here for proper format:
`data.query` returns a dataframe, you can't just do `dataframe1 & dataframe2`. You would do something like
```
data.query(' AND '.join(['{} {} {}'.format(f, o, v)
for f, o, v in zip(fields, operations, values)
])
)
```
|
26,785,812
|
I need to do some intense numerical computations and fortunately python offers very simple ways to implement parallelisations. However, the results I got were totally weird and after some trial'n error I stumbled upon the problem.
The following code simply calculates the mean of a random sample of numbers but illustrates my problem:
```
import multiprocessing
import numpy as np
from numpy.random import random
# Define function to generate random number
def get_random(seed):
dummy = random(1000) * seed
return np.mean(dummy)
# Input data
input_data = [100,100,100,100]
pool = multiprocessing.Pool(processes=4)
result = pool.map(get_random, input_data)
print result
for i in input_data:
print get_random(i)
```
Now the output looks like this:
```
[51.003368466729405, 51.003368466729405, 51.003368466729405, 51.003368466729405]
```
for the parallelisation, which is always the same
and like this for the normal not parallelised loop:
```
50.8581749381
49.2887091049
50.83585841
49.3067281055
```
As you can see, the parallelisation just returns the same results, even though it should have calculated difference means just as the loop. Now, sometimes I get only 3 equal numbers with one being different from the other 3.
I suspect that some memory is allocated to all sub processes...
I would love some hints on what is going on here and what a fix would look like. :)
thanks
|
2014/11/06
|
[
"https://Stackoverflow.com/questions/26785812",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4223923/"
] |
When you use `multiprocessing`, you're talking about distinct processes. Distinct processes means distinct Python interpreters. Distinct interpreters means distinct random states. If you aren't seeding the random number generator uniquely on each process, then you're going to get the same starting random state from each process.
|
The answer was to put a new random seed into each process. Changing the function to
```
def get_random(seed):
np.random.seed()
dummy = random(1000) * seed
return np.mean(dummy)
```
gives the wanted results.
|
72,468,946
|
I'm migrating from `setup.py` to `pyproject.toml`. The commands to install my package appear to be the same, but I can't find what the `pyproject.toml` command for cleaning up build artifacts is. What is the equivalent to `python setup.py clean --all`?
|
2022/06/01
|
[
"https://Stackoverflow.com/questions/72468946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7059681/"
] |
The distutils command [clean](https://docs.python.org/3/distutils/apiref.html#module-distutils.command.clean) is not needed for a `pyproject.toml` based build. Modern tools invoking [PEP517](https://peps.python.org/pep-0517/)/[PEP518](https://peps.python.org/pep-0518/) hooks, such as [build](https://pypi.org/project/build/), create a temporary directory or a cache directory to store intermediate files while building, rather than littering the project directory with a `build` subdirectory.
Anyway, it was [not really an exciting command](https://github.com/python/cpython/blob/3.11/Lib/distutils/command/clean.py) in the first place and `rm -rf build` does the same job.
|
I ran into this same issue when I was migrating. What wim answered seems to be mostly true. If you do as the setuptools documentation says and use `python -m build` then the `build` directory will not be created, but a `dist` will. However if you do `pip install .` a `build` directory will be left behind even if you are using a `pyproject.toml` file. This can cause issues if you change your package structure or rename files as sometimes the old version that is in the `build` directory will be installed instead of your current changes. Personally I run `pip install . && rm -rf build` or `pip install . && rmdir /s /q build` for Windows. This could be expanded to remove any other unwanted artifacts.
|
11,023,990
|
I would like to use Python to run a macro contained in MacroBook.xlsm on a worksheet in Data.csv.
Normally in excel, I have both files open and shift focus to the Data.csv file and run the macro from MacroBook. The python script downloads the Data.csv file daily, so I can't put the macro in that file.
Here's my code:
```
import win32com.client
import os
import xl
excel = win32com.client.Dispatch("Excel.Application")
macrowb = xl.Workbook('C:\MacroBook.xlsm')
wb1 = xl.Workbook('C:\Database.csv')
excel.Run("FilterLoans")
```
I get an error,
>
> pywintypes.com\_error: (-2147352567, 'Exception occurred.', (0,
> u'Microsoft Excel', u"Cannot run the macro 'FilterLoans'. The macro
> may not be available in this workbook or all macros may be disabled.",
> u'xlmain11.chm', 0, -2146827284), None)
>
>
>
The error states that FilterLoans is not available in the Database.csv file...how can I import it?
|
2012/06/13
|
[
"https://Stackoverflow.com/questions/11023990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1137778/"
] |
Just return an empty enumerable in the base method.
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
return Enumerable.Empty<Uri>();
}
```
Or if you're targeting a version of the .NET framework < 3.5 return an empty List.
|
Built in arrays support IEnumerable so you can use:
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
return new Uri[0];
}
```
|
11,023,990
|
I would like to use Python to run a macro contained in MacroBook.xlsm on a worksheet in Data.csv.
Normally in excel, I have both files open and shift focus to the Data.csv file and run the macro from MacroBook. The python script downloads the Data.csv file daily, so I can't put the macro in that file.
Here's my code:
```
import win32com.client
import os
import xl
excel = win32com.client.Dispatch("Excel.Application")
macrowb = xl.Workbook('C:\MacroBook.xlsm')
wb1 = xl.Workbook('C:\Database.csv')
excel.Run("FilterLoans")
```
I get an error,
>
> pywintypes.com\_error: (-2147352567, 'Exception occurred.', (0,
> u'Microsoft Excel', u"Cannot run the macro 'FilterLoans'. The macro
> may not be available in this workbook or all macros may be disabled.",
> u'xlmain11.chm', 0, -2146827284), None)
>
>
>
The error states that FilterLoans is not available in the Database.csv file...how can I import it?
|
2012/06/13
|
[
"https://Stackoverflow.com/questions/11023990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1137778/"
] |
Built in arrays support IEnumerable so you can use:
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
return new Uri[0];
}
```
|
The reason why empty method doesn't work is that the compiler assumes that if you don't use the `yield` keyword in the method, then you want to create a normal method, not an iterator. That's also why your `if (false)` hack works.
To properly write a method that returns an empty collection, you could either return an empty collection in the usual way:
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
return Enumerable.Empty<Uri>();
}
```
Or you could use `yield break`:
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
yield break;
}
```
|
11,023,990
|
I would like to use Python to run a macro contained in MacroBook.xlsm on a worksheet in Data.csv.
Normally in excel, I have both files open and shift focus to the Data.csv file and run the macro from MacroBook. The python script downloads the Data.csv file daily, so I can't put the macro in that file.
Here's my code:
```
import win32com.client
import os
import xl
excel = win32com.client.Dispatch("Excel.Application")
macrowb = xl.Workbook('C:\MacroBook.xlsm')
wb1 = xl.Workbook('C:\Database.csv')
excel.Run("FilterLoans")
```
I get an error,
>
> pywintypes.com\_error: (-2147352567, 'Exception occurred.', (0,
> u'Microsoft Excel', u"Cannot run the macro 'FilterLoans'. The macro
> may not be available in this workbook or all macros may be disabled.",
> u'xlmain11.chm', 0, -2146827284), None)
>
>
>
The error states that FilterLoans is not available in the Database.csv file...how can I import it?
|
2012/06/13
|
[
"https://Stackoverflow.com/questions/11023990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1137778/"
] |
Just return an empty enumerable in the base method.
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
return Enumerable.Empty<Uri>();
}
```
Or if you're targeting a version of the .NET framework < 3.5 return an empty List.
|
Use an empty array, or:
```
yield break; //end enumeration
```
Pulling up svick's idea from the comments:
```
return Enumerable.Empty<Uri>();
```
This is faster because `Enumerable.Empty` always returns a cached, pre-allocated instance of some empty enumerable.
|
11,023,990
|
I would like to use Python to run a macro contained in MacroBook.xlsm on a worksheet in Data.csv.
Normally in excel, I have both files open and shift focus to the Data.csv file and run the macro from MacroBook. The python script downloads the Data.csv file daily, so I can't put the macro in that file.
Here's my code:
```
import win32com.client
import os
import xl
excel = win32com.client.Dispatch("Excel.Application")
macrowb = xl.Workbook('C:\MacroBook.xlsm')
wb1 = xl.Workbook('C:\Database.csv')
excel.Run("FilterLoans")
```
I get an error,
>
> pywintypes.com\_error: (-2147352567, 'Exception occurred.', (0,
> u'Microsoft Excel', u"Cannot run the macro 'FilterLoans'. The macro
> may not be available in this workbook or all macros may be disabled.",
> u'xlmain11.chm', 0, -2146827284), None)
>
>
>
The error states that FilterLoans is not available in the Database.csv file...how can I import it?
|
2012/06/13
|
[
"https://Stackoverflow.com/questions/11023990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1137778/"
] |
Use an empty array, or:
```
yield break; //end enumeration
```
Pulling up svick's idea from the comments:
```
return Enumerable.Empty<Uri>();
```
This is faster because `Enumerable.Empty` always returns a cached, pre-allocated instance of some empty enumerable.
|
The reason why empty method doesn't work is that the compiler assumes that if you don't use the `yield` keyword in the method, then you want to create a normal method, not an iterator. That's also why your `if (false)` hack works.
To properly write a method that returns an empty collection, you could either return an empty collection in the usual way:
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
return Enumerable.Empty<Uri>();
}
```
Or you could use `yield break`:
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
yield break;
}
```
|
11,023,990
|
I would like to use Python to run a macro contained in MacroBook.xlsm on a worksheet in Data.csv.
Normally in excel, I have both files open and shift focus to the Data.csv file and run the macro from MacroBook. The python script downloads the Data.csv file daily, so I can't put the macro in that file.
Here's my code:
```
import win32com.client
import os
import xl
excel = win32com.client.Dispatch("Excel.Application")
macrowb = xl.Workbook('C:\MacroBook.xlsm')
wb1 = xl.Workbook('C:\Database.csv')
excel.Run("FilterLoans")
```
I get an error,
>
> pywintypes.com\_error: (-2147352567, 'Exception occurred.', (0,
> u'Microsoft Excel', u"Cannot run the macro 'FilterLoans'. The macro
> may not be available in this workbook or all macros may be disabled.",
> u'xlmain11.chm', 0, -2146827284), None)
>
>
>
The error states that FilterLoans is not available in the Database.csv file...how can I import it?
|
2012/06/13
|
[
"https://Stackoverflow.com/questions/11023990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1137778/"
] |
Just return an empty enumerable in the base method.
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
return Enumerable.Empty<Uri>();
}
```
Or if you're targeting a version of the .NET framework < 3.5 return an empty List.
|
The reason why empty method doesn't work is that the compiler assumes that if you don't use the `yield` keyword in the method, then you want to create a normal method, not an iterator. That's also why your `if (false)` hack works.
To properly write a method that returns an empty collection, you could either return an empty collection in the usual way:
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
return Enumerable.Empty<Uri>();
}
```
Or you could use `yield break`:
```
public virtual IEnumerable<Uri> GetBaseAddresses()
{
yield break;
}
```
|
52,377,332
|
[This](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-using-sdk-python.html) page shows how to send an email using SES. The example works by reading the credentials from `~/.aws/credentials`, which are the root (yet "shared"??) credentials.
The documentation advises in various places against using the root credentials.
Acquiring temporary credentials
using [roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-api.html) is mentioned as an option, yet `assume_role()` is not defined for SES client objects.
How do I send an email through SES with temporary SES-specific credentials?
**Update**
The context for my question is an application running on an EC2 instance.
|
2018/09/18
|
[
"https://Stackoverflow.com/questions/52377332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704972/"
] |
Here you go. There were a few problems.
1) When you return a value from a function, you need to assign it to a variable so you can pass it into the next function.
2) String literals like the letter grade "F" need to be inside single or double quote marks.
```
def main():
student_name = input('Please enter your first and last name: ')
scores = askForScore()
avg_score = calc_average(scores)
letter_grade = determine_grade(avg_score)
print(letter_grade)
def askForScore():
score1 = float(input('Please enter the first test score:'))
score2 = float(input('Please enter the second test score:'))
score3 = float(input('Please enter the third test score:'))
score4 = float(input('Please enter the fourth test score:'))
score5 = float(input('Please enter the fifth test score:'))
return (score1, score2, score3, score4, score5)
def calc_average(scores):
avg_score = (scores[0] + scores[1] + scores[2] + scores[3] + scores[4]) / 5
return avg_score
def determine_grade(avg_score):
if avg_score >= 90 and avg_score <= 100:
return 'A'
elif avg_score >= 80 and avg_score <= 89:
return 'B'
elif avg_score >= 70 and avg_score <= 79:
return 'C'
elif avg_score >= 60 and avg_score <= 69:
return 'D'
else:
return 'F'
main()
```
|
Make sure you understand some Python concepts such as the scope of variables, return statements and function arguments. In your case, for instance, `score1` ... `score5` inside `askForScore` are not "readable" by `calc_average`. In fact, `calc_average` returns the values you need and those values need to be passed to the next function as arguments like this:
```
...
score1, score2, score3, score4, score5 = askForScore()
calc_average(score1, score2, score3, score4, score5)
...
```
|
21,072,841
|
I am testing some python functionalities as web server. Typed :
```
$ python -m SimpleHTTPServer 8080
```
...and setup port forwarding on router to this 8080. I can access via web with <http://my.ip.adr.ess:8080/>, whereas my.ip.adr.ess stands for my IP adress.
When I started my xampp server it is accessible with <http://my.ip.adr.ess/> and no 8080 port is required for accessing.
What should I have to do to python server responds like that?
|
2014/01/12
|
[
"https://Stackoverflow.com/questions/21072841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/891304/"
] |
It means that xampp is running on port 80 which is default for http://. You need to run SimpleHTTPServer on that port too. [More info about running SimpleHTTPServer on port 80](https://unix.stackexchange.com/questions/24598/how-can-i-start-the-python-simplehttpserver-on-port-80).
|
Specify the port as `80` (default port for HTTP protocol).
```
python -m SimpleHTTPServer 80
```
You may need superuser permission in Unix to bind port 80 (under 1024).
```
sudo python -m SimpleHTTPServer 80
```
|
58,026,436
|
I am working on a bank statement, corresponding to the output dataframe and an ending balance corresponding to the output['balance'][0] I would like to calculate all balance values for the individual transactions as described below. It's a very straightforward calculation and yet it doesn't seem to be working - is there something quite obvious I am missing? Thanks in advance!
```
output['balance'] = ''
output['balance'][0] = 21.15
if len(output[amount]) > 0:
return output[balance][i+1].append((output[balance][i]-output[amount][i+1]))
else:
output[balance].append((output[balance][0]))
output[['balance']] = output['Amount'].apply(lambda amount: bal_calc(output, amount))```
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2896 try:
-> 2897 return self._engine.get_loc(key)
2898 except KeyError:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 4.95
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-271-b85947935fca> in <module>
----> 1 output[['balance']] = output['Amount'].apply(lambda amount: bal_calc(output, amount))
~\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
4040 else:
4041 values = self.astype(object).values
-> 4042 mapped = lib.map_infer(values, f, convert=convert_dtype)
4043
4044 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-271-b85947935fca> in <lambda>(amount)
----> 1 output[['balance']] = output['Amount'].apply(lambda amount: bal_calc(output, amount))
<ipython-input-270-cbf5ac20716d> in bal_calc(output, amount)
2 output['balance'] = ''
3 output['balance'][0] = 21.15
----> 4 if len(output[amount]) > 0:
5 return output[balance][i+1].append((output[balance][i]-output[amount][i+1]))
6 else:
~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2978 if self.columns.nlevels > 1:
2979 return self._getitem_multilevel(key)
-> 2980 indexer = self.columns.get_loc(key)
2981 if is_integer(indexer):
2982 indexer = [indexer]
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2897 return self._engine.get_loc(key)
2898 except KeyError:
-> 2899 return self._engine.get_loc(self._maybe_cast_indexer(key))
2900 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2901 if indexer.ndim > 1 or indexer.size > 1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 4.95
```
|
2019/09/20
|
[
"https://Stackoverflow.com/questions/58026436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7698202/"
] |
I would need to have all of your code and be able to run it locally in order to diagnose the problem because your posting is devoid of details (I would need to see inside your `ManipulatePixel` function, as well as the code that calls `ProcessFrame`). but here's some general tips that apply in your case.
* 2D arrays in .NET are significantly slower than 1D arrays and staggered arrays, even in .NET Core today - this is a longstanding bug.
+ See here:
- <https://github.com/dotnet/coreclr/issues/4059>
- [Why are multi-dimensional arrays in .NET slower than normal arrays?](https://stackoverflow.com/questions/468832/why-are-multi-dimensional-arrays-in-net-slower-than-normal-arrays)
- [Multi-dimensional array vs. One-dimensional](https://stackoverflow.com/questions/5476000/multi-dimensional-array-vs-one-dimensional)
+ So consider changing your code to use either a jagged array ([which also helps with memory locality/proximity caching, as each thread would have its own private buffer](https://stackoverflow.com/questions/12065774/why-does-cache-locality-matter-for-array-performance)) or a 1D array with your own code being responsible for bounds-checking.
+ Or better-yet: use `stackalloc` to manage the buffer's lifetime and pass that by-pointer (`unsafe` ahoy!) to your thread delegate.
* Sharing memory buffers between threads makes it harder for the system to optimize safe memory accesses.
* Avoid allocating a new buffer for each frame encountered - if a frame has a limited lifespan then consider using reusable buffers using a buffer-pool.
* Consider using the SIMD and AVX features in .NET. While modern C/C++ compilers are smart enough to compile code to use those instructions, the .NET JIT isn't so hot - but you can make explicit calls into [SMID/AVX instructions using the SIMD-enabled types](https://learn.microsoft.com/en-us/dotnet/standard/numerics#simd-enabled-types) (you'll need to use .NET Core 2.0 or later for the best accelerated functionality)
* Also, avoid copying individual bytes or scalar values inside a `for` loop in C#, instead consider using `Buffer.BlockCopy` for bulk copy operations (as these can use hardware memory copy features).
* Regarding your observation of "80% CPU usage" - if you have a loop in a program then that *will* cause 100% CPU usage within the time-slices provided by the operating-system - if you don't see 100% usage then your code then:
+ Your code is actually running *faster* than real-time (this is a good thing!) - (unless you're certain your program can't keep-up with the input?)
+ Your codes' thread (or threads) is blocked by something, such as a blocking IO call or a misplaced `Thread.Sleep`. Use tools like ETW to see what your process is doing when you think it should be CPU-bound.
+ Ensure you aren't using any `lock` (`Monitor`) calls or using other thread or memory synchronization primitives.
|
Efficiency matters ( it is **not** true-**`[PARALLEL]`**, but may, yet need not, benefit from a *"just"*-`[CONCURRENT]` work
The BEST, yet a rather hard way, if ultimate performance is a MUST :
--------------------------------------------------------------------
in-line an assembly, optimised as per cache-line sizes in the CPU hierarchy and keep indexing that follows the actual memory-layout of the 2D data `{ column-wise | row-wise }`. Given there is no 2D-kernel-transformation mentioned, your process does not need to "touch" any topological-neighbours, the indexing can step in whatever order "across" both of the ranges of the 2D-domain and the `ManipulatePixel()` may get more efficient on transforming rather blocks-of pixels, instead of bearing all overheads for calling a process just for each isolated atomicised-1px ( ILP + cache-efficiency are on your side ).
Given your target production-platform CPU-family, best use (block-SIMD)-vectorised instructions available from AVX2, best AVX512 code. As you most probably know, may use C/C++ using AVX-intrinsics for performance optimisations with assembly-inspection and finally "copy" the best resulting assembly for your C# assembly-inlining. Nothing will run faster. Tricks with CPU-core affinity mapping and eviction/reservation are indeed a last resort, yet may help for indeed an *almost* hard-real-time production settings ( though, hard R/T systems are seldom to get developed in an ecosystem with non-deterministic behaviour )
A CHEAP, few-seconds step :
---------------------------
Test and benchmark the run-time per batch of frames of a reversed composition of moving the more-"expensive"-part, the `Parallel.For(...{...})` inside the `for(var col = 0; col < width; ++col){...}` to see the change of the costs of instantiations of the `Parallel.For()` instrumentation.
Next, if going this cheap way, think about re-factoring the `ManipulatePixel()` to at least use a block of data, aligned with data-storage layout and being a multiple of cache-line length ( for cache-hits **`~ 0.5 ~ 5 [ns]`** improved costs-of-memory accesses, being **`~ 100 ~ 380 [ns]`** otherwise - here, a will to distribute a work (the worse per 1px) across all NUMA-CPU-cores will result in paying way more time, due to extended access-latencies for cross-NUMA-(non-local) memory addresses and besides never re-using an expensively cached block-of-fetched-data, you knowingly pay excessive costs from cross-NUMA-(non-local) memory fetches ( from which you "use" just 1px and "throw" away all the rest of the cached-block ( as those pixels will get re-fetched and manipulated in some other CPU-core in some other time ~ a triple-waste of time ~ sorry to have mentioned that explicitly, but **when shaving each possible `[ns]` this cannot happen in production pipeline** ) )
---
Anyway, let me wish you perseverance and good luck on your steps forwards to gain the needed efficiency back onto your side.
|
58,026,436
|
I am working on a bank statement, corresponding to the output dataframe and an ending balance corresponding to the output['balance'][0] I would like to calculate all balance values for the individual transactions as described below. It's a very straightforward calculation and yet it doesn't seem to be working - is there something quite obvious I am missing? Thanks in advance!
```
output['balance'] = ''
output['balance'][0] = 21.15
if len(output[amount]) > 0:
return output[balance][i+1].append((output[balance][i]-output[amount][i+1]))
else:
output[balance].append((output[balance][0]))
output[['balance']] = output['Amount'].apply(lambda amount: bal_calc(output, amount))```
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2896 try:
-> 2897 return self._engine.get_loc(key)
2898 except KeyError:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 4.95
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-271-b85947935fca> in <module>
----> 1 output[['balance']] = output['Amount'].apply(lambda amount: bal_calc(output, amount))
~\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
4040 else:
4041 values = self.astype(object).values
-> 4042 mapped = lib.map_infer(values, f, convert=convert_dtype)
4043
4044 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-271-b85947935fca> in <lambda>(amount)
----> 1 output[['balance']] = output['Amount'].apply(lambda amount: bal_calc(output, amount))
<ipython-input-270-cbf5ac20716d> in bal_calc(output, amount)
2 output['balance'] = ''
3 output['balance'][0] = 21.15
----> 4 if len(output[amount]) > 0:
5 return output[balance][i+1].append((output[balance][i]-output[amount][i+1]))
6 else:
~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2978 if self.columns.nlevels > 1:
2979 return self._getitem_multilevel(key)
-> 2980 indexer = self.columns.get_loc(key)
2981 if is_integer(indexer):
2982 indexer = [indexer]
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2897 return self._engine.get_loc(key)
2898 except KeyError:
-> 2899 return self._engine.get_loc(self._maybe_cast_indexer(key))
2900 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2901 if indexer.ndim > 1 or indexer.size > 1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 4.95
```
|
2019/09/20
|
[
"https://Stackoverflow.com/questions/58026436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7698202/"
] |
I would need to have all of your code and be able to run it locally in order to diagnose the problem because your posting is devoid of details (I would need to see inside your `ManipulatePixel` function, as well as the code that calls `ProcessFrame`). but here's some general tips that apply in your case.
* 2D arrays in .NET are significantly slower than 1D arrays and staggered arrays, even in .NET Core today - this is a longstanding bug.
+ See here:
- <https://github.com/dotnet/coreclr/issues/4059>
- [Why are multi-dimensional arrays in .NET slower than normal arrays?](https://stackoverflow.com/questions/468832/why-are-multi-dimensional-arrays-in-net-slower-than-normal-arrays)
- [Multi-dimensional array vs. One-dimensional](https://stackoverflow.com/questions/5476000/multi-dimensional-array-vs-one-dimensional)
+ So consider changing your code to use either a jagged array ([which also helps with memory locality/proximity caching, as each thread would have its own private buffer](https://stackoverflow.com/questions/12065774/why-does-cache-locality-matter-for-array-performance)) or a 1D array with your own code being responsible for bounds-checking.
+ Or better-yet: use `stackalloc` to manage the buffer's lifetime and pass that by-pointer (`unsafe` ahoy!) to your thread delegate.
* Sharing memory buffers between threads makes it harder for the system to optimize safe memory accesses.
* Avoid allocating a new buffer for each frame encountered - if a frame has a limited lifespan then consider using reusable buffers using a buffer-pool.
* Consider using the SIMD and AVX features in .NET. While modern C/C++ compilers are smart enough to compile code to use those instructions, the .NET JIT isn't so hot - but you can make explicit calls into [SMID/AVX instructions using the SIMD-enabled types](https://learn.microsoft.com/en-us/dotnet/standard/numerics#simd-enabled-types) (you'll need to use .NET Core 2.0 or later for the best accelerated functionality)
* Also, avoid copying individual bytes or scalar values inside a `for` loop in C#, instead consider using `Buffer.BlockCopy` for bulk copy operations (as these can use hardware memory copy features).
* Regarding your observation of "80% CPU usage" - if you have a loop in a program then that *will* cause 100% CPU usage within the time-slices provided by the operating-system - if you don't see 100% usage then your code then:
+ Your code is actually running *faster* than real-time (this is a good thing!) - (unless you're certain your program can't keep-up with the input?)
+ Your codes' thread (or threads) is blocked by something, such as a blocking IO call or a misplaced `Thread.Sleep`. Use tools like ETW to see what your process is doing when you think it should be CPU-bound.
+ Ensure you aren't using any `lock` (`Monitor`) calls or using other thread or memory synchronization primitives.
|
Here's what I ended up doing, mostly based on Dai's answer:
* made sure to query image pixel dimensions once at the beginning of the processing functions, not within the for loop's conditional statement. With parallel loops, it would seem this creates competitive access of those properties from multriple threads which noticeably slows things down.
* removed allocation of output buffers within the processing functions. They now return void and accept the output buffer as an argument. The caller creates one buffer for each image processing step (filtering, scaling, colorizing) only, which doesn't change in size but gets overwritten with each frame.
* removed an extra data processing step where raw image data in the format ushort (what the camera originally spits out) was converted to double (actual temperature values). Instead, processing is applied to the raw data directly. Conversion to actual temperatures will be dealt with later, as necessary.
I also tried, without success, to use 1D arrays instead of 2D but there is actually no difference in performance. I don't know if it's because the bug Dai mentioned was fixed in the meantime, but I couldn't confirm 2D arrays to be any slower than 1D arrays.
Probably also worth mentioning, the ManipulatePixel() function in my original post was actually more of a placeholder rather than a real call to another function. Here's a more proper example of what I am doing to a frame, including the changes I made:
```
private static void Rescale(ushort[,] originalImg, byte[,] scaledImg, in (ushort, ushort) limits)
{
Debug.Assert(originalImg != null);
Debug.Assert(originalImg.Length != 0);
Debug.Assert(scaledImg != null);
Debug.Assert(scaledImg.Length == originalImg.Length);
ushort min = limits.Item1;
ushort max = limits.Item2;
int width = originalImg.GetLength(1);
int height = originalImg.GetLength(0);
Parallel.For(0, height, row =>
{
for (var col = 0; col < width; ++col)
{
ushort value = originalImg[row, col];
if (value < min)
scaledImg[row, col] = 0;
else if (value > max)
scaledImg[row, col] = 255;
else
scaledImg[row, col] = (byte)(255.0 * (value - min) / (max - min));
}
});
}
```
This is just one step and some others are much more complex but the approach would be similar.
Some of the things mentioned like SIMD/AVX or the answer of user3666197 unfortunately are well beyond my abilities right now so I couldn't test that out.
It's still relatively easy to put enough processing load into the stream to tank the frame rate but for my application the performance should be enough now. Thanks to everyone who provided input, I'll mark Dai's answer as accepted because I found it the most helpful.
|
58,026,436
|
I am working on a bank statement, corresponding to the output dataframe and an ending balance corresponding to the output['balance'][0] I would like to calculate all balance values for the individual transactions as described below. It's a very straightforward calculation and yet it doesn't seem to be working - is there something quite obvious I am missing? Thanks in advance!
```
output['balance'] = ''
output['balance'][0] = 21.15
if len(output[amount]) > 0:
return output[balance][i+1].append((output[balance][i]-output[amount][i+1]))
else:
output[balance].append((output[balance][0]))
output[['balance']] = output['Amount'].apply(lambda amount: bal_calc(output, amount))```
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2896 try:
-> 2897 return self._engine.get_loc(key)
2898 except KeyError:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 4.95
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-271-b85947935fca> in <module>
----> 1 output[['balance']] = output['Amount'].apply(lambda amount: bal_calc(output, amount))
~\Anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds)
4040 else:
4041 values = self.astype(object).values
-> 4042 mapped = lib.map_infer(values, f, convert=convert_dtype)
4043
4044 if len(mapped) and isinstance(mapped[0], Series):
pandas/_libs/lib.pyx in pandas._libs.lib.map_infer()
<ipython-input-271-b85947935fca> in <lambda>(amount)
----> 1 output[['balance']] = output['Amount'].apply(lambda amount: bal_calc(output, amount))
<ipython-input-270-cbf5ac20716d> in bal_calc(output, amount)
2 output['balance'] = ''
3 output['balance'][0] = 21.15
----> 4 if len(output[amount]) > 0:
5 return output[balance][i+1].append((output[balance][i]-output[amount][i+1]))
6 else:
~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2978 if self.columns.nlevels > 1:
2979 return self._getitem_multilevel(key)
-> 2980 indexer = self.columns.get_loc(key)
2981 if is_integer(indexer):
2982 indexer = [indexer]
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2897 return self._engine.get_loc(key)
2898 except KeyError:
-> 2899 return self._engine.get_loc(self._maybe_cast_indexer(key))
2900 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2901 if indexer.ndim > 1 or indexer.size > 1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 4.95
```
|
2019/09/20
|
[
"https://Stackoverflow.com/questions/58026436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7698202/"
] |
Efficiency matters ( it is **not** true-**`[PARALLEL]`**, but may, yet need not, benefit from a *"just"*-`[CONCURRENT]` work
The BEST, yet a rather hard way, if ultimate performance is a MUST :
--------------------------------------------------------------------
in-line an assembly, optimised as per cache-line sizes in the CPU hierarchy and keep indexing that follows the actual memory-layout of the 2D data `{ column-wise | row-wise }`. Given there is no 2D-kernel-transformation mentioned, your process does not need to "touch" any topological-neighbours, the indexing can step in whatever order "across" both of the ranges of the 2D-domain and the `ManipulatePixel()` may get more efficient on transforming rather blocks-of pixels, instead of bearing all overheads for calling a process just for each isolated atomicised-1px ( ILP + cache-efficiency are on your side ).
Given your target production-platform CPU-family, best use (block-SIMD)-vectorised instructions available from AVX2, best AVX512 code. As you most probably know, may use C/C++ using AVX-intrinsics for performance optimisations with assembly-inspection and finally "copy" the best resulting assembly for your C# assembly-inlining. Nothing will run faster. Tricks with CPU-core affinity mapping and eviction/reservation are indeed a last resort, yet may help for indeed an *almost* hard-real-time production settings ( though, hard R/T systems are seldom to get developed in an ecosystem with non-deterministic behaviour )
A CHEAP, few-seconds step :
---------------------------
Test and benchmark the run-time per batch of frames of a reversed composition of moving the more-"expensive"-part, the `Parallel.For(...{...})` inside the `for(var col = 0; col < width; ++col){...}` to see the change of the costs of instantiations of the `Parallel.For()` instrumentation.
Next, if going this cheap way, think about re-factoring the `ManipulatePixel()` to at least use a block of data, aligned with data-storage layout and being a multiple of cache-line length ( for cache-hits **`~ 0.5 ~ 5 [ns]`** improved costs-of-memory accesses, being **`~ 100 ~ 380 [ns]`** otherwise - here, a will to distribute a work (the worse per 1px) across all NUMA-CPU-cores will result in paying way more time, due to extended access-latencies for cross-NUMA-(non-local) memory addresses and besides never re-using an expensively cached block-of-fetched-data, you knowingly pay excessive costs from cross-NUMA-(non-local) memory fetches ( from which you "use" just 1px and "throw" away all the rest of the cached-block ( as those pixels will get re-fetched and manipulated in some other CPU-core in some other time ~ a triple-waste of time ~ sorry to have mentioned that explicitly, but **when shaving each possible `[ns]` this cannot happen in production pipeline** ) )
---
Anyway, let me wish you perseverance and good luck on your steps forwards to gain the needed efficiency back onto your side.
|
Here's what I ended up doing, mostly based on Dai's answer:
* made sure to query image pixel dimensions once at the beginning of the processing functions, not within the for loop's conditional statement. With parallel loops, it would seem this creates competitive access of those properties from multriple threads which noticeably slows things down.
* removed allocation of output buffers within the processing functions. They now return void and accept the output buffer as an argument. The caller creates one buffer for each image processing step (filtering, scaling, colorizing) only, which doesn't change in size but gets overwritten with each frame.
* removed an extra data processing step where raw image data in the format ushort (what the camera originally spits out) was converted to double (actual temperature values). Instead, processing is applied to the raw data directly. Conversion to actual temperatures will be dealt with later, as necessary.
I also tried, without success, to use 1D arrays instead of 2D but there is actually no difference in performance. I don't know if it's because the bug Dai mentioned was fixed in the meantime, but I couldn't confirm 2D arrays to be any slower than 1D arrays.
Probably also worth mentioning, the ManipulatePixel() function in my original post was actually more of a placeholder rather than a real call to another function. Here's a more proper example of what I am doing to a frame, including the changes I made:
```
private static void Rescale(ushort[,] originalImg, byte[,] scaledImg, in (ushort, ushort) limits)
{
Debug.Assert(originalImg != null);
Debug.Assert(originalImg.Length != 0);
Debug.Assert(scaledImg != null);
Debug.Assert(scaledImg.Length == originalImg.Length);
ushort min = limits.Item1;
ushort max = limits.Item2;
int width = originalImg.GetLength(1);
int height = originalImg.GetLength(0);
Parallel.For(0, height, row =>
{
for (var col = 0; col < width; ++col)
{
ushort value = originalImg[row, col];
if (value < min)
scaledImg[row, col] = 0;
else if (value > max)
scaledImg[row, col] = 255;
else
scaledImg[row, col] = (byte)(255.0 * (value - min) / (max - min));
}
});
}
```
This is just one step and some others are much more complex but the approach would be similar.
Some of the things mentioned like SIMD/AVX or the answer of user3666197 unfortunately are well beyond my abilities right now so I couldn't test that out.
It's still relatively easy to put enough processing load into the stream to tank the frame rate but for my application the performance should be enough now. Thanks to everyone who provided input, I'll mark Dai's answer as accepted because I found it the most helpful.
|
29,360,607
|
I was looking up how to create a function that removes duplicate characters from a string in python and found this on stack overflow:
```
from collections import OrderedDict
def remove_duplicates (foo) :
print " ".join(OrderedDict.fromkeys(foo))
```
It works, but how? I've searched what OrderedDict and fromkeys mean but I can't find anything that explains how it works in this context.
|
2015/03/31
|
[
"https://Stackoverflow.com/questions/29360607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4728174/"
] |
I will give it a shot:
[OrderedDict](https://docs.python.org/3/library/collections.html#collections.OrderedDict) are dictionaries that store keys in order they are added. Normal dictionaries don't. If you look at **doc** of `fromkeys`, you find:
>
> OD.fromkeys(S[, v]) -> New ordered dictionary with keys from S.
>
>
>
So the `fromkeys` class method, creates an `OrderedDict` using items in the input iterable S (in my example characters from a string) as keys. In a dictionary, keys are unique, so duplicate items in `S` are ignored.
For example:
```
s = "abbcdece" # example string with duplicate characters
print(OrderedDict.fromkeys(s))
```
This results in an OrderedDict:
```
OrderedDict([('a', None), ('b', None), ('c', None), ('d', None), ('e', None)])
```
Then `" ".join(some_iterable)` takes an iterable and joins its elements using a space in this case. It uses only keys, as iterating through a dictionary is done by its keys. For example:
```
for k in OrderedDict.fromkeys(s): # k is a key of the OrderedDict
print(k)
```
Results in:
```
a
b
c
d
e
```
Subsequently, call to join:
```
print(" ".join(OrderedDict.fromkeys(s)))
```
will print out:
```
a b c d e
```
**Using set**
Sometimes, people use a set for this:
```
print( " ".join(set(s)))
# c a b d e
```
But unlike sets in C++, sets in python do not guarantee order. So using a set will give you unique values easily, but they might be in a different order then they are in the original list or string (as in the above example).
Hope this helps a bit.
|
By list comprehension
```
print ' '.join([character for index, character in enumerate(foo) if character not in foo[:index]])
```
|
22,036,124
|
I declared a few global variables in a python file and would like to reset their values to None in a function. Is there a better/hack/pythonic way to declare all variables as global and assign them a value in one line?
```
doctype, content_type, framework, cms, server = (None,)*5
def reset():
doctype, content_type, framework, cms, server = (None,)*5
```
|
2014/02/26
|
[
"https://Stackoverflow.com/questions/22036124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2113279/"
] |
Chain `=`, since you're assining immutable `None` to them:
```
doctype = content_type = framework = cms = server = None
```
If you wanna use the `reset` function, you have to declare them as `global` inside it:
```
def reset():
global doctype, content_type, framework, cms, server
doctype = content_type = framework = cms = server = None
```
|
I would use **one** global mutable object in this case, `dict` for example:
```
conf = dict.fromkeys(['doctype', 'content_type', 'framework', 'cms', 'server'])
def reset():
for k in conf:
conf[k] = None
```
or class. This way you can incapsulate `reset` in class itself:
```
class Config():
doctype = None
content_type = None
framework = None
cms = None
server = None
@classmethod
def reset(cls):
for attr in [i for i in cls.__dict__.keys()
if i[:1] != '_' and not hasattr(getattr(cls, i), '__call__')]:
setattr(cls, attr, None)
```
|
22,036,124
|
I declared a few global variables in a python file and would like to reset their values to None in a function. Is there a better/hack/pythonic way to declare all variables as global and assign them a value in one line?
```
doctype, content_type, framework, cms, server = (None,)*5
def reset():
doctype, content_type, framework, cms, server = (None,)*5
```
|
2014/02/26
|
[
"https://Stackoverflow.com/questions/22036124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2113279/"
] |
Use [`globals`](http://docs.python.org/2/library/functions.html#globals) to get a reference to the dict of global variables:
```
Python 2.7.5+ (default, Sep 19 2013, 13:48:49)
>>> globals().update({'a': 2})
>>> a
2
>>>
```
In your case:
```
globals().update({
'doctype': None,
'content_type': None,
...
})
```
Use a dict comprehension to do this in one line:
Or this:
```
for var_name in ('doctype', 'content_type', 'framework', 'cms', 'server'):
globals()[var_name] = None
```
Or this:
```
module = sys.modules[__name__]
for var_name in ('doctype', 'content_type', 'framework', 'cms', 'server'):
setattr(var_name, None)
```
|
I would use **one** global mutable object in this case, `dict` for example:
```
conf = dict.fromkeys(['doctype', 'content_type', 'framework', 'cms', 'server'])
def reset():
for k in conf:
conf[k] = None
```
or class. This way you can incapsulate `reset` in class itself:
```
class Config():
doctype = None
content_type = None
framework = None
cms = None
server = None
@classmethod
def reset(cls):
for attr in [i for i in cls.__dict__.keys()
if i[:1] != '_' and not hasattr(getattr(cls, i), '__call__')]:
setattr(cls, attr, None)
```
|
50,878,885
|
I am new in machine learning area. i am trying to run python program on browser by converting trained model in tensorflow js.
[this attention\_ocr](https://github.com/tensorflow/models/tree/master/research/attention_ocr/python) is related to OCR written in python. i have generated HDF5/H5 file and converted that in web specific format with `tensorflowjs_converter`[[ref]](https://js.tensorflow.org/tutorials/import-keras.html).
I follow all instruction given in [this](https://js.tensorflow.org/tutorials/import-keras.html) document but at the time of running in browser it throwing me error *(refer screenshot)*
[](https://i.stack.imgur.com/N4pzc.png)
>
> I am looking for solution to remove this error...!
>
>
>
**Referance :**
[tensorflow.org](https://js.tensorflow.org/tutorials/)
[How to import a TensorFlow SavedModel into TensorFlow.js](https://github.com/tensorflow/tfjs-converter)
[Importing a Keras model into TensorFlow.js](https://js.tensorflow.org/tutorials/import-keras.html)
|
2018/06/15
|
[
"https://Stackoverflow.com/questions/50878885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8367883/"
] |
Lambda (native code) layers are not supported in TensorFlow.js. You will need to replace it with a custom layer. This is tricky. Here is an example custom layer: <https://github.com/tensorflow/tfjs-examples/tree/master/custom-layer>
|
You have to create a custom layer class as @BlessedKey stated above (<https://github.com/tensorflow/tfjs-examples/tree/master/custom-layer>).
You also have to edit the model.json file. The model definition must be updated point to the new class you created for your custom layer instead of the Lambda class. Find the lambda layer inside your model.json and change the "class\_name": "Lambda" attribute to "class\_name": "YourCustomLayer". You can find an example here: <https://github.com/tensorflow/tfjs/issues/283>.
Also make sure to return the correct tensor shape from `computeOutputShape(inputShape)` or you'll get bothered by this pesky guy:
```
TypeError: Cannot read property 'dtype' of undefined
at executor.js:29
at t.e.add (executor.js:96)
at SA (executor.js:341)
at training.js:1063
at engine.js:425
at t.e.scopedRun (engine.js:436)
at t.e.tidy (engine.js:423)
at Nb (globals.js:182)
at s (training.js:1046)
at training.js:1045
```
|
66,988,750
|
**Summary**:
I'm trying to use multiprocess and multiprocessing to parallelise work with the following attributes:
* Shared datastructure
* Multiple arguments passed to a function
* Setting number of processes based on current system
**Errors**:
My approach works for a small amount of work but fails with the following on larger tasks:
`OSError: [Errno 24] Too many open files`
**Solutions tried**
Running on a macOS Catalina system, `ulimit -n` gives `1024` within Pycharm.
Is there a way to avoid having to change `ulimit`? I want to avoid this as the code will ideally work out of the box for various sytems.
I've seen in related questions like [this thread](https://stackoverflow.com/questions/65298058/python-multiprocessing-pool-oserror-too-many-files-open) that recommend using .join and gc.collect in the comments, other threads recommend closing any opened files but I do not access files in my code.
```
import gc
import time
import numpy as np
from math import pi
from multiprocess import Process, Manager
from multiprocessing import Semaphore, cpu_count
def do_work(element, shared_array, sema):
shared_array.append(pi*element)
gc.collect()
sema.release()
# example_ar = np.arange(1, 1000) # works
example_ar = np.arange(1, 10000) # fails
# Parallel code
start = time.time()
# Instantiate a manager object and a share a datastructure
manager = Manager()
shared_ar = manager.list()
# Create semaphores linked to physical cores on a system (1/2 of reported cpu_count)
sema = Semaphore(cpu_count()//2)
job = []
# Loop over every element and start a job
for e in example_ar:
sema.acquire()
p = Process(target=do_work, args=(e, shared_ar, sema))
job.append(p)
p.start()
_ = [p.join() for p in job]
end_par = time.time()
# Serial code equivalent
single_ar = []
for e in example_ar:
single_ar.append(pi*e)
end_single = time.time()
print(f'Parallel work took {end_par-start} seconds, result={sum(list(shared_ar))}')
print(f'Serial work took {end_single-end_par} seconds, result={sum(single_ar)}')
```
|
2021/04/07
|
[
"https://Stackoverflow.com/questions/66988750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7482692/"
] |
The way to avoid changing the ulimit is to make sure that your process pool size does not increase beyond 1024. That's why 1000 works and 10000 fails.
Here's an example of managing the processes with a Pool which will ensure you don't go above the ceiling of your ulimit value:
```
from multiprocessing import Pool
def f(x):
return x*x
if __name__ == '__main__':
with Pool(5) as p:
print(p.map(f, [1, 2, 3]))
```
<https://docs.python.org/3/library/multiprocessing.html#introduction>
>
> other threads recommend closing any opened files but I do not access
> files in my code
>
>
>
You don't have files open, but your processes are opening file descriptors which is what the OS is seeing here.
|
Check limit on number of file descriptors. I changed my ulimit to `4096` from `1024` and it worked.
Check:
```
ulimit -n
```
For me it was `1024`, and I updated it to `4096` and it worked.
```
ulimit -n 4096
```
|
5,014,261
|
I'm using win32com.client to write data to an excel file.
This takes too much time (the code below simulates the amount of data I want to update excel with, and it takes ~2 seconds).
Is there a way to update multiple cells (with different values) in one call rather than filling them one by one? or maybe using a different method which is more efficient?
I'm using python 2.7 and office 2010.
Here is the code:
```
from win32com.client import Dispatch
xlsApp = Dispatch('Excel.Application')
xlsApp.Workbooks.Add()
xlsApp.Visible = True
workSheet = xlsApp.Worksheets(1)
for i in range(300):
for j in range(20):
workSheet.Cells(i+1,j+1).Value = (i+10000)*j
```
|
2011/02/16
|
[
"https://Stackoverflow.com/questions/5014261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619303/"
] |
A few suggestions:
**ScreenUpdating off, manual calculation**
Try the following:
```
xlsApp.ScreenUpdating = False
xlsApp.Calculation = -4135 # manual
try:
#
worksheet = ...
for i in range(...):
#
finally:
xlsApp.ScreenUpdating = True
xlsApp.Calculation = -4105 # automatic
```
**Assign several cells at once**
Using VBA, you can set a range's value to an array. Setting several values at once might be faster:
```
' VBA code
ActiveSheet.Range("A1:D1").Value = Array(1, 2, 3, 4)
```
I have never tried this using Python, I suggest you try something like:
```
worksheet.Range("A1:D1").Value = [1, 2, 3, 4]
```
**A different approach**
Consider using [openpyxl](https://bitbucket.org/ericgazoni/openpyxl/wiki/Home) or [xlwt](http://pypi.python.org/pypi/xlwt). Openpyxls lets you create `.xlsx` files without having Excel installed. Xlwt does the same thing for `.xls` files.
|
used the range suggestion of the other answer, I wrote this:
```
def writeLineToExcel(wsh,line):
wsh.Range( "A1:"+chr(len(line)+96).upper()+"1").Value=line
xlApp = Dispatch("Excel.Application")
xlApp.Visible = 1
xlDoc = xlApp.Workbooks.Open("test.xlsx")
wsh = xlDoc.Sheets("Sheet1")
writeLineToExcel(wsh,[1, 2, 3, 4])
```
you may also write multiple lines at once:
```
def writeLinesToExcel(wsh,lines): # assume that all lines have the same length
wsh.Range( "A1:"+chr(len(lines)+96).upper()+str(len(lines[0]))).Value=lines
writeLinesToExcel(wsh,[ [1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10,11,12],
[13,14,15,16],
])
```
|
5,014,261
|
I'm using win32com.client to write data to an excel file.
This takes too much time (the code below simulates the amount of data I want to update excel with, and it takes ~2 seconds).
Is there a way to update multiple cells (with different values) in one call rather than filling them one by one? or maybe using a different method which is more efficient?
I'm using python 2.7 and office 2010.
Here is the code:
```
from win32com.client import Dispatch
xlsApp = Dispatch('Excel.Application')
xlsApp.Workbooks.Add()
xlsApp.Visible = True
workSheet = xlsApp.Worksheets(1)
for i in range(300):
for j in range(20):
workSheet.Cells(i+1,j+1).Value = (i+10000)*j
```
|
2011/02/16
|
[
"https://Stackoverflow.com/questions/5014261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/619303/"
] |
A few suggestions:
**ScreenUpdating off, manual calculation**
Try the following:
```
xlsApp.ScreenUpdating = False
xlsApp.Calculation = -4135 # manual
try:
#
worksheet = ...
for i in range(...):
#
finally:
xlsApp.ScreenUpdating = True
xlsApp.Calculation = -4105 # automatic
```
**Assign several cells at once**
Using VBA, you can set a range's value to an array. Setting several values at once might be faster:
```
' VBA code
ActiveSheet.Range("A1:D1").Value = Array(1, 2, 3, 4)
```
I have never tried this using Python, I suggest you try something like:
```
worksheet.Range("A1:D1").Value = [1, 2, 3, 4]
```
**A different approach**
Consider using [openpyxl](https://bitbucket.org/ericgazoni/openpyxl/wiki/Home) or [xlwt](http://pypi.python.org/pypi/xlwt). Openpyxls lets you create `.xlsx` files without having Excel installed. Xlwt does the same thing for `.xls` files.
|
Note that you can set ranges via numeric adresses easily by using the following code:
```
cl1 = Sheet1.Cells(X1,Y1)
cl2 = Sheet1.Cells(X2,Y2)
Range = Sheet1.Range(cl1,cl2)
```
|
67,887,059
|
I am trying to create a python code that will read the subject of the most recent email in every folder of my outlook account.
I am able to open my email account and loop through every folder in it, however I cannot open my most recent email.
I looked at similar questions and tried using the `get.Last()` method. To use this method I understand that I have to sort my emails but I don't think that I am using the `.sort` method correctly because it is causing new errors.
```
Traceback (most recent call last):
File "c:/Users/myname/OneDrive/Documents/Computer Science/Email reader/project.py", line 24, in <module>
checksubj = messages.Subject
AttributeError: 'NoneType' object has no attribute 'Subject'
```
Here is my code:
```
import win32com.client
import win32com
import os
import sys
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
folder = outlook.Folders.Item(3)
print(folder.Name)
for subfolder in folder.Folders:
print(subfolder.Name)
messages = subfolder.Items
messages.sort
messages = messages.GetLast()
checksubj = messages.Subject
checksend = messages.Sender
if "Success" in checksubj:
print(str(checksend)+" Success")
elif "Failure" in checksubj:
print(str(checksend)+" Failure")
```
|
2021/06/08
|
[
"https://Stackoverflow.com/questions/67887059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16163886/"
] |
`Workbooks.Open` does have a `notify` parameter to indicate to wait until the file can be opened for read/write. It presents an interface to the user, so if your application is unattended, that probably isn't a good solution. In that case, I would set up a timer to retry after a short time period. The `Thread.Sleep` solution you mentioned is probably implementing something like that.
---
The documentation I could find about `Workbooks.Open` doesn't indicate what happens on error, e.g. if exceptions are generated or `null` is returned, so to be most compatible with your existing code, I went with generating exceptions and chose `FileLoadException` as a likely one to be thrown if the file can't be opened for write operations. You'll need to test and see what happens.
It might also be that `Workbooks.Open` returns `null` on failure, in which case you might need to check an error code to see if it's because the file is in read-only mode vs. file doesn't exist. You don't want to retry if the file doesn't exist.
```
using System;
using System.Threading;
private void writeExcel()
{
Excel.Application excelApp = null;
Excel.Workbook excelBook = null;
bool retry = false;
try
{
excelApp = new Excel.Application();
excelBook = excelApp.Workbooks.Open(@"C:\Users\ed0510\Desktop\SomeExcel.xlsx", ReadOnly: false, Password: "123");
Excel.Worksheet workSheet = excelBook.Worksheets["SomeWorkSheet"];
workSheet.Cells[1, 1].Value = "Something";
}
catch (FileLoadException ex)
{
// TODO: output exception details to error log
Log(ex);
// Indicate to retry
retry = true;
}
finally
{
if (excelApp != null)
{
if (excelBook != null)
{
excelBook.Close(true);
}
excelApp.Quit();
}
}
// Failed and need to retry?
if (retry)
{
// Wait a minute
Thread.Sleep(60 * 1000);
// Retry
writeExcel();
}
}
```
|
For anyone struggling with this problem in the future, I later came across scenarios when the accepted answer didn't quite work how I wanted it to. Here is what I came up with:
```
using System;
using System.Threading;
private void writeExcel()
{
string path = @"C:\Users\ed0510\Desktop\SomeExcel.xlsx";
if (IsExcelOpen(path))
{
throw new ExcelFileIsOpen();
}
Excel.Application excelApp = null;
Excel.Workbook excelBook = null;
bool retry = false;
try
{
excelApp = new Excel.Application();
excelBook = excelApp.Workbooks.Open(@"C:\Users\ed0510\Desktop\SomeExcel.xlsx", ReadOnly: false, Password: "123");
Excel.Worksheet workSheet = excelBook.Worksheets["SomeWorkSheet"];
workSheet.Cells[1, 1].Value = "Something";
}
catch
{
++numOfRetries;
if (numOfRetries <= maxNumOfRetries)
{
retry = true;
}
else
{
numOfRetries = 0;
saveFailed = true;
}
}
finally
{
if (excelApp != null)
{
if (excelBook != null)
{
excelBook.Close(true);
}
excelApp.Quit();
}
if (retry)
{
Thread.Sleep(5 * 1000);
retry = false;
SavingIntoExcelHDT();
}
}
```
As you can see, first I check if the excel is open, as the `FileLoadException` didn't always work how I wanted it. To check whether the excel is open, I use this method:
```
private bool IsExcelOpen(string path)
{
FileStream fs = null;
try
{
fs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.None);
return false;
}
catch (IOException)
{
return true;
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
```
I'm not sure this is the best way to do this, but it works perfectly for me.
|
196,930
|
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff current OS is Vista:
```
>>> isWindowsVista()
True
```
|
2008/10/13
|
[
"https://Stackoverflow.com/questions/196930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745/"
] |
Python has the lovely 'platform' module to help you out.
```
>>> import platform
>>> platform.win32_ver()
('XP', '5.1.2600', 'SP2', 'Multiprocessor Free')
>>> platform.system()
'Windows'
>>> platform.version()
'5.1.2600'
>>> platform.release()
'XP'
```
NOTE: As mentioned in the comments proper values may not be returned when using older versions of python.
|
The simplest solution I found is this one:
```
import sys
def isWindowsVista():
'''Return True iff current OS is Windows Vista.'''
if sys.platform != "win32":
return False
import win32api
VER_NT_WORKSTATION = 1
version = win32api.GetVersionEx(1)
if not version or len(version) < 9:
return False
return ((version[0] == 6) and
(version[1] == 0) and
(version[8] == VER_NT_WORKSTATION))
```
|
196,930
|
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff current OS is Vista:
```
>>> isWindowsVista()
True
```
|
2008/10/13
|
[
"https://Stackoverflow.com/questions/196930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745/"
] |
The simplest solution I found is this one:
```
import sys
def isWindowsVista():
'''Return True iff current OS is Windows Vista.'''
if sys.platform != "win32":
return False
import win32api
VER_NT_WORKSTATION = 1
version = win32api.GetVersionEx(1)
if not version or len(version) < 9:
return False
return ((version[0] == 6) and
(version[1] == 0) and
(version[8] == VER_NT_WORKSTATION))
```
|
An idea from <http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html> might help, which can basically answer your question:
```
win_version = {4: "NT", 5: "2K", 6: "XP"}[os.sys.getwindowsversion()[0]]
print "win_version=", win_version
```
|
196,930
|
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff current OS is Vista:
```
>>> isWindowsVista()
True
```
|
2008/10/13
|
[
"https://Stackoverflow.com/questions/196930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745/"
] |
The simplest solution I found is this one:
```
import sys
def isWindowsVista():
'''Return True iff current OS is Windows Vista.'''
if sys.platform != "win32":
return False
import win32api
VER_NT_WORKSTATION = 1
version = win32api.GetVersionEx(1)
if not version or len(version) < 9:
return False
return ((version[0] == 6) and
(version[1] == 0) and
(version[8] == VER_NT_WORKSTATION))
```
|
```
import platform
if platform.release() == "Vista":
# Do something.
```
or
```
import platform
if "Vista" in platform.release():
# Do something.
```
|
196,930
|
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff current OS is Vista:
```
>>> isWindowsVista()
True
```
|
2008/10/13
|
[
"https://Stackoverflow.com/questions/196930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745/"
] |
Python has the lovely 'platform' module to help you out.
```
>>> import platform
>>> platform.win32_ver()
('XP', '5.1.2600', 'SP2', 'Multiprocessor Free')
>>> platform.system()
'Windows'
>>> platform.version()
'5.1.2600'
>>> platform.release()
'XP'
```
NOTE: As mentioned in the comments proper values may not be returned when using older versions of python.
|
The solution used in Twisted, which doesn't need pywin32:
```
def isVista():
if getattr(sys, "getwindowsversion", None) is not None:
return sys.getwindowsversion()[0] == 6
else:
return False
```
Note that it will also match Windows Server 2008.
|
196,930
|
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff current OS is Vista:
```
>>> isWindowsVista()
True
```
|
2008/10/13
|
[
"https://Stackoverflow.com/questions/196930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745/"
] |
The solution used in Twisted, which doesn't need pywin32:
```
def isVista():
if getattr(sys, "getwindowsversion", None) is not None:
return sys.getwindowsversion()[0] == 6
else:
return False
```
Note that it will also match Windows Server 2008.
|
An idea from <http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html> might help, which can basically answer your question:
```
win_version = {4: "NT", 5: "2K", 6: "XP"}[os.sys.getwindowsversion()[0]]
print "win_version=", win_version
```
|
196,930
|
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff current OS is Vista:
```
>>> isWindowsVista()
True
```
|
2008/10/13
|
[
"https://Stackoverflow.com/questions/196930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745/"
] |
The solution used in Twisted, which doesn't need pywin32:
```
def isVista():
if getattr(sys, "getwindowsversion", None) is not None:
return sys.getwindowsversion()[0] == 6
else:
return False
```
Note that it will also match Windows Server 2008.
|
```
import platform
if platform.release() == "Vista":
# Do something.
```
or
```
import platform
if "Vista" in platform.release():
# Do something.
```
|
196,930
|
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff current OS is Vista:
```
>>> isWindowsVista()
True
```
|
2008/10/13
|
[
"https://Stackoverflow.com/questions/196930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745/"
] |
Python has the lovely 'platform' module to help you out.
```
>>> import platform
>>> platform.win32_ver()
('XP', '5.1.2600', 'SP2', 'Multiprocessor Free')
>>> platform.system()
'Windows'
>>> platform.version()
'5.1.2600'
>>> platform.release()
'XP'
```
NOTE: As mentioned in the comments proper values may not be returned when using older versions of python.
|
An idea from <http://www.brunningonline.net/simon/blog/archives/winGuiAuto.py.html> might help, which can basically answer your question:
```
win_version = {4: "NT", 5: "2K", 6: "XP"}[os.sys.getwindowsversion()[0]]
print "win_version=", win_version
```
|
196,930
|
How, in the simplest possible way, distinguish between Windows XP and Windows Vista, using Python and [pywin32](http://python.net/crew/mhammond/win32/Downloads.html) or [wxPython](http://www.wxpython.org/)?
Essentially, I need a function that called will return True iff current OS is Vista:
```
>>> isWindowsVista()
True
```
|
2008/10/13
|
[
"https://Stackoverflow.com/questions/196930",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18745/"
] |
Python has the lovely 'platform' module to help you out.
```
>>> import platform
>>> platform.win32_ver()
('XP', '5.1.2600', 'SP2', 'Multiprocessor Free')
>>> platform.system()
'Windows'
>>> platform.version()
'5.1.2600'
>>> platform.release()
'XP'
```
NOTE: As mentioned in the comments proper values may not be returned when using older versions of python.
|
```
import platform
if platform.release() == "Vista":
# Do something.
```
or
```
import platform
if "Vista" in platform.release():
# Do something.
```
|
63,621,597
|
I have a pandas dataframe where I need to conditionally update the value based on the first two letters. The pattern is simple and the code below works, but it doesn't feel pythonic. I need to extend this to other letters (at least 11-19/A-J) and, while I could just add additional rows, I'd really like to do this the right way. Existing code below
```
df['REFERENCE_ID'] = df['PRECERT_ID'].astype(str)
df.loc[df['REFERENCE_ID'].str.startswith('11'), 'REFERENCE_ID'] = 'A' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('12'), 'REFERENCE_ID'] = 'B' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('13'), 'REFERENCE_ID'] = 'C' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('14'), 'REFERENCE_ID'] = 'D' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('15'), 'REFERENCE_ID'] = 'E' + df['PRECERT_ID'].str[-7:]
```
I thought I might be able to use a list of letters, like
```
letters = list(string.ascii_uppercase)
```
but I'm new to dataframes (and python in general) and can't figure out the syntax to get the dataframe equivalent of
```
letters = list(string.ascii_uppercase)
text = '1523456789'
first = int(text[:2])
text = letters[first-11] + text[-7:]
```
I wasn't able to find something addressing this, but would be grateful for any help or a link to a similar question if it exists. Thank you.
|
2020/08/27
|
[
"https://Stackoverflow.com/questions/63621597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12140123/"
] |
As already noticed, the sponsored links are simply not at their position before some mouse event occurs. Once the mouse event occurs, the elements are added to the DOM, supposedly this is how Facebook avoids people crawling it too easily.
So, if you have a quest to find the sponsored links, then you will need to do the following
* find out what is the exact event which results in the links being added
* conduct experiments until you find out how you can programmatically generate that event
* implement a crawling algorithm that does some scrolling on the wall for a long while and then induces the given event. At that point you might get many sponsored links
Note: sponsored links are paid by companies and they would not be very happy if their ad slots are being used up by uninterested bots.
|
The approach I took to solve this issue is as follows:
```
// using an IIFE ("Immediately-Invoked Function Expression"):
(function() {
'use strict';
// using Arrow function syntax to define the callback function
// supplied to the (later-created) mutation observer, with
// two arguments (supplied automatically by that mutation
// observer), the first 'mutationList' is an Array of
// MutationRecord Objects that list the changes that were
// observed, and the second is the observer that observed
// the change:
const nodeRemoval = (mutationList, observer) => {
// here we use Array.prototype.forEach() to iterate over the
// Array of MutationRecord Objects, using an Arrow function
// in which we refer to the current MutationRecord of the
// Array over which we're iterating as 'mutation':
mutationList.forEach( (mutation) => {
// if the mutation.addedNodes property exists and
// also has a non-falsy length (zero is falsey, numbers
// above zero are truthy and negative numbers - while truthy -
// seem invalid in the length property):
if (mutation.addedNodes && mutation.addedNodes.length) {
// here we retrieve a list of nodes that have the
// "aria-label" attribute-value equal to 'Advertiser link':
mutation.target.querySelectorAll('[aria-label="Advertiser link"]')
// we use NodeList.prototype.forEach() to iterate over
// the returned list of nodes (if any) and use (another)
// Arrow function:
.forEach(
// here we pass a reference to the current Node of the
// NodeList we're iterating over, and use
// ChildNode.remove() to remove each of the nodes:
(adLink) => adLink.remove() );
}
});
},
// here we retrieve the <body> element (since I can't find
// any element with a predictable class or ID that will
// consistently exist as an ancestor of the ad links):
targetNode = document.querySelector('body'),
// we define the types of changes we're looking for:
options = {
// we're looking for changes amongst the
// element's descendants:
childList: true,
// we're not looking for attribute-changes:
attributes: false,
(if this is false, or absent, we look only to
changes/mutations on the target element itself):
subtree: true
},
// here we create a new MutationObserver, and supply
// the name of the callback function:
observer = new MutationObserver(nodeRemoval);
// here we specify what the created MutationObserver
// should observe, supplying the targetNode (<body>)
// and the defined options:
observer.observe(targetNode, options);
})();
```
I realise that in your question you're looking for elements that match a different attribute and attribute-value (`document.querySelector('a[href*="/ads/about"]')`) but as that attribute-value wouldn't match my own situation I couldn't use it in my code, but it should be as simple as replacing:
```
mutation.target.querySelectorAll('[aria-label="Advertiser link"]')
```
With:
```
mutation.target.querySelector('a[href*="/ads/about"]')
```
Though it's worth noting that `querySelector()` will return only the first node that matches the selector, or `null`; so you may need to incorporate some checks into your code.
While there may look to be quite a bit of code, above, uncommented this becomes merely:
```
(function() {
'use strict';
const nodeRemoval = (mutationList, observer) => {
mutationList.forEach( (mutation) => {
if (mutation.addedNodes && mutation.addedNodes.length) {
mutation.target.querySelectorAll('[aria-label="Advertiser link"]').forEach( (adLink) => adLink.remove() );
}
});
},
targetNode = document.querySelector('body'),
options = {
childList: true,
attributes: false,
subtree: true
},
observer = new MutationObserver(nodeRemoval);
observer.observe(targetNode, options);
})();
```
References:
* [`Array.prototype.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach).
* [Arrow Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
* [`childNode.remove()`](https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove).
* [`MutationObserver()` Interface](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver).
* [`NodeList.prototype.forEach()`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach).
|
63,621,597
|
I have a pandas dataframe where I need to conditionally update the value based on the first two letters. The pattern is simple and the code below works, but it doesn't feel pythonic. I need to extend this to other letters (at least 11-19/A-J) and, while I could just add additional rows, I'd really like to do this the right way. Existing code below
```
df['REFERENCE_ID'] = df['PRECERT_ID'].astype(str)
df.loc[df['REFERENCE_ID'].str.startswith('11'), 'REFERENCE_ID'] = 'A' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('12'), 'REFERENCE_ID'] = 'B' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('13'), 'REFERENCE_ID'] = 'C' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('14'), 'REFERENCE_ID'] = 'D' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('15'), 'REFERENCE_ID'] = 'E' + df['PRECERT_ID'].str[-7:]
```
I thought I might be able to use a list of letters, like
```
letters = list(string.ascii_uppercase)
```
but I'm new to dataframes (and python in general) and can't figure out the syntax to get the dataframe equivalent of
```
letters = list(string.ascii_uppercase)
text = '1523456789'
first = int(text[:2])
text = letters[first-11] + text[-7:]
```
I wasn't able to find something addressing this, but would be grateful for any help or a link to a similar question if it exists. Thank you.
|
2020/08/27
|
[
"https://Stackoverflow.com/questions/63621597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12140123/"
] |
As already noticed, the sponsored links are simply not at their position before some mouse event occurs. Once the mouse event occurs, the elements are added to the DOM, supposedly this is how Facebook avoids people crawling it too easily.
So, if you have a quest to find the sponsored links, then you will need to do the following
* find out what is the exact event which results in the links being added
* conduct experiments until you find out how you can programmatically generate that event
* implement a crawling algorithm that does some scrolling on the wall for a long while and then induces the given event. At that point you might get many sponsored links
Note: sponsored links are paid by companies and they would not be very happy if their ad slots are being used up by uninterested bots.
|
I ran into the same issue on chrome. If it helps anyone, I solved it by accessing the frame by
```
window.frames["myframeID"].document.getElementById("myElementID")
```
|
4,936,594
|
I'm writing a chat program in Python that needs to connect to a server before user input from sys.stdin is accepted. If a connection cannot be made then the program exits.
Running this from the shell, if a connection fails and input was sent while attempting to connect, the input is echoed to the shell after the program exits:
```
jtink@gab-dec:~$ python chat.py
attempting to connect...
Hey there! # This is user input
How are you? # This is more user input
connection failed
jtink@gab-dec:~$ Hey there!
Hey there!: command not found
jtink@gab-dev:~$ How are you?
How are you?: command not found
jtink@gab-dev:~$
```
Is there a way to tell if there is input left on sys.stdin, so that I can read it before the chat program exits?
I have read [this similar question](https://stackoverflow.com/questions/699390/whats-the-best-way-to-tell-if-a-python-program-has-anything-to-read-from-stdin), but the answers only describe how to tell if input is being piped to a python program, not how to tell if there is input.
|
2011/02/08
|
[
"https://Stackoverflow.com/questions/4936594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396241/"
] |
Well,
You should do something like that (pseudo-code):
1 - start a transaction
2 - post master record
3 - get the id inserted on master
4 - pass the master id to detail dataset
5 - post detail record
6 - If it worked, commit transaction. Otherwise, rollback transaction.
|
Just an side note: CTP of the new SQL Server codename 'Denali' will bring the feature of SEQUENCES, working much near of whar firebird generator works. So this task will become MUCH easier:
When you get the command from gui to start an insert, get an ID from sequence
Use it to fill the PK field of master record
Post master record
While you have detail records to insert
Fill detail(s) record
Post detail record
Commit transaction
Very niiiice...
|
62,673,374
|
i'm pretty new to python but i know how to use most of the things in it, included random.choice. I want to choose a random file name from 2 files [list](https://i.stack.imgur.com/zeMzN.jpg).
To do so, i'm using this line of code:
```
minio = Minio('myip',
access_key='mykey',
secret_key='mykey',
)
images = minio.list_objects('mybucket', recursive=True)
for img2 in images:
names = img2.object_name
print(random.choice([names]))
```
Everytime i try to run it, it prints always the same file's name *(c81d9307-7666-447d-bcfb-2c13a40de5ca.png)*
I tried to put the "print" function in the "for" block, but it prints out both of the files' names
|
2020/07/01
|
[
"https://Stackoverflow.com/questions/62673374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13834756/"
] |
You are setting the variable `names` to one specific instsance of images right now. That means it is only a single value. Try adding them to an array or similar instead.
For example:
```
names = [img2.object_name for img2 in images]
print(random.choice(names))
```
|
```
minio = Minio('myip',
access_key='mykey',
secret_key='mykey',
)
images = minio.list_objects('mybucket', recursive=True)
names = []
for img2 in images:
names.append(img2.object_name)
print(random.choice([names]))
```
Try this, the problem may that your names was not list varible
|
62,673,374
|
i'm pretty new to python but i know how to use most of the things in it, included random.choice. I want to choose a random file name from 2 files [list](https://i.stack.imgur.com/zeMzN.jpg).
To do so, i'm using this line of code:
```
minio = Minio('myip',
access_key='mykey',
secret_key='mykey',
)
images = minio.list_objects('mybucket', recursive=True)
for img2 in images:
names = img2.object_name
print(random.choice([names]))
```
Everytime i try to run it, it prints always the same file's name *(c81d9307-7666-447d-bcfb-2c13a40de5ca.png)*
I tried to put the "print" function in the "for" block, but it prints out both of the files' names
|
2020/07/01
|
[
"https://Stackoverflow.com/questions/62673374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13834756/"
] |
You are setting the variable `names` to one specific instsance of images right now. That means it is only a single value. Try adding them to an array or similar instead.
For example:
```
names = [img2.object_name for img2 in images]
print(random.choice(names))
```
|
If you want to choose one of the file names, try this :
```
minio = Minio('myip',
access_key='mykey',
secret_key='mykey',
)
images = minio.list_objects('mybucket', recursive=True)
names = []
for img2 in images:
names.append(img2.object_name)
print(random.choice(names))
```
The first code tries to randomly select a value from the array, `[names]`, but this only contain a single value, the value of the `names` variable after the last iteration of the for loop. Instead of doing that, create an array, `names` and append the values of `img2.object_name` from each iteration of the for loop to this array. And use this array to get the random name.
|
62,673,374
|
i'm pretty new to python but i know how to use most of the things in it, included random.choice. I want to choose a random file name from 2 files [list](https://i.stack.imgur.com/zeMzN.jpg).
To do so, i'm using this line of code:
```
minio = Minio('myip',
access_key='mykey',
secret_key='mykey',
)
images = minio.list_objects('mybucket', recursive=True)
for img2 in images:
names = img2.object_name
print(random.choice([names]))
```
Everytime i try to run it, it prints always the same file's name *(c81d9307-7666-447d-bcfb-2c13a40de5ca.png)*
I tried to put the "print" function in the "for" block, but it prints out both of the files' names
|
2020/07/01
|
[
"https://Stackoverflow.com/questions/62673374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13834756/"
] |
You are setting the variable `names` to one specific instsance of images right now. That means it is only a single value. Try adding them to an array or similar instead.
For example:
```
names = [img2.object_name for img2 in images]
print(random.choice(names))
```
|
Your `names` is just a simple variable that contains the most recently seen image name, rather than a list full of them.
The very last line of your script works as the one below:
```
value = 2
print(random.choice([value]))
```
which always prints 2. To get what you want, you need a list of all images. Here is your code with a simple fix:
```
names = []
for img2 in images:
names.append(img2.object_name)
print(random.choice(names))
```
These code can be made considerably shorter with [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions):
```
names = [img2.object_name for img2 in images]
print(random.choice([names]))
```
|
15,643,094
|
I'm a programming novice and only rarely use python so please bear with me as I try to explain what I am trying to do :)
I have the following XML:
```
<?xml version = "1.0" encoding = "utf-8"?>
<Patients>
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>20</SWOL28>
<TEN28>20</TEN28>
</Joints>
</DAS>
<VisitDate>2010-02-17</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>10</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>15</SWOL28>
<TEN28>20</TEN28>
</Joints>
</DAS>
<VisitDate>2010-02-10</VisitDate>
</Visit>
</Visits>
</Patient>
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>34</SWOL28>
<TEN28>0</TEN28>
</Joints>
</DAS>
<VisitDate>2010-08-17</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>10</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28></SWOL28>
<TEN28>2</TEN28>
</Joints>
</DAS>
<VisitDate>2010-07-10</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>9</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>56</SWOL28>
<TEN28>6</TEN28>
</Joints>
</DAS>
<VisitDate>2009-07-10</VisitDate>
</Visit>
</Visits>
</Patient>
</Patients>
```
All I want to do here is update certain 'SWOL28' values if they match the patientCode and VisitDate that I have stored in a text file. As I understand, elementtree does not include a parent reference, as if it did, I could just use findall() from the root and work backwards from there. As it stands here is my psuedocode:
1. For each line in the text file:
2. Put Visit\_Date Patient\_Code New\_SWOL28 into variables
3. For each patient element:
4. If patientCode = Patient\_Code
5. For each Visit element:
6. If VisitDate = Visit\_Date
7. If SWOL28 element exists for this visit
8. Update SWOL28 to New\_SWOL28
But I am stuck at step number 5. How do I get a list of visits to iterated through? Apologies if this is a very dumb question but I have searched high and low for an answer I assure you! I have stripped down my code to the bare example of the part I need to fix below:
```
import xml.etree.ElementTree as ET
tree = ET.parse('DB3.xml')
root = tree.getroot()
for child in root: # THIS GETS ME ALL THE PATIENT ATTRIBUTES
print child.tag
for x in child/Visit: # THIS IS WHAT I CANNOT FIND THE CORRECT SYNTAX FOR
# I WOULD THEN PERFORM STEPS 6, 7 AND 8 HERE
```
I would be deeply appreciative of any ideas any of you may have on this. I am not a programming natural that's for sure!
Thanks in advance,
Sarah
**Edit 1:**
On the advice of SVK below I tried the following:
```
import xml.etree.ElementTree as ET
tree = ET.parse('Untitled.xml')
root = tree.getroot()
for child in root:
print child.tag
child.find( "visits" )
for x in child.iter("visit"):
print x.tag, x.text
```
But the only output I get is:
Patient
Patient
and none of the lower tags. Any ideas?
|
2013/03/26
|
[
"https://Stackoverflow.com/questions/15643094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704003/"
] |
You can iterate over all the "visit" tags directly under an element "element" like this:
```
for x in element.iter("visit"):
```
You can find the first direct child of element matching a certain tag with:
```
element.find( "visits" )
```
It looks like you will first have to locate the "visits" element, which is the parent of "visit", and then iterate through its "visit" children. Putting those together you'd have something like this:
```
for patient_element in root:
print patient_element.tag
visits_element = patient_element.find( "visits" )
for visit_element in visits_element.iter("visit"):
print visit_element.tag, visit_element.text
# ... further processing of each visit element here
```
In general look at the section "Finding interesting elements" in the documentation for xml.etree.ElementTree: <http://docs.python.org/2/library/xml.etree.elementtree.html#finding-interesting-elements>
|
You could use a CssSelector to get the nodes you want from the Patient element:
```
from lxml.cssselect import CSSSelector
visitSelector = CSSSelector('Visit')
visits = visitSelector(child)
```
you can do the same to get the patientCode Tag and the SWOL28 tag
then you can access and modifiy the text of the elements using `element.text`
|
15,643,094
|
I'm a programming novice and only rarely use python so please bear with me as I try to explain what I am trying to do :)
I have the following XML:
```
<?xml version = "1.0" encoding = "utf-8"?>
<Patients>
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>20</SWOL28>
<TEN28>20</TEN28>
</Joints>
</DAS>
<VisitDate>2010-02-17</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>10</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>15</SWOL28>
<TEN28>20</TEN28>
</Joints>
</DAS>
<VisitDate>2010-02-10</VisitDate>
</Visit>
</Visits>
</Patient>
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>34</SWOL28>
<TEN28>0</TEN28>
</Joints>
</DAS>
<VisitDate>2010-08-17</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>10</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28></SWOL28>
<TEN28>2</TEN28>
</Joints>
</DAS>
<VisitDate>2010-07-10</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>9</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>56</SWOL28>
<TEN28>6</TEN28>
</Joints>
</DAS>
<VisitDate>2009-07-10</VisitDate>
</Visit>
</Visits>
</Patient>
</Patients>
```
All I want to do here is update certain 'SWOL28' values if they match the patientCode and VisitDate that I have stored in a text file. As I understand, elementtree does not include a parent reference, as if it did, I could just use findall() from the root and work backwards from there. As it stands here is my psuedocode:
1. For each line in the text file:
2. Put Visit\_Date Patient\_Code New\_SWOL28 into variables
3. For each patient element:
4. If patientCode = Patient\_Code
5. For each Visit element:
6. If VisitDate = Visit\_Date
7. If SWOL28 element exists for this visit
8. Update SWOL28 to New\_SWOL28
But I am stuck at step number 5. How do I get a list of visits to iterated through? Apologies if this is a very dumb question but I have searched high and low for an answer I assure you! I have stripped down my code to the bare example of the part I need to fix below:
```
import xml.etree.ElementTree as ET
tree = ET.parse('DB3.xml')
root = tree.getroot()
for child in root: # THIS GETS ME ALL THE PATIENT ATTRIBUTES
print child.tag
for x in child/Visit: # THIS IS WHAT I CANNOT FIND THE CORRECT SYNTAX FOR
# I WOULD THEN PERFORM STEPS 6, 7 AND 8 HERE
```
I would be deeply appreciative of any ideas any of you may have on this. I am not a programming natural that's for sure!
Thanks in advance,
Sarah
**Edit 1:**
On the advice of SVK below I tried the following:
```
import xml.etree.ElementTree as ET
tree = ET.parse('Untitled.xml')
root = tree.getroot()
for child in root:
print child.tag
child.find( "visits" )
for x in child.iter("visit"):
print x.tag, x.text
```
But the only output I get is:
Patient
Patient
and none of the lower tags. Any ideas?
|
2013/03/26
|
[
"https://Stackoverflow.com/questions/15643094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704003/"
] |
This is untested by it should be fairly close to what you want.
```
for patient in root:
patient_code = patient.find('PatientCharacteristics').find('patientCode')
if patient_code.text == code:
for visit in patient.find('Visits'):
visit_date = visit.find('VisitDate')
if visit_date.text == date:
swol28 = visit.find('DAS').find('Joints').find('SWOL28')
if swol28.text:
visit.find('DAS').find('Joints').set('SWOL28', new_swol28)
```
|
You can iterate over all the "visit" tags directly under an element "element" like this:
```
for x in element.iter("visit"):
```
You can find the first direct child of element matching a certain tag with:
```
element.find( "visits" )
```
It looks like you will first have to locate the "visits" element, which is the parent of "visit", and then iterate through its "visit" children. Putting those together you'd have something like this:
```
for patient_element in root:
print patient_element.tag
visits_element = patient_element.find( "visits" )
for visit_element in visits_element.iter("visit"):
print visit_element.tag, visit_element.text
# ... further processing of each visit element here
```
In general look at the section "Finding interesting elements" in the documentation for xml.etree.ElementTree: <http://docs.python.org/2/library/xml.etree.elementtree.html#finding-interesting-elements>
|
15,643,094
|
I'm a programming novice and only rarely use python so please bear with me as I try to explain what I am trying to do :)
I have the following XML:
```
<?xml version = "1.0" encoding = "utf-8"?>
<Patients>
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>20</SWOL28>
<TEN28>20</TEN28>
</Joints>
</DAS>
<VisitDate>2010-02-17</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>10</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>15</SWOL28>
<TEN28>20</TEN28>
</Joints>
</DAS>
<VisitDate>2010-02-10</VisitDate>
</Visit>
</Visits>
</Patient>
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>34</SWOL28>
<TEN28>0</TEN28>
</Joints>
</DAS>
<VisitDate>2010-08-17</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>10</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28></SWOL28>
<TEN28>2</TEN28>
</Joints>
</DAS>
<VisitDate>2010-07-10</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>9</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>56</SWOL28>
<TEN28>6</TEN28>
</Joints>
</DAS>
<VisitDate>2009-07-10</VisitDate>
</Visit>
</Visits>
</Patient>
</Patients>
```
All I want to do here is update certain 'SWOL28' values if they match the patientCode and VisitDate that I have stored in a text file. As I understand, elementtree does not include a parent reference, as if it did, I could just use findall() from the root and work backwards from there. As it stands here is my psuedocode:
1. For each line in the text file:
2. Put Visit\_Date Patient\_Code New\_SWOL28 into variables
3. For each patient element:
4. If patientCode = Patient\_Code
5. For each Visit element:
6. If VisitDate = Visit\_Date
7. If SWOL28 element exists for this visit
8. Update SWOL28 to New\_SWOL28
But I am stuck at step number 5. How do I get a list of visits to iterated through? Apologies if this is a very dumb question but I have searched high and low for an answer I assure you! I have stripped down my code to the bare example of the part I need to fix below:
```
import xml.etree.ElementTree as ET
tree = ET.parse('DB3.xml')
root = tree.getroot()
for child in root: # THIS GETS ME ALL THE PATIENT ATTRIBUTES
print child.tag
for x in child/Visit: # THIS IS WHAT I CANNOT FIND THE CORRECT SYNTAX FOR
# I WOULD THEN PERFORM STEPS 6, 7 AND 8 HERE
```
I would be deeply appreciative of any ideas any of you may have on this. I am not a programming natural that's for sure!
Thanks in advance,
Sarah
**Edit 1:**
On the advice of SVK below I tried the following:
```
import xml.etree.ElementTree as ET
tree = ET.parse('Untitled.xml')
root = tree.getroot()
for child in root:
print child.tag
child.find( "visits" )
for x in child.iter("visit"):
print x.tag, x.text
```
But the only output I get is:
Patient
Patient
and none of the lower tags. Any ideas?
|
2013/03/26
|
[
"https://Stackoverflow.com/questions/15643094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704003/"
] |
You can iterate over all the "visit" tags directly under an element "element" like this:
```
for x in element.iter("visit"):
```
You can find the first direct child of element matching a certain tag with:
```
element.find( "visits" )
```
It looks like you will first have to locate the "visits" element, which is the parent of "visit", and then iterate through its "visit" children. Putting those together you'd have something like this:
```
for patient_element in root:
print patient_element.tag
visits_element = patient_element.find( "visits" )
for visit_element in visits_element.iter("visit"):
print visit_element.tag, visit_element.text
# ... further processing of each visit element here
```
In general look at the section "Finding interesting elements" in the documentation for xml.etree.ElementTree: <http://docs.python.org/2/library/xml.etree.elementtree.html#finding-interesting-elements>
|
If you use `lxml.etree`, you can use `xpath` to find the elements you need to update.
E.g.
```
doc.xpath('Patient[PatientCharacteristics/patientCode=$patient]/Visits/Visit[VisitDate=$visit]',patient="3",visit="2009-07-10")
```
So
```
from lxml import etree
doc = etree.parse("DB3.xml")
changes = [
dict(patient='3',visit='2010-08-17',swol28="99"),
]
def update_doc(x,d):
for row in d:
for visit in x.xpath('Patient[PatientCharacteristics/patientCode=$patient]/Visits/Visit[VisitDate=$visit]',**row):
for swol28 in visit.xpath('DAS/Joints/SWOL28'):
swol28.text = row['swol28']
update_doc(doc,changes)
print etree.tostring(doc)
```
Should yield you something that contains:
```
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>99</SWOL28>
<TEN28>0</TEN28>
</Joints>
</DAS>
<VisitDate>2010-08-17</VisitDate>
</Visit>
</Visits>
</Patient>
```
|
15,643,094
|
I'm a programming novice and only rarely use python so please bear with me as I try to explain what I am trying to do :)
I have the following XML:
```
<?xml version = "1.0" encoding = "utf-8"?>
<Patients>
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>20</SWOL28>
<TEN28>20</TEN28>
</Joints>
</DAS>
<VisitDate>2010-02-17</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>10</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>15</SWOL28>
<TEN28>20</TEN28>
</Joints>
</DAS>
<VisitDate>2010-02-10</VisitDate>
</Visit>
</Visits>
</Patient>
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>34</SWOL28>
<TEN28>0</TEN28>
</Joints>
</DAS>
<VisitDate>2010-08-17</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>10</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28></SWOL28>
<TEN28>2</TEN28>
</Joints>
</DAS>
<VisitDate>2010-07-10</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>9</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>56</SWOL28>
<TEN28>6</TEN28>
</Joints>
</DAS>
<VisitDate>2009-07-10</VisitDate>
</Visit>
</Visits>
</Patient>
</Patients>
```
All I want to do here is update certain 'SWOL28' values if they match the patientCode and VisitDate that I have stored in a text file. As I understand, elementtree does not include a parent reference, as if it did, I could just use findall() from the root and work backwards from there. As it stands here is my psuedocode:
1. For each line in the text file:
2. Put Visit\_Date Patient\_Code New\_SWOL28 into variables
3. For each patient element:
4. If patientCode = Patient\_Code
5. For each Visit element:
6. If VisitDate = Visit\_Date
7. If SWOL28 element exists for this visit
8. Update SWOL28 to New\_SWOL28
But I am stuck at step number 5. How do I get a list of visits to iterated through? Apologies if this is a very dumb question but I have searched high and low for an answer I assure you! I have stripped down my code to the bare example of the part I need to fix below:
```
import xml.etree.ElementTree as ET
tree = ET.parse('DB3.xml')
root = tree.getroot()
for child in root: # THIS GETS ME ALL THE PATIENT ATTRIBUTES
print child.tag
for x in child/Visit: # THIS IS WHAT I CANNOT FIND THE CORRECT SYNTAX FOR
# I WOULD THEN PERFORM STEPS 6, 7 AND 8 HERE
```
I would be deeply appreciative of any ideas any of you may have on this. I am not a programming natural that's for sure!
Thanks in advance,
Sarah
**Edit 1:**
On the advice of SVK below I tried the following:
```
import xml.etree.ElementTree as ET
tree = ET.parse('Untitled.xml')
root = tree.getroot()
for child in root:
print child.tag
child.find( "visits" )
for x in child.iter("visit"):
print x.tag, x.text
```
But the only output I get is:
Patient
Patient
and none of the lower tags. Any ideas?
|
2013/03/26
|
[
"https://Stackoverflow.com/questions/15643094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704003/"
] |
This is untested by it should be fairly close to what you want.
```
for patient in root:
patient_code = patient.find('PatientCharacteristics').find('patientCode')
if patient_code.text == code:
for visit in patient.find('Visits'):
visit_date = visit.find('VisitDate')
if visit_date.text == date:
swol28 = visit.find('DAS').find('Joints').find('SWOL28')
if swol28.text:
visit.find('DAS').find('Joints').set('SWOL28', new_swol28)
```
|
You could use a CssSelector to get the nodes you want from the Patient element:
```
from lxml.cssselect import CSSSelector
visitSelector = CSSSelector('Visit')
visits = visitSelector(child)
```
you can do the same to get the patientCode Tag and the SWOL28 tag
then you can access and modifiy the text of the elements using `element.text`
|
15,643,094
|
I'm a programming novice and only rarely use python so please bear with me as I try to explain what I am trying to do :)
I have the following XML:
```
<?xml version = "1.0" encoding = "utf-8"?>
<Patients>
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>20</SWOL28>
<TEN28>20</TEN28>
</Joints>
</DAS>
<VisitDate>2010-02-17</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>10</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>15</SWOL28>
<TEN28>20</TEN28>
</Joints>
</DAS>
<VisitDate>2010-02-10</VisitDate>
</Visit>
</Visits>
</Patient>
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>34</SWOL28>
<TEN28>0</TEN28>
</Joints>
</DAS>
<VisitDate>2010-08-17</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>10</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28></SWOL28>
<TEN28>2</TEN28>
</Joints>
</DAS>
<VisitDate>2010-07-10</VisitDate>
</Visit>
<Visit>
<DAS>
<CRP>9</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>56</SWOL28>
<TEN28>6</TEN28>
</Joints>
</DAS>
<VisitDate>2009-07-10</VisitDate>
</Visit>
</Visits>
</Patient>
</Patients>
```
All I want to do here is update certain 'SWOL28' values if they match the patientCode and VisitDate that I have stored in a text file. As I understand, elementtree does not include a parent reference, as if it did, I could just use findall() from the root and work backwards from there. As it stands here is my psuedocode:
1. For each line in the text file:
2. Put Visit\_Date Patient\_Code New\_SWOL28 into variables
3. For each patient element:
4. If patientCode = Patient\_Code
5. For each Visit element:
6. If VisitDate = Visit\_Date
7. If SWOL28 element exists for this visit
8. Update SWOL28 to New\_SWOL28
But I am stuck at step number 5. How do I get a list of visits to iterated through? Apologies if this is a very dumb question but I have searched high and low for an answer I assure you! I have stripped down my code to the bare example of the part I need to fix below:
```
import xml.etree.ElementTree as ET
tree = ET.parse('DB3.xml')
root = tree.getroot()
for child in root: # THIS GETS ME ALL THE PATIENT ATTRIBUTES
print child.tag
for x in child/Visit: # THIS IS WHAT I CANNOT FIND THE CORRECT SYNTAX FOR
# I WOULD THEN PERFORM STEPS 6, 7 AND 8 HERE
```
I would be deeply appreciative of any ideas any of you may have on this. I am not a programming natural that's for sure!
Thanks in advance,
Sarah
**Edit 1:**
On the advice of SVK below I tried the following:
```
import xml.etree.ElementTree as ET
tree = ET.parse('Untitled.xml')
root = tree.getroot()
for child in root:
print child.tag
child.find( "visits" )
for x in child.iter("visit"):
print x.tag, x.text
```
But the only output I get is:
Patient
Patient
and none of the lower tags. Any ideas?
|
2013/03/26
|
[
"https://Stackoverflow.com/questions/15643094",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/704003/"
] |
This is untested by it should be fairly close to what you want.
```
for patient in root:
patient_code = patient.find('PatientCharacteristics').find('patientCode')
if patient_code.text == code:
for visit in patient.find('Visits'):
visit_date = visit.find('VisitDate')
if visit_date.text == date:
swol28 = visit.find('DAS').find('Joints').find('SWOL28')
if swol28.text:
visit.find('DAS').find('Joints').set('SWOL28', new_swol28)
```
|
If you use `lxml.etree`, you can use `xpath` to find the elements you need to update.
E.g.
```
doc.xpath('Patient[PatientCharacteristics/patientCode=$patient]/Visits/Visit[VisitDate=$visit]',patient="3",visit="2009-07-10")
```
So
```
from lxml import etree
doc = etree.parse("DB3.xml")
changes = [
dict(patient='3',visit='2010-08-17',swol28="99"),
]
def update_doc(x,d):
for row in d:
for visit in x.xpath('Patient[PatientCharacteristics/patientCode=$patient]/Visits/Visit[VisitDate=$visit]',**row):
for swol28 in visit.xpath('DAS/Joints/SWOL28'):
swol28.text = row['swol28']
update_doc(doc,changes)
print etree.tostring(doc)
```
Should yield you something that contains:
```
<Patient>
<PatientCharacteristics>
<patientCode>3</patientCode>
</PatientCharacteristics>
<Visits>
<Visit>
<DAS>
<CRP>14</CRP>
<ESR/>
<Joints>
<DAS_PROFILE>28/28</DAS_PROFILE>
<SWOL28>99</SWOL28>
<TEN28>0</TEN28>
</Joints>
</DAS>
<VisitDate>2010-08-17</VisitDate>
</Visit>
</Visits>
</Patient>
```
|
36,669,131
|
I matched 2 columns in a DataFrame and yield the result in Boolean value in a new 'bool' column.
First I wrote:
```
df_new = df[[7 for 32 in df if df 39 == 'False']]
```
But it didn't work.
Then I wrote only to match the columns
My code is
```
df['bool'] = (df.iloc[:, 7] == df.iloc[:, 32])
```
The above code matched the columns positioned at 7 and 32 and placed `bool` value at column 39. In this I want to slice the data and choose the rows with a false value.
[Data](http://i.stack.imgur.com/hB6gX.png)
I wrote:
```
df_filtered = df[df['bool'] == 'False']
```
But I got the Future error as
>
> [c:\python34\lib\site-packages\pandas\core\ops.py:714: FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison
> result = getattr(x, name)(y)](http://i.stack.imgur.com/3YnOh.png)
>
>
>
Not sure what wrong I am doing.
I've also tried
```
df[df[39] == 'False']
```
|
2016/04/16
|
[
"https://Stackoverflow.com/questions/36669131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4673147/"
] |
You can compare the columns directly:
```
df = pd.DataFrame({'a': [1, 2, 3], 'b': [1, 3, 2]})
df['Bool'] = df.a == df.b
>>> df
a b Bool
0 1 1 True
1 2 3 False
2 3 2 False
```
To filter for False values, use the negation flag, i.e. `~`:
```
>>> df[~df.Bool]
a b Bool
1 2 3 False
2 3 2 False
```
|
I don't know your situation, I get the "FutureWarning: in the future, boolean array-likes will be handled as a boolean array index" when I use those code as below:
```
>>> import numpy as np
>>> test=np.array([1,2,3])
>>> test3=test[[False,True,False]]
__main__:1: FutureWarning: in the future, boolean array-likes will be handled as a boolean array index
>>> test3=test[np.array([False,True,False])]
>>> test3
array([2])
>>>
```
I think these are some relations between the two "FutureWarning", I hope my situation can help you.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.