title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Extract all single {key:value} pairs from dictionary
38,957,159
<p>I have a dictionary which maps some keys to 1 or <strong>more</strong> values. </p> <p>In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?</p> <p>My dict looks something like this:</p> <pre><code>&gt;&gt;print dict {'key1':['value11',value12, ...], 'key2': ['value21'], 'key3':['value31', 'value32']} </code></pre> <p>So in the above example, I would expect my output to be <code>1</code></p>
0
2016-08-15T14:34:25Z
38,957,250
<p>Iterate through values in dictionary and count:</p> <pre><code>count = 0 for value in dic.values(): if len(value) == 1: count += 1 print count </code></pre>
0
2016-08-15T14:39:43Z
[ "python", "dictionary" ]
Extract all single {key:value} pairs from dictionary
38,957,159
<p>I have a dictionary which maps some keys to 1 or <strong>more</strong> values. </p> <p>In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?</p> <p>My dict looks something like this:</p> <pre><code>&gt;&gt;print dict {'key1':['value11',value12, ...], 'key2': ['value21'], 'key3':['value31', 'value32']} </code></pre> <p>So in the above example, I would expect my output to be <code>1</code></p>
0
2016-08-15T14:34:25Z
38,957,257
<p>You could just filter your dictionary out like this:</p> <pre><code>data = { 'key1': ['value11', 'value12'], 'key2': ['value21'], 'key3': ['value31', 'value32'] } result = filter(lambda (k, v): len(v) == 1, data.iteritems()) print result, "=&gt;", len(result) </code></pre>
0
2016-08-15T14:39:58Z
[ "python", "dictionary" ]
Extract all single {key:value} pairs from dictionary
38,957,159
<p>I have a dictionary which maps some keys to 1 or <strong>more</strong> values. </p> <p>In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?</p> <p>My dict looks something like this:</p> <pre><code>&gt;&gt;print dict {'key1':['value11',value12, ...], 'key2': ['value21'], 'key3':['value31', 'value32']} </code></pre> <p>So in the above example, I would expect my output to be <code>1</code></p>
0
2016-08-15T14:34:25Z
38,957,260
<p>You can use <a href="http://stackoverflow.com/questions/38957159/extract-all-single-keyvalue-pairs-from-dictionary/38957260#comment65268425_38957159">@MosesKoledoye's</a> solution for the short (and probably a tiny bit faster) solution, or this naive version:</p> <pre><code>print(len([value for value in d.values() if hasattr(value, '__len__') and len(value) == 1])) </code></pre>
1
2016-08-15T14:40:12Z
[ "python", "dictionary" ]
Extract all single {key:value} pairs from dictionary
38,957,159
<p>I have a dictionary which maps some keys to 1 or <strong>more</strong> values. </p> <p>In order to map to more than 1 value, I'm mapping each individual key to a list. How can I get the number of the single pairs? Is there a quick pythonic way to do this?</p> <p>My dict looks something like this:</p> <pre><code>&gt;&gt;print dict {'key1':['value11',value12, ...], 'key2': ['value21'], 'key3':['value31', 'value32']} </code></pre> <p>So in the above example, I would expect my output to be <code>1</code></p>
0
2016-08-15T14:34:25Z
38,957,270
<p>With <code>d</code> being the dictionary:</p> <pre><code>sum(len(v) == 1 for v in d.values()) </code></pre> <p>Or:</p> <pre><code>map(len, d.values()).count(1) </code></pre> <p>(The latter requires <code>list</code> around the <code>map</code> if you're using Python 3.)</p>
2
2016-08-15T14:40:53Z
[ "python", "dictionary" ]
How to predict new values using statsmodels.formula.api (python)
38,957,178
<p>I trained the logistic model using the following, from breast cancer data and ONLY using one feature 'mean_area'</p> <pre><code>from statsmodels.formula.api import logit logistic_model = logit('target ~ mean_area',breast) result = logistic_model.fit() </code></pre> <p>There is a built in predict method in the trained model. However that gives the predicted values of all the training samples. As follows</p> <pre><code>predictions = result.predict() </code></pre> <p>Suppose I want the prediction for a new value say 30 How do I used the trained model to out put the value? (rather than reading the coefficients and computing manually)</p>
0
2016-08-15T14:35:27Z
38,958,427
<p>You can provide new values to the <code>.predict()</code> model as illustrated in output #11 in this <a href="http://statsmodels.sourceforge.net/devel/examples/notebooks/generated/discrete_choice.html" rel="nofollow">notebook</a> from the docs for a single observation. You can provide multiple observations as <code>2d array</code>, for instance a <code>DataFrame</code> - <a href="http://statsmodels.sourceforge.net/0.6.0/generated/statsmodels.discrete.discrete_model.Logit.predict.html#statsmodels.discrete.discrete_model.Logit.predict" rel="nofollow">see docs</a>. </p> <p>Since you are using the formula API, your input needs to be in the form of a <code>pd.DataFrame</code> so that the column references are available. In your case, you could use something like <code>.predict(pd.DataFrame({'mean_area': [1,2,3]})</code>.</p> <p><code>statsmodels</code> <code>.predict()</code> uses the observations used for fitting only as default when no alternative is provided.</p>
0
2016-08-15T15:49:57Z
[ "python", "machine-learning", "scikit-learn", "logistic-regression", "statsmodels" ]
How to iterate over/manipulate a list of class objects in python (Node Crawl in a decentralized network simulation)
38,957,286
<p>Can anyone help me with the an iteration over a list of class objects?</p> <p>I want to setup a simulation of nodes interacting with each other in a decentralized network. Each node is created as an object in the class Node. Every node gets his name and a list of max three other nodes (also objects in sam class) he is connected to.</p> <p>for the simulation later on it is necessary that each node has three lists. l1 contains all nodes he is connected to l2 contains all nodes the nodes from l1 are connected to l3 contains all nodes the nodes from l2 are connected to</p> <p>I want to create l2 and l3 dynamically. My idea was since every node knows the nodes he is directly conected to I just have to fetch l1 from every node. So far I have this (although I don't like how l2 is created now since its static).</p> <pre><code>class Node: def __init__(self,nid,ports): self.id=nid self.port1=ports[0] self.port2=ports[1] self.port3=ports[2] self.l1=[self.port1,self.port2,self.port3] self.l2=[] self.l3=[] def node_crawl(self): self.l2=self.port1.l1+self.port2.l1+self.port3.l1 def show_node(self): print (" Node-id: ", self.id) print (" Net-Setup","\n","Port 1: ",self.port1,"\n","Port 2: ",self.port2,"\n","Port 3: ",self.port3) if __name__ == '__main__': node1=Node("node1",[node2,node3,node6]) node2=Node("node2",[node1,node3,node5]) node3=Node("node3",[node2,node4,node6]) node4=Node("node4",[node3,node5,node6]) node5=Node("node5",[node2,node4]) node6=Node("node6",[node3,node4,node1]) node1.node_crawl() </code></pre> <p>I thought maybe I can write a for loop to use every element from the preceeding list. </p> <pre><code>for i in self.l1: self.l2.append(self.l1[i].l1) </code></pre> <p>But that doesn't work. Python tells me that indices must be integers or slices. Any advice would be highly appreciated. Later I will have to clean the lists of double mentioned nodes any advice on that would be great too. Cheers</p>
1
2016-08-15T14:41:20Z
38,957,974
<p>Okay so thanks to wwii I found the answer</p> <pre><code> for i in self.l1: self.l2.extend(i.l1) for i in self.l2: self.l3.extend(i.l1) </code></pre> <p>nodes appearing double in the list can be eliminated with:</p> <pre><code>from collections import OrderedDict as odict self.l2=list(odict.fromkeys(self.l2)) self.l3=list(odict.fromkeys(self.l3)) </code></pre>
1
2016-08-15T15:19:31Z
[ "python", "list", "class", "loops", "object" ]
select certain files from directory
38,957,382
<p>In the same directory I have several files, some of them are sample measurements and others are references. They look like this:</p> <pre><code>blablabla_350.dat blablabla_351.dat blablabla_352.dat blablabla_353.dat ... blablabla_100.dat blablabla_101.dat blablabla_102.dat </code></pre> <p>The ones ending from 350 to 353 are my samples, the ones ending at 100, 101 and 102 are the references. The good thing is that samples and references are consecutives in numbers.</p> <p>I would like to separate them in two different lists, samples and references.</p> <p>One idea should be something like (not working yet): </p> <pre><code>import glob samples = [] references = [] ref = raw_input("Enter first reference name: ") num_refs = raw_input("How many references are? ") ref = sorted(glob.glob(ref+num_refs)) samples = sorted(glob.glob(*.dat)) not in references </code></pre> <p>So the reference list will take the first name specified and the subsequents (given by the number specified). All the rest will be samples. Any ideas how to put this in python?</p>
0
2016-08-15T14:46:39Z
38,957,527
<p>You can use <code>glob.glob</code> to get the list of all <code>*.dat</code> files then filter that list using a list comprehension with a conditional. In my solution I use a regular expression to extract the number from the filename as text. I then convert it to an integer and check if that integer lies between <code>ref_from</code> and <code>ref_to</code>. This works even if some of the reference files numbered between <code>ref_from</code> and <code>ref_to</code> are missing.</p> <p>The list of samples is obtained through a set operation: it is the result of removing the set of <code>references</code> from the set of <code>data_files</code>. We can do this since all every filename can be assumed to be unique.</p> <pre><code>import glob import re samples = [] references = [] ref_from = 350 ref_to = 353 def ref_filter(filename): return ref_from &lt;= int(re.search('_([0-9]+).dat', filename).group(1)) &lt;= ref_to data_files = sorted(glob.glob("*.dat")) references = [filename for filename in data_files if ref_filter(filename)] samples = list(set(data_files) - set(references)) print references print samples </code></pre> <p>Alternatively, if you know all samples between <code>ref_from</code> and <code>ref_to</code> are going to be present, you can get rid of the function <code>ref_filter</code> and replace</p> <pre><code>references = [filename for filename in data_files if ref_filter(filename)] </code></pre> <p>with</p> <pre><code>references = ['blablabla_' + str(n) + '.dat' for n in xrange(ref_from, ref_to + 1)] </code></pre>
2
2016-08-15T14:55:03Z
[ "python", "glob" ]
select certain files from directory
38,957,382
<p>In the same directory I have several files, some of them are sample measurements and others are references. They look like this:</p> <pre><code>blablabla_350.dat blablabla_351.dat blablabla_352.dat blablabla_353.dat ... blablabla_100.dat blablabla_101.dat blablabla_102.dat </code></pre> <p>The ones ending from 350 to 353 are my samples, the ones ending at 100, 101 and 102 are the references. The good thing is that samples and references are consecutives in numbers.</p> <p>I would like to separate them in two different lists, samples and references.</p> <p>One idea should be something like (not working yet): </p> <pre><code>import glob samples = [] references = [] ref = raw_input("Enter first reference name: ") num_refs = raw_input("How many references are? ") ref = sorted(glob.glob(ref+num_refs)) samples = sorted(glob.glob(*.dat)) not in references </code></pre> <p>So the reference list will take the first name specified and the subsequents (given by the number specified). All the rest will be samples. Any ideas how to put this in python?</p>
0
2016-08-15T14:46:39Z
38,957,579
<p>You can use <code>glob.glob('*.dat')</code> to get a list of all of the files and then slice that list according to your criteria. The slice will begin at the index of the first reference name, and be as large as the number of references.</p> <p>Extract that slice to get your references. Delete that slice to get your samples.</p> <pre><code>import glob samples = [] references = [] ref = raw_input("Enter first reference name: ") # blablabla_100.dat num_refs = int(raw_input("How many references are? ")) # 3 all_files = sorted(glob.glob('*.dat')) first_ref = all_files.index(ref) ref_files = all_files[first_ref:first_ref+num_refs] sample_files = all_files del sample_files[first_ref:first_ref+num_refs] del all_files print ref_files, sample_files </code></pre> <p>Result:</p> <pre><code>['blablabla_100.dat', 'blablabla_101.dat', 'blablabla_102.dat'] ['blablabla_350.dat', 'blablabla_351.dat', 'blablabla_352.dat', 'blablabla_353.dat'] </code></pre>
2
2016-08-15T14:57:49Z
[ "python", "glob" ]
select certain files from directory
38,957,382
<p>In the same directory I have several files, some of them are sample measurements and others are references. They look like this:</p> <pre><code>blablabla_350.dat blablabla_351.dat blablabla_352.dat blablabla_353.dat ... blablabla_100.dat blablabla_101.dat blablabla_102.dat </code></pre> <p>The ones ending from 350 to 353 are my samples, the ones ending at 100, 101 and 102 are the references. The good thing is that samples and references are consecutives in numbers.</p> <p>I would like to separate them in two different lists, samples and references.</p> <p>One idea should be something like (not working yet): </p> <pre><code>import glob samples = [] references = [] ref = raw_input("Enter first reference name: ") num_refs = raw_input("How many references are? ") ref = sorted(glob.glob(ref+num_refs)) samples = sorted(glob.glob(*.dat)) not in references </code></pre> <p>So the reference list will take the first name specified and the subsequents (given by the number specified). All the rest will be samples. Any ideas how to put this in python?</p>
0
2016-08-15T14:46:39Z
38,957,581
<p>try something like</p> <pre><code>import glob samples = [] references = [] ref = raw_input("Enter first reference name: ") num_refs = int(raw_input("How many references are? ")) for number in num_refs: refferences.append(ref+number) for filename in sorted(glob.glob('*.dat')): if filename not in refferences: samples.append(filename) </code></pre>
-1
2016-08-15T14:58:00Z
[ "python", "glob" ]
select certain files from directory
38,957,382
<p>In the same directory I have several files, some of them are sample measurements and others are references. They look like this:</p> <pre><code>blablabla_350.dat blablabla_351.dat blablabla_352.dat blablabla_353.dat ... blablabla_100.dat blablabla_101.dat blablabla_102.dat </code></pre> <p>The ones ending from 350 to 353 are my samples, the ones ending at 100, 101 and 102 are the references. The good thing is that samples and references are consecutives in numbers.</p> <p>I would like to separate them in two different lists, samples and references.</p> <p>One idea should be something like (not working yet): </p> <pre><code>import glob samples = [] references = [] ref = raw_input("Enter first reference name: ") num_refs = raw_input("How many references are? ") ref = sorted(glob.glob(ref+num_refs)) samples = sorted(glob.glob(*.dat)) not in references </code></pre> <p>So the reference list will take the first name specified and the subsequents (given by the number specified). All the rest will be samples. Any ideas how to put this in python?</p>
0
2016-08-15T14:46:39Z
38,957,642
<p>You can also do it without <code>glob</code> by using the <code>os</code> package:</p> <pre><code>import os, re files = os.listdir(r'C:\path\to\files') samples, references = [], [] for file in files: if re.search(r'blablabla_1\d{2}', file): references.append(file) elif re.serach(r'blablabla_3\d{2}', file): samples.append(file) else: print('{0} is neither sample nor reference'.format(file)) </code></pre>
0
2016-08-15T15:01:31Z
[ "python", "glob" ]
Hi, I just installed requests with pip but I can't import it
38,957,513
<p>For example my Code is: </p> <pre><code>import requests r = requests.get('https://www.python.org') r.status_code </code></pre> <p>And the Result is: </p> <pre><code>Traceback (most recent call last): File "C:\Users\Till\workspace\firstproject\Learning_python\Web_crawler.py", line 6, in &lt;module&gt; import requests File "C:\Python32\lib\site-packages\requests\__init__.py", line 64, in &lt;module&gt; from .models import Request, Response, PreparedRequest File "C:\Python32\lib\site-packages\requests\models.py", line 856 http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url) ^ SyntaxError: invalid Syntax </code></pre>
-2
2016-08-15T14:53:48Z
38,957,543
<p>Requests requires Python 3.3 or newer. It doesn't work on Python 3.2 as that version doesn't support the required <code>u'...'</code> compatibility syntax for string literals.</p> <p>From the <a href="http://docs.python-requests.org/en/master/#supported-features" rel="nofollow"><code>requests</code> documentation</a>:</p> <blockquote> <p>Requests officially supports Python 2.6–2.7 &amp; 3.3–3.5, and runs great on PyPy.</p> </blockquote> <p>Note that 3.2 is rather.. ancient. You really want to upgrade to a more recent Python 3 revision.</p>
8
2016-08-15T14:56:01Z
[ "python", "python-requests" ]
Hi, I just installed requests with pip but I can't import it
38,957,513
<p>For example my Code is: </p> <pre><code>import requests r = requests.get('https://www.python.org') r.status_code </code></pre> <p>And the Result is: </p> <pre><code>Traceback (most recent call last): File "C:\Users\Till\workspace\firstproject\Learning_python\Web_crawler.py", line 6, in &lt;module&gt; import requests File "C:\Python32\lib\site-packages\requests\__init__.py", line 64, in &lt;module&gt; from .models import Request, Response, PreparedRequest File "C:\Python32\lib\site-packages\requests\models.py", line 856 http_error_msg = u'%s Client Error: %s for url: %s' % (self.status_code, reason, self.url) ^ SyntaxError: invalid Syntax </code></pre>
-2
2016-08-15T14:53:48Z
38,957,635
<p>Well, as issue is that Requests require Python-3.3 or higher so you will need to upgrade your Python. I noticed you are on windows so follow this link to download the installer for latest stable Python-3.5.2 (<a href="https://www.python.org/ftp/python/3.5.2/python-3.5.2-webinstall.exe" rel="nofollow">https://www.python.org/ftp/python/3.5.2/python-3.5.2-webinstall.exe</a>).</p> <p>Also, look into using virtualenvs(<a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">https://virtualenv.pypa.io/en/stable/</a>). They are a great way to insulate the python packages you have installed and you can set it up using for different projects that may have different requirements.</p>
0
2016-08-15T15:01:00Z
[ "python", "python-requests" ]
memory efficient way to write an uncompressed file from a gzip file
38,957,623
<p>using Python 3.5</p> <p>I am uncompressing a gzip file, writing to another file. After looking into an out of memory problem, I find an example in the docs for the gzip module:</p> <pre><code>import gzip import shutil with open('/home/joe/file.txt', 'rb') as f_in: with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) </code></pre> <p>This does compression, and I want uncompression, so I take it that I can just reverse the pattern, giving </p> <pre><code>with open(unzipped_file, 'wb') as f_out, gzip.open(zipped_file, 'rb') as f_in: shutil.copyfileobj(f_in, f_out) </code></pre> <p>My question is, why did I get into memory trouble with the following:</p> <pre><code>with gzip.open(zipped_file, 'rb') as zin, open(unzipped_file, 'wb') as wout: wout.write(zin.read()) </code></pre> <p>Either I laid on the last straw, or I was naive in believing that the files would act like generators and stream the unzip process, taking very little memory. Should these two methods be equivalent?</p>
1
2016-08-15T15:00:12Z
38,957,865
<p>Here is the <code>shutil.copyfileObj</code> method.</p> <pre><code>def copyfileobj(fsrc, fdst, length=16*1024): """copy data from file-like object fsrc to file-like object fdst""" while 1: buf = fsrc.read(length) if not buf: break fdst.write(buf) </code></pre> <p>It reads the file in chunks of length of 16*1024. And when you are trying to reverse the process, you are not taking regard of the size of the file which will get read into memory and land you into memory problem.</p>
2
2016-08-15T15:13:02Z
[ "python", "python-3.x", "gzip", "generator", "shutil" ]
memory efficient way to write an uncompressed file from a gzip file
38,957,623
<p>using Python 3.5</p> <p>I am uncompressing a gzip file, writing to another file. After looking into an out of memory problem, I find an example in the docs for the gzip module:</p> <pre><code>import gzip import shutil with open('/home/joe/file.txt', 'rb') as f_in: with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out: shutil.copyfileobj(f_in, f_out) </code></pre> <p>This does compression, and I want uncompression, so I take it that I can just reverse the pattern, giving </p> <pre><code>with open(unzipped_file, 'wb') as f_out, gzip.open(zipped_file, 'rb') as f_in: shutil.copyfileobj(f_in, f_out) </code></pre> <p>My question is, why did I get into memory trouble with the following:</p> <pre><code>with gzip.open(zipped_file, 'rb') as zin, open(unzipped_file, 'wb') as wout: wout.write(zin.read()) </code></pre> <p>Either I laid on the last straw, or I was naive in believing that the files would act like generators and stream the unzip process, taking very little memory. Should these two methods be equivalent?</p>
1
2016-08-15T15:00:12Z
38,963,601
<p>Instead of the memory hungry (and naive)</p> <pre><code>import gzip with gzip.open(zipped_file, 'rb') as zin, open(unzipped_file, 'wb') as wout: wout.write(zin.read()) </code></pre> <p>Based on the earlier answers I tested this:</p> <pre><code>import gzip block_size = 64*1024 with gzip.open(zipped_file, 'rb') as zin, open(unzipped_file, 'wb') as wout: while True: uncompressed_block = zin.read(block_size) if not uncompressed_block: break wout.write(uncompressed_block) </code></pre> <p>Verified on a 4.8G file.</p>
0
2016-08-15T21:50:44Z
[ "python", "python-3.x", "gzip", "generator", "shutil" ]
Compute first order derivative with MongoDB aggregation framework
38,957,649
<p>Is it possible to calculate a first order derivative using the aggregate framework?</p> <p>For example, I have the data : </p> <pre><code>{time_series : [10,20,40,70,110]} </code></pre> <p>I'm trying to obtain an output like: </p> <pre><code>{derivative : [10,20,30,40]} </code></pre>
13
2016-08-15T15:02:00Z
39,154,290
<p>it's a bit dirty, but perhaps something like this?</p> <pre><code>use test_db db['data'].remove({}) db['data'].insert({id: 1, time_series: [10,20,40,70,110]}) var mapF = function() { emit(this.id, this.time_series); emit(this.id, this.time_series); }; var reduceF = function(key, values){ var n = values[0].length; var ret = []; for(var i = 0; i &lt; n-1; i++){ ret.push( values[0][i+1] - values[0][i] ); } return {'gradient': ret}; }; var finalizeF = function(key, val){ return val.gradient; } db['data'].mapReduce( mapF, reduceF, { out: 'data_d1', finalize: finalizeF } ) db['data_d1'].find({}) </code></pre> <p>The "strategy" here is to emit the data to be operated on twice so that it is accessible in the reduce stage, return an object to avoid the message <em>"reduce -> multiple not supported yet"</em> and then filter back the array in the finalizer.</p> <p>This script then produces:</p> <pre><code>MongoDB shell version: 3.2.9 connecting to: test switched to db test_db WriteResult({ "nRemoved" : 1 }) WriteResult({ "nInserted" : 1 }) { "result" : "data_d1", "timeMillis" : 13, "counts" : { "input" : 1, "emit" : 2, "reduce" : 1, "output" : 1 }, "ok" : 1 } { "_id" : 1, "value" : [ 10, 20, 30, 40 ] } bye </code></pre> <p>Alternatively, one could move all the processing into the finalizer (<code>reduceF</code> is not called here since <code>mapF</code> is assumed to emit unique keys):</p> <pre><code>use test_db db['data'].remove({}) db['data'].insert({id: 1, time_series: [10,20,40,70,110]}) var mapF = function() { emit(this.id, this.time_series); }; var reduceF = function(key, values){ }; var finalizeF = function(key, val){ var x = val; var n = x.length; var ret = []; for(var i = 0; i &lt; n-1; i++){ ret.push( x[i+1] - x[i] ); } return ret; } db['data'].mapReduce( mapF, reduceF, { out: 'data_d1', finalize: finalizeF } ) db['data_d1'].find({}) </code></pre>
4
2016-08-25T20:33:03Z
[ "python", "mongodb", "mapreduce", "pymongo", "aggregation-framework" ]
Compute first order derivative with MongoDB aggregation framework
38,957,649
<p>Is it possible to calculate a first order derivative using the aggregate framework?</p> <p>For example, I have the data : </p> <pre><code>{time_series : [10,20,40,70,110]} </code></pre> <p>I'm trying to obtain an output like: </p> <pre><code>{derivative : [10,20,30,40]} </code></pre>
13
2016-08-15T15:02:00Z
39,185,810
<p>We can do this using the aggregation framework in MongoDB 3.2 or newer because what we really need is a way to keep tracking of the index of the <em>current</em> and <em>previous</em> element in our array and fortunately starting from MongoDB 3.2 we can use the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/" rel="nofollow"><code>$unwind</code></a> operator to deconstruct our array and include the index of each element in the array by specifying a document as operand instead of the traditional "path" prefixed by <em>$</em>.</p> <p>From there we have two options. The first is in MongoDB 3.2 and the second in the upcoming release of MongoDB (as of this writing).</p> <p>Next in the pipeline, we need to <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/group/" rel="nofollow"><code>$group</code></a> our documents and use the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/push/" rel="nofollow"><code>$push</code></a> accumulator operator to return an array of sub-documents that look like this:</p> <pre><code>{ "_id" : ObjectId("57c11ddbe860bd0b5df6bc64"), "time_series" : [ { "value" : 10, "index" : NumberLong(0) }, { "value" : 20, "index" : NumberLong(1) }, { "value" : 40, "index" : NumberLong(2) }, { "value" : 70, "index" : NumberLong(3) }, { "value" : 110, "index" : NumberLong(4) } ] } </code></pre> <hr> <p>Finally comes the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/project" rel="nofollow"><code>$project</code></a> stage. In this stage, we need to use the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/map/" rel="nofollow"><code>$map</code></a> operator to apply a series of expression to each element in the the newly computed array in the <code>$group</code> stage.</p> <p>Here is what is going on inside the <code>$map</code> (see <code>$map</code> as a for loop) <strong>in</strong> expression:</p> <p>For each subdocument, we assign the <em>value</em> field to a variable using the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/let" rel="nofollow"><code>$let</code></a> variable operator. We then subtract it value from the value of the "value" field of the next element in the array.</p> <p>Since the next element in the array is the element at the current index plus one, all we need is the help of the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/arrayElemAt" rel="nofollow"><code>$arrayElemAt</code></a> operator and a simple <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/add" rel="nofollow"><code>$add</code></a>ition of the current element's index and <code>1</code>. </p> <p>The <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/subtract" rel="nofollow"><code>$subtract</code></a> expression return a negative value so we need to multiply the value by <code>-1</code> using the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/multiply" rel="nofollow"><code>$multiply</code></a> operator.</p> <p>We also need to <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/filter" rel="nofollow"><code>$filter</code></a> the resulted array because it the last element is <code>None</code> or <code>null</code>. The reason is that when the current element is the last element, <code>$subtract</code> return <code>None</code> because the index of the next element equal the size of the array. </p> <pre><code>db.collection.aggregate( [ { "$unwind": { "path": "$time_series", "includeArrayIndex": "index" }}, { "$group": { "_id": "$_id", "time_series": { "$push": { "value": "$time_series", "index": "$index" } } }}, { "$project": { "time_series": { "$filter": { "input": { "$map": { "input": "$time_series", "as": "el", "in": { "$multiply": [ { "$subtract": [ "$$el.value", { "$let": { "vars": { "nextElement": { "$arrayElemAt": [ "$time_series", { "$add": [ "$$el.index", 1 ]} ]} }, "in": "$$nextElement.value" } } ]}, -1 ] } } }, "as": "item", "cond": { "$gte": [ "$$item", 0 ] } } } }} ] ) </code></pre> <hr> <p>In the upcoming version will provide another alternative.</p> <p>First in the <code>$group</code> stage we return two different arrays. One for the elements and the other one for their indexes then <code>$zip</code> the two arrays as shown <a href="http://stackoverflow.com/a/38476739/3100115">here</a>. From their, we simply access each element using integer indexing instead of assigning their value to a variable with <code>$let</code>. </p> <pre><code>db.collection.aggregate( [ { "$unwind": { "path": "$time_series", "includeArrayIndex": "index" }}, { "$group": { "_id": "$_id", "values": { "$push": "$time_series" }, "indexes": { "$push": "$index" } }}, { "$project": { "time_series": { "$filter": { "input": { "$map": { "input": { "$zip": { "inputs": [ "$values", "$indexes" ] } }, "as": "el", "in": { "$multiply": [ { "$subtract": [ { "$arrayElemAt": [ "$$el", 0 ]}, { "$arrayElemAt": [ "$values", { "$add": [ { "$arrayElemAt": [ "$$el", 1 ]}, 1 ]} ]} ]}, -1 ] } } }, "as": "item", "cond": { "$gte": [ "$$item", 0 ] } } } }} ] ) </code></pre> <p>Note that we could also reverse the array early in the <code>$project</code> stage using <code>$reverse</code> as shown <a href="http://stackoverflow.com/a/38039263/3100115">here</a> to avoid using <code>$multiply</code>.</p> <hr> <p>Both queries<sup>*</sup> yield something like:</p> <pre><code>{ "_id" : ObjectId("57c11ddbe860bd0b5df6bc64"), "time_series" : [ 10, 20, 30, 40 ] } </code></pre> <hr> <p>Another option which I think is less efficient is perform a map/reduce operation on our collection using the <a href="http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.map_reduce" rel="nofollow"><code>map_reduce</code></a> method.</p> <pre><code>&gt;&gt;&gt; import pymongo &gt;&gt;&gt; from bson.code import Code &gt;&gt;&gt; client = pymongo.MongoClient() &gt;&gt;&gt; db = client.test &gt;&gt;&gt; collection = db.collection &gt;&gt;&gt; mapper = Code(""" ... function() { ... var derivatives = []; ... for (var index=1; index&lt;this.time_series.length; index++) { ... derivatives.push(this.time_series[index] - this.time_series[index-1]); ... } ... emit(this._id, derivatives); ... } ... """) &gt;&gt;&gt; reducer = Code(""" ... function(key, value) {} ... """) &gt;&gt;&gt; for res in collection.map_reduce(mapper, reducer, out={'inline': 1})['results']: ... print(res) # or do something with the document. ... {'value': [10.0, 20.0, 30.0, 40.0], '_id': ObjectId('57c11ddbe860bd0b5df6bc64')} </code></pre> <hr> <p>You can also retrieve all the document and use the <code>numpy.diff</code> to return the derivative like this:</p> <pre><code>import numpy as np for document in collection.find({}, {'time_series': 1}): result = np.diff(document['time_series']) </code></pre> <p>Now how about a little benchmarking:</p> <h3>Machine:</h3> <pre><code>OS: Ubuntu 16.04 Memory: 15.6 GiB Processor: Intel® Xeon(R) CPU E3-1231 v3 @ 3.40GHz × 8 </code></pre> <p>The three queries run in this order on my machine give respectively the following result:</p> <h1>Benchmark test result with 500 documents:</h1> <h3>MongoDB 3.2</h3> <pre><code>100 loops, best of 3: 2.32 ms per loop </code></pre> <h3>MongoDB 3.3.11</h3> <pre><code>1000 loops, best of 3: 1.72 ms per loop </code></pre> <h3>MapReduce</h3> <pre><code>100 loops, best of 3: 15.7 ms per loop </code></pre> <h3>Numpy using <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.diff.html" rel="nofollow"><code>numpy.diff</code></a></h3> <pre><code>100 loops, best of 3: 3.61 ms per loop </code></pre> <h1>Conclusion</h1> <p>Using the aggregation is the best option here as expected even if the solution is not obvious.</p> <p>The <code>mapReduce</code> solution is trivial but very inefficient because of the JavaScript evaluation. </p> <p><sub>* You can test the second query by installing a current development version of MongoDB (as the time of this writing).</sub></p>
5
2016-08-27T21:14:36Z
[ "python", "mongodb", "mapreduce", "pymongo", "aggregation-framework" ]
Read uncompressed image from byte array
38,957,724
<p>I created a uncompressed dicom video from an ultrasound device. Now I want to read it frame by frame in a python application and for now save the file. Later I want to add some image processing. So far I've tried to extract the bytes belonging to the first frame.</p> <pre><code>import dicom import array from PIL import Image filename = 'image.dcm' img = dicom.read_file(filename) byte_array = array.array('B', img.PixelData[0:(img.Rows * img.Columns)]) </code></pre> <p>How do I get now this bytearray into a file (bitmap, jpeg whatever)? I've tried using the python image library with <code>image = Image.fromarray(byte_array)</code> but got an error.</p> <blockquote> <p>AttributeError: 'str' object has no attribute '<strong>array_interface</strong>'</p> </blockquote> <p>I guess somewhere I also have to specify the dimensions of the image but haven't figured out how.</p>
1
2016-08-15T15:06:05Z
39,032,594
<p>Thanks to the comments I figured out how to solve it. The Image was in 'RGB' and the shape of the array was (3L, 800L, 376L). Instead of converting it to a byte array I can take the <code>pixel_array</code> as numpy array and reshape it to (800L, 376L, 3L). </p> <pre><code>import dicom from PIL import Image filename = 'image.dcm' img = dicom.read_file(filename) output = img.pixel_array.reshape((img.Rows, img.Columns, 3)) image = Image.fromarray(output).convert('LA') image.save('output.png') </code></pre>
0
2016-08-19T06:39:34Z
[ "python", "image", "dicom" ]
Project Euler 22 Python | 300k from right result
38,957,774
<p>I'm working on Problem 22 from Project Euler.</p> <p><em>Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file?</em></p> <p>My Code below works for the COLIN example and also I tried with a small list of 5 names and it was correct. But here my result is 870873746 and it should be 871198282. So ~324k are missing. I edited the names.txt file. Each Name is in one line and without "".</p> <pre><code>nameList = [] letterDict = {"A" : 1, "B" : 2, "C" : 3, "D" : 4, "E" : 5, "F" : 6, "G" : 7, "H" : 8, "I" : 9, "J" : 10, "K" : 11, "L" : 12, "M" : 13, "N" : 14, "O" : 15, "P": 16, "Q" : 17, "R" : 18, "S" : 19, "T" : 20, "U" : 21, "V" : 22, "W" : 23, "X" : 24, "Y" : 25, "Z" : 26} a = 0 namescoresum = 0 b = 0 c = 0 while a &lt; 5163: x = raw_input() nameList.append(x) a += 1 nameList.sort() print nameList for name in nameList: b += 1 lettersum = 0 for letter in name: c += 1 lettersum += letterDict[letter] indexofname = nameList.index(name) namescoresum += (lettersum * indexofname) print "NAMESCORESUM: ", namescoresum </code></pre>
1
2016-08-15T15:08:06Z
38,957,902
<p>I believe you have an off-by-one error. Remember that array indexes start at zero, but ordinal numbers (like first, second, 938th) start at one.</p> <p>Try this:</p> <pre><code>namescoresum += lettersum * (indexofname+1) </code></pre> <p>To determine for sure if you have an off-by-one error, add this to your <code>for</code> loop:</p> <pre><code>if name == 'COLIN': print 'COLIN', indexofname </code></pre>
0
2016-08-15T15:15:01Z
[ "python", "list" ]
Project Euler 22 Python | 300k from right result
38,957,774
<p>I'm working on Problem 22 from Project Euler.</p> <p><em>Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714. What is the total of all the name scores in the file?</em></p> <p>My Code below works for the COLIN example and also I tried with a small list of 5 names and it was correct. But here my result is 870873746 and it should be 871198282. So ~324k are missing. I edited the names.txt file. Each Name is in one line and without "".</p> <pre><code>nameList = [] letterDict = {"A" : 1, "B" : 2, "C" : 3, "D" : 4, "E" : 5, "F" : 6, "G" : 7, "H" : 8, "I" : 9, "J" : 10, "K" : 11, "L" : 12, "M" : 13, "N" : 14, "O" : 15, "P": 16, "Q" : 17, "R" : 18, "S" : 19, "T" : 20, "U" : 21, "V" : 22, "W" : 23, "X" : 24, "Y" : 25, "Z" : 26} a = 0 namescoresum = 0 b = 0 c = 0 while a &lt; 5163: x = raw_input() nameList.append(x) a += 1 nameList.sort() print nameList for name in nameList: b += 1 lettersum = 0 for letter in name: c += 1 lettersum += letterDict[letter] indexofname = nameList.index(name) namescoresum += (lettersum * indexofname) print "NAMESCORESUM: ", namescoresum </code></pre>
1
2016-08-15T15:08:06Z
38,985,628
<p>Also, to complete this question a little bit... in case you wanted to solve the problem with a single comprehension list (assuming you already have your data ready to go), here's some tips:</p> <ul> <li>ord, ASCII, sum, enumerate</li> </ul> <p>There you go :-)</p>
0
2016-08-16T22:47:53Z
[ "python", "list" ]
In Python, use a method both as instance and class method
38,957,820
<p>I'm writing a program which plays Tic Tac Toe and has various versions of <code>ComputerPlayer</code>, such as the <code>RandomPlayer</code> and <code>THandPlayer</code>:</p> <pre><code>class RandomPlayer(ComputerPlayer): def __init__(self, mark): super(RandomPlayer, self).__init__(mark=mark) def get_move(self, board): moves = board.available_moves() if moves: # If "moves" is not an empty list (as it would be if cat's game were reached) return moves[np.random.choice(len(moves))] # Apply random select to the index, as otherwise it will be seen as a 2D array class THandPlayer(ComputerPlayer): def __init__(self, mark): super(THandPlayer, self).__init__(mark=mark) def get_move(self, board): moves = board.available_moves() if moves: # If "moves" is not an empty list (as it would be if cat's game were reached) for move in moves: if board.get_next_board(move, self.mark).winner() == self.mark: # Make winning move (if possible) return move elif board.get_next_board(move, self.opponent_mark).winner() == self.opponent_mark: # Block opponent's winning move return move else: # return moves[np.random.choice(len(moves))] # This is a repetition of the code in RandomPlayer and is not DRY randomplayer = RandomPlayer(mark=self.mark) return randomplayer.get_move(board) # return RandomPlayer.get_move(board) # This returns an error as "get_move" is an instance method </code></pre> <p>The <code>THandPlayer</code> also selects moves at random if no winning move can be made or an opponent's winning move blocked. Right now I am doing this by creating an instance of <code>RandomPlayer</code> and calling <code>get_move</code> on it. This could be made more succinct, however, if <code>get_move</code> could be made such that it can be interpreted both as a class method and an instance method. Is this possible?</p> <p><strong>EDIT</strong></p> <p>To simplify the question, suppose we have two classes, <code>RandomPlayer</code> and <code>OtherPlayer</code>, both which have an instance method <code>get_move</code>:</p> <pre><code>import numpy as np class RandomPlayer: def get_move(self, arr): return np.random.choice(arr) class OtherPlayer: def get_move(self, arr): if max(arr) &gt; 5: return max(arr) else: randomplayer=RandomPlayer() return randomplayer.get_move(arr) arr = np.arange(4) otherplayer = OtherPlayer() print otherplayer.get_move(arr) </code></pre> <p>Is it possible to use <code>RandomPlayer</code>'s <code>get_move</code> method in <code>OtherPlayer</code> without creating an instance of <code>RandomPlayer</code>?</p>
0
2016-08-15T15:10:36Z
38,957,917
<p>It sounds like you're looking for a <a href="https://docs.python.org/3.5/library/functions.html#staticmethod" rel="nofollow"><code>staticmethod</code></a>, which has access to neither <code>cls</code> nor <code>self</code> but can be accessed via either:</p> <pre><code>&gt;&gt;&gt; class Foo: ... @staticmethod ... def bar(): ... print('baz') ... &gt;&gt;&gt; Foo.bar() baz &gt;&gt;&gt; Foo().bar() baz </code></pre>
2
2016-08-15T15:16:11Z
[ "python" ]
In Python, use a method both as instance and class method
38,957,820
<p>I'm writing a program which plays Tic Tac Toe and has various versions of <code>ComputerPlayer</code>, such as the <code>RandomPlayer</code> and <code>THandPlayer</code>:</p> <pre><code>class RandomPlayer(ComputerPlayer): def __init__(self, mark): super(RandomPlayer, self).__init__(mark=mark) def get_move(self, board): moves = board.available_moves() if moves: # If "moves" is not an empty list (as it would be if cat's game were reached) return moves[np.random.choice(len(moves))] # Apply random select to the index, as otherwise it will be seen as a 2D array class THandPlayer(ComputerPlayer): def __init__(self, mark): super(THandPlayer, self).__init__(mark=mark) def get_move(self, board): moves = board.available_moves() if moves: # If "moves" is not an empty list (as it would be if cat's game were reached) for move in moves: if board.get_next_board(move, self.mark).winner() == self.mark: # Make winning move (if possible) return move elif board.get_next_board(move, self.opponent_mark).winner() == self.opponent_mark: # Block opponent's winning move return move else: # return moves[np.random.choice(len(moves))] # This is a repetition of the code in RandomPlayer and is not DRY randomplayer = RandomPlayer(mark=self.mark) return randomplayer.get_move(board) # return RandomPlayer.get_move(board) # This returns an error as "get_move" is an instance method </code></pre> <p>The <code>THandPlayer</code> also selects moves at random if no winning move can be made or an opponent's winning move blocked. Right now I am doing this by creating an instance of <code>RandomPlayer</code> and calling <code>get_move</code> on it. This could be made more succinct, however, if <code>get_move</code> could be made such that it can be interpreted both as a class method and an instance method. Is this possible?</p> <p><strong>EDIT</strong></p> <p>To simplify the question, suppose we have two classes, <code>RandomPlayer</code> and <code>OtherPlayer</code>, both which have an instance method <code>get_move</code>:</p> <pre><code>import numpy as np class RandomPlayer: def get_move(self, arr): return np.random.choice(arr) class OtherPlayer: def get_move(self, arr): if max(arr) &gt; 5: return max(arr) else: randomplayer=RandomPlayer() return randomplayer.get_move(arr) arr = np.arange(4) otherplayer = OtherPlayer() print otherplayer.get_move(arr) </code></pre> <p>Is it possible to use <code>RandomPlayer</code>'s <code>get_move</code> method in <code>OtherPlayer</code> without creating an instance of <code>RandomPlayer</code>?</p>
0
2016-08-15T15:10:36Z
38,958,345
<p>A random move is a specific type of move; put a method which generates one in <code>ComputerPlayer</code>; then both <code>RandomPlayer</code> and <code>THandPlayer</code> can call it as necessary.</p> <pre><code>class ComputerPlayer(...): @staticmethod def choose_random_move(moves): if moves: return moves[np.random.choice(len(moves))] class RandomPlayer(ComputerPlayer): def get_move(self, board): moves = board.available_moves() if moves: return self.choose_random_move(moves) class THandPlayer(ComputerPlayer): def get_move(self, board): moves = board.available_moves() for move in moves: for mark in [self.mark, self.opponent_mark]: if board.get_next_board(move, mark).winner() == mark: return move else: return self.choose_random_move(moves) </code></pre> <p>Some extra notes:</p> <ul> <li><p>If your <code>__init__</code> method doesn't do anything except call <code>super</code> and pass along the exact same arguments, don't implement it; just let the inherited method be called directly.</p></li> <li><p>The two checks for a winner can be refactored.</p></li> <li><p><code>choose_random_move</code> doesn't necessarily need to be a static method; you can keep it as an instance method with a default implementation that ignores any player-specific information in choosing a move. Derived classes can override the method if they like.</p></li> </ul>
1
2016-08-15T15:45:10Z
[ "python" ]
In Python, use a method both as instance and class method
38,957,820
<p>I'm writing a program which plays Tic Tac Toe and has various versions of <code>ComputerPlayer</code>, such as the <code>RandomPlayer</code> and <code>THandPlayer</code>:</p> <pre><code>class RandomPlayer(ComputerPlayer): def __init__(self, mark): super(RandomPlayer, self).__init__(mark=mark) def get_move(self, board): moves = board.available_moves() if moves: # If "moves" is not an empty list (as it would be if cat's game were reached) return moves[np.random.choice(len(moves))] # Apply random select to the index, as otherwise it will be seen as a 2D array class THandPlayer(ComputerPlayer): def __init__(self, mark): super(THandPlayer, self).__init__(mark=mark) def get_move(self, board): moves = board.available_moves() if moves: # If "moves" is not an empty list (as it would be if cat's game were reached) for move in moves: if board.get_next_board(move, self.mark).winner() == self.mark: # Make winning move (if possible) return move elif board.get_next_board(move, self.opponent_mark).winner() == self.opponent_mark: # Block opponent's winning move return move else: # return moves[np.random.choice(len(moves))] # This is a repetition of the code in RandomPlayer and is not DRY randomplayer = RandomPlayer(mark=self.mark) return randomplayer.get_move(board) # return RandomPlayer.get_move(board) # This returns an error as "get_move" is an instance method </code></pre> <p>The <code>THandPlayer</code> also selects moves at random if no winning move can be made or an opponent's winning move blocked. Right now I am doing this by creating an instance of <code>RandomPlayer</code> and calling <code>get_move</code> on it. This could be made more succinct, however, if <code>get_move</code> could be made such that it can be interpreted both as a class method and an instance method. Is this possible?</p> <p><strong>EDIT</strong></p> <p>To simplify the question, suppose we have two classes, <code>RandomPlayer</code> and <code>OtherPlayer</code>, both which have an instance method <code>get_move</code>:</p> <pre><code>import numpy as np class RandomPlayer: def get_move(self, arr): return np.random.choice(arr) class OtherPlayer: def get_move(self, arr): if max(arr) &gt; 5: return max(arr) else: randomplayer=RandomPlayer() return randomplayer.get_move(arr) arr = np.arange(4) otherplayer = OtherPlayer() print otherplayer.get_move(arr) </code></pre> <p>Is it possible to use <code>RandomPlayer</code>'s <code>get_move</code> method in <code>OtherPlayer</code> without creating an instance of <code>RandomPlayer</code>?</p>
0
2016-08-15T15:10:36Z
38,958,680
<p>For the sake of completeness, here is my implementation of the solution suggested by <a href="http://stackoverflow.com/users/476/deceze">deceze</a>, in which I also followed <a href="http://stackoverflow.com/users/1126841/chepner">chepner</a>'s suggestion to refactor the two Boolean statements:</p> <pre><code>class RandomPlayer(ComputerPlayer): def __init__(self, mark): super(RandomPlayer, self).__init__(mark=mark) @staticmethod def get_move(board): moves = board.available_moves() if moves: # If "moves" is not an empty list (as it would be if cat's game were reached) return moves[np.random.choice(len(moves))] # Apply random selection to the index, as otherwise it will be seen as a 2D array class THandPlayer(ComputerPlayer): def __init__(self, mark): super(THandPlayer, self).__init__(mark=mark) def get_move(self, board): moves = board.available_moves() if moves: for move in moves: if THandPlayer.next_move_winner(board, move, self.mark): return move elif THandPlayer.next_move_winner(board, move, self.opponent_mark): return move else: return RandomPlayer.get_move(board) @staticmethod def next_move_winner(board, move, mark): return board.get_next_board(move, mark).winner() == mark </code></pre> <p>A static method is used both to default to the random player and to refactor the Boolean statements.</p>
0
2016-08-15T16:06:44Z
[ "python" ]
In Python, use a method both as instance and class method
38,957,820
<p>I'm writing a program which plays Tic Tac Toe and has various versions of <code>ComputerPlayer</code>, such as the <code>RandomPlayer</code> and <code>THandPlayer</code>:</p> <pre><code>class RandomPlayer(ComputerPlayer): def __init__(self, mark): super(RandomPlayer, self).__init__(mark=mark) def get_move(self, board): moves = board.available_moves() if moves: # If "moves" is not an empty list (as it would be if cat's game were reached) return moves[np.random.choice(len(moves))] # Apply random select to the index, as otherwise it will be seen as a 2D array class THandPlayer(ComputerPlayer): def __init__(self, mark): super(THandPlayer, self).__init__(mark=mark) def get_move(self, board): moves = board.available_moves() if moves: # If "moves" is not an empty list (as it would be if cat's game were reached) for move in moves: if board.get_next_board(move, self.mark).winner() == self.mark: # Make winning move (if possible) return move elif board.get_next_board(move, self.opponent_mark).winner() == self.opponent_mark: # Block opponent's winning move return move else: # return moves[np.random.choice(len(moves))] # This is a repetition of the code in RandomPlayer and is not DRY randomplayer = RandomPlayer(mark=self.mark) return randomplayer.get_move(board) # return RandomPlayer.get_move(board) # This returns an error as "get_move" is an instance method </code></pre> <p>The <code>THandPlayer</code> also selects moves at random if no winning move can be made or an opponent's winning move blocked. Right now I am doing this by creating an instance of <code>RandomPlayer</code> and calling <code>get_move</code> on it. This could be made more succinct, however, if <code>get_move</code> could be made such that it can be interpreted both as a class method and an instance method. Is this possible?</p> <p><strong>EDIT</strong></p> <p>To simplify the question, suppose we have two classes, <code>RandomPlayer</code> and <code>OtherPlayer</code>, both which have an instance method <code>get_move</code>:</p> <pre><code>import numpy as np class RandomPlayer: def get_move(self, arr): return np.random.choice(arr) class OtherPlayer: def get_move(self, arr): if max(arr) &gt; 5: return max(arr) else: randomplayer=RandomPlayer() return randomplayer.get_move(arr) arr = np.arange(4) otherplayer = OtherPlayer() print otherplayer.get_move(arr) </code></pre> <p>Is it possible to use <code>RandomPlayer</code>'s <code>get_move</code> method in <code>OtherPlayer</code> without creating an instance of <code>RandomPlayer</code>?</p>
0
2016-08-15T15:10:36Z
38,958,735
<p>(This is an alternative to my other answer, using a different abstraction.)</p> <p>A random move isn't something associated with a player as much as it is something associated with a board; it's like <code>board.available_moves</code>, but returns a single move instead of all moves.</p> <pre><code> class Board(...): # Given how often this is called by or before # random_move(), it would be smart to implement # some kind of caching so that the available # moves don't have to be recalcuated for the same board # state every time it is called. def available_moves(self): ... def random_move(self): moves = self.available_moves() if moves: return moves[np.random.choice(len(moves))] class RandomPlayer(ComputerPlayer): def get_move(self, board): return board.random_move() class THandPlayer(ComputerPlayer): def get_move(self, board): moves = board.available_moves() if moves: for move in moves: if board.get_next_board(move, self.mark).winner() == self.mark: return move elif board.get_next_board(move, self.opponent_mark).winner() == self.opponent_mark: return move else: return board.random_move() </code></pre>
1
2016-08-15T16:09:33Z
[ "python" ]
Python 2.7 - prime number generator, can't figure out what is wrong with my program
38,957,908
<p>noob programmer here. I am trying to build a small program in 2.7 which generates a prime number, asks the user to continue or not, and then continues generating primes until the user tells it to stop. Unfortunately my program isn't outputting anything at all, and I can't figure out why.</p> <p>Here is my code:</p> <p>First, the part which checks for primes. I know that this part is functioning properly, because the exact same code works properly for my prime factor finder.</p> <pre><code>def isprime(num): #this checks the numbers to see if they're prime prime = True for i in range(2,num): if num/i == (num*1.0)/i: prime = False return False break else: prime = True if prime == True: return True </code></pre> <p>And second, the part which iterates through all the numbers, prints result, and asks to continue or not. The error must be in here somewhere:</p> <pre><code>def primegen(): n = 1 while True: if isprime(n) == True: print n cont = raw_input("continue? Enter Y/N") if cont == 'N': break n+=1 primegen() </code></pre>
0
2016-08-15T15:15:26Z
38,958,001
<p><code>n</code> should be incremented unconditionally. If it isn't the program gets stuck in an infinite loop the first time it encounters a non-prime.</p> <pre><code>def primegen(): n = 1 while True: if isprime(n): print n cont = raw_input("continue? Enter Y/N") if cont == 'N': break n += 1 </code></pre>
1
2016-08-15T15:21:39Z
[ "python", "python-2.7", "primes" ]
Python 2.7 - prime number generator, can't figure out what is wrong with my program
38,957,908
<p>noob programmer here. I am trying to build a small program in 2.7 which generates a prime number, asks the user to continue or not, and then continues generating primes until the user tells it to stop. Unfortunately my program isn't outputting anything at all, and I can't figure out why.</p> <p>Here is my code:</p> <p>First, the part which checks for primes. I know that this part is functioning properly, because the exact same code works properly for my prime factor finder.</p> <pre><code>def isprime(num): #this checks the numbers to see if they're prime prime = True for i in range(2,num): if num/i == (num*1.0)/i: prime = False return False break else: prime = True if prime == True: return True </code></pre> <p>And second, the part which iterates through all the numbers, prints result, and asks to continue or not. The error must be in here somewhere:</p> <pre><code>def primegen(): n = 1 while True: if isprime(n) == True: print n cont = raw_input("continue? Enter Y/N") if cont == 'N': break n+=1 primegen() </code></pre>
0
2016-08-15T15:15:26Z
38,958,593
<p>Your code is a bit chaotic, I would rewrite it like this:</p> <pre><code>def isPrime(num): if num % 2 == 0: return True return False n=1 while True: if isPrime(n): print n cont = raw_input("Do you want to continue? (1,0) ") if not bool(int(cont)): break n += 1 </code></pre>
0
2016-08-15T16:01:04Z
[ "python", "python-2.7", "primes" ]
How to keep track of players' rankings?
38,957,961
<p>I have a <code>Player</code> class with a <code>score</code> attribute:</p> <pre><code>class Player(game_engine.Player): def __init__(self, id): super().__init__(id) self.score = 0 </code></pre> <p>This score increases/decreases as the player succeeds/fails to do objectives. Now I need to tell the player his rank out of the total amount of players with something like</p> <pre><code>print('Your rank is {0} out of {1}') </code></pre> <p>First I thought of having a list of all the players, and whenever anything happens to a player:</p> <ol> <li>I check if his score increased or decreased</li> <li>find him in the list</li> <li>move him until his score is in the correct place</li> </ol> <p>But this would be <em>extremely</em> slow. There can be hundreds of thousands of players, and a player can reset his own score to <code>0</code> which would mean that I'd have to move everyone after him in the stack. Even finding the player would be O(n).</p> <p>What I'm looking for is a high performance solution. RAM usage isn't quite as important, although common sense should be used. How could I improve the system to be a lot faster?</p> <p><strong>Updated info:</strong> I'm storing a player's data into a MySQL database with SQLAlchemy everytime he leaves the gameserver, and I load it everytime he joins the server. These are handled through <code>'player_join'</code> and <code>'player_leave'</code> events:</p> <pre><code>@Event('player_join') def load_player(id): """Load player into the global players dict.""" session = Session() query = session.query(Player).filter_by(id=id) players[id] = query.one_or_none() or Player(id=id) @Event('player_leave') def save_player(id): """Save player into the database.""" session = Session() session.add(players[id]) session.commit() </code></pre> <p>Also, the player's score is updated upon <code>'player_kill'</code> event:</p> <pre><code>@Event('player_kill') def update_score(id, target_id): """Update players' scores upon a kill.""" players[id].score += 2 players[target_id].score -= 2 </code></pre>
15
2016-08-15T15:18:40Z
39,000,851
<p>The problem you have is that you want real-time updates against a database, which requires a db query each time. If you instead maintain a list of scores in memory, and update it at a more reasonable frequency (say once an hour, or even once a minute, if your players are really concerned with their rank), then the players will still experience real-time progress vs a score rank, and they can't really tell if there is a short lag in the updates.</p> <p>With a sorted list of scores in memory, you can instantly get the player's rank (where by instantly, I mean O(lg n) lookup in memory) at the cost of the memory to cache, and of course the time to update the cache when you want to. Compared to a db query of 100k records every time someone wants to glance at their rank, this is a much better option.</p> <p>Elaborating on the sorted list, you must query the db to get it, but you can keep using it for a while. Maybe you store the last_update, and re-query the db only if this list is "too old". So you update quickly by not trying to update all the time, but rather just enough to feel like real-time.</p> <p>In order to find someone's rank nearly instantaneously, you use the bisect module, which supports binary search in a sorted list. The scores are sorted when you get them.</p> <pre><code>from bisect import bisect_left # suppose scores are 1 through 10 scores = range(1, 11) # get the insertion index for score 7 # subtract it from len(scores) because bisect expects ascending sort # but you want a descending rank print len(scores) - bisect_left(scores, 7) </code></pre> <p>This says that a 7 score is rank 4, which is correct.</p>
4
2016-08-17T15:35:23Z
[ "python", "algorithm", "python-3.x", "ranking", "rank" ]
How to keep track of players' rankings?
38,957,961
<p>I have a <code>Player</code> class with a <code>score</code> attribute:</p> <pre><code>class Player(game_engine.Player): def __init__(self, id): super().__init__(id) self.score = 0 </code></pre> <p>This score increases/decreases as the player succeeds/fails to do objectives. Now I need to tell the player his rank out of the total amount of players with something like</p> <pre><code>print('Your rank is {0} out of {1}') </code></pre> <p>First I thought of having a list of all the players, and whenever anything happens to a player:</p> <ol> <li>I check if his score increased or decreased</li> <li>find him in the list</li> <li>move him until his score is in the correct place</li> </ol> <p>But this would be <em>extremely</em> slow. There can be hundreds of thousands of players, and a player can reset his own score to <code>0</code> which would mean that I'd have to move everyone after him in the stack. Even finding the player would be O(n).</p> <p>What I'm looking for is a high performance solution. RAM usage isn't quite as important, although common sense should be used. How could I improve the system to be a lot faster?</p> <p><strong>Updated info:</strong> I'm storing a player's data into a MySQL database with SQLAlchemy everytime he leaves the gameserver, and I load it everytime he joins the server. These are handled through <code>'player_join'</code> and <code>'player_leave'</code> events:</p> <pre><code>@Event('player_join') def load_player(id): """Load player into the global players dict.""" session = Session() query = session.query(Player).filter_by(id=id) players[id] = query.one_or_none() or Player(id=id) @Event('player_leave') def save_player(id): """Save player into the database.""" session = Session() session.add(players[id]) session.commit() </code></pre> <p>Also, the player's score is updated upon <code>'player_kill'</code> event:</p> <pre><code>@Event('player_kill') def update_score(id, target_id): """Update players' scores upon a kill.""" players[id].score += 2 players[target_id].score -= 2 </code></pre>
15
2016-08-15T15:18:40Z
39,002,736
<p>That kind of information can be pulled using SQLAlchemy's sort_by function. If you perform a Query like:</p> <pre><code>leaderboard = session.query(Player).order_by(Player.score).all() </code></pre> <p>You will have the list of Players sorted by their score. Keep in mind that every time you do this you do an I/O with the database which can be rather slow instead of saving the data python variables. </p>
0
2016-08-17T17:18:25Z
[ "python", "algorithm", "python-3.x", "ranking", "rank" ]
How to keep track of players' rankings?
38,957,961
<p>I have a <code>Player</code> class with a <code>score</code> attribute:</p> <pre><code>class Player(game_engine.Player): def __init__(self, id): super().__init__(id) self.score = 0 </code></pre> <p>This score increases/decreases as the player succeeds/fails to do objectives. Now I need to tell the player his rank out of the total amount of players with something like</p> <pre><code>print('Your rank is {0} out of {1}') </code></pre> <p>First I thought of having a list of all the players, and whenever anything happens to a player:</p> <ol> <li>I check if his score increased or decreased</li> <li>find him in the list</li> <li>move him until his score is in the correct place</li> </ol> <p>But this would be <em>extremely</em> slow. There can be hundreds of thousands of players, and a player can reset his own score to <code>0</code> which would mean that I'd have to move everyone after him in the stack. Even finding the player would be O(n).</p> <p>What I'm looking for is a high performance solution. RAM usage isn't quite as important, although common sense should be used. How could I improve the system to be a lot faster?</p> <p><strong>Updated info:</strong> I'm storing a player's data into a MySQL database with SQLAlchemy everytime he leaves the gameserver, and I load it everytime he joins the server. These are handled through <code>'player_join'</code> and <code>'player_leave'</code> events:</p> <pre><code>@Event('player_join') def load_player(id): """Load player into the global players dict.""" session = Session() query = session.query(Player).filter_by(id=id) players[id] = query.one_or_none() or Player(id=id) @Event('player_leave') def save_player(id): """Save player into the database.""" session = Session() session.add(players[id]) session.commit() </code></pre> <p>Also, the player's score is updated upon <code>'player_kill'</code> event:</p> <pre><code>@Event('player_kill') def update_score(id, target_id): """Update players' scores upon a kill.""" players[id].score += 2 players[target_id].score -= 2 </code></pre>
15
2016-08-15T15:18:40Z
39,043,000
<p>Redis sorted sets help with this exact situation (the documentation uses leader boards as the example usage) <a href="http://redis.io/topics/data-types-intro#redis-sorted-sets">http://redis.io/topics/data-types-intro#redis-sorted-sets</a></p> <ul> <li>The key commands you care about are ZADD (update player rank) and ZRANK (get rank for specific player). Both operations are O(log(N)) complexity.</li> </ul> <p>Redis can be used as a cache of player ranking. When your application starts, populate redis from the SQL data. When updating player scores in mysql also update redis.</p> <p>If you have multiple server processes/threads and they could trigger player score updates concurrently then you should also account for the mysql/redis update race condition, eg:</p> <ul> <li>only update redis from a DB trigger; or</li> <li>serialise player score updates; or</li> <li>let data get temporarily out of sync and do another cache update after a delay; or</li> <li>let data get temporarily out of sync and do a full cache rebuild at fixed intervals</li> </ul>
6
2016-08-19T15:40:22Z
[ "python", "algorithm", "python-3.x", "ranking", "rank" ]
Can't access the variable inside the generated code from pyqt5
38,957,964
<p>this is my first post and I would like to thanks the amazing community of Stack Overflow for helping me during all this years! </p> <p>However, after extensive research, i couldn't find a solution to my problem. I have the file generated by QtCreator which contain a progressbar. In my code, I have 2 class, and 1 is a Thread. This Thread must change the value of the progressbar, but I completely fail to do so.</p> <p>I can't access the variable from my Thread, but i can from the init of Mainwindow. I think the problem is the nature of the "self" variable in setprogressBar, but I'm literally stuck finding out what it is.. </p> <p>When i tried to execute this code, here is the result : </p> <pre><code>File "C:\test.py", line 14, in setprogressBar self.progressBar.setProperty("value", pourcentage) AttributeError: type object 'MainWindow' has no attribute 'progressBar' </code></pre> <p>File A, generated with QtCreator : </p> <pre><code>from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") self.progressBar = QtWidgets.QProgressBar(self.widget) self.progressBar.setObjectName("progressBar") </code></pre> <p>File B, my code :</p> <pre><code>from PyQt5 import QtWidgets from UImainwindow import Ui_MainWindow from threading import Thread import sys class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): # access variables inside of the UI's file def __init__(self): super(MainWindow, self).__init__() self.setupUi(self) # gets defined in the UI file self.progressBar.setProperty("value", 24) #This is working def setprogressBar(self, pourcentage): self.progressBar.setProperty("value", pourcentage) #This is not class B(Thread): def __init__(self): Thread.__init__(self) def run(self): MainWindow.setprogressBar(MainWindow ,48) APP = QtWidgets.QApplication(sys.argv) Bi = B() Bi.start() MAINWIN = MainWindow() MAINWIN.show() APP.exec_() </code></pre> <p>Thx a lot for the help guys !</p>
0
2016-08-15T15:18:52Z
38,958,044
<p><code>MainWindow</code> is a class, not an object. What you should do instead is something like:</p> <pre><code>class B(Thread): def __init__(self, target): self.__target = target def run(self): self.__target.setprogressBar(48) MAINWIN = MainWindow() bi = B(MAINWIN) bi.start() MAINWIN.show() </code></pre>
0
2016-08-15T15:23:33Z
[ "python", "multithreading", "pyqt5" ]
The requested address is not valid in its context error
38,958,233
<p>I was following a tutorial called "Black Hat Python" and got a "the requested address is not valid in its context" error. I'm Python IDE version: 2.7.12 This is my code:</p> <pre><code>import socket import threading bind_ip = "184.168.237.1" bind_port = 21 server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((bind_ip,bind_port)) server.listen(5) print "[*] Listening on %s:%d" % (bind_ip,bind_port) def handle_client(client_socket): request = client_socket.rev(1024) print "[*] Recieved: %s" % request client_socket.close() while True: client,addr = server.accept() print "[*] Accepted connection from: %s:%d" % (addr[0],addr[1]) client_handler = threading.Thread(target=handle_client,args=(client,)) client_handler.start() </code></pre> <p>and this is my error:</p> <pre><code>Traceback (most recent call last): File "C:/Python34/learning hacking.py", line 9, in &lt;module&gt; server.bind((bind_ip,bind_port)) File "C:\Python27\lib\socket.py", line 228, in meth return getattr(self._sock,name)(*args) error: [Errno 10049] The requested address is not valid in its context &gt;&gt;&gt; </code></pre>
0
2016-08-15T15:36:35Z
38,958,939
<p>You are trying to bind to an IP address that is not actually assigned to your network interface:</p> <pre><code>bind_ip = "184.168.237.1" </code></pre> <p>See the <a href="https://msdn.microsoft.com/en-gb/library/windows/desktop/ms740668(v=vs.85).aspx" rel="nofollow"><em>Windows Sockets Error Codes</em> documentation</a>:</p> <blockquote> <p><strong>WSAEADDRNOTAVAIL</strong> 10049<br> <em>Cannot assign requested address.</em></p> <p>The requested address is not valid in its context. This normally results from an attempt to bind to an address that is not valid for the local computer.</p> </blockquote> <p>That may be an IP address that your router is listening to before using NAT (network address translation) to talk to your computer, but that doesn't mean your computer sees that IP address at all.</p> <p>Either bind to <code>0.0.0.0</code>, which will use all available IP addresses (both localhost and any public addresses configured):</p> <pre><code>bind_ip = "0.0.0.0" </code></pre> <p>or use any address that your computer is configured for; run <code>ipconfig /all</code> in a console to see your network configuration.</p> <p>You probably also don't want to use ports &lt; 1024; those are reserved for processes running as root only. You'll have to pick a higher number than that if you want to run an unprivileged process (and in the majority of tutorials programs, that is exactly what you want):</p> <pre><code>port = 5021 # arbitrary port number higher than 1023 </code></pre> <p>I believe the specific tutorial you are following uses <code>BIND_IP = '0.0.0.0'</code> and <code>BIND_PORT = 9090</code>.</p>
1
2016-08-15T16:22:18Z
[ "python", "python-2.7", "server" ]
Learning Python - syntax error preventing me from proceeding in tutorial
38,958,343
<p>As the title suggests I'm doing a tutorial. I have however come across this error:</p> <pre><code>&gt;&gt;&gt; from words import (fetch_words, print_words) &gt;&gt;&gt; print_words(fetch_words()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\jjosey\Documents\pyfund\words.py", line 12, in print_words for word in story_words: TypeError: 'NoneType' object is not iterable </code></pre> <p>When calling this file (words.py):</p> <pre><code>from urllib.request import urlopen def fetch_words(): with urlopen('http://sixty-north.com/c/t.txt') as story: story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) def print_words(story_words): for word in story_words: print(word) def main(): words = fetch_words() print_words(words) if __name__ == '__main__': main() </code></pre> <p>I understand that the error suggests I'm calling a null array. But this is exactly what the tutor does in the video, so I'm assuming I've made a typo somewhere that's caused the error to hit me. And this is day one of my learning Python, so I'm not spotting it.</p> <p>Any help appreciated. Thanks</p>
0
2016-08-15T15:45:08Z
38,958,402
<p>Try putting a <code>return</code> statement at the end of <code>fetch_words</code>. Without it, <code>words = fetch_words()</code> will cause <code>words</code> to be <code>None</code>.</p> <pre><code>def fetch_words(): with urlopen('http://sixty-north.com/c/t.txt') as story: story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) return story_words </code></pre>
4
2016-08-15T15:48:36Z
[ "python", "syntax" ]
Learning Python - syntax error preventing me from proceeding in tutorial
38,958,343
<p>As the title suggests I'm doing a tutorial. I have however come across this error:</p> <pre><code>&gt;&gt;&gt; from words import (fetch_words, print_words) &gt;&gt;&gt; print_words(fetch_words()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Users\jjosey\Documents\pyfund\words.py", line 12, in print_words for word in story_words: TypeError: 'NoneType' object is not iterable </code></pre> <p>When calling this file (words.py):</p> <pre><code>from urllib.request import urlopen def fetch_words(): with urlopen('http://sixty-north.com/c/t.txt') as story: story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) def print_words(story_words): for word in story_words: print(word) def main(): words = fetch_words() print_words(words) if __name__ == '__main__': main() </code></pre> <p>I understand that the error suggests I'm calling a null array. But this is exactly what the tutor does in the video, so I'm assuming I've made a typo somewhere that's caused the error to hit me. And this is day one of my learning Python, so I'm not spotting it.</p> <p>Any help appreciated. Thanks</p>
0
2016-08-15T15:45:08Z
38,958,417
<pre><code>def fetch_words(): with urlopen('http://sixty-north.com/c/t.txt') as story: story_words = [] for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) </code></pre> <p>This function has a bug... it does not <code>return</code> a value, though you try to use the returned value later. Try this...</p> <pre><code>def fetch_words(): story_words = [] with urlopen('http://sixty-north.com/c/t.txt') as story: for line in story: line_words = line.decode('utf-8').split() for word in line_words: story_words.append(word) return story_words </code></pre>
0
2016-08-15T15:49:24Z
[ "python", "syntax" ]
Get counts of specific values within a nested Python dictionary
38,958,380
<p>I have a giant nested dictionary (6k records) that I need to sort and count based on two values within my second dict. </p> <pre><code>item_dict = { 64762.0: { 'In Sheet': 'No', 'Paid': Y, 'Region': "AMER'", 'Matrix Position': 'Check' }, 130301.0: { 'Paid': N, 'Region': "AMER'", 'Matrix Position': 'Calculate' }, 13111.0: { 'In Sheet': 'Yes', 'Region': "EMEA'", 'Matrix Position': 'Check' }, 130321.0: { 'Matrix Position': 'Enhance', 'In Sheet': 'No', 'Paid': Y, 'Region': "JP'" } } </code></pre> <p>So, I need to get counts between regions and Matrix positions. So, I'd wind up with:</p> <pre><code>Amer and Calculate: 1 EMEA and Calculate: 0 EMEA and Check= 1 AMER and Check= 1 EMEA and Enhance= 0 JP and Check=0 </code></pre> <p>Et cetera. The thing is, the full data set has 5 regions with 4 potential matrix positions. Is the best way to do this by using a for loop to search for each potential combination, then adding that to its own list?</p> <pre><code>AmerCalculate=[] for row in item_dict: if item_dict[row]['Region'] == "AMER'" and item_dict[row]['Matrix Position'] == "Calculate": AmerCalculate.append(row) </code></pre> <p>Then, to get the lengths, do len(AmerCalculate)? Is there a more elegant way of doing this so I don't have to manually type out all 20 combinations? </p>
1
2016-08-15T15:47:18Z
38,958,710
<pre><code>AmerCalculate={} Regions = ["AMER", "EMEA", "JP"] Positions = ["Calculate", "Check"] for row in item_dict(): for region in regions: for pos in Positions: if (item_dict[row]['Region']==region) and (item_dict[row][MatrixPosition] == pos: AmerCalculate(str(region)+ ' and ' +str(pos) + ":")+=1 </code></pre> <p>This will return a dictionary with the format as follows: {<code>"region + matrixposition:": total}</code> for example <code>{Amer and Calculate: 1, EMEA and calculate: 1}</code></p> <p>Do you need to return the key? or just the totals of each position per region?</p>
0
2016-08-15T16:08:32Z
[ "python", "dictionary", "nested" ]
Get counts of specific values within a nested Python dictionary
38,958,380
<p>I have a giant nested dictionary (6k records) that I need to sort and count based on two values within my second dict. </p> <pre><code>item_dict = { 64762.0: { 'In Sheet': 'No', 'Paid': Y, 'Region': "AMER'", 'Matrix Position': 'Check' }, 130301.0: { 'Paid': N, 'Region': "AMER'", 'Matrix Position': 'Calculate' }, 13111.0: { 'In Sheet': 'Yes', 'Region': "EMEA'", 'Matrix Position': 'Check' }, 130321.0: { 'Matrix Position': 'Enhance', 'In Sheet': 'No', 'Paid': Y, 'Region': "JP'" } } </code></pre> <p>So, I need to get counts between regions and Matrix positions. So, I'd wind up with:</p> <pre><code>Amer and Calculate: 1 EMEA and Calculate: 0 EMEA and Check= 1 AMER and Check= 1 EMEA and Enhance= 0 JP and Check=0 </code></pre> <p>Et cetera. The thing is, the full data set has 5 regions with 4 potential matrix positions. Is the best way to do this by using a for loop to search for each potential combination, then adding that to its own list?</p> <pre><code>AmerCalculate=[] for row in item_dict: if item_dict[row]['Region'] == "AMER'" and item_dict[row]['Matrix Position'] == "Calculate": AmerCalculate.append(row) </code></pre> <p>Then, to get the lengths, do len(AmerCalculate)? Is there a more elegant way of doing this so I don't have to manually type out all 20 combinations? </p>
1
2016-08-15T15:47:18Z
38,958,810
<p>Use another dictionary to couple that data set together, from there you can generate the output you're looking for:</p> <pre><code>def dict_counter(dict_arg): d = {'AMER':[],'EMEA':[],'JP':[]} # Regions as keys. for int_key in dict_arg: sub_dict = dict_arg[int_key] for key, value in sub_dict.items(): if value in d: d[value].append(sub_dict['Matrix Position']) return d </code></pre> <p><strong>Sample Output:</strong></p> <pre><code>&gt;&gt;&gt; item_dict= {12.0: {'In Sheet': 'No', 'Paid': 'Y', 'Region': "AMER", 'Matrix Position': 'Enhance'},1232.0: {'In Sheet': 'No', 'Paid': 'Y', 'Region': "AMER", 'Matrix Position': 'Check'}, 64762.0: {'In Sheet': 'No', 'Paid': 'Y', 'Region': "AMER", 'Matrix Position': 'Check'}, 130301.0: {'Paid': 'N', 'Region': "AMER", 'Matrix Position': 'Calculate'}, 13111.0: {'In Sheet': 'Yes', 'Region': "EMEA", 'Matrix Position': 'Check'}, 130321.0: {'Matrix Position': 'Enhance','In Sheet': 'No', 'Paid': 'Y', 'Region': "JP"}} &gt;&gt;&gt; print dict_counter(item_dict) {'JP': ['Enhance'], 'AMER': ['Check', 'Calculate'], 'EMEA': ['Check']} </code></pre> <p>We now have the <em>basis</em> to generate the report you're looking for. We can use <code>Counter</code> to get a count of all position instances. Here's an example of how we could go about checking for counts in the <code>list</code> mapped value.</p> <pre><code>from collections import Counter d = dict_counter(item_dict) for k, v in d.items(): for i, j in Counter(v).items(): print k,'and',i,'=',j &gt;&gt;&gt; JP and Enhance = 1 &gt;&gt;&gt; AMER and Enhance = 1 &gt;&gt;&gt; AMER and Check = 2 &gt;&gt;&gt; AMER and Calculate = 1 &gt;&gt;&gt; EMEA and Check = 1 </code></pre>
1
2016-08-15T16:14:09Z
[ "python", "dictionary", "nested" ]
Get counts of specific values within a nested Python dictionary
38,958,380
<p>I have a giant nested dictionary (6k records) that I need to sort and count based on two values within my second dict. </p> <pre><code>item_dict = { 64762.0: { 'In Sheet': 'No', 'Paid': Y, 'Region': "AMER'", 'Matrix Position': 'Check' }, 130301.0: { 'Paid': N, 'Region': "AMER'", 'Matrix Position': 'Calculate' }, 13111.0: { 'In Sheet': 'Yes', 'Region': "EMEA'", 'Matrix Position': 'Check' }, 130321.0: { 'Matrix Position': 'Enhance', 'In Sheet': 'No', 'Paid': Y, 'Region': "JP'" } } </code></pre> <p>So, I need to get counts between regions and Matrix positions. So, I'd wind up with:</p> <pre><code>Amer and Calculate: 1 EMEA and Calculate: 0 EMEA and Check= 1 AMER and Check= 1 EMEA and Enhance= 0 JP and Check=0 </code></pre> <p>Et cetera. The thing is, the full data set has 5 regions with 4 potential matrix positions. Is the best way to do this by using a for loop to search for each potential combination, then adding that to its own list?</p> <pre><code>AmerCalculate=[] for row in item_dict: if item_dict[row]['Region'] == "AMER'" and item_dict[row]['Matrix Position'] == "Calculate": AmerCalculate.append(row) </code></pre> <p>Then, to get the lengths, do len(AmerCalculate)? Is there a more elegant way of doing this so I don't have to manually type out all 20 combinations? </p>
1
2016-08-15T15:47:18Z
38,958,867
<p>To get all combinations, you can use <code>itertools.product</code>. Then you can store the result in a dictionary:</p> <pre><code>result = {} for r, p in itertools.product(regions, positions): result[(r,p)] = len( [None for item in item_dict.values() if item['Region'] == r and item['Matrix Position'] == p] ) print(result[("AMER", "Calculate")]) </code></pre>
0
2016-08-15T16:17:31Z
[ "python", "dictionary", "nested" ]
Get counts of specific values within a nested Python dictionary
38,958,380
<p>I have a giant nested dictionary (6k records) that I need to sort and count based on two values within my second dict. </p> <pre><code>item_dict = { 64762.0: { 'In Sheet': 'No', 'Paid': Y, 'Region': "AMER'", 'Matrix Position': 'Check' }, 130301.0: { 'Paid': N, 'Region': "AMER'", 'Matrix Position': 'Calculate' }, 13111.0: { 'In Sheet': 'Yes', 'Region': "EMEA'", 'Matrix Position': 'Check' }, 130321.0: { 'Matrix Position': 'Enhance', 'In Sheet': 'No', 'Paid': Y, 'Region': "JP'" } } </code></pre> <p>So, I need to get counts between regions and Matrix positions. So, I'd wind up with:</p> <pre><code>Amer and Calculate: 1 EMEA and Calculate: 0 EMEA and Check= 1 AMER and Check= 1 EMEA and Enhance= 0 JP and Check=0 </code></pre> <p>Et cetera. The thing is, the full data set has 5 regions with 4 potential matrix positions. Is the best way to do this by using a for loop to search for each potential combination, then adding that to its own list?</p> <pre><code>AmerCalculate=[] for row in item_dict: if item_dict[row]['Region'] == "AMER'" and item_dict[row]['Matrix Position'] == "Calculate": AmerCalculate.append(row) </code></pre> <p>Then, to get the lengths, do len(AmerCalculate)? Is there a more elegant way of doing this so I don't have to manually type out all 20 combinations? </p>
1
2016-08-15T15:47:18Z
38,959,121
<p>Is it critical for you to use pure <code>Python</code>? I guess, if you wanted just to do this once, you could do this without care of performance or beauty, either you want to know something new.</p> <p>What's about <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a> library which can solve this problem in fast and elegant way without ugly loops? It allows to group your data in way you want to and manipulate it. For example, this code</p> <pre><code>data_frame.groupby(['Region', 'Matrix Position'])['Matrix Position'].count() </code></pre> <p>Will give you what you wanted without doing any loops, not needed subroutines in fast and convenient way</p> <pre><code>Region Matrix Position AMER' Calculate 1 Check 1 EMEA' Check 1 JP' Enhance 1 </code></pre> <p>It may help you to continue processing/preparation of your data as it has a lot of abilities for data processing and analysis.</p> <p>One more example: following code will calculate amount of rows with <code>AMER'</code> region and <code>Check</code> matrix position</p> <pre><code>from pandas import DataFrame data_frame = DataFrame(item_dict).transpose() filtered_data = data_frame[(data_frame['Region'] == "AMER'") &amp; (data_frame['Matrix Position'] == 'Check')] result = len(filtered_data.index) </code></pre>
0
2016-08-15T16:34:17Z
[ "python", "dictionary", "nested" ]
requests.get returns <!doctype> instead <Response>
38,958,492
<p>I have an issue with requests.get(). If I paste the URL manually into the code as here:</p> <pre><code>r = requests.get('https://berlin.kauperts.de/Strassen/Igelsteig-12557-Berlin.html') print(r) </code></pre> <p>I get: <code>&lt;Response [200]&gt;</code>. Which works quite fine. Instead if I try to ask for the requests out of a list of files as in:</p> <pre><code>indir = '/home/d/Desktop/civiv_hacking/Streetnames/dump/berlin.kauperts.de/Strassen' for root, dirs, filenames in os.walk(indir): for z in filenames: x = urlparse.urljoin('https://berlin.kauperts.de/Strassen/', z+'/'), [t[0] for t in x], print(t), for r in requests.get(t): print(r), </code></pre> <p>I get: <code>https://berlin.kauperts.de/Strassen/Igelsteig-12557-Berlin/ &lt;!DOCTYPE html&gt; &lt;html lang="de" xml:lang="de" xmlns="http://www.w3.org/1999/xhtml"&gt; </code> How can I make requests.get() return <code>&lt;Response [200]&gt;</code> instead of just the doctype information?</p>
0
2016-08-15T15:54:27Z
38,958,539
<p>If you want to see the <a href="http://docs.python-requests.org/en/master/api/#requests.Response" rel="nofollow"><code>Response</code></a> <em>string representation</em>, you should not be iterating over it, just print:</p> <pre><code>url = urlparse.urljoin('https://berlin.kauperts.de/Strassen/', z) response = requests.get(url) print(response) # would print "&lt;Response [200]&gt;" </code></pre>
1
2016-08-15T15:57:38Z
[ "python", "parsing", "url", "request", "python-requests" ]
Comparing content in two csv files
38,958,591
<p>So I have two csv files. <code>Book1.csv</code> has more data than <code>similarities.csv</code> so I want to pull out the rows in <code>Book1.csv</code> that <strong>do not</strong> occur in <code>similarities.csv</code> Here's what I have so far </p> <pre><code> with open('Book1.csv', 'rb') as csvMasterForDiff: with open('similarities.csv', 'rb') as csvSlaveForDiff: masterReaderDiff = csv.reader(csvMasterForDiff) slaveReaderDiff = csv.reader(csvSlaveForDiff) testNotInCount = 0 testInCount = 0 for row in masterReaderDiff: if row not in slaveReaderDiff: testNotInCount = testNotInCount + 1 else : testInCount = testInCount + 1 print('Not in file: '+ str(testNotInCount)) print('Exists in file: '+ str(testInCount)) </code></pre> <p>However, the results are</p> <pre><code>Not in file: 2093 Exists in file: 0 </code></pre> <p>I know this is incorrect because at least the first 16 entries in <code>Book1.csv</code> do not exist in <code>similarities.csv</code> not all of them. What am I doing wrong?</p>
1
2016-08-15T16:00:57Z
38,958,706
<p>A <code>csv.reader</code> object is an <em>iterator</em>, which means you can only iterate through it <strong>once</strong>. You should be using lists/sets for containment checking, e.g.:</p> <pre><code>slave_rows = set(slaveReaderDiff) for row in masterReaderDiff: if row not in slave_rows: testNotInCount += 1 else: testInCount += 1 </code></pre>
1
2016-08-15T16:08:16Z
[ "python", "csv" ]
Comparing content in two csv files
38,958,591
<p>So I have two csv files. <code>Book1.csv</code> has more data than <code>similarities.csv</code> so I want to pull out the rows in <code>Book1.csv</code> that <strong>do not</strong> occur in <code>similarities.csv</code> Here's what I have so far </p> <pre><code> with open('Book1.csv', 'rb') as csvMasterForDiff: with open('similarities.csv', 'rb') as csvSlaveForDiff: masterReaderDiff = csv.reader(csvMasterForDiff) slaveReaderDiff = csv.reader(csvSlaveForDiff) testNotInCount = 0 testInCount = 0 for row in masterReaderDiff: if row not in slaveReaderDiff: testNotInCount = testNotInCount + 1 else : testInCount = testInCount + 1 print('Not in file: '+ str(testNotInCount)) print('Exists in file: '+ str(testInCount)) </code></pre> <p>However, the results are</p> <pre><code>Not in file: 2093 Exists in file: 0 </code></pre> <p>I know this is incorrect because at least the first 16 entries in <code>Book1.csv</code> do not exist in <code>similarities.csv</code> not all of them. What am I doing wrong?</p>
1
2016-08-15T16:00:57Z
38,958,803
<p>After converting it into <code>sets</code>, you can do a lot of <code>set</code> related &amp; helpful operation without writing much of a code.</p> <pre><code>slave_rows = set(slaveReaderDiff) master_rows = set(masterReaderDiff) master_minus_slave_rows = master_rows - slave_rows common_rows = master_rows &amp; slave_rows print('Not in file: '+ str(len(master_minus_slave_rows))) print('Exists in file: '+ str(len(common_rows))) </code></pre> <p>Here are various <a href="https://docs.python.org/2.7/library/stdtypes.html#set" rel="nofollow">set operations</a> that you can do.</p>
0
2016-08-15T16:13:55Z
[ "python", "csv" ]
Pandas: create json file from dataframe
38,958,639
<p>I have dataframe</p> <pre><code>ID, visiting 111, 03.2015 111, 07.2015 111, 05.2016 222, 12.2013 222, 04.2016 333, 02.2014 333, 06.2015, 333, 11.2015 </code></pre> <p>I need to get file like this(I need to specify all month since december 2013 to june 2016)</p> <pre><code>{ "111": { "2013-12": 0, "2014-01": 0, "2014-02": 0, "2014-03": 0, "2014-04": 0, "2014-05": 0, "2014-06": 0, "2014-07": 0, "2014-08": 0, "2014-09": 0, "2014-10": 0, "2014-11": 0, "2014-12": 0, "2015-01": 0, "2015-02": 0, "2015-03": 1, "2015-04": 0, "2015-05": 0, "2015-06": 0, "2015-07": 1, "2015-08": 0, "2015-09": 0, "2015-10": 0, "2015-11": 0, "2015-12": 0, "2016-01": 0, "2016-02": 0, "2016-03": 0, "2016-04": 0, "2016-05": 1, "2016-06": 0 }, "222": { ... } } </code></pre> <p>How can I get that from Pandas?</p>
-1
2016-08-15T16:03:45Z
38,958,959
<p>It would by more efficent using <code>groupby</code>s, but this gets the job done:</p> <pre><code>txt = """ID, visiting 111, 03.2015 111, 07.2015 111, 05.2016 222, 12.2013 222, 04.2016 333, 02.2014 333, 06.2015 333, 11.2015""" split = [line.split(', ') for line in txt.split('\n')] df = pd.DataFrame(split[1:], columns=split[0]) results = {} for ID in df.ID.unique(): results[ID] = {} for year in range(2013, 2017): if year == 2013: months = [12] elif year == 2016: months = range(1, 7) else: months = range(1, 13) for month in months: search_text = '{:02d}.{}'.format(month, year) result_text = '{}-{:02d}'.format(year, month) for ID in df.ID.unique(): if len(df[(df.ID == ID)&amp;(df.visiting == search_text)]) &gt; 0: boolean = 1 else: boolean = 0 results[ID][result_text] = boolean import json results = json.dumps(results) </code></pre>
0
2016-08-15T16:23:44Z
[ "python", "json", "pandas" ]
Using python multiprocess outside the main script
38,958,640
<p>According to the <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing-programming" rel="nofollow">docs</a> of python's multiprocess the spawning of process needs to be inside of the <code>if __name__ == '__main__':</code> clause to prevent spawning infinite processes.</p> <p>My question, is it possible to use multiprocess inside of an import?</p> <p>Something along those lines of this: let's say I have this py which is the main executed file:</p> <pre><code>import foo def main(): foo.run_multiprocess() if __name__ =='__main__': main() </code></pre> <p>and the foo.py file which is imported:</p> <pre><code>def run_multiprocess(number_to_check): if number_to_check == 5: print(number_to_check) if __name__ == '__main__': list_to_check = {1,2,3,4,5,6,7} pool = Pool(processes=4) pool.map(process_image, list_to_check) </code></pre> <p>Obviusly this won't work because the code inside the if statment in foo.py won't run. Is there a way to make it work though?</p>
0
2016-08-15T16:03:46Z
38,959,596
<p>Multiprocessing doesn't have to run within the <code>__main__</code> block, <code>__main__</code> block is only used if the file is ran via <code>python filename.py</code>.</p> <p>So if you did:</p> <p><code>m1.py</code>:</p> <pre><code>from multiprocessing import Pool def f(x): return x^2 def f2(): p = Pool(5) p.map(f, [1,2,3,4,5]) </code></pre> <p><code>m2.py</code>:</p> <pre><code>from m1 import f2 def __main__(): # this is not required, but a good practice f2() # this would run multiprocessing code </code></pre> <p>and then call <code>python m2.py</code>, your code would run correctly, with mp.</p>
0
2016-08-15T17:05:34Z
[ "python", "python-3.x", "python-multithreading", "python-multiprocessing" ]
How to make a plot of data from several sheets in same excel file by using Python pandas
38,958,654
<p>I have 4 sheets, they have same numbers of columns and same numbers of data.</p> <p>But I want to make a plot of pressure as y while date as X. So there will be four lines in one graph. I can make them separately but not all together. The date is all same in the four sheets but for each date, each sheet may have different amount values.That's something you can find in my codes about is_basin_name to help to select only one pressure for each time. Do I need to select these to make a new sheet? Or is there an alternative way to make this plot?</p> <p>Here are the codes of my single sheet's plot:</p> <pre><code>import pandas as pd import pandas as pd import numpy as np import matplotlib.pyplot as plt a=pd.read_excel('mslp0.0001.xlsx', '0.1-20', index_col=None, na_values=['NA']) c=[] c=a[['basin name','lead time(hours)','max 10-m wind 9kt0','min MSLP(hPa)','wind speed threshold(kt)']] is_basin_name = a['lat*10'] &gt; 0 is_wind_thresh =a['wind speed threshold(kt)'] == 34 #data to make a plot of mslp and 10m wind with leading time valid_data = a[is_basin_name &amp; is_wind_thresh] #plot of mslp and lead time ax=valid_data.plot(kind='line',x='lead time(hours)',y='min MSLP(hPa)') plt.show() </code></pre> <p>The excel file (cannot make a table here, so describe):</p> <p>There are two columns for each sheet, date and pressure.</p>
0
2016-08-15T16:04:36Z
38,959,228
<p>I'm assuming you are trying to merge and plot all the data coming from the four sheets. In this case, you could load data from each sheet into a pandas df and merge them together. This is made easier given that your sheets have the same amount of data. You can use pandas directly:</p> <pre><code>import pandas as pd data = pd.ExcelFile(".../pressure_data.xlsx") list_dfs = [] sheets = data.sheet_names for sheet in sheets: list_dfs = data.parse(sheet) df = pd.concat(list_dfs) #plot </code></pre> <p><a href="http://pandas.pydata.org/pandas-docs/stable/merging.html" rel="nofollow">pandas concat</a>: see first example. </p> <p>By the way, what does this mean? 'Date pressure 1. 1 2. 2 3. 2 4. 2'</p>
0
2016-08-15T16:41:22Z
[ "python", "excel", "pandas" ]
How to make a plot of data from several sheets in same excel file by using Python pandas
38,958,654
<p>I have 4 sheets, they have same numbers of columns and same numbers of data.</p> <p>But I want to make a plot of pressure as y while date as X. So there will be four lines in one graph. I can make them separately but not all together. The date is all same in the four sheets but for each date, each sheet may have different amount values.That's something you can find in my codes about is_basin_name to help to select only one pressure for each time. Do I need to select these to make a new sheet? Or is there an alternative way to make this plot?</p> <p>Here are the codes of my single sheet's plot:</p> <pre><code>import pandas as pd import pandas as pd import numpy as np import matplotlib.pyplot as plt a=pd.read_excel('mslp0.0001.xlsx', '0.1-20', index_col=None, na_values=['NA']) c=[] c=a[['basin name','lead time(hours)','max 10-m wind 9kt0','min MSLP(hPa)','wind speed threshold(kt)']] is_basin_name = a['lat*10'] &gt; 0 is_wind_thresh =a['wind speed threshold(kt)'] == 34 #data to make a plot of mslp and 10m wind with leading time valid_data = a[is_basin_name &amp; is_wind_thresh] #plot of mslp and lead time ax=valid_data.plot(kind='line',x='lead time(hours)',y='min MSLP(hPa)') plt.show() </code></pre> <p>The excel file (cannot make a table here, so describe):</p> <p>There are two columns for each sheet, date and pressure.</p>
0
2016-08-15T16:04:36Z
38,965,617
<p>I don't have your excel file so you'll need to test it yourself.</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt #sheetname=None will load all sheets in to a dict of dataframes dict_of_df = pd.read_excel('mslp0.0001.xlsx', sheetname=None, index_col=None, na_values=['NA']) ax = None for sheet, df in dict_of_df.iteritems(): is_basin_name = df['lat*10'] &gt; 0 is_wind_thresh = df['wind speed threshold(kt)'] == 34 #data to make a plot of mslp and 10m wind with leading time valid_data = df[is_basin_name &amp; is_wind_thresh] #plot of mslp and lead time ax = valid_data.plot(kind='line',x='lead time(hours)',y='min MSLP(hPa)', ax=ax, label=sheet) #ax=ax will re-use the same ax for plotting so your lines will be in the same chart. When hitting this line for the first time, ax=None so a new chart will be created. Use label=sheet to identify which line is from which sheet. plt.legend(loc=0) #probably legend is shown by default already. plt.show() </code></pre>
0
2016-08-16T02:06:28Z
[ "python", "excel", "pandas" ]
BeautifulSoup confused
38,958,697
<p>I am working on script in python with BeautifulSoup to find some data from html. I got a stacked and so much confused, my brain stopped working, I don't have any idea how to scrape full address of these elements:</p> <pre><code>&lt;li class="spacer"&gt; &lt;span&gt;Location:&lt;/span&gt; &lt;br&gt;Some Sample Street&lt;br&gt; Abbeville, AL 00000 &lt;/li&gt; </code></pre> <p>I have tried something like <code>location = info.find('li', 'spacer').text</code> but still I got only string "Location: " . Tried with many parents - child relations but still can't figure out how to scrape this one..</p> <p>Can anybody help me?</p>
0
2016-08-15T16:07:41Z
38,958,944
<p>Try this out:</p> <pre><code>locations = info.find_all('span',Class_="spacer") for location in locations: print (location.text) </code></pre>
0
2016-08-15T16:22:47Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
BeautifulSoup confused
38,958,697
<p>I am working on script in python with BeautifulSoup to find some data from html. I got a stacked and so much confused, my brain stopped working, I don't have any idea how to scrape full address of these elements:</p> <pre><code>&lt;li class="spacer"&gt; &lt;span&gt;Location:&lt;/span&gt; &lt;br&gt;Some Sample Street&lt;br&gt; Abbeville, AL 00000 &lt;/li&gt; </code></pre> <p>I have tried something like <code>location = info.find('li', 'spacer').text</code> but still I got only string "Location: " . Tried with many parents - child relations but still can't figure out how to scrape this one..</p> <p>Can anybody help me?</p>
0
2016-08-15T16:07:41Z
38,977,308
<p>You can use the <a href="https://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#nextSibling%20and%20previousSibling" rel="nofollow">nextSibling</a> to navigate to the next elements inside the <code>li</code> and after the <code>span</code></p> <p>Example:</p> <pre><code>from bs4 import BeautifulSoup as Soup html_text= """ &lt;li class="spacer"&gt; &lt;span&gt;Location:&lt;/span&gt; &lt;br&gt;Some Sample Street&lt;br&gt; Abbeville, AL 00000 &lt;/li&gt; """ location_address = "" html_souped = Soup(html_text, 'html.parser') # get the next sibling after the span: siblings = html_souped.find('li', {'class': 'spacer'}).find('span').nextSibling # iterate until the end of the li element: while siblings.nextSibling is not None: # add the text to the location: location_address += siblings.nextSibling.text siblings = siblings.nextSibling # print the stripped location: print('location: ' + location_address.strip()) </code></pre> <p>This will work perfectly for all your list if the list has the same format as your given example. </p>
0
2016-08-16T14:15:39Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
Python script doesn't delete file from archive -- printed command via terminal works fine
38,958,760
<p>I'm creating an archive in Python using this code:</p> <pre><code>#Creates archive using string like [proxy_16-08-15_08.57.07.tar] proxyArchiveLabel = 'proxy_%s' % EXECUTION_START_TIME + '.tar' log.info('Packaging %s ...' % proxyArchiveLabel) #Removes .tar from label during creation shutil.make_archive(proxyArchiveLabel.rsplit('.',1)[0], 'tar', verbose=True) </code></pre> <p>So this creates an archive fine in the local directory. The problem is, there's a specific directory in my archive I want to remove, due to it's size and lack of necessity for this task.</p> <pre><code>ExecWithLogging('tar -vf %s --delete ./roles/jobs/*' % proxyArchiveLabel) # ------------ def ExecWithLogging(cmd): print cmd p = subprocess.Popen(cmd.split(' '), env=os.environ, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while(True): log.info(p.stdout.readline().strip()) if(p.poll() is not None): break </code></pre> <p>However, this seems to do basically nothing. The size remains the same. If I print <code>cmd</code> inside of the <code>ExecWithLogging</code>, and copy/past that command to a terminal in the working directory of the script, it works fine. Just to be sure, I also tried hard-coding the full path to where the archive is created as part of the <code>tar -vf %s --delete</code> command, but still nothing seemed to happen.</p> <p>I do get this output in my INFO log: <code>tar: Pattern matching characters used in file names</code>, so I'm kind of thinking <code>Popen</code> is interpreting my command incorrectly somehow... (or rather, I'm more likely passing in something incorrectly). </p> <p>Am I doing something wrong? What else can I try?</p>
0
2016-08-15T16:11:21Z
38,958,998
<p>You may have to use the <code>--wildcards</code> option in the tar command, which enables pattern matching. This may well be what you are seeing in your log, be it somewhat cryptically.</p> <p>Edit: In answer to your question Why? I suspect that the shell is performing the wildcard expansion whilst the command proffered through Popen is not. The --wildcard option for tar, forces tar to perform the wildcard expansion.<br> For a more detailed explanation see here:<br> <a href="http://aplawrence.com/Linux/tar_wilcards.html" rel="nofollow">Tar and wildcards</a> </p>
2
2016-08-15T16:26:36Z
[ "python", "python-2.7", "command", "archive" ]
browser automation with PhantomJS and Firefox, support of the different browsers
38,958,761
<p>Why the code works with webdriver.Firefox but do not work with webdriver.PhantomJS ?</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.PhantomJS() # why not? # driver.set_window_size(1400, 1050) # driver = webdriver.Firefox() # Firefox 45, works correctly driver.get("https://www.rec-registry.gov.au/rec-registry/app/public/lgc-register") driver.find_elements_by_tag_name('button')[4].click() # status # show the needed elements for the next action, # enter(open the door) to the div.ms-drop area driver.find_elements_by_class_name('ms-drop')[4].find_element_by_css_selector('ul&gt;li:nth-child(12)').click() # registered driver.find_element_by_id('search-submit').send_keys(Keys.RETURN) # search driver.save_screenshot('lgc1.png') </code></pre>
1
2016-08-15T16:11:21Z
38,959,160
<p>You should try using <code>.click()</code> for click purpose instead of <code>send_keys(Keys.RETURN)</code> as below :</p> <pre><code>driver.find_element_by_id('search-submit').click() </code></pre>
0
2016-08-15T16:36:40Z
[ "python", "selenium", "selenium-webdriver", "phantomjs", "browser-automation" ]
Not getting ord() of hexadecimal values when reading from file
38,958,786
<p>Suppose <code>a = '\x00\x01\x02'</code></p> <p>Now when I use <code>ord()</code> by looping through <code>a</code>, I get the output I want.</p> <p><strong>Program:</strong></p> <pre><code>for i in a: ord(i) </code></pre> <p><strong>Output:</strong></p> <pre><code>0 1 2 </code></pre> <p>But now when I do the same by reading from a file, I keep getting TypeError.</p> <p>This is what I did- I created a file named <em>abc.txt</em>. Inside <em>abc.txt</em> there is the same string as <code>a</code>which is <code>'\x00\x01\x02'</code>.</p> <p>This is the program I wrote for going through the contents of the file:</p> <pre><code>file = open('abc.txt', 'r') for i in file: ord(i) file.close() </code></pre> <p>And this is the error I get:</p> <pre><code>TypeError: ord() expected a character, but string of length 15 found </code></pre> <p>Where am I going wrong? It works perfectly fine when I'm assigning the string to a variable but I keep getting error when I'm performing the same operation while reading from a file.</p> <p><strong>EDIT</strong></p> <p>I tried Morgan Thrapp's solution and it worked. But now I have another problem. When I'm looping through <code>a</code>, I get the ord() of the hexadecimal values given in the string. But when I'm going by Morgan's method, I get the ord() of single characters in the string. The program doesn't see it as hexadecimal values in the string while looping. I also changed the title so that it is more clear what I'm trying to do.</p>
-2
2016-08-15T16:12:47Z
38,958,861
<p>The problem is that you're iterating over the file line by line, but the string character by character.</p> <p>The easiest way is to either use a second nested loop, or <code>map</code>.</p> <pre><code>with open('abc.txt') as input_file: for line in input_file: for character in line: print(ord(character)) </code></pre>
2
2016-08-15T16:17:14Z
[ "python", "python-2.7" ]
Add data to Django database through views or JSON dictionary
38,958,844
<p>I have been searching through various opensource forums for a definitive answer on how to do this. I am open to any number of methods, but I am a little green at Django and Python for that matter so please bare with me. </p> <p>The simplest of my tables is as follows:</p> <pre><code>class Player(models.Model): number = models.CharField(max_length=2) player = models.CharField(max_length=50) position = models.CharField(max_length=2) height = models.CharField(max_length=50) weight = models.CharField(max_length=50) birth = models.DateField() exp = models.CharField(max_length=50) college = models.CharField(max_length=50) def __str__(self): return self.player </code></pre> <p>I have a list of over 500 players with these data associated, and I've also been able to create a JSON string that reads as:</p> <pre><code>[ {"number": playernumber, "player": playername, "position": playerposition, "height":playerheight, "weight": playerweight, "birth":playerbirthdate "exp": playerexperience "college": playercollege } ] </code></pre> <p>I believe that the documentation has changed recently to promote the use of data migrations, but I'm a bit unclear on whether that is to change the fields of the data or to actually enter bits of data into this. Also, the JSON string might change from time-to-time (either adding records or editing fields) so I'd like to have a bit of flexibility with how this data gets entered into the database.</p> <p>I am also open to entering this data through a view, but I'm not sure on how to execute that view to get the data into the database.</p> <p>I hope that I have made my issue clear. </p> <p>Thanks for any help.</p> <p>Aaron</p>
0
2016-08-15T16:15:59Z
38,958,907
<p>I can suggest two options:</p> <ol> <li>Through the view. Eventually you create a <code>FormView</code> with a form to upload a file or just a textbox and handle the json on backend.</li> <li>You may create a manage.py command that receives path to a file as a parameter.</li> </ol> <p>In both cases handling of your json will look like follows regardless of where you put it:</p> <pre><code>json_objects = json.loads(raw_json) objects = [] for json_obj in json_objects: objects.append(Player(** json_obj)) Player.objects.bulk_create(objects) </code></pre> <p>You may delete all players with <code>Player.objects.all().delete()</code> before executing <code>bulk_create</code> in case you are need to refresh all players. Alternatively, you have an option to use <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#update-or-create" rel="nofollow">update_or_create</a> method to update existing objects while creating new ones.</p>
0
2016-08-15T16:20:16Z
[ "python", "json", "django", "models" ]
Appengine throwing BadRequestError: The property.name is the empty string
38,958,864
<p>I have an application that has worked successfully in the past. Today however, it's started throwing an error when I try write to datastore. For example, I'm creating a new entity of this model</p> <pre><code> class EventInstallment(ndb.Model): somekey = ndb.KeyProperty() somename = ndb.StringProperty(default = "") start_date = ndb.DateTimeProperty() notes = ndb.StringProperty("") moderator_approved = ndb.BooleanProperty(default = True) added_by = ndb.KeyProperty() created = ndb.DateTimeProperty(auto_now_add = True) </code></pre> <p>using this code</p> <pre><code> ins = somemodel() ins.somename = "26-september-2016" ins.somekey = the_key ins.start_date = datetime.datetime.now() ins.put() </code></pre> <p>and this exception gets thrown.</p> <pre><code> Traceback (most recent call last): File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/admin/__init__.py", line 363, in post exec(compiled_code, globals()) File "&lt;string&gt;", line 8, in &lt;module&gt; File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/model.py", line 3451, in _put return self._put_async(**ctx_options).get_result() File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 383, in get_result self.check_success() File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 427, in _help_tasklet_along value = gen.throw(exc.__class__, exc, tb) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/context.py", line 824, in put key = yield self._put_batcher.add(entity, options) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 427, in _help_tasklet_along value = gen.throw(exc.__class__, exc, tb) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/context.py", line 358, in _put_tasklet keys = yield self._conn.async_put(options, datastore_entities) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/ext/ndb/tasklets.py", line 513, in _on_rpc_completion result = rpc.get_result() File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/api/apiproxy_stub_map.py", line 613, in get_result return self.__get_result_hook(self) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 1881, in __put_hook self.check_rpc_success(rpc) File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/datastore/datastore_rpc.py", line 1373, in check_rpc_success raise _ToDatastoreError(err) BadRequestError: The property.name is the empty string. </code></pre> <p>Any idea what this issue might be? It looks like a change in GAE ndb - as it worked as recently as 1 month ago...</p>
0
2016-08-15T16:17:18Z
38,960,654
<p>Shouldn't <code>notes = ndb.StringProperty("")</code> be: <code>notes = ndb.StringProperty(default = "")</code> ?</p>
1
2016-08-15T18:19:00Z
[ "python", "google-app-engine", "app-engine-ndb" ]
only 404s returned when using ngrok for kik
38,958,913
<p>I'm trying to develop a kik bot. I used ngrok to tunnel my localhost to a ngrok server. However, whenever I run my python program and start the ngrok server and message the bot on my phone, all it returns are 404 errors. Here is my python code </p> <pre><code>from flask import Flask, request, Response import os from kik import KikApi, Configuration from kik.messages import messages_from_json, TextMessage app = Flask(__name__) BOT_USERNAME = os.environ.get('BOT_USERNAME') BOT_API_KEY = os.environ.get('BOT_API_KEY') kik = KikApi(BOT_USERNAME, BOT_API_KEY) kik.set_configuration(Configuration(webhook='my_webhook')) @app.route('/incoming', methods=['POST']) def incoming(): if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()): return Response(status=403) messages = messages_from_json(request.json['messages']) for message in messages: if isinstance(message, TextMessage): kik.send_messages([ TextMessage( to=message.from_user, chat_id=message.chat_id, body=message.body ) ]) return Response(status=200) if __name__ == "__main__": app.run(port=8080, debug=True) </code></pre> <p>Basically, when I run this file, ngrok and the localhost tell me "404 not found". I followed the directions <a href="https://dev.kik.com/#/docs/messaging#api-authentication-with-webhook-endpoint" rel="nofollow">here</a> and made a POST to set up my bot's configuration. When I check the kik bot for the webhook, it shows the ngrok url. Is there something else I need to do to be able to send messages to the bot as a normal user? I know the kik authenticates using the "X-Kik-Username", so does that have something to do with it? </p> <p><a href="http://i.stack.imgur.com/W4vne.png" rel="nofollow">Error messages from ngrok</a></p>
0
2016-08-15T16:20:38Z
39,002,146
<p>I figured it out. I changed the route in the code from "/incoming" to "/". That allowed for the right response. </p>
0
2016-08-17T16:45:05Z
[ "python", "flask", "http-status-code-404", "bots", "ngrok" ]
How to plot a "grouped scatterplot" with non-categorical data?
38,958,925
<p>I am a bit confused how to use <code>seaborn.stripplot()</code> to plot multiple columns of data points when these data do not have "categorical" labels. </p> <p>For example, users can plot "grouped" scatterplots as follows, with the <code>tips</code> dataset:</p> <pre><code>import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import seaborn as sns tips = sns.load_dataset("tips") # internal dataset print(tips) total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 4 24.59 3.61 Female No Sun Dinner 4 5 25.29 4.71 Male No Sun Dinner 4 .... ..... ..... ..... </code></pre> <p>There are measurements grouped together by the category <code>day</code>, whereby we produce scatterplots as follows:</p> <pre><code>sns.stripplot(x="day", y="total_bill", data=tips) </code></pre> <p><a href="http://i.stack.imgur.com/Onnji.png" rel="nofollow"><img src="http://i.stack.imgur.com/Onnji.png" alt="enter image description here"></a></p> <p>Now, I would like to re-produce this "grouped scatterplot format" plot with non-categorical data, with data in each column:</p> <pre><code>df = pd.read_csv("my_data.csv") df total_bill_A total_bill_B total_bill_C total_bill_D 0 16.99 21.01 15.99 14.50 1 10.34 21.66 12.99 16.50 2 21.01 23.50 7.25 17.50 3 23.68 23.31 9.99 12.50 4 24.59 23.61 10.00 15.50 5 25.29 24.71 11.00 19.50 .... .... </code></pre> <p>The y-axis here is <code>price</code>, and the x axis should be each of these columns, <code>total_bill_A</code>, <code>total_bill_B</code>, <code>total_bill_C</code>, and <code>total_bill_D</code>, similar to the above for Thursday, Friday, Saturday, Sunday.</p> <p>How could I plot something like these <code>seaborn</code>? Is it possible to do this with <code>seaborn.stripplot()</code>? </p>
0
2016-08-15T16:21:25Z
38,959,936
<p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow"><code>melt</code></a> the dataframe and name the parameters accordingly to apply to the <code>stripplot</code> as follows:</p> <pre><code>df_strip = pd.melt(df, var_name='total_bill', value_name='price') sns.stripplot(x="total_bill", y="price", data=df_strip) </code></pre> <p><a href="http://i.stack.imgur.com/W3uMU.png" rel="nofollow"><img src="http://i.stack.imgur.com/W3uMU.png" alt="Image"></a></p>
3
2016-08-15T17:31:15Z
[ "python", "pandas", "matplotlib", "plot", "seaborn" ]
Python descending list
38,958,929
<p>I want to make a functions which return false if the list input in the function is not in descending order ,</p> <p>now for descending([19,17,18,7]) it returns true </p> <p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p> <pre><code>def des(l): for i in range(len(l)): if (l[i]&lt;l[i+1]): return [False,i] else: return True </code></pre>
0
2016-08-15T16:21:34Z
38,959,030
<p>Try this out:</p> <pre><code>def des(l): for x in l: try: if x &lt; l[l.index(x)+1 ]-1: return True except: pass return False </code></pre>
0
2016-08-15T16:28:42Z
[ "python", "python-2.7", "python-3.x" ]
Python descending list
38,958,929
<p>I want to make a functions which return false if the list input in the function is not in descending order ,</p> <p>now for descending([19,17,18,7]) it returns true </p> <p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p> <pre><code>def des(l): for i in range(len(l)): if (l[i]&lt;l[i+1]): return [False,i] else: return True </code></pre>
0
2016-08-15T16:21:34Z
38,959,034
<p>It can be written in a more declarative way:</p> <pre><code>def is_descending(array): return array == sorted(array, reverse=True) </code></pre> <p>Or, for python3:</p> <pre><code>def is_descending(array): return array == list(sorted(array, reverse=True)) </code></pre>
3
2016-08-15T16:28:51Z
[ "python", "python-2.7", "python-3.x" ]
Python descending list
38,958,929
<p>I want to make a functions which return false if the list input in the function is not in descending order ,</p> <p>now for descending([19,17,18,7]) it returns true </p> <p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p> <pre><code>def des(l): for i in range(len(l)): if (l[i]&lt;l[i+1]): return [False,i] else: return True </code></pre>
0
2016-08-15T16:21:34Z
38,959,036
<p>Your code doesn't work because you are returning <code>True</code>/<code>False</code> after one check. You should return <code>True</code> only after you check the entire list. Following is one way of doing it:</p> <pre><code>def des(l): for i in range(1,len(l)): if (l[i] &gt; l[i-1]): return False return True l = [19,17,12,10] print (des(l)) </code></pre>
2
2016-08-15T16:28:56Z
[ "python", "python-2.7", "python-3.x" ]
Python descending list
38,958,929
<p>I want to make a functions which return false if the list input in the function is not in descending order ,</p> <p>now for descending([19,17,18,7]) it returns true </p> <p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p> <pre><code>def des(l): for i in range(len(l)): if (l[i]&lt;l[i+1]): return [False,i] else: return True </code></pre>
0
2016-08-15T16:21:34Z
38,959,057
<p>Here is another way to write your function:</p> <pre><code>def des(l): return all(i&gt;j for i,j in zip(l,l[1:])) </code></pre>
1
2016-08-15T16:30:32Z
[ "python", "python-2.7", "python-3.x" ]
Python descending list
38,958,929
<p>I want to make a functions which return false if the list input in the function is not in descending order ,</p> <p>now for descending([19,17,18,7]) it returns true </p> <p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p> <pre><code>def des(l): for i in range(len(l)): if (l[i]&lt;l[i+1]): return [False,i] else: return True </code></pre>
0
2016-08-15T16:21:34Z
38,959,066
<p>The problem is that you only ever make one check, and always <em>immediately</em> return <code>True</code> or <code>False</code>.</p> <p>Instead, you shouldn't be returning `True until you have checked the whole list:</p> <pre><code>def des(l): for i in range(len(l)): if (l[i]&lt;l[i+1]): return [False,i] return True </code></pre> <p>This will give you another problem, however: </p> <pre><code>&gt;&gt;&gt; des([4,3,2,1]) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 3, in des IndexError: list index out of range </code></pre> <p>This is because when you get to the last value in your <code>range</code>, you look at a value beyond the end of the list. The easiest way to fix that is to subtract one from your range:</p> <pre><code>def des(l): for i in range(len(l) - 1): if (l[i]&lt;l[i+1]): return [False,i] return True </code></pre> <p>In python, it's generally bad practice to use <code>range(len(...))</code>. A better option is <a href="https://docs.python.org/2/library/functions.html?highlight=enumerate#enumerate" rel="nofollow"><code>enumerate</code></a>, which returns a sequence of <code>(index, value)</code> pairs, but that doesn't solve the above problem:</p> <pre><code>def des(l): for i, v in enumerate(l): if (v &lt; l[i+1]): return [False,i] return True </code></pre> <p>This still has the IndexOutOfRange error. We can fix that by pretending the list we're iterating over is one shorter:</p> <pre><code>def des(l): for i, v in enumerate(l[:-1]): if (v &lt; l[i+1]): return [False,i] return True </code></pre> <p>And there you have a much more "pythonic" (i.e. in the style a python expert would do) solution.</p> <p>There is one other unpythonic problem with this code: if you do <code>if des(my_list)): ...</code>, it won't work. This is because a non-empty <code>list</code> (what you're creating using the <code>[]</code> in the return statement, is <em>always</em> truthy.</p> <p>If you want to get the index of the ascending item, there's not really any way round that, but it should be made clearer in the function name.</p> <p>Also, you can't do</p> <pre><code>is_descending, bad_index = des(...) </code></pre> <p>Because you just return <code>True</code> on success. Better would be </p> <pre><code>def des(l): for i, v in enumerate(l[:-1]): if (v &lt; l[i+1]): return (False,i) return (True, None) </code></pre> <p>Note also that I'm using parentheses to group my result pairs, this creates a new <code>tuple</code>. In general, <code>list</code>s should be used if <em>all</em> of the members represent the same thing, <code>tuple</code> should be used if the members represent <em>different</em> things, such as in this case, they represent a <em>result</em>, and <em>where the failure occurred</em>.</p>
1
2016-08-15T16:31:04Z
[ "python", "python-2.7", "python-3.x" ]
Python descending list
38,958,929
<p>I want to make a functions which return false if the list input in the function is not in descending order ,</p> <p>now for descending([19,17,18,7]) it returns true </p> <p>i don't know why for some reason it is exiting out of if statement and printing true every time.</p> <pre><code>def des(l): for i in range(len(l)): if (l[i]&lt;l[i+1]): return [False,i] else: return True </code></pre>
0
2016-08-15T16:21:34Z
38,959,087
<pre><code>def des(l): for i in range(len(l)): if (l[i]&lt;l[i+1]): return [False,i] return True </code></pre> <p>You return True if its not false, You must only return true when the entire for loop has run through. Therefore it must be outside the for loop. If once the loop has run through and nothing has been returned, then return True</p>
0
2016-08-15T16:32:05Z
[ "python", "python-2.7", "python-3.x" ]
adding values of dictionaries in python
38,959,089
<p>I want to add the score of individual players and want to display the most runs scored by the player. This is the example of dictionaries that i am referring:</p> <pre><code>{'match1': {'player1': 57, 'player2': 38}, 'match2': {'player3': 9, 'player1': 42}, 'match3': {'player2': 41, 'player4': 63, 'player3': 91}} </code></pre> <p>I tried many solutions but unable to make a logic so that it will add the scores of individual players from different matches. Any help will be appreciable. Thanks in advance.</p>
-5
2016-08-15T16:32:21Z
38,959,194
<pre><code>def score(match): players = {} for key in match: for player in match[key]: if player not in players: players[player] =match[key][player] else: players[player]+=match[key][player] return players </code></pre> <p>Quick overview, if the player is not in the new dictionary, create the membership and point the key to the score of that player. Else add the score to the total of that player</p>
0
2016-08-15T16:39:31Z
[ "python", "python-2.7", "python-3.x", "dictionary" ]
adding values of dictionaries in python
38,959,089
<p>I want to add the score of individual players and want to display the most runs scored by the player. This is the example of dictionaries that i am referring:</p> <pre><code>{'match1': {'player1': 57, 'player2': 38}, 'match2': {'player3': 9, 'player1': 42}, 'match3': {'player2': 41, 'player4': 63, 'player3': 91}} </code></pre> <p>I tried many solutions but unable to make a logic so that it will add the scores of individual players from different matches. Any help will be appreciable. Thanks in advance.</p>
-5
2016-08-15T16:32:21Z
38,959,235
<p>Iterate over the nested <code>dictionary</code> and add up scores to a dictionary of player totals.</p> <pre><code>def find_totals(d): total = {} for match, results in d.items(): for player, score in results.items(): total[player] = total.get(player, 0) + score return total </code></pre> <p><strong>Sample Output</strong></p> <pre><code>&gt;&gt;&gt; d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}} &gt;&gt;&gt; print find_totals(d) {'player2': 79, 'player3': 100, 'player1': 99, 'player4': 63} </code></pre>
2
2016-08-15T16:41:52Z
[ "python", "python-2.7", "python-3.x", "dictionary" ]
adding values of dictionaries in python
38,959,089
<p>I want to add the score of individual players and want to display the most runs scored by the player. This is the example of dictionaries that i am referring:</p> <pre><code>{'match1': {'player1': 57, 'player2': 38}, 'match2': {'player3': 9, 'player1': 42}, 'match3': {'player2': 41, 'player4': 63, 'player3': 91}} </code></pre> <p>I tried many solutions but unable to make a logic so that it will add the scores of individual players from different matches. Any help will be appreciable. Thanks in advance.</p>
-5
2016-08-15T16:32:21Z
38,959,903
<p>Here is the solution for your problem,</p> <pre><code>d = {'match1':{'player1':57, 'player2':38}, 'match2':{'player3':9, 'player1':42}, 'match3':{'player2':41, 'player4':63, 'player3':91}} players = {} for key, val in enumerate(d): #print val for ele,value in enumerate(d[val]): #print value if value not in players: players[value] = d[val][value] else: players[value] += d[val][value] print players highest = 0 highest_player = "" for key, value in enumerate(players): if players[value]&gt;highest: highest = players[value] highest_player = highest_player.replace(highest_player, value) print highest_player,players[highest_player] </code></pre> <p>Hope this helps you.</p>
0
2016-08-15T17:29:18Z
[ "python", "python-2.7", "python-3.x", "dictionary" ]
How to deploy Django project without fabric
38,959,099
<p>This might be a dumb question, maybe not. I'm currently done with the development of a Django project and would like to deploy it. Since Python 3 is not supported by Fabric. I need to install and configure things by myself I guess.</p> <p>So the question I have is what software should I use in the virtualenv of my project? </p> <pre><code>NGINX gunicorn memcached supervisord git </code></pre> <p>Or should all of these software be installed <strong>outside</strong> of the virtualenv?</p>
0
2016-08-15T16:32:53Z
38,959,291
<ol> <li><p>All of these are system-wide software and not merely python packages. </p></li> <li><p>Fabric doesn't work in your server, what it does is only to read the <code>fabfile.py</code>, connect to your server and take actions according to file. So you can install Fabric to your python2.7 site-packages, and still use <code>fab live deploy</code> in your project. Only it wouldn't work in your virtualenv, so you'll either open a new tab or just say <code>deactivate</code></p></li> </ol>
0
2016-08-15T16:45:33Z
[ "python", "django", "python-3.x", "nginx" ]
How to deploy Django project without fabric
38,959,099
<p>This might be a dumb question, maybe not. I'm currently done with the development of a Django project and would like to deploy it. Since Python 3 is not supported by Fabric. I need to install and configure things by myself I guess.</p> <p>So the question I have is what software should I use in the virtualenv of my project? </p> <pre><code>NGINX gunicorn memcached supervisord git </code></pre> <p>Or should all of these software be installed <strong>outside</strong> of the virtualenv?</p>
0
2016-08-15T16:32:53Z
38,961,278
<p>I'm using <a href="https://www.ansible.com/" rel="nofollow">Ansible</a> to do my deploys. With Ansible I can provision all my server and do deploys easily. I recommend.</p>
0
2016-08-15T18:59:39Z
[ "python", "django", "python-3.x", "nginx" ]
How to deploy Django project without fabric
38,959,099
<p>This might be a dumb question, maybe not. I'm currently done with the development of a Django project and would like to deploy it. Since Python 3 is not supported by Fabric. I need to install and configure things by myself I guess.</p> <p>So the question I have is what software should I use in the virtualenv of my project? </p> <pre><code>NGINX gunicorn memcached supervisord git </code></pre> <p>Or should all of these software be installed <strong>outside</strong> of the virtualenv?</p>
0
2016-08-15T16:32:53Z
38,961,929
<p>I have not tried memcached, but I can tell about the rest. </p> <p>First, you install nginx and supervisord outside of virtualenv.</p> <p>Second, in virtualenv using pip you install gunicorn. </p> <p>Finally, you have got folder (e.g. /var/www/youproject/), and inside that folder you have virtualenv (/var/www/youproject/myenv), then project for django (/var/www/youproject/mysite/). Then inside your django folder you can clone the project from github. You can also do it with SFTP, but cloning through github is easiest I think. Of course, upload ur django project from you local development server to github.</p> <p>If you want to have git in production server either, then be sure you don't include sensitive, private data (e.g. passwords), unless you have private repository at github. You install git globally (OS package manager), then initialize it inside your django project. </p>
2
2016-08-15T19:44:10Z
[ "python", "django", "python-3.x", "nginx" ]
Multiply sequence by non-int of type 'str'
38,959,103
<p>Hey guys im new here and im just starting out. I tried to make a BMI calculator by simply getting input and doing calculations but it doesn't work for some reason. This is the program:</p> <pre><code>print "how old are you?", age = raw_input() print "how tall are you?", height = raw_input() print "how much do you weigh?", weight = raw_input() print "So, you're %r years old, %r meters tall and %r Kilograms heavy.\n Ain't too bad but could be better to be honest!" %(age, height, weight) print "Your BMI is %d" % (weight (height * height)) </code></pre> <p>and this is the output:</p> <pre><code>how old are you? 1 how tall are you? 2 how much do you weigh? 4 So, you're '1' years old, '2' meters tall and '4' Kilograms heavy. Ain't too bad but could be better to be honest! Traceback (most recent call last): File "ex10.py", line 11, in &lt;module&gt; print "Your BMI is %d" % (weight (height * height)) TypeError: can't multiply sequence by non-int of type 'str' </code></pre> <p>Thanks guys!!!</p>
-1
2016-08-15T16:33:13Z
38,962,061
<p>Your user input values are strings. You are trying to perform mathematical operations on them. You need to convert them to numbers first.</p> <p>Here is a question that will set you on the path to converting the strings to integers: <a href="http://stackoverflow.com/questions/642154/how-to-convert-strings-into-integers-in-python">How to convert strings into integers in Python?</a></p> <p>Looking closer I believe your issue is that this line is incorrect:</p> <pre><code>print "Your BMI is %d" % (weight (height * height)) </code></pre> <p>You're attempting to call a method <code>weight</code> passing in 2 strings multiplied. This won't work for several reasons. I believe you want:</p> <pre><code>print "Your BMI is %d" % (weight / (height * height)) </code></pre> <p>Notice the division operator in there. I looked up BMI and found the equation to be weight over height squared.</p>
0
2016-08-15T19:52:10Z
[ "python", "string" ]
Multiply sequence by non-int of type 'str'
38,959,103
<p>Hey guys im new here and im just starting out. I tried to make a BMI calculator by simply getting input and doing calculations but it doesn't work for some reason. This is the program:</p> <pre><code>print "how old are you?", age = raw_input() print "how tall are you?", height = raw_input() print "how much do you weigh?", weight = raw_input() print "So, you're %r years old, %r meters tall and %r Kilograms heavy.\n Ain't too bad but could be better to be honest!" %(age, height, weight) print "Your BMI is %d" % (weight (height * height)) </code></pre> <p>and this is the output:</p> <pre><code>how old are you? 1 how tall are you? 2 how much do you weigh? 4 So, you're '1' years old, '2' meters tall and '4' Kilograms heavy. Ain't too bad but could be better to be honest! Traceback (most recent call last): File "ex10.py", line 11, in &lt;module&gt; print "Your BMI is %d" % (weight (height * height)) TypeError: can't multiply sequence by non-int of type 'str' </code></pre> <p>Thanks guys!!!</p>
-1
2016-08-15T16:33:13Z
38,988,169
<p>With your help, this is the working code:</p> <p>print "how old are you?",</p> <p>age = int(raw_input())</p> <p>print "how tall are you?",</p> <p>height = float(raw_input())</p> <p>print "how much do you weigh?",</p> <p>weight = float(raw_input())</p> <p>print "So, you're %r years old, %r meters tall and %r Kilograms heavy.\n </p> <p>Ain't too bad but could be better to be honest!" %(</p> <p>age, height, weight)</p> <p>weight = float (weight) height = float (height)</p> <p>print "Your BMI is %d" % (float(weight) / (float(height) * float(height)))</p> <p>THANK YOU VERY MUCH!</p>
0
2016-08-17T04:33:51Z
[ "python", "string" ]
Accessing mangled member of another instance
38,959,180
<p>I use this logic to maintain a directed tree of <code>Object</code> instances :</p> <pre><code>class Object: def __init__(self, *parents: 'Object'): self.__parents = list(parents) @property def __ascendants(self): for parent in self.__parents: yield from parent.__ascendants yield parent </code></pre> <p>This code runs fine, but PyLint is complaining about <code>__ascendants</code> being a protected member of <code>parent</code>, which is, to PyLint, a client class.</p> <p>In the case of a protected, non-mangled, member, that would be fine : I should not access such members as they could be overriden by an <code>Object</code> subclass.</p> <p>But in this case, as the attributes are mangled, it's not possible for a subclass to override them, which is why I allow myself to use them even on external objects (provided to the constructor).</p> <p><strong>TLDR</strong> ; I'm looking for a way to make PyLint accept accessing mangled attributes of a client subclass, without having to resort to <code>#pylint: disable=protected-access</code> each time, or disabling the warning globally.</p> <p>It looks like I can use the <code>astng</code> callback to register a <code>MANAGER</code>, and transform a module so that PyLint can use additional information. However, I was only able to add stub members (so that dynamically added members can be used without warnings), and I'm not really sure that I can solve my problem this way.</p> <p>I also tried to add <code>assert isinstance(parent, Object)</code>, but it won't help.</p> <p><strong>EDIT</strong> :</p> <p>I was able to write the code so that PyLInt doesn't raise <code>protected-access</code>, but only to raise <code>bad-staticmethod-argument</code>. I don't use other staticmethod s in this particular class, so maybe this can be an acceptable answer to this problem :</p> <pre><code>class Object: def __init__(self, *parents: 'Object'): self.__parents = list(parents) @staticmethod def __get_ascendants(self: 'Object'): for parent in self.__parents: yield from self.__get_ascendants(parent) yield parent </code></pre> <p><strong>EDIT 2</strong> : (inspired by @shx2)</p> <p>Using a lambda with the correct argument name also fools Pylint:</p> <pre><code>class Object: def __init__(self, *parents: 'Object'): self.__parents = list(parents) @property def __ascendants(self): get_ascendants = lambda self: self.__ascendants for parent in self.__parents: yield from get_ascendants(parent) yield parent </code></pre> <p><strong>EDIT 3</strong> : Because names do not leak out of generator expressions (or list omprehensions), it can also be written this way :</p> <pre><code>from itertools import chain class Object: def __init__(self, *parents: 'Object'): self.__parents = list(parents) @property def __ascendants(self): return chain(*( chain(self.__ascendants, (self, )) for self in self.__parents )) </code></pre>
1
2016-08-15T16:38:33Z
38,961,467
<p>Why are you making the <code>ascendants</code> method a mangled property? If you really want to use such a complicated inheritance and keep multiple <code>parents</code> attribute for each of superclasses, mangling <code>parents</code> will work. However, it seems like there is no use in mangling <code>ascendants</code> function because it belongs to the class, not to the object itself:</p> <pre><code>class Object(object): def __init__(self, parents): self.__parents = list(parents) def ascendants(self): for parent in self.__parents: yield from parent.ascendants() yield parent </code></pre>
1
2016-08-15T19:12:09Z
[ "python", "oop", "code-analysis", "pylint", "private-members" ]
Accessing mangled member of another instance
38,959,180
<p>I use this logic to maintain a directed tree of <code>Object</code> instances :</p> <pre><code>class Object: def __init__(self, *parents: 'Object'): self.__parents = list(parents) @property def __ascendants(self): for parent in self.__parents: yield from parent.__ascendants yield parent </code></pre> <p>This code runs fine, but PyLint is complaining about <code>__ascendants</code> being a protected member of <code>parent</code>, which is, to PyLint, a client class.</p> <p>In the case of a protected, non-mangled, member, that would be fine : I should not access such members as they could be overriden by an <code>Object</code> subclass.</p> <p>But in this case, as the attributes are mangled, it's not possible for a subclass to override them, which is why I allow myself to use them even on external objects (provided to the constructor).</p> <p><strong>TLDR</strong> ; I'm looking for a way to make PyLint accept accessing mangled attributes of a client subclass, without having to resort to <code>#pylint: disable=protected-access</code> each time, or disabling the warning globally.</p> <p>It looks like I can use the <code>astng</code> callback to register a <code>MANAGER</code>, and transform a module so that PyLint can use additional information. However, I was only able to add stub members (so that dynamically added members can be used without warnings), and I'm not really sure that I can solve my problem this way.</p> <p>I also tried to add <code>assert isinstance(parent, Object)</code>, but it won't help.</p> <p><strong>EDIT</strong> :</p> <p>I was able to write the code so that PyLInt doesn't raise <code>protected-access</code>, but only to raise <code>bad-staticmethod-argument</code>. I don't use other staticmethod s in this particular class, so maybe this can be an acceptable answer to this problem :</p> <pre><code>class Object: def __init__(self, *parents: 'Object'): self.__parents = list(parents) @staticmethod def __get_ascendants(self: 'Object'): for parent in self.__parents: yield from self.__get_ascendants(parent) yield parent </code></pre> <p><strong>EDIT 2</strong> : (inspired by @shx2)</p> <p>Using a lambda with the correct argument name also fools Pylint:</p> <pre><code>class Object: def __init__(self, *parents: 'Object'): self.__parents = list(parents) @property def __ascendants(self): get_ascendants = lambda self: self.__ascendants for parent in self.__parents: yield from get_ascendants(parent) yield parent </code></pre> <p><strong>EDIT 3</strong> : Because names do not leak out of generator expressions (or list omprehensions), it can also be written this way :</p> <pre><code>from itertools import chain class Object: def __init__(self, *parents: 'Object'): self.__parents = list(parents) @property def __ascendants(self): return chain(*( chain(self.__ascendants, (self, )) for self in self.__parents )) </code></pre>
1
2016-08-15T16:38:33Z
39,068,082
<blockquote> <p>I'm looking for a way to make PyLint accept accessing mangled attributes of a client subclass</p> </blockquote> <p>There are ways to fool pylint.</p> <p>One way is to disguise <code>parent</code> as <code>self</code>:</p> <pre><code>@property def __ascendants(self): for parent in self.__parents: self = parent yield from self.__ascendants yield self </code></pre> <p>Another is accessing the attribute indirectly, using <code>getattr</code>. Instead of:</p> <pre><code>yield from parent.__ascendants </code></pre> <p>do:</p> <pre><code>yield from getattr(parent, '__ascendants') </code></pre>
1
2016-08-21T19:29:06Z
[ "python", "oop", "code-analysis", "pylint", "private-members" ]
"with", context manager, python: What's going on in simple terms?
38,959,182
<p>Novice Python coder here coming from a Java background. I'm still puzzled by this:</p> <pre><code>with open(...) as f: do_something(f) </code></pre> <p>even after Googling and reading some of the answers here (I just couldn't get my head around them).</p> <p>My understanding is that there is this thing called a context manager that is some sort of wrapper that contains a reference to a file that is created. Regarding</p> <pre><code>as f: </code></pre> <p>the 'as' above is like the 'as' below</p> <pre><code>import numpy as np </code></pre> <p>It's just an alias. 'f' doesn't refer to a file, but to the context manager. The context manager, using the decorator pattern, implements all the methods the file that is opened does, so that I can treat it like a file object (and get at the file object by calling the appropriate methods, which will be called on the file inside the context manager). And, of course, the file is closed when the block completes (the whole point of this). </p> <p>This begs the question: Does open() in general return a file (or a reference to a file), or a context manager? Does it return context managers in general, and that's what we've been using all the time without knowing it? Or does it return file types except in this special context when returns something different like a context manager.</p> <p>Is this anywhere near right? Would anyone like to clarify?</p>
-1
2016-08-15T16:38:38Z
38,959,232
<p>File objects <em>are themselves context managers</em>, in that they have <a href="https://docs.python.org/2/library/stdtypes.html#contextmanager.__enter__" rel="nofollow"><code>__enter__</code></a> and <a href="https://docs.python.org/2/library/stdtypes.html#contextmanager.__exit__" rel="nofollow"><code>__exit__</code></a> methods. <code>with</code> notifies the <code>file</code> object when the context is entered and exited (by calling <code>__enter__</code> and <code>__exit__</code>, respectively), and this is how a file object "knows" to close the file. There is no wrapper object involved here; file objects provide those two methods (in Java terms you could say that file objects implement the context manager interface).</p> <p>Note that <code>as</code> is <em>not</em> an alias just like <code>import module as altname</code>; instead, the <em>return value</em> of <code>contextmanager.__enter__()</code> is assigned to the target. The <code>fileobject.__enter__()</code> method returns <code>self</code> (so the file object itself), to make it easier to use the syntax:</p> <pre><code>with open(...) as fileobj: </code></pre> <p>If <code>fileobject.__enter__()</code> did not do this but either returned <code>None</code> or another object, you couldn't inline the <code>open()</code> call; to keep a reference to the returned file object you'd have to assign the result of <code>open()</code> to a variable first before using it as a context manager:</p> <pre><code>fileobj = open(...) with fileobj as something_enter_returned: fileobj.write() </code></pre> <p>or</p> <pre><code>fileobj = open(...) with fileobj: # no as, ignore whatever fileobj.__enter__() produced fileobj.write() </code></pre> <p>Note that nothing stops you from using the latter pattern in your own code; you don't <em>have</em> to use an <code>as target</code> part here if you already have another reference to the file object, or simply don't need to even access the file object further.</p> <p>However, other context managers could return something different. Some database connectors return a database cursor:</p> <pre><code>conn = database.connect(....) with conn as cursor: cursor.execute(...) </code></pre> <p>and exiting the context causes the transaction to be committed or rolled back (depending on wether or not there was an exception).</p>
3
2016-08-15T16:41:47Z
[ "python", "with-statement" ]
"with", context manager, python: What's going on in simple terms?
38,959,182
<p>Novice Python coder here coming from a Java background. I'm still puzzled by this:</p> <pre><code>with open(...) as f: do_something(f) </code></pre> <p>even after Googling and reading some of the answers here (I just couldn't get my head around them).</p> <p>My understanding is that there is this thing called a context manager that is some sort of wrapper that contains a reference to a file that is created. Regarding</p> <pre><code>as f: </code></pre> <p>the 'as' above is like the 'as' below</p> <pre><code>import numpy as np </code></pre> <p>It's just an alias. 'f' doesn't refer to a file, but to the context manager. The context manager, using the decorator pattern, implements all the methods the file that is opened does, so that I can treat it like a file object (and get at the file object by calling the appropriate methods, which will be called on the file inside the context manager). And, of course, the file is closed when the block completes (the whole point of this). </p> <p>This begs the question: Does open() in general return a file (or a reference to a file), or a context manager? Does it return context managers in general, and that's what we've been using all the time without knowing it? Or does it return file types except in this special context when returns something different like a context manager.</p> <p>Is this anywhere near right? Would anyone like to clarify?</p>
-1
2016-08-15T16:38:38Z
38,959,274
<p>Context managers are fairly simple beasts ... They're simply classes that define <a href="https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers" rel="nofollow">two separate methods</a> (<a href="https://docs.python.org/3/reference/datamodel.html#object.__enter__" rel="nofollow"><code>__enter__</code></a> and <a href="https://docs.python.org/3/reference/datamodel.html#object.__exit__" rel="nofollow"><code>__exit__</code></a>). Whatever is returned from <code>__enter__</code> is bound in the <code>as x</code> clause of the <code>with</code> statement when the <code>with</code> statement is executed.</p> <p>Here's a really stupid example:</p> <pre><code>&gt;&gt;&gt; class CM(object): ... def __enter__(self): ... print('In __enter__') ... return 'Hello world' ... def __exit__(self, *args): ... print('In __exit__') ... &gt;&gt;&gt; with CM() as x: ... print(x) ... In __enter__ Hello world In __exit__ </code></pre> <p>You'll frequently see context managers simply returning <code>self</code> from the <code>__enter__</code> method, but I wrote the example above to demonstrate that you don't <em>have</em> to. Also note that you don't need to construct the context manager in the <code>with</code> statement, you can construct it ahead of time:</p> <pre><code>cm = CM() with cm as x: ... </code></pre> <p>The reason for context managers is that when used in conjunction with the <code>with</code> statement, python guarantees that <code>__exit__</code> will be called (even if an exception happens inside the <code>with</code> suite)<sup>1</sup>.</p> <p><code>file</code> objects are implemented using the context manager API (they have well defined <code>__enter__</code> and <code>__exit__</code> methods) so <code>file</code> objects <em>are</em> context managers. When used with a <code>with</code> statement, python guarantees that when the <code>with</code> suite is exited, the file will be closed.</p> <p><sup><sup>1</sup>barring catastrophic system failure -- e.g. if your computer blows up...</sup></p>
0
2016-08-15T16:44:25Z
[ "python", "with-statement" ]
"with", context manager, python: What's going on in simple terms?
38,959,182
<p>Novice Python coder here coming from a Java background. I'm still puzzled by this:</p> <pre><code>with open(...) as f: do_something(f) </code></pre> <p>even after Googling and reading some of the answers here (I just couldn't get my head around them).</p> <p>My understanding is that there is this thing called a context manager that is some sort of wrapper that contains a reference to a file that is created. Regarding</p> <pre><code>as f: </code></pre> <p>the 'as' above is like the 'as' below</p> <pre><code>import numpy as np </code></pre> <p>It's just an alias. 'f' doesn't refer to a file, but to the context manager. The context manager, using the decorator pattern, implements all the methods the file that is opened does, so that I can treat it like a file object (and get at the file object by calling the appropriate methods, which will be called on the file inside the context manager). And, of course, the file is closed when the block completes (the whole point of this). </p> <p>This begs the question: Does open() in general return a file (or a reference to a file), or a context manager? Does it return context managers in general, and that's what we've been using all the time without knowing it? Or does it return file types except in this special context when returns something different like a context manager.</p> <p>Is this anywhere near right? Would anyone like to clarify?</p>
-1
2016-08-15T16:38:38Z
38,959,585
<p>This is the most basic context manager you could create:</p> <pre><code>class UselessContextManager(object): def __enter__(self): pass def __exit__(self, type, value, traceback): pass with UselessContextManager() as nothing: print(nothing is None) </code></pre> <p>If you want to get a little feel for what the actually process flow looks like, try this one:</p> <pre><code>class PrintingContextManager(object): def __init__(self, *args, **kwargs): print('Initializing with args: {} and kwargs: {}'.format(args, kwargs)) def __enter__(self): print('I am entering the context') print('I am returning 42') return 42 def __exit__(self, type, value, traceback): print('And now I am exiting') print('Creating manager') manager = PrintingContextManager() print('Entering with block') with manager as fnord: print('Fnord is {}'.format(fnord)) print('End of context') print('Out of context') </code></pre> <p>Output: </p> <pre><code>Creating manager Initializing with args: () and kwargs: {} Entering with block I am entering the context I am returning 42 Fnord is 42 End of context And now I am exiting Out of context </code></pre> <p>You should try modifying the code to print out <code>type, value, traceback</code> and then raise an exception inside the <code>with</code> block.</p> <p>As you can see, the <code>with</code> syntax is <em>almost</em> just short for:</p> <pre><code>thing = ContextManager() try: stuff = thing.__enter__() except Exception as e: stuff.__exit__(type(e), e.args[0], e.__traceback__) </code></pre> <p><a href="https://www.python.org/dev/peps/pep-0343/" rel="nofollow">Though truthfully it's a bit different</a></p> <p>You can see that files are always context managers:</p> <pre><code>&gt;&gt;&gt; f = open('/tmp/spanish_inquisition.txt', 'w') &gt;&gt;&gt; f.__enter__ &lt;function TextIOWrapper.__enter__&gt; &gt;&gt;&gt; f.__exit__ &lt;function TextIOWrapper.__exit__&gt; </code></pre> <blockquote> <p>I didn't know a File could be a ContextManager simply by implementing two methods, without inheriting from a super class or explicitly implementing an interface. Again, I'm new to this language.</p> </blockquote> <p>In Python that <em>is</em> explicitly implementing an interface. In Java, you have to specify what interface you want to adhere to. In Python, you just do it. Need a file-like object? Add a <code>.read()</code> method. Maybe <code>.seek()</code>, <code>.open()</code>, and <code>.close()</code> depending on what they expect. But in Python...</p> <pre><code>it = DecoyDuck() if it.walks_like_a_duck() and it.talks_like_a_duck() and it.quacks_like_a_duck(): print('It must be a duck') </code></pre>
0
2016-08-15T17:04:59Z
[ "python", "with-statement" ]
openpyxl - get input from QLineEdit and save in excel
38,959,214
<p>I want to use openpyxl to get the user input from a QLineEdit and save it to an Excel file. The script below works well when no QLineEdit is envolved but is not working under openpyxl. The error message I get is: cannot convert QlineEdit to Excel. </p> <pre><code>self.le.setText(str(text)) text = self.le.text() wb = load_workbook (source_file) ws = wb.active ws.append ([text]) wb.save (source_file) </code></pre> <p>What would be a way to this? C</p> <p>Any help would be appreciated. Thanks in advance.</p>
0
2016-08-15T16:40:37Z
38,959,397
<p>Its possible that with more code I could provide a more certain answer, but QT has several problems with typing in python. More specifically it returns 'Qtypes' for a lot of common python types that need to be manually converted before they can be serialized. Try this:</p> <pre><code>self.le.setText(str(text)) text = str(self.le.text()) wb = load_workbook (source_file) ws = wb.active ws.append ([text]) wb.save (source_file) </code></pre>
1
2016-08-15T16:52:29Z
[ "python", "openpyxl" ]
Python and Listbox (GUI)
38,959,246
<p>I have constructed a listbox using tkinter Now I want the user to click on an item in the listbox that creates a variable with the selection. </p> <pre><code>listbox.bind('&lt;ButtonRelease-1&gt;', get_list) def get_list(event): index = listbox.curselection()[0] seltext = listbox.get(index) print(seltext) </code></pre> <p>This properly prints out the selection. However, I am unable to get the "seltext" out of the function and able to use it later in the code. Someone recommended the get_list(event) however I don't know where event came from. Appreciate the help</p> <p>EDIT:</p> <pre><code> for f in filename: with open(f) as file_selection: for line in file_selection: Man_list = (line.split(',')[1]) listbox.insert(END, Man_list) file_selection.close() def get_list(event): global seltext # get selected line index index = listbox.curselection()[0] # get th e line's text global seltext seltext = listbox.get(index) # left mouse click on a list item to display selection listbox.bind('&lt;ButtonRelease-1&gt;', get_list) </code></pre>
1
2016-08-15T16:42:48Z
38,959,824
<p>This is an issue with how you are structuring your code more than anything. Event handlers are not built to return values. Use a global variable or class property to retrieve and store the value. A global variable can be set like so:</p> <pre><code>from Tkinter import * def get_list(event): global seltext index = listbox.curselection()[0] seltext = listbox.get(index) root = Tk() listbox = Listbox(root) listbox.pack() listbox.bind('&lt;ButtonRelease-1&gt;', get_list) for item in ["one", "two", "three", "four"]: listbox.insert(END, item) seltext = None root.mainloop() </code></pre> <p>But a class property is the better option. Your Tkinter application should be <a class='doc-link' href="http://stackoverflow.com/documentation/tkinter/987/introduction-to-tkinter/17033/hello-world-modular-object-oriented#t=20160815171142185703">modular</a> to ensure everything is easily accessible and prevent problems like this. You can set variables to <code>self</code> and access them later that way.</p> <pre><code>from Tkinter import * class Application(Tk): def __init__(self): Tk.__init__(self) listbox = Listbox(self) listbox.pack() listbox.bind('&lt;ButtonRelease-1&gt;', self.get_list) for item in ["one", "two", "three", "four"]: listbox.insert(END, item) self.listbox = listbox # make listbox a class property so it # can be accessed anywhere within the class def get_list(self, event): index = self.listbox.curselection()[0] self.seltext = self.listbox.get(index) if __name__ == '__main__': app = Application() app.mainloop() </code></pre>
1
2016-08-15T17:23:14Z
[ "python", "user-interface", "tkinter" ]
Manipulating web pages with python
38,959,269
<p>My aim is to be able to automatically manipulate a web page with a script. Filling in information and selecting the correct drop down box. With minimal user input. </p> <p>So my example here I'm using the national rail website. </p> <pre><code>import win32com.client from time import sleep ie = win32com.client.Dispatch("InternetExplorer.Application") ie.Visible = 1 ie.navigate("http://www.nationalrail.co.uk/") while ie.ReadyState != 4: # Wait for browser to finish loading sleep(1) print("Webpage Loaded") page = ie.Document links = page.links </code></pre> <p>If I wanted to change the box When "Leaving" to arriving, fill in the From "Station / Postcode" and hit Go. How would I go about doing this?</p> <p>Also is win32com the best method for manipulating webpages like this?</p>
1
2016-08-15T16:43:55Z
38,959,434
<p>While I'm sure every Python user can appreciate you trying to do this in the most difficult way possible, why not make things easier for yourself and use the library <a href="http://selenium-python.readthedocs.io/getting-started.html" rel="nofollow">Selenium?</a></p> <p>Here's your code &amp; what you're trying to do, in Selenium:</p> <pre><code>from selenium import webdriver driver = webdriver.Firefox() # Initialize the webdriver session driver.get('http://www.nationalrail.co.uk/') # replaces "ie.navigate" driver.find_element_by_id('sltArr').find_elements_by_tag_name('option')[1].click() # Selects the "Arrive" option </code></pre> <p>See? Much better looking! That last line selects the "Leaving" form, finds the <code>option</code> tags within it, and selects the Arrive option. With this bit of code, you should be able to figure out the rest of what you want to do with this site as well.</p>
1
2016-08-15T16:54:58Z
[ "python", "python-3.x", "win32com" ]
Python Socket Server Can Only Handle 1 Client at a time
38,959,333
<p>I am trying to make a server-client program using threads to handle each client, but the server will only accept one client at a time. If the first client disconnects, then the second client is accepted. Furthermore, each client can only send data once, then the program fails to send any more.</p> <p>Prior to posting, I have looked at MANY other Stack Overflow posts, including the following:</p> <p><a href="http://stackoverflow.com/questions/20172765/how-can-i-make-a-server-communicate-with-more-than-1-client-at-the-same-time">how can I make a server communicate with more than 1 client at the same time?</a></p> <p><a href="http://stackoverflow.com/questions/5520821/python-multithreaded-server">python multithreaded server</a></p> <p><a href="http://stackoverflow.com/questions/31103188/my-python-socket-server-can-only-receive-one-message-from-the-client">My Python socket server can only receive one message from the client</a></p> <p>But through looking at these posts I have found no solution.</p> <p>Here is the server code:</p> <pre><code>import socket from threading import * def main(): s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('172.20.3.62', 5000)) s.listen(1) clients = [] print("listening") def clienthandler(c): clients.append(c) try: while True: data = c.recv(1024).decode("UTF-8") if not data: break else: print(data) for client in clients: client.send(data.encode("UTF-8")) except: clients.remove(c) c.close() while True: c, addr = s.accept() print("accepted a client") Thread(target=clienthandler(c)).start() if __name__ == '__main__': main() </code></pre> <p>Here is the client code:</p> <pre><code>import socket from threading import * def main(): s=socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('172.20.3.62', 5000)) print("connected") def send(): msg = input("ENTER:") s.send(msg.encode("UTF-8")) def receive(): while True: data = s.recv(1024).decode("UTF-8") if data: print(data) else: break Thread(target=send).start() Thread(target=receive).start() if __name__ == '__main__': main() </code></pre>
0
2016-08-15T16:47:52Z
38,959,657
<p>Thanks to user Rawing. His/Her solution was: Thread(target=clien‌​thandler(c)) -> Thread(target=clien‌​thandler, args=(c,)) This allowed for more than one thread, and I was able to solve the only one message problem by putting the client send block in a while loop.</p>
0
2016-08-15T17:10:44Z
[ "python", "multithreading", "sockets" ]
Convert XML to CSV with python
38,959,337
<p>I have the following XML files that need to be converted to CSV for Magento import. Under <code>&lt;values&gt; &lt;Value AttributeID="attributes"&gt;&lt;/Value&gt;</code> there are a few hundred possibilities that are different for each product. </p> <p>I've tried using <code>xml2csv</code> and <code>xmlutils.xml2csv</code> via command line with no luck. Any help would be appreciated. </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;STEP-ProductInformation&gt; &lt;Products&gt; &lt;Product UserTypeID="Item" ParentID="12345678" AnalyzerResult="included" ID="123456"&gt; &lt;Name&gt;X8MM&lt;/Name&gt; &lt;ClassificationReference InheritedFrom="" ClassificationID="" AnalyzerResult=""/&gt; &lt;Values&gt; &lt;Value AttributeID="Retail Price"&gt;46.44&lt;/Value&gt; &lt;Value AttributeID="Item Class"&gt;03017&lt;/Value&gt; &lt;Value AttributeID="Item Group"&gt;03&lt;/Value&gt; &lt;Value AttributeID="Consumer Description"&gt;Super-X 8mm Mauser (8x57) 170 Grain Power-Point&lt;/Value&gt; &lt;Value AttributeID="Quantity Case"&gt;10&lt;/Value&gt; &lt;Value AttributeID="Bullet Weight"&gt;170 gr.&lt;/Value&gt; &lt;Value AttributeID="Made In The USA"&gt;Made In The USA&lt;/Value&gt; &lt;Value AttributeID="Item Code"&gt;X8MM&lt;/Value&gt; &lt;Value AttributeID="Caliber"&gt;8x57 Mauser&lt;/Value&gt; &lt;Value AttributeID="Catalog Vendor Name"&gt;WINCHESTER&lt;/Value&gt; &lt;Value AttributeID="Quantity per Box"&gt;20&lt;/Value&gt; &lt;Value AttributeID="Item Status"&gt;OPEN&lt;/Value&gt; &lt;Value AttributeID="Wildcat Eligible"&gt;Y&lt;/Value&gt; &lt;Value AttributeID="Item Description"&gt;WIN SUPX 8MAU 170 PP 20&lt;/Value&gt; &lt;Value AttributeID="Primary Vendor"&gt;307AM&lt;/Value&gt; &lt;Value AttributeID="Caliber-Gauge"&gt;8X57 MAUSER&lt;/Value&gt; &lt;Value AttributeID="InventoryTyp"&gt;REG&lt;/Value&gt; &lt;Value AttributeID="Bullet Style"&gt;Power-Point&lt;/Value&gt; &lt;Value AttributeID="ProductPageNumber"/&gt; &lt;Value AttributeID="Model Header"&gt;8mm Mauser (8x57)&lt;/Value&gt; &lt;Value AttributeID="Master Model Body Copy"&gt;Power Point assures quick and massive knock-down. Strategic notching provides consistent and reliable expansion. Contoured jacket maximum expansion performance. Alloyed lead core increases retained weight for deeper penetration.&lt;/Value&gt; &lt;Value AttributeID="Master Model Header"&gt;Super-X Power-Point&lt;/Value&gt; &lt;Value AttributeID="Vendor Group"&gt;WIN&lt;/Value&gt; &lt;/Values&gt; &lt;AssetCrossReference Type="Primary Image" AssetID="WIN_X8MM" AnalyzerResult="included"/&gt; &lt;/Product&gt; &lt;/Products&gt; &lt;/STEP-ProductInformation&gt; </code></pre>
0
2016-08-15T16:48:23Z
38,959,631
<p>I'm not familiar with "Magento", but this program converts your XML file to a CSV file. The resulting CSV file has one column for <code>Name</code> and one column for each <code>Value</code>.</p> <pre><code>from xml.etree import ElementTree as ET import csv tree = ET.parse('x.xml') root = tree.getroot() columns = ['Name'] + [ value.attrib.get('AttributeID').encode('utf-8') for value in tree.findall('.//Product//Value')] with open('x.csv', 'w') as ofile: ofile = csv.DictWriter(ofile, set(columns)) ofile.writeheader() for product in tree.findall('.//Product'): d = {value.attrib.get('AttributeID').encode('utf-8'): (value.text or '').encode('utf-8') for value in product.findall('.//Values/Value')} d['Name'] = product.findtext('Name') ofile.writerow(d) </code></pre>
0
2016-08-15T17:08:39Z
[ "python", "xml", "csv", "magento" ]
Efficently multiply a matrix with itself after offsetting it by one in numpy
38,959,365
<p>I am trying to write a function that takes a matrix A, then offsets it by one, and does element wise matrix multiplication on the shared area. Perhaps an example will help. Suppose I have the matrix:</p> <pre><code>A = np.array([[1,2,3],[4,5,6],[7,8,9]]) </code></pre> <p>What i'd like returned is: (1*2) + (4*5) + (7*8) = 78</p> <p>The following code does it, but inefficently:</p> <pre><code>import numpy as np A = np.array([[1,2,3],[4,5,6],[7,8,9]]) Height = A.shape[0] Width = A.shape[1] Sum1 = 0 for y in range(0, Height): for x in range(0,Width-2): Sum1 = Sum1 + \ A.item(y,x)*A.item(y,x+1) print("%d * %d"%( A.item(y,x),A.item(y,x+1))) print(Sum1) </code></pre> <p>With output:</p> <pre><code>1 * 2 4 * 5 7 * 8 78 </code></pre> <p>Here is my attempt to write the code more efficently with numpy:</p> <pre><code>import numpy as np A = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(np.sum(np.multiply(A[:,0:-1], A[:,1:]))) </code></pre> <p>Unfortunately, this time I get 186. I am at a loss where did I go wrong. i'd love someone to either correcty me or offer another way to implement this.</p> <p>Thank you.</p>
0
2016-08-15T16:50:05Z
38,961,194
<p>In this 3 column case, you are just multiplying the 1st 2 columns, and taking the sum:</p> <pre><code>A[:,:2].prod(1).sum() Out[36]: 78 </code></pre> <p>Same as <code>(A[:,0]*A[:,1]).sum()</code></p> <p>Now just how does that generalize to more columns?</p> <p>In your original loop, you can cut out the row iteration by taking the sum of this list:</p> <pre><code>[A[:,x]*A[:,x+1] for x in range(0,A.shape[1]-2)] Out[40]: [array([ 2, 20, 56])] </code></pre> <p>Your description talks about multiplying the shared area; what direction are you doing the offset? From the calculation it looks like the offset is negative.</p> <pre><code>A[:,:-1] Out[47]: array([[1, 2], [4, 5], [7, 8]]) </code></pre> <p>If that is the offset logic, than I could rewrite my calculation as</p> <pre><code>A[:,:-1].prod(1).sum() </code></pre> <p>which should work for many more columns.</p> <p>===================</p> <p>Your 2nd try:</p> <pre><code>In [3]: [A[:,:-1],A[:,1:]] Out[3]: [array([[1, 2], [4, 5], [7, 8]]), array([[2, 3], [5, 6], [8, 9]])] In [6]: A[:,:-1]*A[:,1:] Out[6]: array([[ 2, 6], [20, 30], [56, 72]]) In [7]: _.sum() Out[7]: 186 </code></pre> <p>In other words instead of 1*2, you are calculating [1,2]*[2*3]=[2,6]. Nothing wrong with that, if that's you you really intend. The key is being clear about 'offset' and 'overlap'.</p>
0
2016-08-15T18:54:50Z
[ "python", "numpy" ]
Python Regexp for extracting tags and words
38,959,382
<p>I have the following string:</p> <pre><code>str1 = "I/TAG1 like/TAG2 red/TAG3 apples/TAG3 ./TAG4" </code></pre> <p>And I have two lists in python</p> <pre><code>tokens = [] tags = [] </code></pre> <p>My desired output would be:</p> <pre><code>tokens = ['I', 'like', 'red', 'apples', '.'] tags = ['TAG1', 'TAG2', 'TAG3', 'TAG3', 'TAG4'] </code></pre> <p>I am trying to use a regexp like this one:</p> <pre><code>r"\w*\/" </code></pre> <p>But that extracts the words with the slash, i.e I/. How can I get the desired output, at least for tokens (get everything before the /)?</p>
2
2016-08-15T16:51:16Z
38,959,428
<p>You can use:</p> <pre><code>&gt;&gt;&gt; re.findall(r'([\w.]+)/([\w.]+)', str1) [('I', 'TAG1'), ('like', 'TAG2'), ('red', 'TAG3'), ('apples', 'TAG3'), ('.', 'TAG4')] </code></pre> <p><strong>Code:</strong></p> <pre><code>&gt;&gt;&gt; tags=[] &gt;&gt;&gt; vals=[] &gt;&gt;&gt; for m in re.findall(r'([\w.]+)/([\w.]+)', str1): ... tags.append(m[0]) ... vals.append(m[1]) ... &gt;&gt;&gt; print tags ['I', 'like', 'red', 'apples', '.'] &gt;&gt;&gt; print vals ['TAG1', 'TAG2', 'TAG3', 'TAG3', 'TAG4'] </code></pre>
4
2016-08-15T16:54:39Z
[ "python", "regex", "python-2.7", "tokenize" ]
Python Regexp for extracting tags and words
38,959,382
<p>I have the following string:</p> <pre><code>str1 = "I/TAG1 like/TAG2 red/TAG3 apples/TAG3 ./TAG4" </code></pre> <p>And I have two lists in python</p> <pre><code>tokens = [] tags = [] </code></pre> <p>My desired output would be:</p> <pre><code>tokens = ['I', 'like', 'red', 'apples', '.'] tags = ['TAG1', 'TAG2', 'TAG3', 'TAG3', 'TAG4'] </code></pre> <p>I am trying to use a regexp like this one:</p> <pre><code>r"\w*\/" </code></pre> <p>But that extracts the words with the slash, i.e I/. How can I get the desired output, at least for tokens (get everything before the /)?</p>
2
2016-08-15T16:51:16Z
38,959,488
<p>You can use a combination of <code>str.split()</code> by space and by slash. Then calling <code>zip()</code> to pipe the output into two separate lists:</p> <pre><code>&gt;&gt;&gt; tokens, tags = zip(*[item.split("/") for item in str1.split()]) &gt;&gt;&gt; tokens ('I', 'like', 'red', 'apples', '.') &gt;&gt;&gt; tags ('TAG1', 'TAG2', 'TAG3', 'TAG3', 'TAG4') </code></pre>
2
2016-08-15T16:58:13Z
[ "python", "regex", "python-2.7", "tokenize" ]
How to call the functions present in one .py file from other .py file?
38,959,396
<p>I have two files and I'd like to import a class from the other file.</p> <p>File <code>one.py</code>:</p> <pre><code>class One: def printNumber( self, a ): print (a) </code></pre> <p>and file <code>two.py</code>:</p> <pre><code>#import One # gives error no module named One #import one # gives error no module named one class Two: # Here I want to call printNumber method from one.py </code></pre>
-3
2016-08-15T16:52:18Z
38,959,562
<p><strong>Keep the files in the same directory</strong> then use something like the below format.</p> <pre><code>from one import One one = One() class Two: a = 5 one.printNumber(a) </code></pre> <p>Edit: When working in Pycharm you need to mark your sources root to import your own files.</p> <p><a href="http://i.stack.imgur.com/6sPmi.png" rel="nofollow"><img src="http://i.stack.imgur.com/6sPmi.png" alt="enter image description here"></a></p>
0
2016-08-15T17:03:26Z
[ "python", "python-3.x", "import" ]
Pygame screen is read-only
38,959,441
<p>I'm working on a pygame program, and want to display some text on the screen.</p> <p>I define my screen here:</p> <pre><code>screenDi = pygame.display.Info() height = screenDi.current_h width = screenDi.current_w size = width, height screen = pygame.display.set_mode(size) </code></pre> <p>and define my text function here:</p> <pre><code>def text(text,x,y): font = pygame.font.SysFont('Calibri',50,True,False) text = font.render(text,True,BLACK) screen.blit = (text,[x,y])` </code></pre> <p>However, when I include this line in the main program:</p> <pre><code>text('Hello',100,100) </code></pre> <p>python returns the following error:</p> <p><code>pygame.Surface object attribute 'blit' is read-only</code></p> <p>Any idea how i could fix this?</p>
0
2016-08-15T16:55:22Z
38,959,491
<p>blit() is a function, but you're trying to assign it:</p> <pre><code>screen.blit = (text,[x,y]) </code></pre> <p>Try it without the = :</p> <pre><code>screen.blit(text,[x,y]) </code></pre>
1
2016-08-15T16:58:19Z
[ "python", "pygame", "blit" ]
Draw Line chart with openpyxl - Axis/drawing issue
38,959,471
<p>I'm having problems getting the LineChart() feature of Openpyxl to draw the chart in the way that I'd like it. </p> <p>I've been using the documentation on <a href="http://openpyxl.readthedocs.io/en/default/charts/line.html" rel="nofollow">the official page</a>, but I get <a href="http://i.stack.imgur.com/8ig1c.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/8ig1c.jpg" alt="This result in Excel"></a>.</p> <p>This is the desired result (ignore the colour/formatting, just need to get the data points correct, then I can style it):</p> <p><a href="http://i.stack.imgur.com/xF3jp.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/xF3jp.jpg" alt="enter image description here"></a></p> <p>I've tried to rearrange the data into vertical slices in the masterList list in the same way they demonstrate in the documentation, but I don't understand how the graph actually uses the data between the </p> <pre><code>for i in masterList: #print ("Appending ", i, "to the sheet") sheet.append(i) </code></pre> <p>section, and the below line:</p> <pre><code>data = Reference(sheet, min_col = 4, min_row = 7, max_col = currentCell, max_row = 28) </code></pre> <p>Whole function below. version = "v1.9", currentCell = number of dates we have data for, and sheet is the current active worksheet in the workbook. </p> <pre><code>def drawChart(self, sheet, currentCell, version): print ("CurrentCell = ", currentCell) ### Get the chart data dateData, versionData, versionXABData = ([] for i in range(3)) #Make 3 lists for i in range(currentCell): temp = sheet.cell(row = 7, column = 4+i).value if not temp: temp = 0 dateData.append(temp) else: dateData.append(temp) #Put the dates in a list for i in range(currentCell): temp = sheet.cell(row = 28, column = 4+i).value if not temp: temp = 0 versionData.append(temp) else: versionData.append(temp) #Put the version Totals in another for i in range(currentCell): temp = sheet.cell(row = 27, column = 4+i).value if not temp: temp = 0 versionXABData.append(temp) else: versionXABData.append(temp) #Put the version XAB bugs in another print ("Dates are: ", dateData, '\n', "VersionData is: ",versionData, '\n', "Version XAB is: ", versionXABData, '\n') masterList = [list() for i in range(currentCell)] #Make a list containing the total number of empty lists for each day we have data for masterList[0].append("Date") masterList[0].append("Total "+ version +" Bugs") masterList[0].append("Total "+ version +" XAB Bugs") print (masterList[0]) for i in range(1, currentCell): #print (" Length of dataData = ", len(dateData), '\n', "Length of versionData = ", len(versionData), '\n', "Length of versionXABData = ", len(versionXABData), '\n',"i = ", i) masterList[i].append(dateData[i]) masterList[i].append(versionData[i]) masterList[i].append(versionXABData[i]) for i in masterList: #print ("Appending ", i, "to the sheet") sheet.append(i) chart1 = LineChart() chart1.title = "DoT Bug Burndown" chart1.style = 13 chart1.y_axis.title = "No of Bugs" chart1.x_axis.title = "Date" chart1.width = 30 chart1.height = 20 data = Reference(sheet, min_col = 4, min_row = 7, max_col = currentCell, max_row = 28) chart1.add_data(data, titles_from_data=True) sheet.add_chart(chart1, "K31") </code></pre>
-1
2016-08-15T16:57:20Z
39,069,632
<p>This was solved by writing the new data to a new sheet after reading it. </p> <p>The way it was originally meant that it wasn't using the correct axis orientation, so the revised code below appends the content of the masterList to a new sheet of the workbook, in data columns (as opposed to rows), as is shown in the LineChart example of the supporting documentation.</p> <pre><code>def drawChart(self, sheet, sheet2, currentCell, version): print ("CurrentCell = ", currentCell) ### Get the chart data dateData, versionData, versionXABData = ([] for i in range(3)) #Make 3 lists for i in range(currentCell): temp1 = sheet.cell(row = 7, column = 4+i).value temp2 = str(temp1) temp3 = temp2[:10] if not temp1: temp2 = 0 dateData.append(temp3) else: dateData.append(temp3) #Put the dates in a list for i in range(currentCell): temp = sheet.cell(row = 28, column = 4+i).value if not temp: temp = 0 versionData.append(temp) else: versionData.append(temp) #Put the version Totals in another for i in range(currentCell): temp = sheet.cell(row = 27, column = 4+i).value if not temp: temp = 0 versionXABData.append(temp) else: versionXABData.append(temp) #Put the version XAB bugs in another print ("Dates are: ", dateData, '\n', "VersionData is: ",versionData, '\n', "Version XAB is: ", versionXABData, '\n') masterList = [list() for i in range(currentCell)] #Make a list containing the total number of empty lists for each day we have data for masterList[0].append("Date") masterList[0].append("Total "+ version +" Bugs") masterList[0].append("Total "+ version +" XAB Bugs") print ("MasterList = ", masterList[0]) for i in range(1, currentCell): #print (" Length of dataData = ", len(dateData), '\n', "Length of versionData = ", len(versionData), '\n', "Length of versionXABData = ", len(versionXABData), '\n',"i = ", i) masterList[i].append(dateData[i]) masterList[i].append(versionData[i]) masterList[i].append(versionXABData[i]) for i in masterList: print ("Appending ", i, "to the sheet") sheet2.append(i) chart1 = LineChart() chart1.title = version + " Bug Burndown" chart1.style = 2 chart1.y_axis.title = "No of Bugs" chart1.width = 30 chart1.height = 20 data = Reference(sheet2, min_col=2, min_row=1, max_col=3, max_row=36) chart1.add_data(data, titles_from_data=True) #s = Series(y, xvalues = x) dates = Reference(sheet2, min_col=1, min_row=2, max_row=36) chart1.set_categories(dates) chart1.legend.position = 'b' s1 = chart1.series[0] s2 = chart1.series[1] s1.graphicalProperties.line.width = 50000 s2.graphicalProperties.line.width = 50000 </code></pre>
0
2016-08-21T23:13:40Z
[ "python", "excel", "graph", "openpyxl" ]
How to iterate a large table in Django without running out of memory?
38,959,478
<p>I have a Django model whose table has millions of records in it. I'm trying to do some emergency maintenance on all of the records in the table at a shell but I'm unable to do a <code>MyModel.objects.all()</code> without completely exhausting memory on my system.</p> <p>Even a <code>pass</code> causes the OOM killer to be called, killing my process:</p> <pre><code>for ii in MyModel.objects.all(): pass </code></pre> <p>The reason is because Django's <code>QuerySet</code> is trying to build up its "result cache", by building a list with <em>all</em> of my records in it, here:</p> <pre><code># django/db/models/query.py def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self.iterator()) # &lt;&lt;&lt;&lt; this guy! if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() </code></pre> <p>But my machine can't hold the whole list in memory.</p> <p>Of course, iterating <code>.all()</code> on such a large table would be a terrible idea in a real app, so the scope of this problem is rather limited (maintenance activities) but it does come up from time to time.</p>
0
2016-08-15T16:57:41Z
38,959,523
<p>You might not be able to fit all of the full records in memory, but there's a good chance you can fit all of the primary keys in memory. So you can iterate the list of all primary keys and do a <code>.get()</code> on each one and operate on the records individually:</p> <pre><code>for pk in MyModel.objects.values_list('pk', flat=True): ii = MyModel.objects.get(pk=pk) ii.maintenance_activity() </code></pre> <p>This is not super CPU efficient, of course, but it's much more memory efficient. Given that this sort of thing should only come up for maintenance activities, the less-than-ideal performance hopefully shouldn't be a problem.</p>
0
2016-08-15T17:00:21Z
[ "python", "django" ]
How to iterate a large table in Django without running out of memory?
38,959,478
<p>I have a Django model whose table has millions of records in it. I'm trying to do some emergency maintenance on all of the records in the table at a shell but I'm unable to do a <code>MyModel.objects.all()</code> without completely exhausting memory on my system.</p> <p>Even a <code>pass</code> causes the OOM killer to be called, killing my process:</p> <pre><code>for ii in MyModel.objects.all(): pass </code></pre> <p>The reason is because Django's <code>QuerySet</code> is trying to build up its "result cache", by building a list with <em>all</em> of my records in it, here:</p> <pre><code># django/db/models/query.py def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self.iterator()) # &lt;&lt;&lt;&lt; this guy! if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() </code></pre> <p>But my machine can't hold the whole list in memory.</p> <p>Of course, iterating <code>.all()</code> on such a large table would be a terrible idea in a real app, so the scope of this problem is rather limited (maintenance activities) but it does come up from time to time.</p>
0
2016-08-15T16:57:41Z
38,959,569
<p>The first thing to try is using the <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#iterator" rel="nofollow"><code>iterator()</code></a> method on the queryset before iterating over it:</p> <pre><code>for ii in MyModel.objects.all().iterator(): </code></pre>
3
2016-08-15T17:04:02Z
[ "python", "django" ]
How to iterate a large table in Django without running out of memory?
38,959,478
<p>I have a Django model whose table has millions of records in it. I'm trying to do some emergency maintenance on all of the records in the table at a shell but I'm unable to do a <code>MyModel.objects.all()</code> without completely exhausting memory on my system.</p> <p>Even a <code>pass</code> causes the OOM killer to be called, killing my process:</p> <pre><code>for ii in MyModel.objects.all(): pass </code></pre> <p>The reason is because Django's <code>QuerySet</code> is trying to build up its "result cache", by building a list with <em>all</em> of my records in it, here:</p> <pre><code># django/db/models/query.py def _fetch_all(self): if self._result_cache is None: self._result_cache = list(self.iterator()) # &lt;&lt;&lt;&lt; this guy! if self._prefetch_related_lookups and not self._prefetch_done: self._prefetch_related_objects() </code></pre> <p>But my machine can't hold the whole list in memory.</p> <p>Of course, iterating <code>.all()</code> on such a large table would be a terrible idea in a real app, so the scope of this problem is rather limited (maintenance activities) but it does come up from time to time.</p>
0
2016-08-15T16:57:41Z
38,959,702
<p>If you are using python3.X you can try some async tasks.</p> <p>It may be useful to create a schedule fetch.</p> <p>Something like this:</p> <pre><code>async def _fetch_all(self): if self._result_cache is None: self._result_cache = await list(self.iterator()) # &lt;&lt;&lt;&lt; this guy! if self._prefetch_related_lookups and not self._prefetch_done: await self._prefetch_related_objects() </code></pre> <p>To run your code:</p> <pre><code>import asyncio my_model = MyModel() asyncio.get_event_loop().run_until_complete(my_model._fetch_all()) </code></pre> <p>But if you are using 2.7 you will need to create a async task with celery or try some tools to do that like <a href="http://www.kirit.com/Django%20Async/Using%20Django%20Async%20from%20your%20code" rel="nofollow">Django Async</a>.</p> <p>Hope it helps.</p> <p><a href="http://stackoverflow.com/questions/23793961/asynchronous-signals-with-asyncio">Take a look</a></p>
0
2016-08-15T17:13:40Z
[ "python", "django" ]
Python regex - find patterns in a file and put them in a list
38,959,481
<p>I am trying to use regex to find all the matched patterns in a BibTex file. The file looks like this:</p> <pre><code>bib_file = """ @article{Fu_2007_ssr, doi = {10.1016/j.surfrep.2007.07.001} } @article{Shibuya_2007_apl, doi = {10.1063/1.2816907} } """ </code></pre> <p>My goal is to find all the matched patterns with is from <code>@article</code> to <code>}</code> and put these patterns into a list. So my final list will be like this:</p> <pre><code>['@article{Fu_2007_ssr,\n doi = {10.1016/j.surfrep.2007.07.001}\n }', '@article{Shibuya_2007_apl,\n doi = {10.1063/1.2816907}\n }'] </code></pre> <p>Currently, I have my code:</p> <pre><code> rx_sequence = re.compile(r'(@article(.*)}\n)', re.DOTALL) article = rx_sequence.search(bib_file).group(1) </code></pre> <p>But the <code>article</code> is a string, how can I find each matched pattern and append it to a list?</p>
1
2016-08-15T16:57:48Z
38,959,605
<p>You can match all these articles with</p> <pre><code>r"(@article.*?\n[ \t]*}[ \t]*)(?:\n|$)" </code></pre> <p>(to be used with <code>re.DOTALL</code> modifier for the <code>.</code> to match any char incl. a newline). See the <a href="https://regex101.com/r/pO5hP6/2" rel="nofollow">regex demo</a></p> <p><strong>Pattern details</strong>:</p> <ul> <li><code>(@article.*?\n[ \t]*}[ \t]*)</code> - Group 1 capturing a sequence of: <ul> <li><code>@article</code> - a literal text <code>@article</code></li> <li><code>.*?</code> - any zero or more chars, as few as possible, up to the first...</li> <li><code>\n[ \t]*}[ \t]*</code> - newline, followed with 0+ spaces/tabs, <code>}</code> and again 0+ spaces/tabs and... </li> </ul></li> <li><code>(?:\n|$)</code> - either a newline (<code>\n</code>) or end of string (<code>$</code>).</li> </ul> <p><a href="http://ideone.com/ezGSJa" rel="nofollow">Python demo</a>:</p> <pre><code>import re p = re.compile(r'(@article.*?\n[ \t]*}[ \t]*)(?:\n|$)', re.DOTALL) s = "@article{Fu_2007_ssr,\ndoi = {10.1016/j.surfrep.2007.07.001}\n}\n\n@article{Shibuya_2007_apl,\n doi = {10.1063/1.2816907}\n}" print(p.findall(s)) # =&gt; ['@article{Fu_2007_ssr,\ndoi = {10.1016/j.surfrep.2007.07.001}\n}', # '@article{Shibuya_2007_apl,\n doi = {10.1063/1.2816907}\n}'] </code></pre> <p>Note that unrolling the pattern as </p> <pre><code>@article.*(?:\n(?![ \t]*}[ \t]*(?:\n|$)).*)*\s*} </code></pre> <p>will make it more robust. See <a href="https://regex101.com/r/pO5hP6/4" rel="nofollow">another regex demo</a> and a <a href="http://ideone.com/edW2nN" rel="nofollow">Python demo</a> (this regex does not require a <code>re.DOTALL</code> modifier).</p>
1
2016-08-15T17:06:20Z
[ "python", "regex" ]
Python regex - find patterns in a file and put them in a list
38,959,481
<p>I am trying to use regex to find all the matched patterns in a BibTex file. The file looks like this:</p> <pre><code>bib_file = """ @article{Fu_2007_ssr, doi = {10.1016/j.surfrep.2007.07.001} } @article{Shibuya_2007_apl, doi = {10.1063/1.2816907} } """ </code></pre> <p>My goal is to find all the matched patterns with is from <code>@article</code> to <code>}</code> and put these patterns into a list. So my final list will be like this:</p> <pre><code>['@article{Fu_2007_ssr,\n doi = {10.1016/j.surfrep.2007.07.001}\n }', '@article{Shibuya_2007_apl,\n doi = {10.1063/1.2816907}\n }'] </code></pre> <p>Currently, I have my code:</p> <pre><code> rx_sequence = re.compile(r'(@article(.*)}\n)', re.DOTALL) article = rx_sequence.search(bib_file).group(1) </code></pre> <p>But the <code>article</code> is a string, how can I find each matched pattern and append it to a list?</p>
1
2016-08-15T16:57:48Z
38,959,776
<p>Alternatively, you could use <a href="https://bibtexparser.readthedocs.io/en/v0.6.2/" rel="nofollow"><code>bibtexparser</code></a> which saves you all the trouble:</p> <pre><code>&gt;&gt;&gt; import bibtexparser &gt;&gt;&gt; bib_file = """ ... @article{Fu_2007_ssr, ... doi = {10.1016/j.surfrep.2007.07.001} ... } ... ... @article{Shibuya_2007_apl, ... doi = {10.1063/1.2816907} ... } ... """ &gt;&gt;&gt; b = bibtexparser.loads(bib_file) &gt;&gt;&gt; b.entries [{'ENTRYTYPE': 'article', 'ID': 'Fu_2007_ssr', 'doi': '10.1016/j.surfrep.2007.07.001'}, {'ENTRYTYPE': 'article', 'ID': 'Shibuya_2007_apl', 'doi': '10.1063/1.2816907'}] </code></pre> <p>There, you have a list containing the items from the bib file properly splitted and mapped to their bib titles.</p>
1
2016-08-15T17:18:37Z
[ "python", "regex" ]
maximal subset of integers that are not evenly divisible by k
38,959,567
<p>This is a practice problem I am solving:</p> <p>Given a set S of distinct integers, print the size of a maximal subset S' of S where the sum of any 2 numbers in S' are not evenly divisible by k.</p> <p>My approach was to limit the problem to the subset <code>S[0...i]</code> where 0 &lt; i &lt;= n-1 and determine the length of the maximal subset for that subproblem, then extend the subproblem by 1. I know there is a different approach to this problem but I am confused why my solution does not work. </p> <p>ex) for n = 10, k = 5, and <code>S</code> = <code>[770528134, 663501748, 384261537, 800309024, 103668401, 538539662, 385488901, 101262949, 557792122, 46058493]</code></p> <pre><code>dp = [0 for _ in range(n)] dp[0] = 1 for i in range(1, n): flag = 0 for j in range(i): if s[j] == "#": pass elif (not s[j] == "#") and (s[j] + s[i])%k==0: dp[i] = dp[i-1] flag = 1 s[i] = "#" break if not flag == 1: dp[i] = dp[i-1] + 1 print dp[-1] </code></pre> <p>The output should be <code>6</code> but my function prints <code>5</code>. What I try to do is iterate from <code>j=0</code> to <code>i</code> and check if for any <code>j</code> &lt; <code>i</code> if <code>(s[j] + s[i])%k==0</code>. If so, then considering <code>s[i]</code> in S' would be erroneous so instead mark <code>s[i]</code> with a <code>#</code> to indicate it is not in S'. </p>
-1
2016-08-15T17:03:51Z
38,960,396
<p>Your lack of comments and explanatory names makes your code very hard to follow, so I do not understand it. (Your example using a list when you talk of sets, and the use of both <code>s</code> and <code>S</code> for your "set", do not help.) However, the basic idea of your algorithm is flawed: this problem for a given set cannot be solved by extending the solution for a proper subset.</p> <p>For example, take <code>k=3</code>, set <code>S=[1,4,2,5,8]</code>. For the first three elements <code>[1,4,2]</code>, the solution is <code>[1,4]</code>. For the first four elements <code>[1,4,2,5]</code>, the solution is either <code>[1,4]</code> or <code>[2,5]</code>. For the entire set, the solution is <code>[2,5,8]</code>. You see there is no "path" from the solution from the first three elements through the first five: you need to "restart" at either the first four or the entire set.</p> <p>A solution that does work partitions the entire set S into equivalence classes where the elements in each class have the same remainder when divided by k. Examining these equivalence classes gives the final result. Let me know if you need more details. Note that you will need to decide clearly if <code>any 2 numbers in S'</code> means any 2 <em>distinct</em> numbers in S': this changes what you do at one or two of the equivalence classes.</p>
2
2016-08-15T18:01:16Z
[ "python", "algorithm" ]
Re-defining already assigned python class
38,959,609
<p>I am new to Python and I inherited someone's code that had the following code structure. Why do I get an object not callable and how can I redefine this method again even after re-assigning l.bar. Another question would therefore be what's the difference between l.bar and l.bar()?</p> <pre><code>&gt;&gt;&gt; class foo(object): ... def __init__(self): ... self.name = "Food" ... class bar(object): ... def __init__(self): ... self.name = "Is" ... class tea(object): ... def __init__(self): ... self.name = "Good" ... &gt;&gt;&gt; l = foo() &gt;&gt;&gt; m = l.bar() &gt;&gt;&gt; m.name = "Was" &gt;&gt;&gt; l.bar = m &gt;&gt;&gt; r = l.bar() Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: 'bar' object is not callable </code></pre>
-2
2016-08-15T17:06:33Z
38,959,712
<p>As others have pointed out, it's generally not good practice to have nested classes. But, here's a breakdown of what's happening:</p> <pre><code>class foo(object): def __init__(self): self.name = "Food" class bar(object): def __init__(self): self.name = "Is" class tea(object): def __init__(self): self.name = "Good" l = foo() # l is now an instance of foo print l.name # "Food" m = l.bar() # m is now an instance of bar print m.name # "Is" m.name = "Was" # you've assigned m's name to "Was" print m.name # "Was" l.bar = m # you are overriding foo's nested bar class now with an instance of bar print l.name # "Food" print l.bar # &lt;__main__.bar object at 0x108371ad0&gt;: this is now an instance, not a class print l.bar.name # "Was" r = l.bar() # you are now trying to call an instance of bar </code></pre> <p>The last line doesn't work because of the same reasons calling <code>l()</code> or <code>foo()()</code> doesn't work.</p> <p>If you <em>absolutely must</em> figure out a way to make foo.bar().name return something else, you can create a new class and reassign foo.bar to it. But, this is really gross and not recommended. Hopefully, you can just change that original code.</p> <pre><code>print foo.bar().name # "Is" class NewBar(object): def __init__(self): self.name = 'Was' foo.bar = NewBar print foo.bar().name # "Was" </code></pre>
2
2016-08-15T17:14:12Z
[ "python", "oop", "inner-classes" ]
Re-defining already assigned python class
38,959,609
<p>I am new to Python and I inherited someone's code that had the following code structure. Why do I get an object not callable and how can I redefine this method again even after re-assigning l.bar. Another question would therefore be what's the difference between l.bar and l.bar()?</p> <pre><code>&gt;&gt;&gt; class foo(object): ... def __init__(self): ... self.name = "Food" ... class bar(object): ... def __init__(self): ... self.name = "Is" ... class tea(object): ... def __init__(self): ... self.name = "Good" ... &gt;&gt;&gt; l = foo() &gt;&gt;&gt; m = l.bar() &gt;&gt;&gt; m.name = "Was" &gt;&gt;&gt; l.bar = m &gt;&gt;&gt; r = l.bar() Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: 'bar' object is not callable </code></pre>
-2
2016-08-15T17:06:33Z
38,959,726
<blockquote> <p>Why do i get an object not callable</p> </blockquote> <p>You assigned <code>l.bar</code> to be an instance of the class <code>foo.bar</code> (specifically, you assigned <code>m</code> to it). Instances of that class aren't callable, therefore <code>l.bar</code> isn't callable.</p> <blockquote> <p>how can i redefine this method again even after re-assigning l.bar</p> </blockquote> <p>Maybe this advice is too obvious, but don't re-assign <code>l.bar</code>.</p> <p>However, you can reset <code>l.bar</code> so that it refers to the method it originally referred to, by doing <code>del l.bar</code>.</p> <p>The reason this works is because if the individual object has no <code>bar</code> attribute of its own, then Python looks next to see whether its class has an attribute of the same name. So, to begin with the expression <code>l.bar</code> evaluates to the class <code>foo.bar</code>, since <code>l</code> has type <code>foo</code>. Then you assigned <code>l</code> a <code>bar</code> attribute of its own, so <code>l.bar</code> suddenly starts evaluating to that object instead. You can restore normality by deleting the object's own attribute.</p> <blockquote> <p>what's the difference between l.bar and l.bar()</p> </blockquote> <p><code>l.bar</code> just gets the value of the attribute <code>bar</code> from the object <code>l</code> (or from its class, if the object <code>l</code> doesn't have one of its own, as explained above. If that fails too it'd go to base classes). <code>l.bar()</code> gets the value of that attribute and then calls it. <code>()</code> at this position means a function call, so the thing you put it after had better be callable.</p>
1
2016-08-15T17:14:59Z
[ "python", "oop", "inner-classes" ]
Re-defining already assigned python class
38,959,609
<p>I am new to Python and I inherited someone's code that had the following code structure. Why do I get an object not callable and how can I redefine this method again even after re-assigning l.bar. Another question would therefore be what's the difference between l.bar and l.bar()?</p> <pre><code>&gt;&gt;&gt; class foo(object): ... def __init__(self): ... self.name = "Food" ... class bar(object): ... def __init__(self): ... self.name = "Is" ... class tea(object): ... def __init__(self): ... self.name = "Good" ... &gt;&gt;&gt; l = foo() &gt;&gt;&gt; m = l.bar() &gt;&gt;&gt; m.name = "Was" &gt;&gt;&gt; l.bar = m &gt;&gt;&gt; r = l.bar() Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: 'bar' object is not callable </code></pre>
-2
2016-08-15T17:06:33Z
38,959,743
<p>It is not clear which of the following problems you are experiencing:</p> <h1>1. indentation issue</h1> <p>When copy-pasting from source to terminal, indentation sometimes gets messed up. in ipython you can use <code>%paste</code> to safely paste code.</p> <p>The correctly indented class declarations are:</p> <pre><code>class foo(object): def __init__(self): self.name = "Food" class bar(object): def __init__(self): self.name = "Is" class tea(object): def __init__(self): self.name = "Good" </code></pre> <p>But then the other commands make no sense.</p> <h1>2. instance is not the same as class</h1> <p>When defining a class inside a class, you have to use the outer class name to "get" to the inner class name. I.e.:</p> <pre><code>class foo(object): def __init__(self): self.name = "Food" class bar(object): def __init__(self): self.name = "Is" class tea(object): def __init__(self): self.name = "Good" foo_inst = foo() bar_inst = foo.bar() tea_inst = foo.bar.tea() </code></pre> <p>Anyhow, these lines still make not much sense:</p> <pre><code>&gt;&gt;&gt; l.bar = m &gt;&gt;&gt; r = l.bar() </code></pre> <p>Why would you want to override <code>bar</code> which is (was) a class name...</p>
0
2016-08-15T17:16:18Z
[ "python", "oop", "inner-classes" ]
Loop between 2 csv files stops at first mach
38,959,621
<p>I have 2 <code>csv</code> files: the source file has only one column with IDs (one ID per line). The 2nd <code>csv</code> file has the IDs plus extra info. I would like to check each ID from <code>file1</code> against all the records in <code>file2</code> and if there is a match, to print out the row that matched (from <code>file1</code>) with the corresponding info from <code>file2</code>.</p> <p>The files look like this.</p> <p>Source:</p> <pre><code>0234906006000 0234765306000 0231316005000 0234906006000 0212134006000 0125667806000 3334906006000 1778986006000 0239906006000 </code></pre> <p>Mine:</p> <pre><code>02349-34-010-000,Adam 05125-07-033-000,Michael 05172-04-042-000,Debora 8071-33-001-000,Matt 2349-38-007, 2349-38-011, 2349-38-012,Ken 0234906006000,Roger 3334906006000,Hummels 0231316005000,Don 0501401028000,Gregg </code></pre> <p>My code looks like:</p> <pre><code>import csv source = csv.reader(open("denver_source.csv")) mine = csv.reader(open("denver_mine.csv")) output = {} for line in source: print(line[0]) for xline in mine: if line[0] not in xline: continue output[line[0]] = xline print(xline) print("Result", output) </code></pre> <p>I get a result but I do not get all the matches, only the first match:</p> <pre><code>0234906006000 ['0501401028000', 'Gregg'] 0234765306000 ['0501401028000', 'Gregg'] 0231316005000 ['0501401028000', 'Gregg'] 0234906006000 ['0501401028000', 'Gregg'] 0212134006000 ['0501401028000', 'Gregg'] 0125667806000 ['0501401028000', 'Gregg'] 3334906006000 ['0501401028000', 'Gregg'] 1778986006000 ['0501401028000', 'Gregg'] 0239906006000 ['0501401028000', 'Gregg'] Result: {'0234906006000': ['0234906006000', 'Roger']} </code></pre> <p>Can you please help me understand where I fail in continuing the loop properly in the second file? I apologize if this was posted before but I only found more complex examples.</p>
1
2016-08-15T17:08:00Z
38,959,790
<p>You're specifically referring to line[0]. That's why it's only giving you the first match. Your loop is going X amount of times (x being how many lines are in the csv), but still checking to see if line[0] is in <code>mine</code>every loop iteration.</p> <p>Try this:</p> <pre><code>import csv source = csv.reader(open("denver_source.csv")) mine = csv.reader(open("denver_mine.csv")) output = {} for line in source: print(line) for xline in mine: if line not in xline: continue output[line] = xline print(xline) print("Result", output) </code></pre>
1
2016-08-15T17:19:48Z
[ "python", "python-3.x", "csv", "for-loop" ]
Loop between 2 csv files stops at first mach
38,959,621
<p>I have 2 <code>csv</code> files: the source file has only one column with IDs (one ID per line). The 2nd <code>csv</code> file has the IDs plus extra info. I would like to check each ID from <code>file1</code> against all the records in <code>file2</code> and if there is a match, to print out the row that matched (from <code>file1</code>) with the corresponding info from <code>file2</code>.</p> <p>The files look like this.</p> <p>Source:</p> <pre><code>0234906006000 0234765306000 0231316005000 0234906006000 0212134006000 0125667806000 3334906006000 1778986006000 0239906006000 </code></pre> <p>Mine:</p> <pre><code>02349-34-010-000,Adam 05125-07-033-000,Michael 05172-04-042-000,Debora 8071-33-001-000,Matt 2349-38-007, 2349-38-011, 2349-38-012,Ken 0234906006000,Roger 3334906006000,Hummels 0231316005000,Don 0501401028000,Gregg </code></pre> <p>My code looks like:</p> <pre><code>import csv source = csv.reader(open("denver_source.csv")) mine = csv.reader(open("denver_mine.csv")) output = {} for line in source: print(line[0]) for xline in mine: if line[0] not in xline: continue output[line[0]] = xline print(xline) print("Result", output) </code></pre> <p>I get a result but I do not get all the matches, only the first match:</p> <pre><code>0234906006000 ['0501401028000', 'Gregg'] 0234765306000 ['0501401028000', 'Gregg'] 0231316005000 ['0501401028000', 'Gregg'] 0234906006000 ['0501401028000', 'Gregg'] 0212134006000 ['0501401028000', 'Gregg'] 0125667806000 ['0501401028000', 'Gregg'] 3334906006000 ['0501401028000', 'Gregg'] 1778986006000 ['0501401028000', 'Gregg'] 0239906006000 ['0501401028000', 'Gregg'] Result: {'0234906006000': ['0234906006000', 'Roger']} </code></pre> <p>Can you please help me understand where I fail in continuing the loop properly in the second file? I apologize if this was posted before but I only found more complex examples.</p>
1
2016-08-15T17:08:00Z
38,960,086
<p>Well after you iterate through the second <code>.csv</code> in your inner loop you reach the end and no new lines can be read again.</p> <p>You should be using something like this where the second file is going to <code>seek(0)</code> to go back to the beginning after the inner loop breaks. Also, it is advisable to use <code>with</code> statements to open files since they make sure the file is closed when its body has executed:</p> <pre><code>with open("denver_source.csv") as cf1, open("denver_mine.csv") as cf2: source = csv.reader(cf1) mine = csv.reader(cf2) for line in source: for xline in mine: if line[0] in xline: output[line[0]] = xline break cf2.seek(0) </code></pre> <p>The noteworthy thing here is that you call <code>seek(0)</code> on the file you supply to <code>csv.reader</code> and not the instance of <code>csv.reader</code>. That is, you call <code>cf2.seek(0)</code> and not <code>mine.seek(0)</code>; the changes will be reflected on the <code>reader</code> instance and you'll be able to re-iterate as needed.</p> <p>Of course, you could re-factor this to use the <code>with</code> for every iteration of <code>line in source</code> instead of <code>seek(0)</code>; that's really down to personal preference.</p>
1
2016-08-15T17:41:27Z
[ "python", "python-3.x", "csv", "for-loop" ]
Reading C structures in Python with ctypes
38,959,713
<p>I'm using ctypes to call foreign functions in Python3.</p> <p>The C function is supposed to return the pointer to the structure:</p> <pre><code>struct sLinkedList { void* data; struct sLinkedList* next; }; typedef struct sLinkedList* LinkedList; </code></pre> <p>And the function as it is defined in C is as follows.</p> <pre><code>LinkedList IedConnection_getServerDirectory (IedConnection self, IedClientError * error, bool getFileNames ) </code></pre> <p>So I have my Python3 code as follows:</p> <pre><code>from ctypes import * ... class LinkedList(Structure): pass LinkedList._fields_ = [("data",c_void_p), ("next", POINTER(LinkedList))] ... IedConnection_getServerDirectory=dlllib.IedConnection_getServerDirectory IedConnection_getServerDirectory.argtypes=[c_void_p, c_void_p] IedConnection_getServerDirectory.restype = c_int LogicalDevicesPtr = IedConnection_getServerDirectory(IedConnection,iedClientError) </code></pre> <p>The IedConnection parameter is retrieved by other function as pointer, and I'm pretty sure it works fine. Also I can see that function itself works fine (it initiates communications, that could be seen in Wireshark).</p> <p>Then I try to get the information as result of function:</p> <pre><code>LogicalDevicesList_p = cast(LogicalDevicesPtr,POINTER(LinkedList)) LogicalDeviceList = LogicalDevicesList_p.contents </code></pre> <p>This lines passes and the following line fails:</p> <pre><code>Rdata = LogicalDeviceList.data </code></pre> <p>with "Segmentation fault: 11"</p> <p>I suppose the problem if with types definitions, but I have no idea where the mistake is. Could anyone help?</p>
4
2016-08-15T17:14:12Z
38,960,415
<p>Well, looks like i've solved it by myself:</p> <pre><code>IedConnection_getServerDirectory.restype = c_int </code></pre> <p>is incorrect and shall was changed to:</p> <pre><code>IedConnection_getServerDirectory.restype = c_void_p </code></pre> <p><strong>And it started working fine already.</strong></p> <p>But additionally I've added third argument to function call to make it more neat:</p> <pre><code>IedConnection_getServerDirectory.argtypes=[c_void_p, c_void_p, c_bool] LogicalDevicesPtr = IedConnection_getServerDirectory(IedConnection,iedClientError,c_bool(False)) </code></pre>
2
2016-08-15T18:01:53Z
[ "python", "c", "ctypes" ]
tensorflow.merge_all_summaries() hangs
38,959,733
<p>I've been having a problem where if I run <code>sess.run(tf.merge_all_summaries())</code> during training, the program will hang. This was also brought up in <a href="https://github.com/tensorflow/tensorflow/issues/3704" rel="nofollow">a github issue</a>, although I'm not sure that my problem is the same.</p> <p>For reference, this is the code I'm using to train:</p> <pre><code>logits = fcn8.upscore # last layer of the network loss = softmax_loss(logits, lb, pipe.NUM_CLASSES) train_op = build_graph(loss, global_step) saver = tf.train.Saver(tf.all_variables()) summary_op = tf.merge_all_summaries() sess.run(tf.initialize_all_variables()) tf.train.start_queue_runners(sess=sess) summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph) for step in range(FLAGS.max_epochs * pipe.EPOCH_LENGTH): if sess.run(queue.size()) == 0: sess.run(enqueue_files) _, loss_val = sess.run([train_op, loss]) if step % 10 == 0: print('loss at step {}: {}'.format(step, loss_val)) summary = sess.run(summary_op) # hangs here summary_writer.add_summary(summary, step) </code></pre> <p>Is this a common thing? Or is there some error I've made in writing the training code? Thanks in advance for any help.</p> <p><strong>EDIT:</strong> It seems like the only time this happens is when the queue is empty when I try to merge summaries. I wonder if this is a coincidence.</p>
1
2016-08-15T17:15:42Z
38,961,775
<p>Your <code>summary_op</code> likely triggers a Queue dequeue which will hang when the queue is empty.</p> <p>One work-around is to restructure your code using variables so that summaries don't trigger queue dequeue, like here -- <a href="http://stackoverflow.com/questions/36783560/tensorflow-reading-images-in-queue-without-shuffling/36783901#36783901">TensorFlow: Reading images in queue without shuffling</a></p> <p>A simpler work-around is to initialize your Session with a deadline so that your empty dequeues fail with <code>DeadlineExceeded</code> after some time rather than hanging</p> <pre><code>tf.reset_default_graph() queue = tf.FIFOQueue(capacity=5, dtypes=[tf.int32]) config = tf.ConfigProto() config.operation_timeout_in_ms=2000 sess = tf.InteractiveSession("", config=config) try: sess.run(queue.dequeue()) except tf.errors.DeadlineExceededError: print "DeadlineExceededError detected" </code></pre>
1
2016-08-15T19:33:00Z
[ "python", "tensorflow" ]
testing client- server on the same computer
38,959,744
<p>I am trying to test socket communication on my laptop using python. However, I'm not sure why the connection is not being established? I keep getting error that the target machine is actively refusing connection. I am trying to use the same computer to run both the client and the server portion. The server is running fine but the client is the one not connecting. I think I have the hostname wrong (127.0.0.1) but not sure what Im supposed to be using? I also tried changing the server hostname to (0.0.0.0) and the IPV4 address for the hostname the client was to connect to but that didn't work either. Any help would be appreciated!</p> <p>My code(server portion):</p> <pre><code>import socket comms_socket =socket.socket() comms_socket.bind(('127.0.0.1', 50000)) comms_socket.listen(10) connection, address = comms_socket.accept() while True: print(connection.recv(4096).decode("UTF-8")) send_data = input("Reply: ") connection.send(bytes(send_data, "UTF-8")) </code></pre> <p>Client portion:</p> <pre><code>import socket comms_socket = socket.socket() comms_socket.connect(('127.0.0.1',50000)) while True: send_data = input("Message: ") comms_socket.send(bytes(send_data, "UTF-8")) print(comms_socket.recv(4096).decode("UTF-8")) </code></pre>
0
2016-08-15T17:16:19Z
38,960,563
<p>Your code won't work with python 2.* , because of the differences in <code>input()</code>, <code>raw_input()</code>, <code>bytes</code>, etc. in python 3.* vs python 2.* . You'd have to minimally make the following changes to get it working with python 2.*. Otherwise, use python 3 to run your code: </p> <p>Server program:</p> <pre><code>import socket comms_socket =socket.socket() comms_socket.bind(('127.0.0.1', 7000)) comms_socket.listen(10) connection, address = comms_socket.accept() while True: print(connection.recv(4096).decode("UTF-8")) send_data = raw_input("Reply: ") # Use raw_input() instead of input() connection.send(send_data.encode("UTF-8")) </code></pre> <p>Client program:</p> <pre><code>import socket comms_socket = socket.socket() comms_socket.connect(('127.0.0.1',7000)) while True: send_data = raw_input("Message: ") comms_socket.send(send_data.encode("UTF-8")) print(comms_socket.recv(4096).decode("UTF-8")) </code></pre> <p>If you want to use <code>bytes</code> as intended in your specific usecase, you should use <code>bytesarray</code> instead in python 2.6 or higher. Check this: <a href="http://stackoverflow.com/questions/5901706/the-bytes-type-in-python-2-7-and-pep-358">the bytes type in python 2.7 and PEP-358</a></p>
0
2016-08-15T18:12:38Z
[ "python", "sockets", "tcp", "client", "communication" ]
UPDATED: Parsing JSON object in python when object contains an array and another associated object at the same level
38,959,786
<p>I'm having trouble with a JSON object being passed to me by one of our products API's. I'm using Python 2.7 to create a function to let our customer service team see details about jobs that are posted on our website. The JSON package returns an array of objects that each contain an array and an object. I need to read the array associated with one of the objects inside the main object, however their not nested. As in the array of applicants is not nested inside the object of Job. This means my usual "response[0][0]['applicantName']" won't work here.</p> <p>The data below is updated, to represent what the API is actually giving me. My apologies before, I had edited it in order to protect the data. Still done the same, but it's the actual result.</p> <p>What I'd like to do is let a user input the jobId and I'll provide them with a list of all the applicants related to that jobID. Since the jobID can sometimes be non-sequential, I can't use an index number, it must be the jobID number. </p> <p>Can someone help?</p> <p>Heres the JSON structure I get:</p> <pre><code>[{u'bids': [{u'applicantId': 221, u'comment': 'I have applied to the job'}, {u'applicantId': 221, u'comment': 'I have applied to the job'}], u'job': {u'jobId': 1}}, {u'bids': [{u'applicantId': 221, u'comment': 'I have applied to the job'}, {u'applicantId': 221, u'comment': 'I have applied to the job'}], u'job': {u'jobId': 1}}] </code></pre> <p>As I said, I'm working in python 2.7 using the "requests" library to call the API and .json() to read it.</p> <p>Thanks in advance!</p>
-1
2016-08-15T17:19:33Z
38,959,921
<p>That content doesn't seem to be a valid json, which means you won't be able to parse it with the typical well-known <code>json.loads</code> function.</p> <p>Also, you won't be able to use <a href="https://docs.python.org/2/library/ast.html#ast.literal_eval" rel="nofollow">ast.literal_eval</a> cos it's not a valid python expression.</p> <p>Not sure this will be a good idea... but assuming you're getting that content as a string I'd try to write my own parser for that type of server-objects instead or just looking for an external library able to parse them.</p>
1
2016-08-15T17:30:20Z
[ "python", "asp.net", "arrays", "json" ]
Mapping set on new index is ignored
38,959,794
<p>Hi ! </p> <p>I just started to learn ElasticSearch, and my first steps wasn't too bad. I put some data into with the help of the ES library available on Python with the following piece of code:</p> <pre><code>from elasticsearch import Elasticsearch jsondata(json.dumps("{ "low": "5.9400", "high": "5.9600", "id": "555", "volume": 1171, "timestamp": "2016-08-15 19:01:03" }" ) ES_HOST = {"host" : "localhost", "port" : 9200} es = Elasticsearch(hosts = [ES_HOST]) es.create(index="index_test", doc_type="tr", body=jsondata ) </code></pre> <p>However, when I wanted to define each type of fields I put, ES just ignore it. I think the way I proceed isn't correct. There is the piece of code I executed just before execute my Python script :</p> <pre><code>curl -XPUT 'http://localhost:9200/index_test/' -d '"mappings": { "tr": { "_source": { "enabled":true } "properties" : { "id" : { "type" : "integer" }, "volume" : { "type" : "integer" }, "high" : { "type" : "float" }, "low" : { "type" : "float" }, "timestamp" : { "type" : "date", "format" : "yyyy-MM-dd HH:mm:ss" } } } }' </code></pre> <p>By default, ES store the data with all fields set as <code>string</code>, except the <code>volume</code> field, set as <code>number</code>. There is the JSON gave by ES via Kibana:</p> <pre><code>{ "_index": "index_test", "_type": "tr", "_id": "AVaPJj8Y0iDATupCtaXZ", "_score": 1, "_source": { "low": "5.9400", "high": "5.9600", "id": "555", "volume": 1171, "timestamp": "2016-08-15 19:01:03" } } </code></pre> <p>Anything I forgot ? Maybe I needed to add the settings part ? </p>
0
2016-08-15T17:20:14Z
38,960,400
<p>There it is !</p> <p>Ok, I've tried to do the following:</p> <pre><code>$curl -XDELETE http://localhost:9200/index_test/ {"acknowledged":true} $curl -XPUT 'http://localhost:9200/index_test/' -d conf/ESConf/ElasticSearchMapping.conf {"acknowledged":true} $curl -XGET 'http://localhost:9200/index_test/' {"index_test":{"aliases":{},"mappings":{},"settings":{"index": {"conf/ESConf/ElasticSearchMapping":{"conf":""},"creation_date":"1471283566621","number_of_shards":"5","number_of_replicas":"1","uuid":"EZoDAOJNQoiX4VQWs1Sx1w","version":{"created":"2030499"}}},"warmers":{}}} </code></pre> <p>So I forgot to add @ before my path, that's why it did not worked ^^":</p> <pre><code>curl -XPUT 'http://localhost:9200/index_test/' -d @conf/ESConf/ElasticSearchMapping.conf </code></pre>
0
2016-08-15T18:01:24Z
[ "python", "elasticsearch" ]
How can I continually send data without shutdown socket connection in python
38,959,847
<p>I wrote a python client to communicate with server side. Each time when I finished sanding out data, I have to call <code>sock.shutdown(socket.SHUT_WR)</code>, otherwise the server would not do any response. But after calling <code>sock.shutdown(socket.SHUT_WR)</code>, I have to reconnect the connection as <code>sock.connect((HOST, PORT))</code>, other wise I can not send data to server. So how can I keep the connection alive without close it. My sample code as following:</p> <pre><code>sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) sock.sendall(data) sock.shutdown(socket.SHUT_WR) received = sock.recv(1024) while len(received)&gt;0: received = sock.recv(1024) sock.sendall(newdata) # this would throw exception </code></pre> <p>The Server Side code as following:</p> <pre><code>def handle(self): cur_thread = threading.current_thread() while True: self.data = self.rfile.read(bufsiz=100) if not self.data: print 'receive none!' break try: data = self.data print 'Received data, length: %d' % len(data) self.wfile.write('get received data\n') except Exception: print 'exception!!' </code></pre>
1
2016-08-15T17:24:51Z
38,960,222
<p>You didn't show any server side code but I suspect it simply reads bytes until it gets none anymore. </p> <p>You can't do this as you found out, because then the only way to tell the server the message is complete is by killing the connection.</p> <p>Instead you'll have to add some form of framing in your protocol. Possible approaches include a designated stop character that the server recognises (such as a single newline character, or perhaps a 0-byte), sending frames in fixed sizes that your client and server agree upon, or send the frame size first as a network encoded integer followed by exactly the specified number of bytes. The server then first reads the integer and then exactly that same number of bytes from the socket. </p> <p>That way you can leave the connection open and send multiple messages.</p>
2
2016-08-15T17:49:33Z
[ "python", "sockets" ]
Add new data to a text file without overwriting it in python
38,959,849
<p>Right, I'm running a while loop that does some calculations, and, at the end, exports the data to a .txt file. The problem is, rather than appending the data to the end of the file, it seems to overwrite it and create a brand new file instead. How would I make it append to the old file?</p> <p>Here's my code:</p> <pre><code>turn = 1 while turn &lt; times: dip1 = randint(1,4) dip2 = randint(1,4) dip = (dip1 + dip2) - 2 adm1 = randint(1,4) adm2 = randint(1,4) adm = (adm1 + adm2) - 2 mil1 = randint(1,4) mil2 = randint(1,4) mil = (mil1 + mil2) - 2 with open("Monarchs Output.txt", "w") as text_file: print("Monarch{}, adm: {}, dip: {}, mil: {}\n".format(turn, adm, dip, mil), file=text_file) turn = turn + 1 </code></pre> <p>Just to note, it runs just fine, all the required imports are at the top of the code.</p>
0
2016-08-15T17:24:53Z
38,959,878
<p>You should use <code>open("Monarchs Output.txt", "a")</code> instead of <code>open("Monarchs Output.txt", "w")</code><br> link: <a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files</a></p>
1
2016-08-15T17:26:37Z
[ "python", "python-3.x" ]