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-ubunt... | 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 ... | 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 wi... |
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-ubunt... | 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 dir... | 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 ... |
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-ubunt... | 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 dir... | 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 y... |
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-ubunt... | 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 dir... | 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 wi... |
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
... | 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 ... | 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 entr... |
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
... | 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
... | 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 entr... |
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
... | 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 ... | 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
... |
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 ... | 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... | 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 d... |
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 bo... |
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 bo... |
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: Co... | 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 go... | 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 pyt... | 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. Ot... | 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:
[]... | 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... |
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:
[]... | 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... |
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:
[]... | 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 fo... | 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... |
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:
[]... | 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:
[]... | 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:
[]... | 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 fo... |
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:
[]... | 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:
[]... | 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 fo... | 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:
[]... | 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 fo... | 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 ... | 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)
... | 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 = filepat... | 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)
... | 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 = filepat... | ### 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])
... |
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 ?
P... | 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 ?
P... | 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 ... | 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, ... | 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 ha... |
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 ... |
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.mo... |
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... |
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.mo... | 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 ... |
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... | 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 ... |
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... | 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 '6... |
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... | 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... | 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 '6... | 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... | 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 notebo... |
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", "Span... | 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",
... |
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... | 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 =... |
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... | 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 speci... | 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 =... |
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... | 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 correc... | 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 templa... |
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... | 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 speci... | 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 templa... |
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... | 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 speci... | 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`... |
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... | 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 correc... | 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... | 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 templa... |
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... | 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.f... | 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`... |
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... | 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.f... | 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 =... |
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... | 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 correc... | 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`... |
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 e... | 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 oth... | 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 globa... |
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 e... | 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 oth... | 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 objec... |
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 e... | 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 objec... | 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 globa... |
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 it... | 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', ... |
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 it... | 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` valu... | 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:
retur... | 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` valu... | 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:
retur... | ```
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` valu... | 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:
retur... | 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` valu... | 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` valu... | 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` valu... | 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 on... | 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 illustr... | 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 eac... | 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/bu... | 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 ar... |
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:... | 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:... | 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 ... |
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:... | 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:... | 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 ... |
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:... | 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 ... |
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... | 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 f... | 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 t... |
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 ... | 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 ther... | 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 i... | 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 ... |
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 ther... | 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 i... | 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... |
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 ther... | 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 ... | 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... |
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... | 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.
>
... | 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... | 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 = fr... | 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 ... |
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... | 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,
...... | 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 ... |
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 we... | 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 la... |
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 follow... | 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
de... | 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 differ... | 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 sev... | 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, ... |
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 differ... | 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 sev... | 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 u... | 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` so... | 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 (I... |
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()
T... | 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 retu... | 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:
... |
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()
T... | 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:
... | 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()
T... | 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:
... | ```
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()
T... | 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 retu... | 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()
T... | 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()
T... | 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()
T... | 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 retu... | 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()
T... | 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 retu... | ```
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 r... | 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 th... | 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... |
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 r... | 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 th... | 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 progr... | 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 ... |
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... | 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... |
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... | 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(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... | 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 ... |
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>
... | 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 t... | 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... |
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>
... | 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')
... | 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 t... |
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>
... | 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 t... | 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... |
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>
... | 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')
... | 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... |
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>
... | 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 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... |
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 ma... | 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 Fa... | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.