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
sequence
Pandas Get a list of index from dataframe.loc
40,059,994
<p>I have looked through various sites and SO posts.Seems easy but somehow i am stuck with this.I am using</p> <pre><code>print frame.loc[(frame['RR'].str.contains("^[^123]", na=False)), 'RR'].isin(series1.str.slice(1)) </code></pre> <p>to get</p> <pre><code>3 True 4 False 8 False Name: RR, dtype: bool </code></pre> <p>Now,somehow i want the <code>indexes</code> only so that i can use that in <code>dataframe.drop</code>. Basically all the indexes where value is <code>True</code> , i have to grab <code>indexes</code> and <code>drop</code> them.Is there any other way as well without using <code>indexes</code>?</p>
2
2016-10-15T14:06:41Z
40,060,245
<p>You are testing two conditions on the same column so these can be combined (and negated):</p> <pre><code>frame[~((frame['RR'].str.contains("^[^123]", na=False)) &amp; (frame['RR'].isin(series1.str.slice(1))))] </code></pre> <p>Here, after <code>~</code> operator, it checks whether a particular row satisfies both conditions - same as the boolean array you get in the end. With <code>~</code>, you turn True's to False's and False's to True's. Finally, <code>frame[condition]</code> returns the rows that satisfy the final condition with boolean indexing.</p> <p>In a more readable format:</p> <pre><code>condition1 = frame['RR'].str.contains("^[^123]", na=False) condition2 = frame['RR'].isin(series1.str.slice(1)) frame[~(condition1 &amp; condition2)] </code></pre> <p>As an alternative (requires 0.18.0), you can get the indices of the True elements with:</p> <pre><code>frame.loc[(frame['RR'].str.contains("^[^123]", na=False)), 'RR'].isin(series1.str.slice(1))[lambda df: df].index </code></pre>
1
2016-10-15T14:29:14Z
[ "python", "python-2.7", "pandas" ]
Google Sheets API HttpError 500 and 503
40,059,997
<p>Edit: solved, the issue was on Google's side. Occurs when requesting a sheet which had diagrams that had invalid intervals in them. Reported bug to Google.</p> <p>Note: This issue has persisted for more than 2 days. I had it previously but it was automatically resolved after waiting a day. It has since rearisen.</p> <p>I am currently using the Google Sheets API through Google's python api client. The authentication is OAuth2.0 and I did not change anything significant in my codebase but all of the sudden I am getting 100% error ratio, and it seems like it should be on Google's end. I fear that I am banned from using the API indefinitely, is this the case? My guess is that when I launched the script and immediately cancelled it with ctrl+c because I wanted to run a new version of it caused some issues.</p> <p>I tried creating another project and using its credentials to make the request and got the same error. Tried having my friend run the script authenticating through his google account and he receives the same error. The independent <a href="http://pastebin.com/PHgpRmHe" rel="nofollow">source code can be found here</a> </p> <p>About the source code: The get_credentials() (and therefore the authentication) is entirely copied from Google's python quickstart script as seen here <a href="https://developers.google.com/sheets/quickstart/python" rel="nofollow">https://developers.google.com/sheets/quickstart/python</a>.</p> <p>Tracebacks:</p> <pre><code>Traceback (most recent call last): File "Google_sheets.py", line 164, in &lt;module&gt; ss=Spreadsheet(SPREADSHEET_ID) File "Google_sheets.py", line 83, in __init__ spreadsheetId=self.ssId, includeGridData=True).execute()['sheets']} File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper return wrapped(*args, **kwargs) File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\googleapiclient\http.py", line 838, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: &lt;HttpError 500 when requesting https://sheets.googleapis.com/v4/spreadsheets/12YdppOoZUNZxhXvcY_cRgfXEfRnR_izlBsF8Sin3rw4?alt=json&amp;includeGridData=true returned "Internal error encountered."&gt; </code></pre> <p>After retrying shortly after, I get another error:</p> <pre><code>Traceback (most recent call last): File "Google_sheets.py", line 164, in &lt;module&gt; ss=Spreadsheet(SPREADSHEET_ID) File "Google_sheets.py", line 83, in __init__ spreadsheetId=self.ssId, includeGridData=True).execute()['sheets']} File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper return wrapped(*args, **kwargs) File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\googleapiclient\http.py", line 838, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: &lt;HttpError 503 when requesting https://sheets.googleapis.com/v4/spreadsheets/12YdppOoZUNZxhXvcY_cRgfXEfRnR_izlBsF8Sin3rw4?includeGridData=true&amp;alt=json returned "The service is currently unavailable."&gt; </code></pre>
0
2016-10-15T14:06:43Z
40,071,563
<p>500 and 503 are Google Server issues. You will need to implement exponential backoff so that you can retry the transaction again. Check this link - <a href="https://developers.google.com/admin-sdk/directory/v1/limits" rel="nofollow">https://developers.google.com/admin-sdk/directory/v1/limits</a></p> <p>And, there is a usage limit for all APIs. Check out this link - <a href="https://developers.google.com/gmail/api/v1/reference/quota" rel="nofollow">https://developers.google.com/gmail/api/v1/reference/quota</a></p>
0
2016-10-16T14:44:01Z
[ "python", "google-spreadsheet", "google-api", "google-api-client", "google-sheets-api" ]
Google Sheets API HttpError 500 and 503
40,059,997
<p>Edit: solved, the issue was on Google's side. Occurs when requesting a sheet which had diagrams that had invalid intervals in them. Reported bug to Google.</p> <p>Note: This issue has persisted for more than 2 days. I had it previously but it was automatically resolved after waiting a day. It has since rearisen.</p> <p>I am currently using the Google Sheets API through Google's python api client. The authentication is OAuth2.0 and I did not change anything significant in my codebase but all of the sudden I am getting 100% error ratio, and it seems like it should be on Google's end. I fear that I am banned from using the API indefinitely, is this the case? My guess is that when I launched the script and immediately cancelled it with ctrl+c because I wanted to run a new version of it caused some issues.</p> <p>I tried creating another project and using its credentials to make the request and got the same error. Tried having my friend run the script authenticating through his google account and he receives the same error. The independent <a href="http://pastebin.com/PHgpRmHe" rel="nofollow">source code can be found here</a> </p> <p>About the source code: The get_credentials() (and therefore the authentication) is entirely copied from Google's python quickstart script as seen here <a href="https://developers.google.com/sheets/quickstart/python" rel="nofollow">https://developers.google.com/sheets/quickstart/python</a>.</p> <p>Tracebacks:</p> <pre><code>Traceback (most recent call last): File "Google_sheets.py", line 164, in &lt;module&gt; ss=Spreadsheet(SPREADSHEET_ID) File "Google_sheets.py", line 83, in __init__ spreadsheetId=self.ssId, includeGridData=True).execute()['sheets']} File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper return wrapped(*args, **kwargs) File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\googleapiclient\http.py", line 838, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: &lt;HttpError 500 when requesting https://sheets.googleapis.com/v4/spreadsheets/12YdppOoZUNZxhXvcY_cRgfXEfRnR_izlBsF8Sin3rw4?alt=json&amp;includeGridData=true returned "Internal error encountered."&gt; </code></pre> <p>After retrying shortly after, I get another error:</p> <pre><code>Traceback (most recent call last): File "Google_sheets.py", line 164, in &lt;module&gt; ss=Spreadsheet(SPREADSHEET_ID) File "Google_sheets.py", line 83, in __init__ spreadsheetId=self.ssId, includeGridData=True).execute()['sheets']} File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper return wrapped(*args, **kwargs) File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\googleapiclient\http.py", line 838, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: &lt;HttpError 503 when requesting https://sheets.googleapis.com/v4/spreadsheets/12YdppOoZUNZxhXvcY_cRgfXEfRnR_izlBsF8Sin3rw4?includeGridData=true&amp;alt=json returned "The service is currently unavailable."&gt; </code></pre>
0
2016-10-15T14:06:43Z
40,072,468
<p>As described in <a href="https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors#standard_errors" rel="nofollow">Standard Error Responses</a>, error codes #500 and #503 are errors associated with servers. Recommended action for this is not to retry the query more than once.</p> <p>To handle these error codes:</p> <blockquote> <p>A 500 or 503 error might result during heavy load or for larger more complex requests. For larger requests consider requesting data for a shorter time period. Also <strong>consider</strong> <a href="https://developers.google.com/analytics/devguides/reporting/core/v3/coreErrors#backoff" rel="nofollow"><strong>implementing exponential backoff</strong></a>.</p> </blockquote> <p>An exponential backoff may be a good strategy for handling those errors if a high volume of requests or heavy network traffic causes the server to return errors. </p> <p>In addition to that, you should also check if your application is exceeding the <a href="https://developers.google.com/sheets/limits" rel="nofollow">usage limits</a>. If it does, it is possible that your application code should be optimized to make fewer requests. You may opt to request additional quota in the Google API Console under the Quotas tab of a project if needed.</p>
0
2016-10-16T16:17:21Z
[ "python", "google-spreadsheet", "google-api", "google-api-client", "google-sheets-api" ]
Google Sheets API HttpError 500 and 503
40,059,997
<p>Edit: solved, the issue was on Google's side. Occurs when requesting a sheet which had diagrams that had invalid intervals in them. Reported bug to Google.</p> <p>Note: This issue has persisted for more than 2 days. I had it previously but it was automatically resolved after waiting a day. It has since rearisen.</p> <p>I am currently using the Google Sheets API through Google's python api client. The authentication is OAuth2.0 and I did not change anything significant in my codebase but all of the sudden I am getting 100% error ratio, and it seems like it should be on Google's end. I fear that I am banned from using the API indefinitely, is this the case? My guess is that when I launched the script and immediately cancelled it with ctrl+c because I wanted to run a new version of it caused some issues.</p> <p>I tried creating another project and using its credentials to make the request and got the same error. Tried having my friend run the script authenticating through his google account and he receives the same error. The independent <a href="http://pastebin.com/PHgpRmHe" rel="nofollow">source code can be found here</a> </p> <p>About the source code: The get_credentials() (and therefore the authentication) is entirely copied from Google's python quickstart script as seen here <a href="https://developers.google.com/sheets/quickstart/python" rel="nofollow">https://developers.google.com/sheets/quickstart/python</a>.</p> <p>Tracebacks:</p> <pre><code>Traceback (most recent call last): File "Google_sheets.py", line 164, in &lt;module&gt; ss=Spreadsheet(SPREADSHEET_ID) File "Google_sheets.py", line 83, in __init__ spreadsheetId=self.ssId, includeGridData=True).execute()['sheets']} File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper return wrapped(*args, **kwargs) File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\googleapiclient\http.py", line 838, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: &lt;HttpError 500 when requesting https://sheets.googleapis.com/v4/spreadsheets/12YdppOoZUNZxhXvcY_cRgfXEfRnR_izlBsF8Sin3rw4?alt=json&amp;includeGridData=true returned "Internal error encountered."&gt; </code></pre> <p>After retrying shortly after, I get another error:</p> <pre><code>Traceback (most recent call last): File "Google_sheets.py", line 164, in &lt;module&gt; ss=Spreadsheet(SPREADSHEET_ID) File "Google_sheets.py", line 83, in __init__ spreadsheetId=self.ssId, includeGridData=True).execute()['sheets']} File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\oauth2client\util.py", line 137, in positional_wrapper return wrapped(*args, **kwargs) File "C:\Users\Larsson\AppData\Local\Programs\Python\Python35-32\lib\site-packages\googleapiclient\http.py", line 838, in execute raise HttpError(resp, content, uri=self.uri) googleapiclient.errors.HttpError: &lt;HttpError 503 when requesting https://sheets.googleapis.com/v4/spreadsheets/12YdppOoZUNZxhXvcY_cRgfXEfRnR_izlBsF8Sin3rw4?includeGridData=true&amp;alt=json returned "The service is currently unavailable."&gt; </code></pre>
0
2016-10-15T14:06:43Z
40,113,172
<p>Solved, the issue was on Google's side. Occurs when requesting a sheet which had diagrams that had invalid/unselected intervals in them. Reported bug to Google.</p> <p>Fix by changing all invalid diagrams to valid ranges.</p>
0
2016-10-18T16:10:55Z
[ "python", "google-spreadsheet", "google-api", "google-api-client", "google-sheets-api" ]
Can't access the key from my hashtable python
40,060,017
<p>So I have a hash table class which is fully functioning, now I want to define another function let say will take a parameter of hash_table and print out every keys from my hash table where </p> <pre><code>def to_print(hash_table): for a in hash_table: if a is not None: print(a) </code></pre> <p>I was told that I need an iterator, so I define an iter function like below:</p> <pre><code>def __iter__(self): for item in self.array: if item is not None: (key, value)=item return key </code></pre> <p>However, I still can't read through my keys in my hash table.Error is happened at my line 'for a in hash_table:' For the iterator, if I change 'return key' to 'print key', it does print out every key. And I didn't define <strong>next</strong> because I think I don't need it(?)</p> <p>Can anyone tell me where's the problem and maybe some hints of it? Thanks in advance.</p> <p>Eg. my hash table consist of &lt;'apple',6>, &lt;'orange', 7>, my output should print out apple and orange.</p>
0
2016-10-15T14:08:13Z
40,060,062
<p><code>__iter__</code> must return iterator, try to do something like:</p> <pre><code>def __iter__(self): return (item[0] for item in self.array if item is not None) </code></pre>
1
2016-10-15T14:12:01Z
[ "python", "class", "iterator", "hashtable" ]
Python script stuck in infinite loop
40,060,069
<p>I am writing a beginner python script for the python challenge ARG. The basic aim is to write a script that will read through a mass of text, pass through only the lower-case characters with exactly 3 capitals either side. The script is supposed to look at an incoming character from a list, store the next 3 characters and previous 3 characters in a list. Once this has happened, the script evaluates whether or not the incoming character is a capital, if it is the loop starts over, if not the script then evaluates if all three characters in the list are capitalised. If the conditions are met, the script should print the current character, else the loops starts over. </p> <p>Whenever I run this script I am left with no debug/error/warnings about the code but it never completes or writes anything to the file. </p> <p>here is the code I have written, any help would be appreciated. </p> <pre><code>#code, where f = text to be processed, d = text file to be written to f = open("test.txt", "r+") f = f.read() fList = list(f) limit = len(fList) #Set location of result d = open("noided.txt", "r+") i, j, k = [0, 0, 0] #Main loop #While there are characters left to be processed while i &lt; limit: #Skip the first 4 characters if i &lt; 4: #print i, fList[i] i += 1 else: #print i, fList[i] currentChar = fList[i] count = 0 prevChars = [fList[i-1],fList[i-2],fList[i-3]] nextChars = fList[i:i + 3] if currentChar.isupper(): i += 1 else: while k &lt; 3: if prevChars[k].isupper() and nextChars[k].isupper(): count += 1 k += 1 elif count == 3: print currentChar d.write(currentChar) i += 1 else: i += 1 </code></pre>
0
2016-10-15T14:12:58Z
40,060,248
<p>For starters, you have no variable named limit. Second, it would be easier to use stack type of list. Think of the stack as a stack of papers. You can parse the letters from the file into the stack (using a for loop), but then you can compare each character before it enters the stack, making this module useful for this kind of project</p>
0
2016-10-15T14:29:28Z
[ "python", "python-2.7" ]
kwargs overriding dict subclass
40,060,094
<p>A minimal example is as follows:</p> <pre><code>class sdict(dict): class dval: def __init__(self, val): self.val = val def __init__(self, args): dictionary = dict(args) for k,v in dictionary.items(): self[k] = v def __setitem__(self,key,value): try: self[key].val = value except KeyError: dict.__setitem__(self,key,self.dval(value)) def __getitem__(self,key): return dict.__getitem__(self,key).val </code></pre> <p>Now I can use this class inside a container to override assignment stuff:</p> <pre><code>class cont(object): def __init___(self): self._mydict = sdict(()) @property def mydict(self): return self._mydict @mydict.setter def mydict(self,dict_initializor): self._mydict = sdict(dict_initializor) return self.mydict </code></pre> <p>I use this so my container holds a dictionary with pointable primitives (i.e. mutable in python language) but whenever I retrieve the item I get the primitive itself. In my case floats, which I multiply, add etc... Adding __str__/__repr__ functions makes this work when printing these, but for debugging purposes these are omitted.</p> <p>This works nicely almost everywhere, except when passing this along using kwargs:</p> <pre><code>def test(a,b): return a*b c = cont() c.mydict = {'a':1,'b':2} print c.mydict['a']+c.mydict['b'],type(c.mydict['a']+c.mydict['b']) print test(**c.mydict) </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>3 &lt;type 'int'&gt; Traceback (most recent call last): File "D:\kabanus\workspace\py-modules\test.py", line 32, in &lt;module&gt; print test(**c.mydict) File "D:\kabanus\workspace\py-modules\test.py", line 28, in test def test(a,b): return a*b TypeError: unsupported operand type(s) for *: 'instance' and 'instance' </code></pre> <p>Obviously the unpacking procedure does not use __getitem__ to create values for the keywords. I also attempted to override values() and items() with no success. Next I set all dict methods not defined by me to None to see if any are called - no success either.</p> <p>Bottom line - how do you get **kwargs unpacking to use __getitem__ or some other method?<br> Is this even possible?</p> <p>I also want to avoid defining mul, add, div and so forth if possible in class dval.</p>
2
2016-10-15T14:15:37Z
40,062,418
<p>Found the answer here, and there should be a way to make this easier to find: <a href="http://stackoverflow.com/questions/19526300/does-argument-unpacking-use-iteration-or-item-getting#19526400">Does argument unpacking use iteration or item-getting?</a></p> <p>Summary: Inheriting from builtins (dict,list...) is problematic since python may ignore your python API entirely (as it did for me) and use the underlying C. This happens in argument unpacking.</p> <p>Solution: use the available abstractions. In my example add:</p> <pre><code>from UserDict import UserDict </code></pre> <p>and replace all "dict" occurrences in the code with UserDict. This solution should be true for lists and tuples. </p>
1
2016-10-15T17:59:31Z
[ "python", "dictionary", "kwargs" ]
Navigating through a string and updating the value of string while navigating
40,060,116
<p>I have got the following code in Python (in PyCharm Community Edition):</p> <pre><code>def defer_tags(sentence): for letter in sentence: print(letter) if letter == '&lt;': end_tag = sentence.find('&gt;') sentence = sentence[end_tag+1:] print(sentence) defer_tags("&lt;h1&gt;Hello") </code></pre> <p>It produced the following output:</p> <pre class="lang-none prettyprint-override"><code>current letter = &lt; new_sentence = Hello current letter = h current letter = 1 current letter = &gt; current letter = H current letter = e current letter = l current letter = l current letter = o </code></pre> <p>Why does loop (<code>letter</code>) navigate through the entire string (<code>sentence</code>) even though the value of <code>sentence</code> has changed inside the loop ?</p> <p>I am printing out the value of <code>sentence</code> after the change but it is not getting reflected in the loop iterations.</p>
0
2016-10-15T14:16:52Z
40,060,327
<p>Better way to catch phrases from tags is just simple to use re.</p> <pre><code>import re def defer_tags(sentence): return re.findall(r'&gt;(.+)&lt;', sentence) defer_tags('&lt;h1&gt;Hello&lt;h1&gt;') &gt; ['Hello'] defer_tags('&lt;h1&gt;Hello&lt;/h1&gt;&lt;h2&gt;Ahoy&lt;/h2&gt;') &gt; ['Hello', 'Ahoy'] </code></pre> <p>This will work if the tags are full. Ie <code>&lt;h2&gt;Hello&lt;/h2&gt;</code> of <code>&lt;h1&gt;Ahoy&lt;/h1&gt; &lt;h2&gt;XX&lt;/h2&gt;</code> etc.</p>
-1
2016-10-15T14:34:56Z
[ "python", "string", "for-loop" ]
Navigating through a string and updating the value of string while navigating
40,060,116
<p>I have got the following code in Python (in PyCharm Community Edition):</p> <pre><code>def defer_tags(sentence): for letter in sentence: print(letter) if letter == '&lt;': end_tag = sentence.find('&gt;') sentence = sentence[end_tag+1:] print(sentence) defer_tags("&lt;h1&gt;Hello") </code></pre> <p>It produced the following output:</p> <pre class="lang-none prettyprint-override"><code>current letter = &lt; new_sentence = Hello current letter = h current letter = 1 current letter = &gt; current letter = H current letter = e current letter = l current letter = l current letter = o </code></pre> <p>Why does loop (<code>letter</code>) navigate through the entire string (<code>sentence</code>) even though the value of <code>sentence</code> has changed inside the loop ?</p> <p>I am printing out the value of <code>sentence</code> after the change but it is not getting reflected in the loop iterations.</p>
0
2016-10-15T14:16:52Z
40,061,374
<p>You can use beautiful soup library in python to do the same. please refer to this <a href="http://stackoverflow.com/questions/5598524/can-i-remove-script-tags-with-beautifulsoup">Can I remove script tags with BeautifulSoup?</a> </p>
-1
2016-10-15T16:15:55Z
[ "python", "string", "for-loop" ]
Navigating through a string and updating the value of string while navigating
40,060,116
<p>I have got the following code in Python (in PyCharm Community Edition):</p> <pre><code>def defer_tags(sentence): for letter in sentence: print(letter) if letter == '&lt;': end_tag = sentence.find('&gt;') sentence = sentence[end_tag+1:] print(sentence) defer_tags("&lt;h1&gt;Hello") </code></pre> <p>It produced the following output:</p> <pre class="lang-none prettyprint-override"><code>current letter = &lt; new_sentence = Hello current letter = h current letter = 1 current letter = &gt; current letter = H current letter = e current letter = l current letter = l current letter = o </code></pre> <p>Why does loop (<code>letter</code>) navigate through the entire string (<code>sentence</code>) even though the value of <code>sentence</code> has changed inside the loop ?</p> <p>I am printing out the value of <code>sentence</code> after the change but it is not getting reflected in the loop iterations.</p>
0
2016-10-15T14:16:52Z
40,070,234
<p>To be explicit, try using beautiful soup following way:</p> <pre><code>&gt;&gt;&gt; from BeautifulSoup import BeautifulSoup &gt;&gt;&gt; soup = BeautifulSoup('&lt;h1&gt;Hello&lt;h1&gt;') &gt;&gt;&gt; soup.text u'Hello' </code></pre>
0
2016-10-16T12:26:14Z
[ "python", "string", "for-loop" ]
working with images in pymongo API
40,060,158
<p>Im doing a pymongo connectivity program that uses python to create a gridfs database on mongodb and adds an image into the database.I've use command line parser to call the methods.I have successfully added the image in the db and it also reflects in the mongodb db but when I call show function it says image not found. Here is the code :</p> <pre><code>import argparse from PIL import Image from pymongo import Connection import gridfs from bson.binary import Binary # setup mongo MONGODB_HOST = 'localhost' MONGODB_PORT = 27017 # connect to the database &amp; get a gridfs handle mongo_con = Connection(MONGODB_HOST, MONGODB_PORT) fs = gridfs.GridFS(mongo_con.ank1) def add_image(): """add an image to mongo's gridfs""" gridfs_filename = 'ofc2.jpg' fileID = fs.put(open('C:\Python27\ofc2.jpg','r'),filename='ofc2.jpg') print "created new gridfs file {0} with id {1}".format(gridfs_filename, fileID) def show(): """start the flask service""" filename='ofc2.jpg' if not fs.exists(filename="ofc2.jpg"): raise Exception("mongo file does not exist! {0}".format(filename)) im_stream = fs.get_last_version(filename) im = Image.open(im_stream) im.show() def main(): # CLI parser = argparse.ArgumentParser() parser.add_argument('--show', action='store_true', help='start the service') parser.add_argument('--add', action='store_true', help='add an image via URL') args = parser.parse_args() if args.show: show() elif args.add: add_image() main() </code></pre> <p>Following is the op:`</p> <pre><code>D:\&gt;python img.py D:\&gt;python img.py D:\&gt;python img.py --add created new gridfs file ofc2.jpg with id 580237fb0f84ea10789b20e6 D:\&gt;python img.py --show Traceback (most recent call last): File "img.py", line 62, in &lt;module&gt; main() File "img.py", line 57, in main show() File "img.py", line 47, in show im = Image.open(im_stream) File "C:\Python27\lib\site-packages\PIL\Image.py", line 1980, in open raise IOError("cannot identify image file") IOError: cannot identify image file </code></pre> <p>on mongodb</p> <p>mongodb output</p> <pre><code>MongoDB Enterprise &gt; show dbs; ank 0.000GB ank1 0.000GB ankit 0.000GB gridfs_example 0.000GB local 0.000GB MongoDB Enterprise &gt; use ank1 switched to db ank1 MongoDB Enterprise &gt; show collections fs.chunks fs.files MongoDB Enterprise &gt; db.fs.files.find().pretty() { "_id" : ObjectId("5802397f0f84ea122c6176a6"), "chunkSize" : 261120, "filename" : "ofc2.jpg", "length" : 335, "uploadDate" : ISODate("2016-10-15T14:13:19.882Z"), "md5" : "ef937ff6e6a00e64a2dda34251ca03b5" } </code></pre> <p>i don't know what the problem is ive done the same program in fedora it worked.but in windows im having this problem is that related to os or the python versions</p>
0
2016-10-15T14:20:31Z
40,085,680
<p>You may need to convert the <code>im_stream</code> to bytes for reading using the <a href="https://docs.python.org/2/library/io.html#buffered-streams" rel="nofollow">BytesIO</a> class.</p> <pre><code>im = Image.open(io.BytesIO(im_stream.read()), 'r') </code></pre>
0
2016-10-17T11:51:00Z
[ "python", "mongodb", "pymongo" ]
Quadratic Formula Solver Error
40,060,179
<p>I'm writing a python quadratic equation solver, and it was working fine, then I ran it another time, and it gave me the following error:</p> <pre><code>Traceback (most recent call last): File "/Users/brinbrody/Desktop/PythonRunnable/QuadraticSolver.py", line 18, in &lt;module&gt; rted = math.sqrt(sqb-ac4) ValueError: math domain error </code></pre> <p>Here's my code:</p> <pre><code>#Quadratic Formula Solver #Imports import math #User Inputs a = int(input("a = ")) b = int(input("b = ")) c = int(input("c = ")) #Variables sqb = b**2 ac4 = 4*a*c a2 = 2*a negb = 0-b #Calculations rted = math.sqrt(sqb-ac4) top1 = negb + rted top2 = negb - rted low1 = round(top1/a2, 2) low2 = round(top2/a2, 2) #Output print("Possible Values of x:") print("1.",low1) print("2. ",low2) </code></pre> <p>This error is consistent with every input I've tried. </p>
0
2016-10-15T14:22:38Z
40,060,369
<p>As xli said, this is due to <code>sqb-ac4</code> returning a negative value, and the python math module can't take the square root of a negative value.</p> <p>A way to fix this is:</p> <pre><code>import sys determin = sqb - ac4 if determin &lt; 0: print("Complex roots") sys.exit() else: rted = math.sqrt(determin) </code></pre>
0
2016-10-15T14:38:59Z
[ "python", "math.sqrt" ]
Loop only reads 1st line of file
40,060,211
<p>I'm trying to convert a JSON file to XML using a small python script, but for some reason the loop only seems to read the first line of the JSON file. </p> <pre><code>from xml.dom import minidom from json import JSONDecoder import json import sys import csv import os import re import dicttoxml from datetime import datetime, timedelta from functools import partial reload(sys) sys.setdefaultencoding('utf-8') nav = 'navigation_items.bson.json' df = 'testxmloutput.txt' def json2xml(json_obj, line_padding=""): result_list = list() json_obj_type = type(json_obj) if json_obj_type is list: for sub_elem in json_obj: result_list.append(json2xml(sub_elem, line_padding)) return "\n".join(result_list) if json_obj_type is dict: for tag_name in json_obj: sub_obj = json_obj[tag_name] result_list.append("%s&lt;%s&gt;" % (line_padding, tag_name)) result_list.append(json2xml(sub_obj, "\t" + line_padding)) result_list.append("%s&lt;/%s&gt;" % (line_padding, tag_name)) return "\n".join(result_list) return "%s%s" % (line_padding, json_obj) def json_parse(fileobj, decoder=JSONDecoder(), buffersize=2048): buffer = '' for chunk in iter(partial(fileobj.read, buffersize), ''): buffer += chunk while buffer: try: result, index = decoder.raw_decode(buffer) yield result buffer = buffer[index:] except ValueError: # Not enough data to decode, read more break </code></pre> <p>def converter(data):</p> <pre><code>f = open(df,'w') data = open(nav) for line in json_parse(data): f.write(dicttoxml.dicttoxml(line, attr_type=False)) f.close() converter(nav) </code></pre> <p>I was under the assumption that the iter would read the first line to memory and move on to the next. The converted output looks great but im too sure where to look on how to get it to loop through to the next line in file. </p>
0
2016-10-15T14:25:47Z
40,060,517
<p>Try json.load to load the file into a dict and then iterate the dict for your output.</p> <pre><code>import sys import json json_file = sys.argv[1] data = {} with open(json_file) as data_file: data = json.load(data_file) for key in data: #do your things </code></pre>
0
2016-10-15T14:54:50Z
[ "python", "json", "xml", "loops" ]
Django Unitest: Table doesn't exist
40,060,253
<p>I created a simple test case like this:</p> <pre><code>from unittest import TestCase import user_manager class UserTest(TestCase): def test_register(self): email = "[email protected]" password = "123456" result, user = user_manager.setup_new_user(email, password) self.assertEqual(result, CodeID.SUCCESS) </code></pre> <p>Then I run the testcase:</p> <pre><code>python manage.py test users </code></pre> <p>And here is the log:</p> <pre><code>Creating test database for alias 'default'... /Users/admin/Projects/MyApp/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py:112: Warning: Table 'mysql.column_stats' doesn't exist return self.cursor.execute(query, args) Creating test database for alias 'myapp_log'... .FE ====================================================================== ERROR: test_register (users.tests.UserTest) ---------------------------------------------------------------------- Traceback (most recent call last): ... ProgrammingError: (1146, "Table 'test_myapp.user' doesn't exist") </code></pre> <p>So it created a test database but seem like it didn't create the tables. Here is my DATABASES setting:</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "myapp", 'USER': "root", 'PASSWORD': "", 'HOST': '127.0.0.1', 'PORT': '', }, 'myapp_log': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "myapp_log", 'USER': "root", 'PASSWORD': "", 'HOST': '127.0.0.1', 'PORT': '', }, } </code></pre> <p>And my model:</p> <pre><code>class User(BaseModel): uid = models.IntegerField(primary_key=True) email = models.CharField(max_length=200) password = models.CharField(max_length=200) create_time = models.IntegerField() update_time = models.IntegerField() status = models.IntegerField() social_token = models.CharField(max_length=200) social_app = models.IntegerField() class Meta: db_table = 'user' </code></pre> <p>Anyone know why the table 'user' is not created?</p> <p>UPDATE:</p> <p>user_manager from my testcase will do some query and add new record on table user. </p> <p>And I thought when I run the testcase, Django will somehow read my models and create a test database with all the table from those models. Am I right about this?</p>
-1
2016-10-15T14:29:39Z
40,060,331
<p>Your test database needs to be different than your production database. Test databases are destroyed once the test cases are run. In your case the database was not created. You should go through this documentation for detailed information <a href="https://docs.djangoproject.com/en/1.10/topics/testing/overview/" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/testing/overview/</a> Can you also add the snippet of your user_manager module</p>
0
2016-10-15T14:35:08Z
[ "python", "mysql", "django", "django-unittest" ]
Django Unitest: Table doesn't exist
40,060,253
<p>I created a simple test case like this:</p> <pre><code>from unittest import TestCase import user_manager class UserTest(TestCase): def test_register(self): email = "[email protected]" password = "123456" result, user = user_manager.setup_new_user(email, password) self.assertEqual(result, CodeID.SUCCESS) </code></pre> <p>Then I run the testcase:</p> <pre><code>python manage.py test users </code></pre> <p>And here is the log:</p> <pre><code>Creating test database for alias 'default'... /Users/admin/Projects/MyApp/venv/lib/python2.7/site-packages/django/db/backends/mysql/base.py:112: Warning: Table 'mysql.column_stats' doesn't exist return self.cursor.execute(query, args) Creating test database for alias 'myapp_log'... .FE ====================================================================== ERROR: test_register (users.tests.UserTest) ---------------------------------------------------------------------- Traceback (most recent call last): ... ProgrammingError: (1146, "Table 'test_myapp.user' doesn't exist") </code></pre> <p>So it created a test database but seem like it didn't create the tables. Here is my DATABASES setting:</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "myapp", 'USER': "root", 'PASSWORD': "", 'HOST': '127.0.0.1', 'PORT': '', }, 'myapp_log': { 'ENGINE': 'django.db.backends.mysql', 'NAME': "myapp_log", 'USER': "root", 'PASSWORD': "", 'HOST': '127.0.0.1', 'PORT': '', }, } </code></pre> <p>And my model:</p> <pre><code>class User(BaseModel): uid = models.IntegerField(primary_key=True) email = models.CharField(max_length=200) password = models.CharField(max_length=200) create_time = models.IntegerField() update_time = models.IntegerField() status = models.IntegerField() social_token = models.CharField(max_length=200) social_app = models.IntegerField() class Meta: db_table = 'user' </code></pre> <p>Anyone know why the table 'user' is not created?</p> <p>UPDATE:</p> <p>user_manager from my testcase will do some query and add new record on table user. </p> <p>And I thought when I run the testcase, Django will somehow read my models and create a test database with all the table from those models. Am I right about this?</p>
-1
2016-10-15T14:29:39Z
40,084,140
<p>So I found out I need to put my models.py in my users folder, and add 'users' into the INSTALL_APPS setting. Now it worked.</p>
0
2016-10-17T10:35:04Z
[ "python", "mysql", "django", "django-unittest" ]
How to color text to later be put in a docx file?
40,060,349
<p>I want to color a text present in the string and pass the string to another python file so that to put received colored string into a docx file. I tried in this way but it is not working.</p> <pre><code>from termcolor import colored from docx import Document document = Document() item_i="\n\n Comma is required in line dependent clause is in beginning\n\n" ctxt = colored(item_i, 'blue') p=document.add_paragraph() p.add_run(ctxt) document.add_page_break() document.save('demo.docx') </code></pre> <p>it displays properly in terminal but not in file, it shows an error</p> <pre><code>from termcolor import colored item_i="\n\n Comma is required in line dependent clause is in beginning\n\n" ctxt = colored(item_i, 'blue') print ctxt </code></pre> <p>In this format it displays properly. Kindly help me to resolve this issue.</p>
-2
2016-10-15T14:37:11Z
40,060,519
<p>You should be using <code>docx</code>'s text formatting since, as Jacques de Hooge said, <code>termcolor</code> is for terminal. See <a href="http://python-docx.readthedocs.io/en/latest/user/text.html#apply-character-formatting" rel="nofollow">here</a>.</p> <pre><code>from docx.shared import RGBColor </code></pre> <p>Then</p> <pre><code>run = p.add_run(item_i) run.font.color.rgb = RGBColor(0x00, 0x00, 0xFF) </code></pre>
2
2016-10-15T14:54:55Z
[ "python", "python-2.7", "python-docx", "termcolor" ]
Not able to install packages in Pycharm
40,060,353
<p>I have pycharm community edition(latest stable build) installed on my Ubuntu 16.04 LTS, I am not able to install packages via pycharm, was able to install them before. I can install the packages via pip, but would like to solve this issue.</p> <p>Below is the Screenshot of the problem</p> <p><a href="https://i.stack.imgur.com/DUkt3.png" rel="nofollow"><img src="https://i.stack.imgur.com/DUkt3.png" alt="enter image description here"></a></p> <p>Have googled for this issue, but could not find any fix, I have a windows machine and it does not face the same issue.</p>
1
2016-10-15T14:37:37Z
40,061,466
<p>I have got a solution, i reffered to <a href="https://youtrack.jetbrains.com/issue/PY-20081#u=1468410176856" rel="nofollow">https://youtrack.jetbrains.com/issue/PY-20081#u=1468410176856</a>.</p> <p>Here they have tried to add <a href="https://pypi.python.org/pypi" rel="nofollow">https://pypi.python.org/pypi</a> as a repository.</p> <p>To add it as a repository, </p> <pre><code>1.) Go to Settings 2.) Project interpreter 3.) Click the + sign on top right edge 4.) Go to manage repositories, 5.) Press the + Sign, then add https://pypi.python.org/pypi 6.) Press Ok </code></pre> <p>Now all the packages should load.</p> <p>Thanks Hami Torun &amp; Simon, I was able to solve it by luck.</p>
1
2016-10-15T16:23:50Z
[ "python", "pycharm" ]
Weird behaviour when running the script
40,060,380
<p>I started to code a guess the number type of game. When I execute the program, it either flows perfectly, either doesn't work...</p> <pre><code>import random from random import randint print("Welcome to guess the number!\nDo you want to play the game?") question = input("") if question == "Yes".lower(): print("Sweet! Let`s begin!\nGuess the number between 1 and 10!") number = random.randint(1, 10) guess = int(input("Take a guess!\n")) if guess &gt; number: print("Your guess is too high") guess = int(input("Take a guess!\n")) if guess &lt; number: print("Your guess is too low") guess = int(input("Take a guess!\n")) if guess == number: print("Your guess was correct!") elif question == "No".lower(): print("Too bad! Bye!") quit() </code></pre> <p>I absolutely no idea whether it happens because of the code, or pycharm is to blame! </p>
0
2016-10-15T14:40:09Z
40,060,613
<p>Changelog:</p> <p>a) You do not need "import random" as you are importing randint on the line below it.</p> <p>b) lower() is not in the right place as it will not work in inputs that are not all lowercase. It needs to be in the question variable</p> <p>c) You use a while loop so that you keep asking for a guess until it is found</p> <p>I guess the game works as it should like this:</p> <pre><code>from random import randint print("Welcome to guess the number!\nDo you want to play the game?") question = input("").lower() if question == "yes": print("Sweet! Let`s begin!\nGuess the number between 1 and 10!") number = randint(1, 10) guess = int(input("Take a guess!\n")) while guess != number: if guess &gt; number: print("Your guess is too high") if guess &lt; number: print("Your guess is too low") guess = int(input("Take a guess!\n")) else: print("Your guess was correct!") else: print("Too bad! Bye!") quit() </code></pre>
-1
2016-10-15T15:03:47Z
[ "python", "pycharm" ]
Weird behaviour when running the script
40,060,380
<p>I started to code a guess the number type of game. When I execute the program, it either flows perfectly, either doesn't work...</p> <pre><code>import random from random import randint print("Welcome to guess the number!\nDo you want to play the game?") question = input("") if question == "Yes".lower(): print("Sweet! Let`s begin!\nGuess the number between 1 and 10!") number = random.randint(1, 10) guess = int(input("Take a guess!\n")) if guess &gt; number: print("Your guess is too high") guess = int(input("Take a guess!\n")) if guess &lt; number: print("Your guess is too low") guess = int(input("Take a guess!\n")) if guess == number: print("Your guess was correct!") elif question == "No".lower(): print("Too bad! Bye!") quit() </code></pre> <p>I absolutely no idea whether it happens because of the code, or pycharm is to blame! </p>
0
2016-10-15T14:40:09Z
40,060,672
<p>You really need a while loop. If the first guess is too high then you get another chance, but it then only tests to see if it is too low or equal. If your guess is too low then your second chance has to be correct.</p> <p>So you don't need to keep testing, you can simplify, but you should really do this at the design stage. Here is my version:</p> <pre><code>import random # from random import randint &lt;&lt; no need for this line print("Welcome to guess the number!") question = input("Do you want to play the game? ") if question.lower() == "yes": print("Sweet! Let`s begin!\nGuess the number between 1 and 10!") number = random.randint(1, 10) guess = None # This initialises the variable while guess != number: # This allows continual guesses guess = int(input("Take a guess!: ")) # Only need one of these if guess &gt; number: print("Your guess is too high") elif guess &lt; number: print("Your guess is too low") else: # if it isn't &lt; or &gt; then it must be equal! print("Your guess was correct!") else: # why do another test? No need. print("Too bad! Bye!") # No need for quit - program will exit anyway # but you should not use quit() in a program # use sys.exit() instead </code></pre> <p>Now I suggest you add a count of the number of guesses the player has before they get it right, and print that at the end!</p> <p>Edit: You will note that my <code>import</code> statement differs from that given by @Denis Ismailaj. We both agree that only one <code>import</code> is required, but hold different opinions as to which one. In my version I <code>import random</code>, this means that you have to say <code>random.randint</code> whereas in the other you only say <code>randint</code>.</p> <p>In a small program there isn't much to choose between them, but programs never get smaller. A larger program, which could easily be importing 6,7,8 or more modules, it is sometimes difficult to track-down which module a function comes from - this is known as <em>namespace pollution</em>. There will be no confusion with a well-known function like <code>randint</code>, and if you explicitly give the name of the function then it can easily be tracked back. It is only a question of personal preference and style.</p> <p>With number of guesses added:</p> <pre><code>import random print("Welcome to guess the number!") question = input("Do you want to play the game? ") if question.lower() == "yes": print("Sweet! Let`s begin!\nGuess the number between 1 and 10!") number = random.randint(1, 10) guess = None nrGuesses = 0 # Added # Allow for continual guesses while guess != number and nrGuesses &lt; 6: # Changed guess = int(input("Take a guess!: ")) # Only need one of these nrGuesses += 1 # Added if guess &gt; number: print("Your guess is too high") elif guess &lt; number: print("Your guess is too low") else: # if it isn't &lt; or &gt; then it must be equal! print("Your guess was correct!") else: print("Too bad! Bye!") print("Number of guesses:", nrGuesses) # Added </code></pre>
0
2016-10-15T15:09:15Z
[ "python", "pycharm" ]
Weird behaviour when running the script
40,060,380
<p>I started to code a guess the number type of game. When I execute the program, it either flows perfectly, either doesn't work...</p> <pre><code>import random from random import randint print("Welcome to guess the number!\nDo you want to play the game?") question = input("") if question == "Yes".lower(): print("Sweet! Let`s begin!\nGuess the number between 1 and 10!") number = random.randint(1, 10) guess = int(input("Take a guess!\n")) if guess &gt; number: print("Your guess is too high") guess = int(input("Take a guess!\n")) if guess &lt; number: print("Your guess is too low") guess = int(input("Take a guess!\n")) if guess == number: print("Your guess was correct!") elif question == "No".lower(): print("Too bad! Bye!") quit() </code></pre> <p>I absolutely no idea whether it happens because of the code, or pycharm is to blame! </p>
0
2016-10-15T14:40:09Z
40,061,087
<p>Here is a variation on the 2 themes already offered as answers.<br> In this option the guessing part is defined as a function, which allows us to offer the option of repeatedly playing the game until the user is bored stiff! The other option offered is to not require the user to input "yes" or "no" but simply something that starts with "y" or "n".</p> <pre><code>from random import randint def game(): print("Guess the number between 1 and 10!") number = randint(1, 10) guess = None while guess != number: guess = int(input("Take a guess!\n")) if guess &gt; number: print("Your guess is too high") elif guess &lt; number: print("Your guess is too low") else: print("Your guess was correct!") return input("Another game y/n ") #return a value which determines if the game will be repeated print("Welcome to guess the number!\nDo you want to play the game?") question = input("") repeat = "y" # define repeat so that the first iteration happens if question.lower().startswith('y') == True: print("Sweet! Let`s begin!") while repeat.lower().startswith('y') == True: # while repeat == "y" keep playing repeat = game() # play the game and set the repeat variable to what is returned print("Bye Bye!") </code></pre>
0
2016-10-15T15:47:42Z
[ "python", "pycharm" ]
Add quotation at start and end of every other line ignoring empty line
40,060,461
<p>I need help on organizing texts. I have the list of thousands vocabs in csv. There are term, definition, and sample sentence for each word. Term and definition is separated by the tab and sample sentence is separated by an empty line.</p> <p>For example:</p> <pre><code>exacerbate worsen This attack will exacerbate the already tense relations between the two communities exasperate irritate, vex he often exasperates his mother with pranks execrable very bad, abominable, utterly detestable an execrable performance </code></pre> <p>I want to organize this so that the sample sentence is enclosed by double quotation marks, has no empty line before and after itself, and the term in sentence is replaced by the hyphen. All that change while keeping the tab after the term, the new line in the beginning of each term, and the only a space between the definition and the example sentence. I need this format for importing it to flashcards web application.</p> <p>Desired outcome using above example:</p> <pre><code>exacerbate worsen "This attack will – the already tense relations between the two communities" exasperate irritate, vex "he often – his mother with pranks" execrable very bad, abominable, utterly detestable "an – performance" </code></pre> <p>I am using Mac. I know basic command lines (including regex) and python, but not enough to figure this out by myself. If you could help me, I am very grateful.</p>
1
2016-10-15T14:49:56Z
40,060,726
<p>Not necessarily bullet-proof, but this script will do the job based on your example:</p> <pre><code>import sys import re input_file = sys.argv[1] is_definition = True current_entry = "" current_definition = "" for line in open(input_file, 'r'): line = line.strip() if line != "": if is_definition == True: is_definition = False [current_entry, current_definition] = line.split("\t") else: is_definition = True example = line print (current_entry + "\t" + current_definition + ' "' + re.sub(current_entry + r'\w*', "-", line) + '"') </code></pre> <p>output:</p> <pre><code>exacerbate worsen "This attack will - the already tense relations between the two communities" exasperate irritate, vex "he often - his mother with pranks" execrable very bad, abominable, utterly detestable "an - performance" </code></pre> <p>The problem with our current approaches is that it won't work for irregular verbs like: "go - went" or "bring - brought" or "seek - sought".</p>
0
2016-10-15T15:14:23Z
[ "python", "regex", "osx", "textedit" ]
Add quotation at start and end of every other line ignoring empty line
40,060,461
<p>I need help on organizing texts. I have the list of thousands vocabs in csv. There are term, definition, and sample sentence for each word. Term and definition is separated by the tab and sample sentence is separated by an empty line.</p> <p>For example:</p> <pre><code>exacerbate worsen This attack will exacerbate the already tense relations between the two communities exasperate irritate, vex he often exasperates his mother with pranks execrable very bad, abominable, utterly detestable an execrable performance </code></pre> <p>I want to organize this so that the sample sentence is enclosed by double quotation marks, has no empty line before and after itself, and the term in sentence is replaced by the hyphen. All that change while keeping the tab after the term, the new line in the beginning of each term, and the only a space between the definition and the example sentence. I need this format for importing it to flashcards web application.</p> <p>Desired outcome using above example:</p> <pre><code>exacerbate worsen "This attack will – the already tense relations between the two communities" exasperate irritate, vex "he often – his mother with pranks" execrable very bad, abominable, utterly detestable "an – performance" </code></pre> <p>I am using Mac. I know basic command lines (including regex) and python, but not enough to figure this out by myself. If you could help me, I am very grateful.</p>
1
2016-10-15T14:49:56Z
40,060,739
<p>Try:</p> <pre><code>suffixList = ["s", "ed", "es", "ing"] #et cetera file = vocab.read() file.split("\n") vocab_words = [file[i] for i in range(0, len(file)-2, 4)] vocab_defs = [file[i] for i in range(2, len(file), 4)] for defCount in range(len(vocab_defs)): vocab_defs[defCount] = "\"" + vocab_defs[defCount] + "\"" newFileText = "" for count in range(len(vocab_words)): vocab_defs[count] = vocab_defs[count].replace(vocab_words[count].split(" ")[0], "-") for i in suffixList: vocab_defs[count] = vocab_defs[count].replace("-%s" % i, "-") newFileText += vocab_words[count] newFileText += " " newFileText += vocab_defs[count] newFileText += "\n" new_vocab_file.write(newFileText) </code></pre> <p>Outputs:</p> <pre><code>============== RESTART: /Users/chervjay/Documents/thingy.py ============== exacerbate worsen "This attack will - the already tense relations between the two communities" exasperate irritate, vex "he often - his mother with pranks" execrable very bad, abominable, utterly detestable "an - performance" &gt;&gt;&gt; </code></pre>
0
2016-10-15T15:15:17Z
[ "python", "regex", "osx", "textedit" ]
Add quotation at start and end of every other line ignoring empty line
40,060,461
<p>I need help on organizing texts. I have the list of thousands vocabs in csv. There are term, definition, and sample sentence for each word. Term and definition is separated by the tab and sample sentence is separated by an empty line.</p> <p>For example:</p> <pre><code>exacerbate worsen This attack will exacerbate the already tense relations between the two communities exasperate irritate, vex he often exasperates his mother with pranks execrable very bad, abominable, utterly detestable an execrable performance </code></pre> <p>I want to organize this so that the sample sentence is enclosed by double quotation marks, has no empty line before and after itself, and the term in sentence is replaced by the hyphen. All that change while keeping the tab after the term, the new line in the beginning of each term, and the only a space between the definition and the example sentence. I need this format for importing it to flashcards web application.</p> <p>Desired outcome using above example:</p> <pre><code>exacerbate worsen "This attack will – the already tense relations between the two communities" exasperate irritate, vex "he often – his mother with pranks" execrable very bad, abominable, utterly detestable "an – performance" </code></pre> <p>I am using Mac. I know basic command lines (including regex) and python, but not enough to figure this out by myself. If you could help me, I am very grateful.</p>
1
2016-10-15T14:49:56Z
40,060,756
<p>Open the terminal to the directory where you have the input file. Save the following code in a <code>.py</code> file:</p> <pre><code>import sys import string import difflib import itertools with open(sys.argv[1]) as fobj: lines = fobj.read().split('\n\n') with open(sys.argv[2], 'w') as out: for i in range(0, len(lines), 2): line1, example = lines[i:i + 2] words = [w.strip(string.punctuation).lower() for w in example.split()] # if the target word is not in the example sentence, # we will find the most similar one target = line1.split('\t')[0] if target in words: most_similar = target else: most_similar = difflib.get_close_matches(target, words, 1)[0] new_example = example.replace(most_similar, '-') out.write('{} "{}"\n'.format(line1.strip(), new_example.strip())) </code></pre> <p>The program needs the input file name and the output file name as command line arguments. That is, execute from the terminal the following command:</p> <pre><code>$ python program.py input.txt output.txt </code></pre> <p>where <code>program.py</code> is the above program, <code>input.txt</code> is your input file, and <code>output.txt</code> is the file that will be created with the format you need.</p> <hr> <p>I ran the program against the example you provided. I had manually add the tabs because in the question there are only spaces. This is the output produced by the program:</p> <pre><code>exacerbate worsen "This attack will - the already tense relations between the two communities" exasperate irritate, vex "he often - his mother with pranks" execrable very bad, abominable, utterly detestable "an - performance" </code></pre> <p>The program correctly substitutes <code>exacerbates</code> with a dash in the second example, even though the word is <code>exacerbate</code>. I cannot guarantee that this technique will work for every word in your file without having the file.</p>
1
2016-10-15T15:16:36Z
[ "python", "regex", "osx", "textedit" ]
Add quotation at start and end of every other line ignoring empty line
40,060,461
<p>I need help on organizing texts. I have the list of thousands vocabs in csv. There are term, definition, and sample sentence for each word. Term and definition is separated by the tab and sample sentence is separated by an empty line.</p> <p>For example:</p> <pre><code>exacerbate worsen This attack will exacerbate the already tense relations between the two communities exasperate irritate, vex he often exasperates his mother with pranks execrable very bad, abominable, utterly detestable an execrable performance </code></pre> <p>I want to organize this so that the sample sentence is enclosed by double quotation marks, has no empty line before and after itself, and the term in sentence is replaced by the hyphen. All that change while keeping the tab after the term, the new line in the beginning of each term, and the only a space between the definition and the example sentence. I need this format for importing it to flashcards web application.</p> <p>Desired outcome using above example:</p> <pre><code>exacerbate worsen "This attack will – the already tense relations between the two communities" exasperate irritate, vex "he often – his mother with pranks" execrable very bad, abominable, utterly detestable "an – performance" </code></pre> <p>I am using Mac. I know basic command lines (including regex) and python, but not enough to figure this out by myself. If you could help me, I am very grateful.</p>
1
2016-10-15T14:49:56Z
40,061,125
<pre><code>#!/usr/local/bin/python3 import re with open('yourFile.csv', 'r') as myfile: data = myfile.read() print(re.sub(r'(^[A-Za-z]+)\t(.+)\n\n(.+)\1[s|ed|es|ing]*(.+)$',r'\1\t\2 "\3-\4"', data, flags = re.MULTILINE)) </code></pre> <p>Output:</p> <blockquote> <p>exacerbate worsen "This attack will - the already tense relations between the two communities"</p> <p>exasperate irritate, vex "he often - his mother with pranks"</p> <p>execrable very bad, abominable, utterly detestable "an - performance"</p> </blockquote>
0
2016-10-15T15:51:16Z
[ "python", "regex", "osx", "textedit" ]
Infinite loop when try to redirect stdout
40,060,556
<p>I'm trying to send stdout to both console and <code>QTextBrowser</code> widget. But I'm getting some kind of infinite loop and then application exits.</p> <p>Here is my code:</p> <pre><code>import sys from PyQt5 import QtWidgets, uic from PyQt5.QtCore import * qtCreatorFile = "qt_ui.ui" Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) self.start_button.clicked.connect(printing) def printing(): print("Pressed!\n") class Logger(QObject): def __init__(self): super().__init__() self.terminal = sys.stdout def write(self, message): self.terminal.write(message) self.log_browser.setText(message) #problem is in this line def flush(self): pass if __name__ == "__main__": sys.stdout = Logger() app = QtWidgets.QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) </code></pre> <p>As a result, when click start_button, following is observed:</p> <pre><code>"C:\...\python.exe" "E:/.../qt_gui.py" Pressed! Pressed! Pressed! ... (totaly 332 times) Pressed! Pressed! Pressed! Process finished with exit code 1 </code></pre> <p>I just can't understand why this line makes loop:</p> <pre><code>self.log_browser.setText(message) </code></pre> <p><strong>Edit after 1st answer:</strong></p> <p>I replaced the line above with <code>print(message)</code>, but still getting same results. I would appreciate any help.</p>
0
2016-10-15T14:58:42Z
40,061,749
<p>Looks like the code you posted is not code you have run, but assuming it is representative, there are two errors: base class of Logger must be inited, and self.log_browser is not defined anywhere. But this does not cause loop, app exits (because there is an exception but no exception hook, see ). Since I don't know what log_browser should be, I defined it as a Mock() (from unittest.mock) which will accept anything done to it, and problem goes away. </p> <pre><code>class Logger(QObject): def __init__(self): super().__init__() self.terminal = sys.stdout from unittest.mock import Mock self.log_browser = Mock() def write(self, message): self.terminal.write(message) self.log_browser.setText(message) # problem was this line def flush(self): pass </code></pre>
0
2016-10-15T16:54:24Z
[ "python", "qt", "python-3.x", "pyqt" ]
Infinite loop when try to redirect stdout
40,060,556
<p>I'm trying to send stdout to both console and <code>QTextBrowser</code> widget. But I'm getting some kind of infinite loop and then application exits.</p> <p>Here is my code:</p> <pre><code>import sys from PyQt5 import QtWidgets, uic from PyQt5.QtCore import * qtCreatorFile = "qt_ui.ui" Ui_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorFile) class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow): def __init__(self): QtWidgets.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) self.start_button.clicked.connect(printing) def printing(): print("Pressed!\n") class Logger(QObject): def __init__(self): super().__init__() self.terminal = sys.stdout def write(self, message): self.terminal.write(message) self.log_browser.setText(message) #problem is in this line def flush(self): pass if __name__ == "__main__": sys.stdout = Logger() app = QtWidgets.QApplication(sys.argv) window = MainWindow() window.show() sys.exit(app.exec_()) </code></pre> <p>As a result, when click start_button, following is observed:</p> <pre><code>"C:\...\python.exe" "E:/.../qt_gui.py" Pressed! Pressed! Pressed! ... (totaly 332 times) Pressed! Pressed! Pressed! Process finished with exit code 1 </code></pre> <p>I just can't understand why this line makes loop:</p> <pre><code>self.log_browser.setText(message) </code></pre> <p><strong>Edit after 1st answer:</strong></p> <p>I replaced the line above with <code>print(message)</code>, but still getting same results. I would appreciate any help.</p>
0
2016-10-15T14:58:42Z
40,066,161
<p>You could emit a custom signal from <code>Logger</code> and connect it to the log browser:</p> <pre><code>class Logger(QObject): loggerMessage = pyqtSignal(str) def __init__(self): super().__init__() self.terminal = sys.stdout def write(self, message): self.terminal.write(message) self.loggerMessage.emit(message) def flush(self): pass if __name__ == "__main__": sys.stdout = Logger() app = QtWidgets.QApplication(sys.argv) window = MainWindow() sys.stdout.loggerMessage.connect(window.log_browser.insertPlainText) window.show() sys.exit(app.exec_()) </code></pre>
0
2016-10-16T02:17:38Z
[ "python", "qt", "python-3.x", "pyqt" ]
How to sum all the keys of a dictionary value to the same dictionary value
40,060,568
<p>Let's say I have a dictionary that has {'a' : '0', 'b' : '2', 'a' : '3', 'b' : '5',}</p> <p>I want the dictionary to say {'a' : '3' 'b' : '7'}</p> <p>How would I do this ? </p>
-2
2016-10-15T15:00:00Z
40,060,774
<p>You can't create dictionary which contains the same key twice. The definition of the dictionary is that you can store in it every key-value option only once.</p>
0
2016-10-15T15:17:57Z
[ "python", "dictionary", "key" ]
How to get argparse to read arguments from a file with an option after positional arguments
40,060,571
<p>I would like to be able to put command-line arguments in a file, and then pass them to a python program, with argparse, using an option rather than a prefix character, for instance: <code> $ python myprogram.py 1 2 --foo 1 -A somefile.txt --bar 2 </code> This is almost the same as <a href="http://stackoverflow.com/questions/27433316/how-to-get-argparse-to-read-arguments-from-a-file-with-an-option-rather-than-pre">this question</a>, except that I need to have some positional arguments at the start; when that solution calls <code>parse_args</code>, it fails if the file does not have the positional arguments in it.</p>
0
2016-10-15T15:00:14Z
40,062,344
<p>If <code>somefile.txt</code> contains</p> <pre><code>one two three </code></pre> <p>then </p> <pre><code>$ python myprogram.py 1 2 --foo 1 @somefile.txt --bar 2 </code></pre> <p>using the <code>prefix char</code> is effectively the same as</p> <pre><code>$ python myprogram.py 1 2 --foo 1 one two three --bar 2 </code></pre> <p>In other words, right at the start of parsing, the @ file is read, and its contents are spliced into the <code>argv</code> list. From there parsing occurs normally.</p> <p>One thing I suggested in the other SO question was to implement that splicing yourself, prior to parsing.</p> <p>The answer that you are referring to uses a <code>custom</code> Action; at the point where the usual <code>Action</code> just places the <code>value</code> in the <code>namespace</code>, this action reads and parses the file:</p> <pre><code>parser.parse_args(f.read().split(), namespace) </code></pre> <p>A variant parses into a new <code>namespace</code> and selectively copies values to the main <code>namespace</code>.</p> <p>Apparently your problem is that your parser has some required arguments, and this <code>parse_args</code> raises an error if the file does not contain those. That's not surprising.</p> <p>One solution is to use a different <code>parser</code> for this file, one that is designed to work with just the content of the file. I would just define it globally.</p> <pre><code>alt_parser.parse_args(f.read().split(), namespace) </code></pre> <p>In other words, you don't have to use the <code>parser</code> that was passed in as a parameter.</p> <p>A variation on this is to put the filename in the namespace, and handle it after the first parsing:</p> <pre><code>args = parser.parse_args() if args.A: argv = open(args.A).read().split() args1 = alt_parser.parse_args(argv) </code></pre> <p>But you might ask, can't we tell what arguments have already been parsed, and take that into account in handling <code>-A</code>? The <code>parser</code> is not a state-machine; parsing does not alter any of its attributes. The only variable that reflects parsing so far is the <code>namespace</code>. All other parsing variables are local to the calling code.</p>
1
2016-10-15T17:51:09Z
[ "python", "argparse" ]
Dictionary removing duplicate along with subtraction and addition of values
40,060,580
<p>New to python here. I would like to eliminate duplicate dictionary key into just one along with performing arithmetic such as adding/subtracting the values if duplicates are found.</p> <p><strong>Current Code Output</strong></p> <blockquote> <p>{('GRILLED AUSTRALIA ANGU',): (('1',), ('29.00',)), ('Beer', 'Carrot Cake', 'Chocolate Cake'): (('10', '1', '1'), ('30.00', '2.50', '3.50')), ('<strong>Beer</strong>', '<strong>Beer</strong>'): (('<strong>1</strong>', '<strong>1</strong>'), ('<strong>3.00</strong>', '<strong>3.00</strong>')), ('Carrot Cake', 'Chocolate Cake'): (('1', '1'), ('2.50', '3.50')), ('Carrot Cake',): (('1',), ('2.50',)), ('BRAISED BEANCURD WITH',): (('1',), ('10.00',)), ('SAUSAGE WRAPPED WITH B', 'ESCARGOT WITH GARLIC H', 'PAN SEARED FOIE GRAS', 'SAUTE FIELD MUSHROOM W', 'CRISPY CHICKEN WINGS', 'ONION RINGS'): (('1', '1', '1', '1', '1', '1'), ('10.00', '12.00', '15.00', '9.00', '7.00', '6.00')), ('<strong>Beer</strong>', '<strong>Beer</strong>', '<strong>Carrot Cake</strong>', '<strong>Chocolate Cake</strong>'): (('<strong>-1</strong>', '<strong>10</strong>', '<strong>1</strong>', '<strong>1</strong>'), ('<strong>-3.00</strong>', '<strong>30.00</strong>', '<strong>2.50</strong>', '<strong>3.50</strong>')), ('Beer',): (('10',), ('30.00',))}</p> </blockquote> <p>What i want: example:</p> <p><strong>SUBTRACTION FOR DUPLICATE</strong></p> <blockquote> <p>{'Beer': [9, 27]} , {'carrot cake': [1, 2.5]} , {'Chocolate Cake': [1, 3.5]} </p> </blockquote> <p>notice that for duplicate item entry i trimmed Beer into one along with (10-1=9) for quantity amount and (30-3=27) for the cost. How do i automate this process?</p> <p><strong>ADDITION FOR DUPLICATE</strong></p> <blockquote> <p>{'Beer': [2, 6]}</p> </blockquote> <p>notice that I added beer and beer into one entry and along with the quantity (1+1) and cost (3+3=6)</p> <p><strong>My code:</strong></p> <pre><code>import csv from itertools import groupby from operator import itemgetter import re d = {} #open directory and saving directory with open("rofl.csv", "rb") as f, open("out.csv", "wb") as out: reader = csv.reader(f) next(reader) writer = csv.writer(out) #the first column header writer.writerow(["item","quantity","amount"]) groups = groupby(csv.reader(f), key=itemgetter(0)) for k, v in groups: v = list(v) sales= [ x[1] for x in v[8:] ] salesstring= str(sales) #using re.findall instead of re.search to return all via regex for items itemoutput= re.findall(r"(?&lt;=\s\s)\w+(?:\s\w+)*(?=\s\s)",textwordfortransaction) #using re.findall instead of re.search to return all via regex for amount aka quantity amountoutput= re.findall(r"'(-?\d+)\s+(?:[A-Za-z ]*)",textwordfortransaction) #using re.findall instead of re.search to return all via regex for cost costoutput= re.findall(r"(?:'-?\d+[A-Za-z ]*)(-?\d+[.]?\d*)",textwordfortransaction) d[tuple(itemoutput)] = tuple(amountoutput),tuple(costoutput) #writing the DATA to output CSV writer.writerow([d]) #to remove the last entry else it would keep on stacking the previous d.clear() </code></pre> <p>link to csv file if needed <a href="https://drive.google.com/open?id=0B1kSBxOGO4uJOFVZSWh2NWx6dHc" rel="nofollow">https://drive.google.com/open?id=0B1kSBxOGO4uJOFVZSWh2NWx6dHc</a></p>
-2
2016-10-15T15:00:52Z
40,060,730
<p>Working with your current output as posted in the question, you can just <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow"><code>zip</code></a> the different lists of tuples of items and quantities and prices to align the items with each other, add them up in two <code>defaultdicts</code>, and finally combine those to the result.</p> <pre><code>output = {('GRILLED AUSTRALIA ANGU',): (('1',), ('29.00',)), ...} from collections import defaultdict prices, quantities = defaultdict(int), defaultdict(int) for key, val in output.items(): for item, quant, price in zip(key, *val): quantities[item] += int(quant) prices[item] += float(price) result = {item: (quantities[item], prices[item]) for item in prices} </code></pre> <p>Afterwards, <code>result</code> is this: Note that you do <em>not</em> need a special case for subtracting duplicates when the quantity and/or price are negative; just add the negative number.</p> <pre><code>{'ESCARGOT WITH GARLIC H': (1, 12.0), 'BRAISED BEANCURD WITH': (1, 10.0), 'CRISPY CHICKEN WINGS': (1, 7.0), 'SAUSAGE WRAPPED WITH B': (1, 10.0), 'ONION RINGS': (1, 6.0), 'PAN SEARED FOIE GRAS': (1, 15.0), 'Beer': (31, 93.0), 'Chocolate Cake': (3, 10.5), 'SAUTE FIELD MUSHROOM W': (1, 9.0), 'Carrot Cake': (4, 10.0), 'GRILLED AUSTRALIA ANGU': (1, 29.0)} </code></pre> <hr> <p>If you want to keep the individual items separate, just move the declaration of <code>prices</code>, <code>quantities</code>, and <code>result</code> <em>inside</em> the outer loop:</p> <pre><code>for key, val in output.items(): prices, quantities = defaultdict(int), defaultdict(int) for item, quant, price in zip(key, *val): quantities[item] += int(quant) prices[item] += float(price) result = {item: (quantities[item], prices[item]) for item in prices} # do something with result or collect in a list </code></pre> <p>Example result for the two-beer line: </p> <pre><code>('Beer', 'Beer', 'Carrot Cake', 'Chocolate Cake') (('-1', '10', '1', '1'), ('-3.00', '30.00', '2.50', '3.50')) {'Chocolate Cake': (1, 3.5), 'Beer': (9, 27.0), 'Carrot Cake': (1, 2.5)} </code></pre> <p>If you prefer the <code>result</code> to group the items, quantities and prices together, use this:</p> <pre><code>items = list(prices) result = (items, [quantities[x] for x in items], [prices[x] for x in items]) </code></pre> <p>Result is this like this:</p> <pre><code>(['Carrot Cake', 'Beer', 'Chocolate Cake'], [1, 9, 1], [2.5, 27.0, 3.5]) </code></pre>
2
2016-10-15T15:14:47Z
[ "python", "dictionary" ]
Python screen capture error
40,060,653
<p>I am trying to modify the code given <a href="https://blog.miguelgrinberg.com/post/video-streaming-with-flask" rel="nofollow">here</a> for screen streaming. In the above tutorial it was for reading images from disk whereas I am trying to take screenshots. I receive this error.</p> <blockquote> <p>assert isinstance(data, bytes), 'applications must write bytes' AssertionError: applications must write bytes</p> </blockquote> <p>What changes should I make for it to work?</p> <p>This is what I've done so far - </p> <pre><code>&lt;br&gt;index.html&lt;br&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Video Streaming Demonstration&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Video Streaming Demonstration&lt;/h1&gt; &lt;img src="{{ url_for('video_feed') }}"&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><br>app.py<br></p> <pre><code>#!/usr/bin/env python from flask import Flask, render_template, Response import time # emulated camera from camera import Camera # Raspberry Pi camera module (requires picamera package) # from camera_pi import Camera app = Flask(__name__) @app.route('/') def index(): """Video streaming home page.""" return render_template('index.html') def gen(camera): """Video streaming generator function.""" while True: time.sleep(0.1) frame = camera.get_frame() yield (frame) @app.route('/video_feed') def video_feed(): """Video streaming route. Put this in the src attribute of an img tag.""" return Response(gen(Camera()), mimetype='multipart/x-mixed-replace; boundary=frame') if __name__ == '__main__': app.run(host='0.0.0.0', debug=True, threaded=True) </code></pre> <p><br>camera.py<br></p> <pre><code>from time import time from PIL import Image from PIL import ImageGrab import sys if sys.platform == "win32": grabber = Image.core.grabscreen class Camera(object): def __init__(self): #self.frames = [open('shot0' + str(f) + '.png', 'rb').read() for f in range(1,61)] self.frames = [ImageGrab.grab() for f in range(1,61)] def get_frame(self): return self.frames[int(time()) % 3] </code></pre> <p>Full error : <a href="http://pastebin.com/4691Npyk" rel="nofollow">Link</a></p>
0
2016-10-15T15:07:11Z
40,061,207
<p>The response payload must be a sequence of bytes. In the example, the images returned are JPEGs as <code>bytes</code> objects. </p> <p>However, the image returned by <code>ImageGrab.grab()</code> is some PIL image class instead of bytes. So, try saving the image as JPEG as <code>bytes</code>:</p> <pre><code>import io </code></pre> <p>Take screenshot only for every iteration in gen:</p> <pre><code>class Camera(object): def get_frame(self): frame = ImageGrab.grab() img_bytes = io.BytesIO() frame.save(img_bytes, format='JPEG') return img_bytes.getvalue() </code></pre> <p>gen function:</p> <pre><code>def gen(camera): while True: time.sleep(0.1) frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n') </code></pre>
0
2016-10-15T15:59:07Z
[ "python", "image", "flask" ]
How to input from input direcory folder and save output file in same name as input file in output folder in python
40,060,691
<p>I want to create input directory for my code will take input files from input directory and save same name as input file in output (different folder) directory.</p> <p>Script: </p> <pre><code>import sys import glob import errno import os d = {} chainIDs = ('A', 'B') atomIDs = ('C4B', 'O4B', 'C1B', 'C2B', 'C3B', 'C4B', 'O4B', 'C1B') count = 0 for doc in os.listdir('/C:/Users/Vishnu/Desktop/Test_folder/Input'): doc1 = "doc_path" + doc doc2 = "/C:/Users/Vishnu/Desktop/Test_folder/Output" + doc1 if doc1.endswith(".pdb"): with open(doc) as pdbfile: single_line = ''.join([line for line in f]) single_space = ' '.join(single_line.split()) for line in map(str.rstrip, pdbfile): if line[:6] != "HETATM": continue chainID = line[21:22] atomID = line[13:16].strip() if chainID not in chainIDs: continue if atomID not in atomIDs: continue try: d[chainID][atomID] = line except KeyError: d[chainID] = {atomID: line} n = 4 for chainID in chainIDs: for i in range(len(atomIDs)-n+1): for j in range(n): with open(doc2.format(count) , "w") as doc2: doc2.write(d[chainID][atomIDs[i+j]]) count += 1 else: continue </code></pre> <p>Below error while running above code, I am new in python, just learning, can anyone please help? error:</p> <pre><code>with open(doc) as pdbfile: ^ IndentationError: expected an indented block &gt;&gt;&gt; </code></pre> <p>Input file:</p> <pre><code>HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C HETATM15252 C4B NAD B 501 36.455 115.053 36.671 1.00 11.25 C HETATM15253 O4B NAD B 501 35.930 114.469 35.492 1.00 11.25 O HETATM15254 C3B NAD B 501 35.307 115.837 37.367 1.00 11.25 C HETATM15256 C2B NAD B 501 34.172 114.876 37.039 1.00 11.25 C HETATM15258 C1B NAD B 501 34.524 114.613 35.551 1.00 11.25 C HETATM15297 C4B NAD C 501 98.229 130.106 18.332 1.00 12.28 C HETATM15298 O4B NAD C 501 98.083 131.545 18.199 1.00 12.28 O HETATM15299 C3B NAD C 501 99.346 129.675 17.343 1.00 12.28 C HETATM15301 C2B NAD C 501 100.220 130.922 17.375 1.00 12.28 C HETATM15303 C1B NAD C 501 99.125 132.008 17.317 1.00 12.28 C HETATM15342 C4B NAD D 501 77.335 156.939 25.788 1.00 11.99 C HETATM15343 O4B NAD D 501 78.705 156.544 25.901 1.00 11.99 O HETATM15344 C3B NAD D 501 77.106 158.059 26.824 1.00 11.99 C HETATM15346 C2B NAD D 501 78.536 158.632 26.878 1.00 11.99 C HETATM15348 C1B NAD D 501 79.351 157.345 26.900 1.00 11.99 C </code></pre> <p><strong>Col 2 is Residue name, Col 4 is A, B, C, D is the chain ID:</strong></p> <p><strong>Expected Output for each chain ID (A, B ..... Z) Chain ID may be A to Z but mostly A to H:</strong></p> <p>for A chain: </p> <pre><code>HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C </code></pre>
0
2016-10-15T15:10:53Z
40,060,713
<p>The <code>IndentationError</code> is showing up because you seem to have indented two tabs underneath your <code>with open(doc) as pdbfile:</code> line. </p> <p>Hope this helps! </p>
0
2016-10-15T15:12:58Z
[ "python", "python-2.7", "python-3.x", "bioinformatics" ]
How to input from input direcory folder and save output file in same name as input file in output folder in python
40,060,691
<p>I want to create input directory for my code will take input files from input directory and save same name as input file in output (different folder) directory.</p> <p>Script: </p> <pre><code>import sys import glob import errno import os d = {} chainIDs = ('A', 'B') atomIDs = ('C4B', 'O4B', 'C1B', 'C2B', 'C3B', 'C4B', 'O4B', 'C1B') count = 0 for doc in os.listdir('/C:/Users/Vishnu/Desktop/Test_folder/Input'): doc1 = "doc_path" + doc doc2 = "/C:/Users/Vishnu/Desktop/Test_folder/Output" + doc1 if doc1.endswith(".pdb"): with open(doc) as pdbfile: single_line = ''.join([line for line in f]) single_space = ' '.join(single_line.split()) for line in map(str.rstrip, pdbfile): if line[:6] != "HETATM": continue chainID = line[21:22] atomID = line[13:16].strip() if chainID not in chainIDs: continue if atomID not in atomIDs: continue try: d[chainID][atomID] = line except KeyError: d[chainID] = {atomID: line} n = 4 for chainID in chainIDs: for i in range(len(atomIDs)-n+1): for j in range(n): with open(doc2.format(count) , "w") as doc2: doc2.write(d[chainID][atomIDs[i+j]]) count += 1 else: continue </code></pre> <p>Below error while running above code, I am new in python, just learning, can anyone please help? error:</p> <pre><code>with open(doc) as pdbfile: ^ IndentationError: expected an indented block &gt;&gt;&gt; </code></pre> <p>Input file:</p> <pre><code>HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C HETATM15252 C4B NAD B 501 36.455 115.053 36.671 1.00 11.25 C HETATM15253 O4B NAD B 501 35.930 114.469 35.492 1.00 11.25 O HETATM15254 C3B NAD B 501 35.307 115.837 37.367 1.00 11.25 C HETATM15256 C2B NAD B 501 34.172 114.876 37.039 1.00 11.25 C HETATM15258 C1B NAD B 501 34.524 114.613 35.551 1.00 11.25 C HETATM15297 C4B NAD C 501 98.229 130.106 18.332 1.00 12.28 C HETATM15298 O4B NAD C 501 98.083 131.545 18.199 1.00 12.28 O HETATM15299 C3B NAD C 501 99.346 129.675 17.343 1.00 12.28 C HETATM15301 C2B NAD C 501 100.220 130.922 17.375 1.00 12.28 C HETATM15303 C1B NAD C 501 99.125 132.008 17.317 1.00 12.28 C HETATM15342 C4B NAD D 501 77.335 156.939 25.788 1.00 11.99 C HETATM15343 O4B NAD D 501 78.705 156.544 25.901 1.00 11.99 O HETATM15344 C3B NAD D 501 77.106 158.059 26.824 1.00 11.99 C HETATM15346 C2B NAD D 501 78.536 158.632 26.878 1.00 11.99 C HETATM15348 C1B NAD D 501 79.351 157.345 26.900 1.00 11.99 C </code></pre> <p><strong>Col 2 is Residue name, Col 4 is A, B, C, D is the chain ID:</strong></p> <p><strong>Expected Output for each chain ID (A, B ..... Z) Chain ID may be A to Z but mostly A to H:</strong></p> <p>for A chain: </p> <pre><code>HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C HETATM15211 C2B NAD A 501 46.447 98.835 6.988 1.00 11.48 C HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O HETATM15209 C3B NAD A 501 47.659 99.689 6.567 1.00 11.48 C HETATM15207 C4B NAD A 501 47.266 101.038 7.214 1.00 11.48 C HETATM15208 O4B NAD A 501 46.466 100.713 8.371 1.00 11.48 O HETATM15213 C1B NAD A 501 46.221 99.300 8.426 1.00 11.48 C </code></pre>
0
2016-10-15T15:10:53Z
40,060,799
<pre><code>import sys import glob import errno import os d = {} chainIDs = ('A', 'B') atomIDs = ('C4B', 'O4B', 'C1B', 'C2B', 'C3B', 'C4B', 'O4B', 'C1B') count = 0 doc_path=r'C:\Users\Vishnu\Desktop\Test_folder\Input' tar_path=r'C:\Users\Vishnu\Desktop\Test_folder\Output' for doc in os.listdir(doc_path): doc1 = doc_path+'\\'+ doc doc2 = tar_path+'\\'+ doc if doc1.endswith(".pdb"): print(doc1,doc2) with open(doc1) as pdbfile: # single_line = ''.join([line for line in f]) # single_space = ' '.join(single_line.split()) for line in map(str.rstrip, pdbfile): if line[:6] != "HETATM": continue chainID = line[21:22] atomID = line[13:16].strip() if chainID not in chainIDs: continue if atomID not in atomIDs: continue try: d[chainID][atomID] = line except KeyError: d[chainID] = {atomID: line} n = 4 for chainID in chainIDs: for i in range(len(atomIDs)-n+1): for j in range(n): with open(doc2 , "w+") as s: s.write(d[chainID][atomIDs[i+j]]) count += 1 else: continue </code></pre>
0
2016-10-15T15:20:43Z
[ "python", "python-2.7", "python-3.x", "bioinformatics" ]
scipy.ndimage.interpolate.affine_transform fails
40,060,786
<p>This code:</p> <pre><code>from scipy.ndimage.interpolation import affine_transform import numpy as np ... nzoom = 1.2 newimage = affine_transform(self.image, matrix=np.array([[nzoom, 0],[0, nzoom]])) </code></pre> <p>fails with:</p> <pre><code>RuntimeError: affine matrix has wrong number of rows </code></pre> <p>What's the problem with the matrix? I also tried <code>matrix=[nzoom, nzoom]</code>, which according to my reading of documentation should do the same, and it fails the same way.</p>
0
2016-10-15T15:19:23Z
40,071,123
<p>The reason why the original code does not work with a 2x2 matrix is because the image in question is 3-dimensional. Mind you, the 3rd dimension is<code>[R,G,B]</code>, but <code>scipy.ndimage</code> does not know about non-spatial dimensions; it treats all dimensions as spatial. The examples using 2x2 matrices were all 2D "gray" images.</p> <p><strong>Solution #1:</strong></p> <p><code>affine_transform</code> maps output coordinates <code>o</code> to source (input) coordinates <code>s</code> as:</p> <pre><code>s = numpy.dot(matrix,o) + offset </code></pre> <p>where <code>matrix</code> and <code>offset</code> are arguments to <code>affine_transform</code>. In the case of a multichannel image we don't want to transform the 3rd dimension. I.e., we want the source coordinates corresponding to an output point </p> <pre><code>o == [x, y, z] # column vector </code></pre> <p>to be</p> <pre><code>s == [c00*x + c01*y + dx, c10*x + c11*y + dy, z] # column vector </code></pre> <p>To achieve that result we need</p> <pre><code>matrix = [[ c00, c01, 0], [ c10, c11, 0], [ 0, 0, 1]] offset = [dx, dy, 0] # column vector </code></pre> <p><strong>Solution #2:</strong></p> <p>An alternative solution is to split the RGB image in 3 channels, transform each channel separately, and combine them together,</p> <pre><code>r = rgb[..., 0] g = rgb[..., 1] b = rgb[..., 2] matrix = np.array([[c00, c01], [c10, c11]]) offset = [dx dy] r = affine_transform(r, matrix=matrix, offset=offset) g = affine_transform(g, matrix=matrix, offset=offset) b = affine_transform(b, matrix=matrix, offset=offset) rgb = np.dstack((r, g, b)) </code></pre> <p>I have not timed either solution, but I expect #2 to be slower that #1.</p>
0
2016-10-16T13:58:32Z
[ "python", "scipy", "affinetransform" ]
Moving Average- Pandas
40,060,842
<p>I would like to add a moving average calculation to my exchange time series.</p> <p>Original data from Quandl</p> <p>Exchange = Quandl.get("BUNDESBANK/BBEX3_D_SEK_USD_CA_AC_000", authtoken="xxxxxxx")</p> <pre><code> Value Date 1989-01-02 6.10500 1989-01-03 6.07500 1989-01-04 6.10750 1989-01-05 6.15250 1989-01-09 6.25500 1989-01-10 6.24250 1989-01-11 6.26250 1989-01-12 6.23250 1989-01-13 6.27750 1989-01-16 6.31250 </code></pre> <h1>Calculating Moving Avarage</h1> <p>MovingAverage = pd.rolling_mean(Exchange,5)</p> <pre><code> Value Date 1989-01-02 NaN 1989-01-03 NaN 1989-01-04 NaN 1989-01-05 NaN 1989-01-09 6.13900 1989-01-10 6.16650 1989-01-11 6.20400 1989-01-12 6.22900 1989-01-13 6.25400 1989-01-16 6.26550 </code></pre> <p>I would like to add the calculated Moving Average as a new column to the right after 'Value' using the same index (Date). Preferably i would also like to rename the calculated moving average to 'MA'</p>
0
2016-10-15T15:25:31Z
40,060,995
<p>The rolling mean returns a <code>Series</code> you only have to add it as a new column of your <code>DataFrame</code> (<code>MA</code>) as described below. </p> <p>For information, the <code>rolling_mean</code> function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas <a href="http://pandas.pydata.org/pandas-docs/stable/computation.html" rel="nofollow">documentation</a></p> <blockquote> <p><strong>Warning</strong> Prior to version 0.18.0, <code>pd.rolling_*</code>, <code>pd.expanding_*</code>, and <code>pd.ewm*</code> were module level functions and are now deprecated. These are replaced by using the <code>Rolling</code>, <code>Expanding</code> and <code>EWM.</code> objects and a corresponding method call.</p> </blockquote> <pre><code>df['MA'] = df.rolling(window=5).mean() print(df) # Value MA # Date # 1989-01-02 6.11 NaN # 1989-01-03 6.08 NaN # 1989-01-04 6.11 NaN # 1989-01-05 6.15 NaN # 1989-01-09 6.25 6.14 # 1989-01-10 6.24 6.17 # 1989-01-11 6.26 6.20 # 1989-01-12 6.23 6.23 # 1989-01-13 6.28 6.25 # 1989-01-16 6.31 6.27 </code></pre>
2
2016-10-15T15:39:28Z
[ "python", "python-3.x", "pandas", "moving-average" ]
Speed up inserts into SQL Server from pyodbc
40,060,864
<p>In <code>python</code>, I have a process to select data from one database (<code>Redshift</code> via <code>psycopg2</code>), then insert that data into <code>SQL Server</code> (via <code>pyodbc</code>). I chose to do a read / write rather than a read / flat file / load because the row count is around 100,000 per day. Seemed easier to simply connect and insert. However - the insert process is slow, taking several minutes. </p> <p>Is there a better way to insert data into SQL Server with Pyodbc?</p> <pre><code>select_cursor.execute(output_query) done = False rowcount = 0 while not done: rows = select_cursor.fetchmany(10000) insert_list = [] if rows == []: done = True break for row in rows: rowcount += 1 insert_params = ( row[0], row[1], row[2] ) insert_list.append(insert_params) insert_cnxn = pyodbc.connect('''Connection Information''') insert_cursor = insert_cnxn.cursor() insert_cursor.executemany(""" INSERT INTO Destination (AccountNumber, OrderDate, Value) VALUES (?, ?, ?) """, insert_list) insert_cursor.commit() insert_cursor.close() insert_cnxn.close() select_cursor.close() select_cnxn.close() </code></pre>
1
2016-10-15T15:27:29Z
40,061,564
<p><s>It's good that you're already using <code>executemany()</code>.</s> [<em>Struck out after reading other answer.</em>] </p> <p>It should speed up a (very little) bit if you move the <code>connect()</code> and <code>cursor()</code> calls for your <code>insert_cnxn</code> and <code>insert_cursor</code> outside of your while loop. (Of course, if you do this, you should also move the 2 corresponding <code>close()</code> calls outside of the loop as well.) In addition to not having to (re)establish the connection every time, re-using the cursor will prevent having to recompile the SQL each time.</p> <p>However, you probably won't see a huge speed up from this just because you're probably only making ~10 passes through that loop anyway (given that you said ~100,000 a day and your loop groups together 10,000 at a time).</p> <p>One other thing you might look into is whether there are any "behind-the-scenes" conversions being made on your <code>OrderDate</code> parameter. You can go to SQL Server Management Studio and look at the execution plan of the query. (Look for your insert query in the "recent expensive queries" list by right-clicking on the server node and choosing "Activity Monitor"; right click on the insert query and look at its Execution Plan.)</p>
0
2016-10-15T16:34:37Z
[ "python", "pyodbc" ]
Speed up inserts into SQL Server from pyodbc
40,060,864
<p>In <code>python</code>, I have a process to select data from one database (<code>Redshift</code> via <code>psycopg2</code>), then insert that data into <code>SQL Server</code> (via <code>pyodbc</code>). I chose to do a read / write rather than a read / flat file / load because the row count is around 100,000 per day. Seemed easier to simply connect and insert. However - the insert process is slow, taking several minutes. </p> <p>Is there a better way to insert data into SQL Server with Pyodbc?</p> <pre><code>select_cursor.execute(output_query) done = False rowcount = 0 while not done: rows = select_cursor.fetchmany(10000) insert_list = [] if rows == []: done = True break for row in rows: rowcount += 1 insert_params = ( row[0], row[1], row[2] ) insert_list.append(insert_params) insert_cnxn = pyodbc.connect('''Connection Information''') insert_cursor = insert_cnxn.cursor() insert_cursor.executemany(""" INSERT INTO Destination (AccountNumber, OrderDate, Value) VALUES (?, ?, ?) """, insert_list) insert_cursor.commit() insert_cursor.close() insert_cnxn.close() select_cursor.close() select_cnxn.close() </code></pre>
1
2016-10-15T15:27:29Z
40,065,211
<p>Your code does follow proper form (aside from the few minor tweaks mentioned in the other answer), but be aware that when pyodbc performs an <code>.executemany</code> what it actually does is submit a separate <code>sp_prepexec</code> for each individual row. That is, for the code</p> <pre class="lang-python prettyprint-override"><code>sql = "INSERT INTO #Temp (id, txtcol) VALUES (?, ?)" params = [(1, 'foo'), (2, 'bar'), (3, 'baz')] crsr.executemany(sql, params) </code></pre> <p>the SQL Server actually performs the following (as confirmed by SQL Profiler)</p> <pre class="lang-sql prettyprint-override"><code>exec sp_prepexec @p1 output,N'@P1 bigint,@P2 nvarchar(3)',N'INSERT INTO #Temp (id, txtcol) VALUES (@P1, @P2)',1,N'foo' exec sp_prepexec @p1 output,N'@P1 bigint,@P2 nvarchar(3)',N'INSERT INTO #Temp (id, txtcol) VALUES (@P1, @P2)',2,N'bar' exec sp_prepexec @p1 output,N'@P1 bigint,@P2 nvarchar(3)',N'INSERT INTO #Temp (id, txtcol) VALUES (@P1, @P2)',3,N'baz' </code></pre> <p>So, for an <code>.executemany</code> "batch" of 10,000 rows you would be </p> <ul> <li>performing 10,000 individual inserts,</li> <li>with 10,000 round-trips to the server, and</li> <li>sending the identical SQL command text (<code>INSERT INTO ...</code>) 10,000 times.</li> </ul> <p>It is <em>possible</em> to have pyodbc send an initial <code>sp_prepare</code> and then do an <code>.executemany</code> calling <code>sp_execute</code>, but the nature of <code>.executemany</code> is that you still would do 10,000 <code>sp_prepexec</code> calls, just executing <code>sp_execute</code> instead of <code>INSERT INTO ...</code>. That could improve performance if the SQL statement was quite long and complex, but for a short one like the example in your question it probably wouldn't make all that much difference.</p> <p>One could also get creative and build "table value constructors" as illustrated in <a href="http://stackoverflow.com/a/25879264/2144390">this answer</a>, but notice that it is only offered as a "Plan B" when native bulk insert mechanisms are not a feasible solution.</p>
1
2016-10-15T23:18:23Z
[ "python", "pyodbc" ]
recursive subset sum function
40,060,892
<p>Our professor shared the following Python code for our class on recursion. It's a solution for the 'subset sum' problem. </p> <p>I've read it again and again and tried checking it and following the parameters step by step with an online tool, but I just don't get it at all. </p> <p>I understand that the code checks if it's possible for a subset of a list L to make the sum 0, but I don't understand how on earth the function checks whether or not the sum is actually 0. To put simply: I don't see a sum function used anywhere, so how can the code know that the sum of the elements of a subset is 0.</p> <pre><code>def possible(L,som=0,used=False): if L==[]: return (som==0) and used else: return (possible(L[1:],som,used) or possible(L[1:],som-L[0],True)) </code></pre> <p>I know there have been some questions about subset-sum in combination with Python, and I have seen one similar function posted, but there was no explanation to go with it (at least not one I understood).</p>
-1
2016-10-15T15:30:11Z
40,061,404
<h3>Summary</h3> <pre><code>def possible(L,som=0,used=False): if the list is empty: return (is our running sum 0 and have we used at least one element?) else: return (what if we ignore the first element?) or \ (what if we use the first element?) </code></pre> <h3>Basic idea</h3> <p>This code is based off the idea that every element in <code>L</code> must either be in or out of any possible subset; there is no third option. This is very useful because we know exactly what we should do for either case. We either include the element in the sum or we don't. This sum is calculated step by step, and is stored in <code>som</code>. The variable name <code>sum</code> is not used because <code>sum</code> is already a Python function (which you seem to already know about). The code would still work in <code>som</code> was renamed to <code>sum</code> but this is bad coding practice. The two cases are represented by the two recursive calls shown below:</p> <p><strong>Case 1:</strong></p> <p>This call tests the case in which the first element is <strong>not</strong> included in the subset.</p> <pre><code>possible(L[1:],som,used) </code></pre> <p>We exclude the first element from any further checks using <code>L[1:]</code>. The first element is not used so it does not change the sum in any way. Thus, no changes are made to <code>som</code> and it is passed on as is. Lastly, <code>used</code> is not changed. I will get to that further in the post. </p> <p><strong>Case 2:</strong></p> <p>This call tests the case in which the first element <strong>is</strong> included in the subset.</p> <pre><code>possible(L[1:],som-L[0],True) </code></pre> <p>As before, we do not want to check the first element again, so we recurse on <code>L[1:]</code>. We <em>are</em> using <code>L[0]</code>, so it must change the current sum (<code>som</code>) in some way. Your professor chose to subtract it, but it works identically if he would have added it instead. <code>used</code> now becomes <code>True</code>. </p> <h3>So what is this <code>used</code> nonsense, and why do we care about it when the list is empty?</h3> <p>A leading question, what is the sum of all of the elements of an empty subset? Personally, my mind first goes to <code>0</code>. But this is a problem, because the empty set is a subset of every list. This means that if we considered the sum of an empty subset to be <code>0</code> every possible set of anything at all, numbers or not, would have a subset with a sum of <code>0</code>. This would yield a much easier implementation:</p> <pre><code>def possible(L): return True </code></pre> <p>But this isn't useful at all. So instead, we should only consider the case in which some element is used, which is where the <code>used</code> variable comes in. It is set to <code>True</code> as soon as any element is included and, when we get to the base case, is used to filter out the empty set case.</p>
1
2016-10-15T16:18:19Z
[ "python", "subset-sum" ]
Why does list index go out of range when using random module?
40,060,952
<p>I am building a Chatbot and I was able to make it answer to me randomly. I added all the responses in a list and whenever I greet it, It shoots me a random answer. Now this is fine, but sometimes, the program throws an exception - <code>IndexError: list index out of range</code>. I don't understand why the list index is going out of range. The list has 6 items, and by using <code>random.randint(0,len(slist))</code> I was able to get a random response.</p> <p>I have used exception handling to fix this problem. But, I want to know why it gives an error. </p> <p>Here's the code without exception handling: </p> <pre><code>if self.Has_user_greeted == False: self.AI_Greet() else: # goes out of range here self.AI_respond = random.randint(0,len(self.AI_Greeted)) print(self.AI_Greeted[self.AI_respond]) </code></pre>
0
2016-10-15T15:36:12Z
40,060,974
<p>That is because list indexes start at <code>0</code> and <code>randint</code> will choose a number in the range you specify <code>inclusively</code> with the upper bound. Observe this example: </p> <pre><code>&gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; len(a) 3 </code></pre> <p>So, now try to get the value at index <code>3</code>:</p> <pre><code>&gt;&gt;&gt; a[3] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: list index out of range </code></pre> <p>Because the highest index is actually <code>2</code>. </p> <p>What you want to do in your example is simply <code>-1</code> the length: </p> <pre><code>random.randint(0,len(self.AI_Greeted) - 1) </code></pre>
0
2016-10-15T15:38:12Z
[ "python", "python-3.x", "random" ]
Why does list index go out of range when using random module?
40,060,952
<p>I am building a Chatbot and I was able to make it answer to me randomly. I added all the responses in a list and whenever I greet it, It shoots me a random answer. Now this is fine, but sometimes, the program throws an exception - <code>IndexError: list index out of range</code>. I don't understand why the list index is going out of range. The list has 6 items, and by using <code>random.randint(0,len(slist))</code> I was able to get a random response.</p> <p>I have used exception handling to fix this problem. But, I want to know why it gives an error. </p> <p>Here's the code without exception handling: </p> <pre><code>if self.Has_user_greeted == False: self.AI_Greet() else: # goes out of range here self.AI_respond = random.randint(0,len(self.AI_Greeted)) print(self.AI_Greeted[self.AI_respond]) </code></pre>
0
2016-10-15T15:36:12Z
40,060,998
<p><code>randint</code> does not act like the rest of Python (for historical reasons relating to other computer languages). In particular, <code>randint()</code> <em>does</em> include the upper bound, unlike Python's list indices and <code>len()</code>.</p> <p>So use <code>randint(0,len(self.AI_Greeted) - 1)</code>.</p>
2
2016-10-15T15:39:47Z
[ "python", "python-3.x", "random" ]
How to use a previously trained model to get labels of images - TensorFlow
40,060,983
<p>After training a model (according to the <a href="https://www.tensorflow.org/versions/r0.11/tutorials/mnist/pros/index.html" rel="nofollow">mnist tutorial</a>), and saving it using this code:</p> <pre><code>saver = tf.train.Saver() save_path = saver.save(sess,'/path/to/model.ckpt') </code></pre> <p>I want to use the saved model in order to find labels for a new batch of images. I succeeded to load the model and test it with an already exist database, as follows:</p> <pre><code># load MNIST data folds = build_database_tuple.load_data(data_home_dir='/path/to/database') # starting the session. using the InteractiveSession we avoid build the entiee comp. graph before starting the session sess = tf.InteractiveSession() # start building the computational graph ... BUILD AND DEFINE ALL THE LAYERS ... y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # TRAIN AND EVALUATION: cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) sess.run(tf.initialize_all_variables()) saver = tf.train.Saver() # Restore variables from disk. savepath = '/path/to/model.ckpt' saver.restore(sess, save_path=savepath) print("Model restored.") print("test accuracy %g"%accuracy.eval(feed_dict={x: folds.test.images, y_: folds.test.labels, keep_prob: 1.0})) </code></pre> <p>Although I succeed to load and test the model, <strong>I don't know how to get y'</strong> array (the model's predictions for the database images).</p> <p>I scanned the web and found a lot of answers for this question, but I couldn't project those answers for this particular case (e.g. <a href="http://stackoverflow.com/questions/37578876/how-to-feed-cifar10-trained-model-with-my-own-image-and-get-label-as-output">this answer</a> that given about the CIFAR10 tutorial, which really different from the MNIST tutorial).</p> <p>A detailed answer will highly appreciated (I'm new with tensorflow and still learning the terminology). Thanks a lot for your help!</p>
0
2016-10-15T15:38:43Z
40,062,398
<p>Define an OP for performing classification, like</p> <pre><code>predictor = tf.argmax(y_conv,1) </code></pre> <p>and then run it on trained model with new inputs</p> <pre><code>print(sess.run(predictor, feed_dict={ x = new_data })) </code></pre> <p>since "predictor" does not depend on <code>y</code> you do not have to provide it and this will still execute.</p> <p>If you just want to see predictions on test images you can also do both things in one run call by removing your accuracy eval call and doing</p> <pre><code>acc, predictions = sess.run([accuracy, predictor], feed_dict={x: folds.test.images, y_: folds.test.labels, keep_prob: 1.0})) print('Accuracy', acc) print('Predictions', predictions) </code></pre>
2
2016-10-15T17:57:45Z
[ "python", "python-2.7", "machine-learning", "neural-network", "tensorflow" ]
How to use a previously trained model to get labels of images - TensorFlow
40,060,983
<p>After training a model (according to the <a href="https://www.tensorflow.org/versions/r0.11/tutorials/mnist/pros/index.html" rel="nofollow">mnist tutorial</a>), and saving it using this code:</p> <pre><code>saver = tf.train.Saver() save_path = saver.save(sess,'/path/to/model.ckpt') </code></pre> <p>I want to use the saved model in order to find labels for a new batch of images. I succeeded to load the model and test it with an already exist database, as follows:</p> <pre><code># load MNIST data folds = build_database_tuple.load_data(data_home_dir='/path/to/database') # starting the session. using the InteractiveSession we avoid build the entiee comp. graph before starting the session sess = tf.InteractiveSession() # start building the computational graph ... BUILD AND DEFINE ALL THE LAYERS ... y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # TRAIN AND EVALUATION: cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1])) train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) sess.run(tf.initialize_all_variables()) saver = tf.train.Saver() # Restore variables from disk. savepath = '/path/to/model.ckpt' saver.restore(sess, save_path=savepath) print("Model restored.") print("test accuracy %g"%accuracy.eval(feed_dict={x: folds.test.images, y_: folds.test.labels, keep_prob: 1.0})) </code></pre> <p>Although I succeed to load and test the model, <strong>I don't know how to get y'</strong> array (the model's predictions for the database images).</p> <p>I scanned the web and found a lot of answers for this question, but I couldn't project those answers for this particular case (e.g. <a href="http://stackoverflow.com/questions/37578876/how-to-feed-cifar10-trained-model-with-my-own-image-and-get-label-as-output">this answer</a> that given about the CIFAR10 tutorial, which really different from the MNIST tutorial).</p> <p>A detailed answer will highly appreciated (I'm new with tensorflow and still learning the terminology). Thanks a lot for your help!</p>
0
2016-10-15T15:38:43Z
40,062,458
<p>Another option to what lejlot just answered(and this option is primarily for learning and understanding what the network is doing ) could be:You can make predictions using feedforward using the weights and biases that your network already learned that means that al the computations you defined in your "BUILD AND DEFINE ALL THE LAYERS" should be applied to a new dataset ,for example asuming that your network is of the shape inputs-> relu layer -> softmax layer. You would compute:</p> <pre><code>relu_layer_oututs = tf.nn.relu(tf.matmul(input_data,weights_layer1)+biases_layer1 ); prediction = tf.nn.softmax(tf.matmul(relu_layer_outputs,weights_layer2)+biases_layer2); </code></pre>
-1
2016-10-15T18:03:46Z
[ "python", "python-2.7", "machine-learning", "neural-network", "tensorflow" ]
Keep pandas matplotlib plot open after code completes
40,061,044
<p>I am using pandas builtin plotting as per below. However as soon as the plotting method returns, the plot disappears. How can I keep the plot(s) open until I click on them to close?</p> <pre><code>import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt def plot_data(): #...create dataframe df1 pd.options.display.mpl_style = 'default' df1.boxplot() df1.hist() if __name__ == '__main__': plot_data() </code></pre>
0
2016-10-15T15:44:22Z
40,061,180
<p>Use a <code>plt.show(block=True)</code> command to keep the plotting windows open.</p> <pre><code>[...] df1.boxplot() df1.hist() plt.show(block=True) </code></pre> <p>In my version of matplotlib (1.4.3), <code>block=True</code> is necessary, but that may not be the case for all versions (<a href="http://stackoverflow.com/questions/12358312/keep-plotting-window-open-in-matplotlib">Keep plotting window open in Matplotlib</a>)</p>
2
2016-10-15T15:56:47Z
[ "python", "pandas", "matplotlib" ]
Python Flask: Go from Swagger YAML to Google App Engine?
40,061,085
<p>I have used the Swagger Editor to create a REST API and I have requested the server code download for Python Flask. I'm trying to deploy this out to Google Cloud Platform (I think that's the latest name? Or is it still GAE?) but I need to fill in some gaps. </p> <p>I know the Swagger code works because I have deployed it locally without any issues. However, it uses the connexion library instead of Flask outright.</p> <p>I'm mostly lost on how I can incorporate an app.yaml file for GCP and the right entrypoints within the generated code. In addition, I know that the generated code declares it's own app server which I don't think you need to do for GCP. Here's my current <strong>app.yaml</strong></p> <pre><code>application: some-app-name version: 1 runtime: python27 api_version: 1 threadsafe: yes entrypoint: python app.py libraries: - name: connexion version: "latest" </code></pre> <p>And here's my <strong>app.py</strong></p> <pre><code>import connexion if __name__ == '__main__': app = connexion.App(__name__, specification_dir='./swagger/') app.add_api('swagger.yaml', arguments={'title': 'this is my API'}) app.run(port=8080) </code></pre> <p>The primary error I'm getting now is</p> <pre><code>google.appengine.api.yaml_errors.EventError: the library "connexion" is not supported </code></pre> <p>I have a feeling that's because of the way I am declaring an app server in my app.py - it probably shouldn't be needed. How would I modify this file to still use my Swagger code but run on GCP?</p>
0
2016-10-15T15:47:31Z
40,078,854
<p>You seem to have some inconsistencies in your file, it's unclear if you intended it to be a <a href="https://cloud.google.com/appengine/docs/python/config/appref" rel="nofollow">standard environment <code>app.yaml</code> file</a> or a <a href="https://cloud.google.com/appengine/docs/flexible/python/runtime#overview" rel="nofollow">flexible environment</a> one. I can't tell as I'm unfamiliar with swagger and flask.</p> <p>If it's supposed to be a standard environment one then:</p> <ul> <li>the <code>entrypoint:</code> is not a supported config keyword</li> <li>the <code>connexion</code> library is not one of <a href="https://cloud.google.com/appengine/docs/python/tools/built-in-libraries-27" rel="nofollow">the runtime-provided third-party libraries</a>, so you can't <a href="https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27#requesting_a_library" rel="nofollow">request it</a> (i.e. listing it in the <code>libraries</code> section). You need to <a href="https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27#installing_a_library" rel="nofollow">install it (vendor it in)</a>. <ul> <li>it's missing the <code>handlers</code> section</li> </ul></li> </ul> <p>Probably a good idea to go through <a href="https://cloud.google.com/appengine/docs/python/getting-started/python-standard-env" rel="nofollow">Getting Started with Flask on App Engine Standard Environment</a> </p> <p>If, however, your goal was a flexible environment <code>app.yaml</code> file then:</p> <ul> <li>you need the <code>vm: true</code> config in it</li> <li><a href="https://cloud.google.com/appengine/docs/flexible/python/runtime#dependencies" rel="nofollow">installing/specifying dependencies</a> is done differently, not via the <code>libraries</code> section.</li> </ul>
0
2016-10-17T05:08:58Z
[ "python", "google-app-engine", "flask", "swagger", "google-cloud-platform" ]
pysd library ParseError
40,061,091
<p>I'm using a library called <code>pysd</code> to translate <code>vensim</code> files to Python, but when I try to do it (library functions) I get a parse error but don't understand what it means.</p> <p>This is my log.</p> <hr> <pre class="lang-none prettyprint-override"><code>ParseError Traceback (most recent call last) &lt;ipython-input-1-9b0f6b9bac1f&gt; in &lt;module&gt;() 1 get_ipython().magic(u'pylab inline') 2 import pysd ----&gt; 3 model = pysd.read_vensim('201520_1A_Volare_Ev.Tecnica.itmx') /Library/Python/2.7/site-packages/pysd/pysd.pyc in read_vensim(mdl_file) 45 """ 46 from .vensim2py import translate_vensim ---&gt; 47 py_model_file = translate_vensim(mdl_file) 48 model = PySD(py_model_file) 49 model.mdl_file = mdl_file /Library/Python/2.7/site-packages/pysd/vensim2py.pyc in translate_vensim(mdl_file) 651 for section in file_sections: 652 if section['name'] == 'main': --&gt; 653 model_elements += get_model_elements(section['string']) 654 655 # extract equation components /Library/Python/2.7/site-packages/pysd/vensim2py.pyc in get_model_elements(model_str) 158 """ 159 parser = parsimonious.Grammar(model_structure_grammar) --&gt; 160 tree = parser.parse(model_str) 161 162 class ModelParser(parsimonious.NodeVisitor): /Library/Python/2.7/site-packages/parsimonious/grammar.pyc in parse(self, text, pos) 121 """ 122 self._check_default_rule() --&gt; 123 return self.default_rule.parse(text, pos=pos) 124 125 def match(self, text, pos=0): /Library/Python/2.7/site-packages/parsimonious/expressions.pyc in parse(self, text, pos) 108 109 """ --&gt; 110 node = self.match(text, pos=pos) 111 if node.end &lt; len(text): 112 raise IncompleteParseError(text, node.end, self) /Library/Python/2.7/site-packages/parsimonious/expressions.pyc in match(self, text, pos) 125 node = self.match_core(text, pos, {}, error) 126 if node is None: --&gt; 127 raise error 128 return node 129 ParseError: Rule 'escape_group' didn't match at '' (line 1, column 20243). </code></pre>
-1
2016-10-15T15:48:15Z
40,115,778
<p><code>.itmx</code> is an iThink extension, which unfortunately PySD doesn't support (yet). In the future, we'll work out a conversion pathway that lets you bring these in. </p>
0
2016-10-18T18:44:03Z
[ "python" ]
awkward lambda function
40,061,106
<p>I cannot find out what <code>key=key</code> does in this simple python code:</p> <pre><code>for key in dict: f = (lambda key=key: print(key)) print(f()) </code></pre>
1
2016-10-15T15:50:11Z
40,061,165
<p>The first key in 'key=key' is the name of the argument of the lambda function. The second key is a local variable, in your case the for loop variable. </p> <p>So, in each iteration a local key variable is defined, then f is defined as a lambda function receiving one argument with a default the same as this local - so when you activate it the print(key) uses this default value.</p> <p>EDIT: I should emphasize that in the context of f(), key is the local f argument, not the for loop variable. It just defaults to the value of the loop variable.</p> <p>EDIT 2: I just now noticed idjaw's comment. While I don't think this is an answer, this is how you should have wrote your code.</p>
0
2016-10-15T15:55:41Z
[ "python" ]
awkward lambda function
40,061,106
<p>I cannot find out what <code>key=key</code> does in this simple python code:</p> <pre><code>for key in dict: f = (lambda key=key: print(key)) print(f()) </code></pre>
1
2016-10-15T15:50:11Z
40,061,324
<p>In <em>this</em> piece of code, <code>key=key</code> does nothing useful at all. You can just as well write the loop as </p> <pre><code>for key in [1,2,3]: f = lambda: key print(f()) </code></pre> <p>This will print <code>1</code>, <code>2</code>, and <code>3</code>. (Note that -- unrelated to the problem -- I also removed the <code>print</code> from the <code>lambda</code>, instead returning the value directly, because it's redundant and will only make the "outer" <code>print</code> print <code>None</code>, as that's what the function would return with <code>print</code>.)</p> <p>But what if you do not execute the function right within the loop, but afterwards?</p> <pre><code>functions = [] for key in [1,2,3]: f = lambda: key functions.append(f) for f in functions: print(f()) </code></pre> <p>Now, this will print <code>3</code>, <code>3</code>, and <code>3</code>, as the <code>key</code> variable is evaluated when the function is <em>called</em>, not when it is <em>defined</em>, i.e. after the loop when it has the value <code>3</code>. This can lead to some serious surprises e.g. when <a href="http://stackoverflow.com/q/19837486/1639625">defining callback functions for different buttons in a loop</a>.</p> <p>Here, using <code>key=key</code> comes into play: This will create a parameter <code>key</code> and assign to it the current value of the <code>key</code> variable in the loop <em>when the function is defined</em> as a default value (hence you do not have to pass a parameter when calling the function). The value of that <code>key</code> paremeter will then stay the same <em>within the scope of the function</em> when the function is called later:</p> <pre><code>functions = [] for key in [1,2,3]: f = lambda key=key: key functions.append(f) </code></pre> <p>This prints <code>1</code>, <code>2</code>, and <code>3</code>, as would be expected. As others have noted, you can use a different name for the parameter, to make this less confusing, e.g. <code>f = lambda param=key: param</code>.</p>
3
2016-10-15T16:10:35Z
[ "python" ]
awkward lambda function
40,061,106
<p>I cannot find out what <code>key=key</code> does in this simple python code:</p> <pre><code>for key in dict: f = (lambda key=key: print(key)) print(f()) </code></pre>
1
2016-10-15T15:50:11Z
40,061,471
<p>This code is not "simple", it's actually somewhat tricky to understand for a Python novice.</p> <p>The <code>for key in dict:</code> simply loops over what <code>dict</code> is. Normally <code>dict</code> is a predefined system library class (the class of standard dictionaries) and iterating over a class object is (normally) nonsense.</p> <p>Python however allows to redefine what <code>dict</code> is bound to: <code>dict</code> is not a keyword, but just a regular name that can be reused as you like - if you like to write bad python code that confuses IDEs and fellow programmers.</p> <p>I'll assume that <code>dict</code> in this context is some kind of container that can be iterated over: it could be a list, a tuple or a dictionary (as the name suggests) for example. Note that iterating over a dictionary means in Python iterating over dictionary keys.</p> <pre><code>f = (lambda key=key: print(key)) </code></pre> <p>this code creates an unnamed function that accepts a parameter named <code>key</code>, and defines the default value to be current value of variable <code>key</code> used in the loop. The body of the function simply calls the standard <code>print</code> function passing <code>key</code> as argument.</p> <p>The code is equivalent to:</p> <pre><code>f = lambda x=key: print(x) </code></pre> <p>that is probably a bit clearer for a novice because avoids reusing the same name.</p> <p>Finally at each iteration this function is called passing no parameters and the result is sent to <code>print</code> standard function. The evaluation of <code>f()</code> will print the <code>key</code> value (passing no parameters the default value will be used) and the result of <code>print</code> (that is <code>None</code>) will be printed by the second <code>print</code> call.</p> <p>There is really nothing good about this example. Actually the <code>lambda x=x:...</code> is a pattern in Python and sometimes is necessary but here is complete nonsense and there's nothing to learn from this use.</p> <p>You should reconsider continuing reading from the source you got this from (I'd suspect that the rest is bad stuff also). Stick to official tutorials for better examples...</p>
2
2016-10-15T16:24:10Z
[ "python" ]
If strings are immutable, then how is this possible?
40,061,167
<p>I am new to python and was going through the python3 docs. In python strings are said to be immutable, then how is this possible:</p> <pre><code>if __name__ == '__main__': l = 'string' print(l) l = l[:2] print(l) </code></pre> <p>returns this output:</p> <pre><code>string st </code></pre>
1
2016-10-15T15:55:43Z
40,061,182
<p>Informally, <code>l</code> now points to a new immutable string, which is a copy of a part of the old one.</p> <p>What you cannot do is modify a string in place. </p> <pre><code>a = "hello" a[0] = "b" # not allowed to modify the string `a` is referencing; raises TypeError print(a) # not reached, since we got an exception at the previous line </code></pre> <p>but you can do this:</p> <pre><code>a = "hello" a = "b" + a[1:] # ok, since we're making a new copy print(a) # prints "bello" </code></pre>
3
2016-10-15T15:57:03Z
[ "python", "python-3.x", "immutability" ]
If strings are immutable, then how is this possible?
40,061,167
<p>I am new to python and was going through the python3 docs. In python strings are said to be immutable, then how is this possible:</p> <pre><code>if __name__ == '__main__': l = 'string' print(l) l = l[:2] print(l) </code></pre> <p>returns this output:</p> <pre><code>string st </code></pre>
1
2016-10-15T15:55:43Z
40,061,230
<p>The key to understand this problem is to realize that variable in Python is just a "pointer" pointing to an underlying object. And you confused the concept of immutable object and immutable variable(which does not exist in Python).</p> <p>For instance, in your case, <code>l</code> was initially a pointer pointing to a <code>str</code> object with content "string". But later, you "redirect" it to a new <code>str</code> object whose content is "st". Note that when the program runs to the line <code>l = l[:2]</code>, it's the pointer being modified, not the object pointed to by the pointer. If you will, you can also "redirect" <code>l</code> to another object with type other than <code>str</code>, say <code>l = 123</code>. Just remember, the original object pointed to by <code>l</code>(<code>str</code> "string") is not modified at all, it's still there in the memory(as long as it is not garbage collected), but just no longer pointed to by <code>l</code>.</p> <p>For you to better understand the concept of immutable object, let's look at a mutable object. For example, <code>list</code> in Python is mutable. </p> <pre><code>l = [1, 2, 3] # a new list with three elements l.append(4) # append a new element 4 to the list (l is now modified!!!) </code></pre> <p>In the code above, we modified <code>l</code> by appending a new element to it. Throughout the program, <code>l</code> points to the same object, but it's the object pointed to by <code>l</code> that is changed in the process. </p>
2
2016-10-15T16:01:28Z
[ "python", "python-3.x", "immutability" ]
Easiest way to return sum of a matrix's neighbors in numpy
40,061,185
<p>I am trying to make a program that needs a matrix's neighbor(excluding itself) sum ex:</p> <pre><code> matrix([[0, 0, 0], [1, 0, 1], [0, 1, 0]]) </code></pre> <p>would return:</p> <pre><code>matrix([[1, 2, 1], [1, 3, 1], [2, 2, 2]]) </code></pre> <p>I have a working code here but its big and messy and I'm new to numpy so I need some help cleaning it up and optimizing. (I feel like there has to be a better way)</p> <p>example code:</p> <pre><code>import numpy as np def NiSum(m): new = [] for x in range(m.shape[0]-1): row = [] for y in range(m.shape[1]-1): Ni = 0 for a in [1,1],[1,0],[1,-1],[0,1],[0,-1],[-1,1],[-1,0],[-1,-1]: Ni += m[x+a[0],y+a[1]] row.append(Ni) new.append(row) return np.matrix(new) example = np.matrix('0 0 0 0 0 0 0 0; '*3+'0 0 0 1 1 1 0 0; '*3+'0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 ') NiSum(example) </code></pre> <p>Thanks for any help !</p>
3
2016-10-15T15:57:26Z
40,061,601
<p>You are summing all values in that <code>3x3</code> neighbourhood, but excluding the element itself. So, we can use <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.convolve2d.html" rel="nofollow"><code>Scipy's 2D convolution</code></a> and subtract that input array/matrix from it for the desired output, like so -</p> <pre><code>from scipy.signal import convolve2d convolve2d(a,np.ones((3,3),dtype=int),'same') - a </code></pre> <p>Sample run -</p> <pre><code>In [11]: a Out[11]: matrix([[0, 0, 0], [1, 0, 1], [0, 1, 0]]) In [12]: convolve2d(a,np.ones((3,3),dtype=int),'same') - a Out[12]: matrix([[1, 2, 1], [1, 3, 1], [2, 2, 2]]) </code></pre> <p>Or simply form a kernel with all ones but zero at the center and use the same 2D convolution -</p> <pre><code>In [31]: kernel = np.array([[1,1,1],[1,0,1],[1,1,1]]) In [32]: np.asmatrix(convolve2d(a,kernel,'same')) Out[32]: matrix([[1, 2, 1], [1, 3, 1], [2, 2, 2]]) </code></pre>
3
2016-10-15T16:38:20Z
[ "python", "python-3.x", "numpy", "matrix", "scipy" ]
Easiest way to return sum of a matrix's neighbors in numpy
40,061,185
<p>I am trying to make a program that needs a matrix's neighbor(excluding itself) sum ex:</p> <pre><code> matrix([[0, 0, 0], [1, 0, 1], [0, 1, 0]]) </code></pre> <p>would return:</p> <pre><code>matrix([[1, 2, 1], [1, 3, 1], [2, 2, 2]]) </code></pre> <p>I have a working code here but its big and messy and I'm new to numpy so I need some help cleaning it up and optimizing. (I feel like there has to be a better way)</p> <p>example code:</p> <pre><code>import numpy as np def NiSum(m): new = [] for x in range(m.shape[0]-1): row = [] for y in range(m.shape[1]-1): Ni = 0 for a in [1,1],[1,0],[1,-1],[0,1],[0,-1],[-1,1],[-1,0],[-1,-1]: Ni += m[x+a[0],y+a[1]] row.append(Ni) new.append(row) return np.matrix(new) example = np.matrix('0 0 0 0 0 0 0 0; '*3+'0 0 0 1 1 1 0 0; '*3+'0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 ') NiSum(example) </code></pre> <p>Thanks for any help !</p>
3
2016-10-15T15:57:26Z
40,062,334
<p>Define a function which computes the sum of all neighbors for a matrix entry, if they exist:</p> <pre><code>def sumNeighbors(M,x,y): l = [] for i in range(max(0,x-1),x+2): # max(0,x-1), such that no negative values in range() for j in range(max(0,y-1),y+2): try: t = M[i][j] l.append(t) except IndexError: # if entry doesn't exist pass return sum(l)-M[x][y] # exclude the entry itself </code></pre> <p>Then you can iterate for every entry in your matrix and pass its result into a new matrix N:</p> <pre><code>import numpy as np M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] M = np.asarray(M) N = np.zeros(M.shape) for i in range(M.shape[0]): for j in range(M.shape[1]): N[i][j] = sumNeighbors(M, i, j) print "Original matrix:\n", M print "Summed neighbors matrix:\n", N </code></pre> <p><strong>Output:</strong></p> <pre><code>Original matrix: [[1 2 3] [4 5 6] [7 8 9]] Summed neighbors matrix: [[ 11. 19. 13.] [ 23. 40. 27.] [ 17. 31. 19.]] </code></pre>
1
2016-10-15T17:50:25Z
[ "python", "python-3.x", "numpy", "matrix", "scipy" ]
Why can yield be indexed?
40,061,280
<p>I thought I could make my python (2.7.10) code simpler by directly accessing the index of a value passed to a generator via <code>send</code>, and was surprised the code ran. I then discovered an index applied to <code>yield</code> doesn't really do anything, nor does it throw an exception:</p> <pre><code>def gen1(): t = yield[0] assert t yield False g = gen1() next(g) g.send('char_str') </code></pre> <p>However, if I try to index <code>yield</code> thrice or more, I get an exception:</p> <pre><code>def gen1(): t = yield[0][0][0] assert t yield False g = gen1() next(g) g.send('char_str') </code></pre> <p>which throws</p> <pre><code>TypeError: 'int' object has no attribute '__getitem__' </code></pre> <p>This was unusually inconsistent behavior, and I was wondering if there is an intuitive explanation for what indexing yield is actually doing?</p>
6
2016-10-15T16:06:41Z
40,061,337
<p>You are not indexing. You are yielding a list; the expression <code>yield[0]</code> is really just the same as the following (but without a variable):</p> <pre><code>lst = [0] yield lst </code></pre> <p>If you look at what <code>next()</code> returned you'd have gotten that list:</p> <pre><code>&gt;&gt;&gt; def gen1(): ... t = yield[0] ... assert t ... yield False ... &gt;&gt;&gt; g = gen1() &gt;&gt;&gt; next(g) [0] </code></pre> <p>You don't <em>have</em> to have a space between <code>yield</code> and the <code>[0]</code>, that's all.</p> <p>The exception is caused by you trying to apply the subscription to the contained <code>0</code> integer:</p> <pre><code>&gt;&gt;&gt; [0] # list with one element, the int value 0 [0] &gt;&gt;&gt; [0][0] # indexing the first element, so 0 0 &gt;&gt;&gt; [0][0][0] # trying to index the 0 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'int' object is not subscriptable </code></pre> <p>If you want to index a value sent to the generator, put parentheses around the <code>yield</code> expression:</p> <pre><code>t = (yield)[0] </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; def gen1(): ... t = (yield)[0] ... print 'Received: {!r}'.format(t) ... yield False ... &gt;&gt;&gt; g = gen1() &gt;&gt;&gt; next(g) &gt;&gt;&gt; g.send('foo') Received: 'f' False </code></pre>
12
2016-10-15T16:11:49Z
[ "python", "python-2.7", "indexing", "generator", "yield" ]
Automate students tests run
40,061,297
<p>I have a folders structure for some tasks, they are like this:</p> <pre><code>- student_id1/answers.py - student_id2/answers.py - student_id3/answers.py - student_id4/answers.py - ... </code></pre> <p>I have a main file: <code>run_tests.py</code>:</p> <pre><code>from student_id1.answers import run_test as test1 from student_id2.answers import run_test as test2 ... try: test1() print("student_id1: OK") except Exception as ee: print("Error for student_id1") try: test2() print("student_id2: OK") except Exception as ee: print("Error for student_id2") ... </code></pre> <p>There can be more folders as they are adding with each new student. I would like to call all tests with a single command, but do not want to add so much lines with each new student.</p> <p>How can I automate this?</p>
4
2016-10-15T16:08:14Z
40,061,352
<p>You can use <code>importlib</code> module: <a href="https://docs.python.org/3/library/importlib.html" rel="nofollow">https://docs.python.org/3/library/importlib.html</a></p> <pre><code>import os import importlib for student_dir in os.listdir(): if os.path.isdir(student_dir): # here you may add an additional check for not desired folders like 'lib', 'settings', etc if not os.path.exists(os.path.join(student_dir, 'answers.py')): print("Error: file answers.py is not found in %s" % (student_dir)) continue student_module = importlib.import_module("%s.answers" % student_dir) try: student_module.run_test() print("%s: OK" % student_dir) except Exception as ee: print("Error for %s" % student_dir) </code></pre>
3
2016-10-15T16:13:21Z
[ "python" ]
Comparatively slow python numpy 3D Fourier Transformation
40,061,307
<p>Dear StackOverflow community!</p> <p>For my work I need to perform discrete fourier transformations (DFTs) on large images. In the current example I require a 3D FT for a 1921 x 512 x 512 image (along with 2D FFTs of 512 x 512 images). Right now, I am using the numpy package and the associated function <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftn.html" rel="nofollow">np.fft.fftn()</a>. The code snippet below exemplarily shows 2D and 3D FFT times on an equal-sized/slightly smaller 2D/3D random-number-generated grid in the following way:</p> <pre><code>import sys import numpy as np import time tas = time.time() a = np.random.rand(512, 512) tab = time.time() b = np.random.rand(100, 512, 512) tbfa = time.time() fa = np.fft.fft2(a) tfafb = time.time() fb = np.fft.fftn(b) tfbe = time.time() print "initializing 512 x 512 grid:", tab - tas print "initializing 100 x 512 x 512 grid:", tbfa - tab print "2D FFT on 512 x 512 grid:", tfafb - tbfa print "3D FFT on 100 x 512 x 512 grid:", tfbe - tfafb </code></pre> <p>Output:</p> <pre><code>initializing 512 x 512 grid: 0.00305700302124 initializing 100 x 512 x 512 grid: 0.301637887955 2D FFT on 512 x 512 grid: 0.0122730731964 3D FFT on 100 x 512 x 512 grid: 3.88418793678 </code></pre> <p>The problem that I have is that I will need this process quite often, so the time spent per image should be short. When testing on my own computer (middle-segment laptop, 2GB RAM allocated to virtual machine (--> therefore smaller test grid)), as you can see the 3D FFT takes ~ 5 s (order-of-magnitude). Now, at work, the machines are way better, cluster/grid-architecture systems and FFTs are much faster. In both cases the 2D ones finish quasi instantaneously.</p> <p>However with 1921x512x512, <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.fft.fftn.html" rel="nofollow">np.fft.fftn()</a> takes ~ 5 min. Since I guess scipy's implementation is not much faster and considering that on MATLAB FFTs of same-sized grids finish within ~ 5 s, my question is whether there is a method to speed the process up to or almost to MATLAB times. My knowledge about FFTs is limited, but apparently MATLAB uses the FFTW algorithm, which python does not. Any reasonable chance that with some pyFFTW package I get similar times? Also, 1921 seems an unlucky choice, having only 2 prime factors (17, 113), so I assume this also plays a role. On the other hand 512 is a well-suited power of two. Are MATLAB-like times achievable if possible also without padding up with zeros to 2048?</p> <p>I'm asking because I'll have to use FFTs a lot (to an amount where such differences will be of huge influence!) and in case there is no possibility to reduce computation times in python, I'd have to switch to other, faster implementations.</p> <p>Any advice is greatly appreciated!</p>
4
2016-10-15T16:08:54Z
40,064,319
<p>Yes, there is a chance that using FFTW through the interface <code>pyfftw</code> will reduce your computation time compared to <code>numpy.fft</code> or <code>scipy.fftpack</code>. The performances of these implementations of DFT algorithms can be compared in benchmarks such as <a href="https://gist.github.com/fnielsen/99b981b9da34ae3d5035" rel="nofollow">this one</a> : some interesting results are reported in <a href="http://stackoverflow.com/questions/6365623/improving-fft-performance-in-python">Improving FFT performance in Python</a></p> <p>I suggest the following code for a test:</p> <pre><code>import pyfftw import numpy import time import scipy f = pyfftw.n_byte_align_empty((127,512,512),16, dtype='complex128') #f = pyfftw.empty_aligned((33,128,128), dtype='complex128', n=16) f[:] = numpy.random.randn(*f.shape) # first call requires more time for plan creation # by default, pyfftw use FFTW_MEASURE for the plan creation, which means that many 3D dft are computed so as to choose the fastest algorithm. fftf=pyfftw.interfaces.numpy_fft.fftn(f) #help(pyfftw.interfaces) tas = time.time() fftf=pyfftw.interfaces.numpy_fft.fftn(f) # here the plan is applied, nothing else. tas = time.time()-tas print "3D FFT, pyfftw:", tas f = pyfftw.n_byte_align_empty((127,512,512),16, dtype='complex128') #f = pyfftw.empty_aligned((33,128,128), dtype='complex128', n=16) f[:] = numpy.random.randn(*f.shape) tas = time.time() fftf=numpy.fft.fftn(f) tas = time.time()-tas print "3D FFT, numpy:", tas tas = time.time() fftf=scipy.fftpack.fftn(f) tas = time.time()-tas print "3D FFT, scipy/fftpack:", tas # first call requires more time for plan creation # by default, pyfftw use FFTW_MEASURE for the plan creation, which means that many 3D dft are computed so as to choose the fastest algorithm. f = pyfftw.n_byte_align_empty((128,512,512),16, dtype='complex128') fftf=pyfftw.interfaces.numpy_fft.fftn(f) tas = time.time() fftf=pyfftw.interfaces.numpy_fft.fftn(f) # here the plan is applied, nothing else. tas = time.time()-tas print "3D padded FFT, pyfftw:", tas </code></pre> <p>For a size of 127*512*512, on my modest computer, I got:</p> <pre><code>3D FFT, pyfftw: 3.94130897522 3D FFT, numpy: 16.0487070084 3D FFT, scipy/fftpack: 19.001199007 3D padded FFT, pyfftw: 2.55221295357 </code></pre> <p>So <code>pyfftw</code> is significantly faster than <code>numpy.fft</code> and <code>scipy.fftpack</code>. Using padding is even faster, but the thing that is computed is different.</p> <p>Lastly, <code>pyfftw</code> may seem slower at the first run due to the fact that it uses the flag <code>FFTW_MEASURE</code> according to the <a href="https://hgomersall.github.io/pyFFTW/pyfftw/interfaces/interfaces.html" rel="nofollow">documentation</a>. It's a good thing if and only if many DFTs of the same size are successively computed.</p>
2
2016-10-15T21:17:53Z
[ "python", "performance", "numpy", "fft" ]
Creating a Django model that can have a many-to-many relationship with itself
40,061,325
<p>I'm trying to write a Django model that can have a many-to-many relationship with itself.</p> <p>This is my <strong>models.py</strong>:</p> <pre><code>class Apps(models.Model): name = models.CharField( verbose_name = 'App Name', max_length = 30 ) logo = models.ImageField( verbose_name = 'Logo' ) description = models.TextField( verbose_name = 'Description' ) google_url = models.URLField( verbose_name = 'Google Play Link', null = True ) apple_url = models.URLField( verbose_name = 'Apple AppStore Link', null = True ) youtube_url = models.URLField( verbose_name = 'Youtube Video Page', null = True ) similar_apps = models.ManyToManyField( 'self', through = 'SimilarApps', related_name = 'similar_apps', verbose_name = 'Similar Apps', help_text = 'Similar Apps', symmetrical = False ) def __unicode__(self): return u'%s' % (self.user.name) class SimilarApps(models.Model): primary = models.ForeignKey( Apps, verbose_name = 'Primary App', related_name = 'primary_app', help_text = 'First of 2 similar Apps.', ) secondary = models.ForeignKey( Apps, verbose_name = 'Matched App', related_name = 'matched_app', help_text = 'Second of 2 similar Apps.', ) </code></pre> <p>When I run <code>manage.py makemigrations</code> I get the following error</p> <pre><code>&lt;class 'appsrfun.admin.SimilarAppsInline'&gt;: (admin.E202) 'appsrfun.SimilarApps' has more than one ForeignKey to 'appsrfun.Apps'. appsrfun.Apps.similar_apps: (fields.E302) Reverse accessor for 'Apps.similar_apps' clashes with field name 'Apps.similar_apps'. HINT: Rename field 'Apps.similar_apps', or add/change a related_name argument to the definition for field 'Apps.similar_apps'. appsrfun.Apps.similar_apps: (fields.E303) Reverse query name for 'Apps.similar_apps' clashes with field name 'Apps.similar_apps'. HINT: Rename field 'Apps.similar_apps', or add/change a related_name argument to the definition for field 'Apps.similar_apps'. </code></pre> <p>Please tell me this is possible and explain how to do it. Thanks</p>
0
2016-10-15T16:10:35Z
40,061,917
<p>This has just got through <code>makemigrations</code> and I'm going to test it:</p> <pre><code>class App(models.Model): name = models.CharField( verbose_name = 'App Name', max_length = 30 ) logo = models.ImageField( verbose_name = 'Logo' ) description = models.TextField( verbose_name = 'Description' ) google_url = models.URLField( verbose_name = 'Google Play Link', null = True ) apple_url = models.URLField( verbose_name = 'Apple AppStore Link', null = True ) youtube_url = models.URLField( verbose_name = 'Youtube Video Page', null = True ) similar_app = models.ManyToManyField( 'self', through = 'MySimilarApp', verbose_name = 'Similar App', help_text = 'Similar App', symmetrical = False, through_fields = ('primary','secondary'), ) def __unicode__(self): return u'%s' % (self.user.name) class MySimilarApp(models.Model): primary = models.ForeignKey( App, verbose_name = 'Primary App', related_name = 'primary_app', help_text = 'First of 2 similar Apps.', ) secondary = models.ForeignKey( App, verbose_name = 'Matched App', related_name = 'matched_app', help_text = 'Second of 2 similar Apps.', ) </code></pre>
0
2016-10-15T17:09:18Z
[ "python", "django" ]
MQTT Client not receiving messages
40,061,342
<p>I'm using the following code from MQTT Paho project to subscribe to messages from my mqtt broker. I tested the connection using <code>mosquitto_sub</code> and I receive the messages there. However, when I run the following code it doesn't receive any messages and no output is printed. I checked the topic and host.</p> <pre><code>import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) client = mqtt.Client() client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) client.loop_forever() </code></pre> <p>The following error is logged by the broker:</p> <pre><code>Invalid protocol "MQTT" in CONNECT from ::1. Socket read error on client (null), disconnecting. </code></pre> <p><strong>EDIT</strong> Thanks to @hardillb for pointing out the outdated MQTT version.</p> <p>Everything worked after I did the following:</p> <ol> <li>sudo apt-get purge mosquitto</li> <li>sudo apt-add-repository ppa:mosquitto-dev/mosquitto-ppa</li> <li>sudo apt-get update</li> <li>sudo apt-get install mosquitto</li> </ol>
0
2016-10-15T16:12:07Z
40,061,644
<p>This is most likely because you are using an old version of mosquitto and the python is expecting a newer build that supports MQTT 3.1.1</p> <p>Try changing the code as shown:</p> <pre><code>import paho.mqtt.client as mqtt # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("test") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print(msg.topic+" "+str(msg.payload)) # Change made HERE client = mqtt.Client(protocol=MQTTv31) client.on_connect = on_connect client.on_message = on_message client.connect("localhost", 1883, 60) client.loop_forever() </code></pre> <p>You should also upgrade your broker as soon as possible, that version is incredibly out of date and has a number of known issues, the current version is 1.4.10</p>
1
2016-10-15T16:43:29Z
[ "python", "publish-subscribe", "mqtt" ]
Scatterplot of two Pandas Series, coloured by date and with legend
40,061,493
<p>I am studying financial time series, in the format of pandas series. To compare two series I do a scatterplot, and to visualise the time evolution in the scatterplot I can colour them. This is all fine.</p> <p>My question relates to the legend showing the colours. I would like the legend to show the date/year that the colour corresponds to, rather than just an the index of the data entry, as now. But I haven't been able to do this, or to find a question like this on stackoverflow.</p> <p>I know the time series knows the dates, and if you just plot a time series, the x-axis will show the dates.</p> <p>My code is</p> <pre><code>from pandas_datareader import data as web import matplotlib.pyplot as plt import pandas as pd #Download data start = '2010-1-1' end = '2016-10-1' AAPL = web.DataReader('AAPL', 'yahoo', start=start, end=end)['Adj Close'] TSLA = web.DataReader('GOOG', 'yahoo', start=start, end=end)['Adj Close'] #Scatterplot plt.scatter(AAPL, TSLA, alpha=.4, c=range(len(AAPL))) plt.colorbar() plt.xlabel("AAPL") plt.ylabel("TSLA") plt.grid() plt.show() </code></pre> <p>This code produces this plot: <a href="https://i.stack.imgur.com/KjU2w.png" rel="nofollow">Scatterplot with colours and legend</a></p> <p>Thanks</p>
0
2016-10-15T16:27:48Z
40,065,339
<p>While there might be an easier answer out there (anyone?), to me the most straightforward way is to change the colorbar ticks manually. </p> <p>Try the following before you invoke <code>plt.show()</code>:</p> <pre><code>clb = plt.gci().colorbar # get the colorbar artist # get the old tick labels (index numbers of the dataframes) clb_ticks = [int(t.get_text()) for t in clb.ax.yaxis.get_ticklabels()] # convert the old, index, ticks into year-month-day format new_ticks = AAPL.index[clb_ticks].strftime("%Y-%m-%d") clb.ax.yaxis.set_ticklabels(new_ticks) </code></pre> <p>Note that <code>strftime</code> does not appear to be implemented in <code>pandas</code> versions older than <code>0.18</code>. In that case you'll have to replace <code>.strftime("%Y-%m-%d")</code> with <code>.apply(lambda x: x.strftime('%Y-%m-%d'))</code> as explained <a href="http://stackoverflow.com/questions/19738169/convert-column-of-date-objects-in-pandas-dataframe-to-strings">here</a>.</p> <p><a href="https://i.stack.imgur.com/v6cPs.png" rel="nofollow"><img src="https://i.stack.imgur.com/v6cPs.png" alt="clb-ymd_labels-pandas"></a></p>
0
2016-10-15T23:40:00Z
[ "python", "pandas", "matplotlib", "legend", "series" ]
How to get n variables in one line?
40,061,538
<p>I have a number <strong>n</strong> and I need to get from a user <strong>n</strong> variables in one line.</p> <p>As far as i know, it's pretty easy to do if you know exactly how many variables you have.</p> <pre><code>*variables* = map(int, input().split()) </code></pre> <p>But if I don't know how many variables there are, what should I do?</p> <p>Also, I'm asked to put the result in array. </p> <p>Unfortunately, I've just started learning Python, so I have <em>absolutely</em> no idea how to do it and can't show any code I've tried. </p>
1
2016-10-15T16:31:50Z
40,061,602
<p>User input being taken as a space separated string: </p> <pre><code>1 2 3 4 5 </code></pre> <p>This being the code you are dealing with: </p> <pre><code>map(int, input().split()) </code></pre> <p>Stating you need a list, then just store it in a single variable: </p> <pre><code>inputs = map(int, input().split()) </code></pre> <p>However, dealing with Python 3, you will end up with <code>map</code> object. So if you actually need a <code>list</code> type, then just call <code>list</code> on the <code>map</code> function:</p> <pre><code>inputs = list(map(int, input().split())) </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; inputs = list(map(int, input().split())) 1 2 3 4 5 &gt;&gt;&gt; type(inputs) &lt;class 'list'&gt; &gt;&gt;&gt; inputs [1, 2, 3, 4, 5] </code></pre>
2
2016-10-15T16:38:26Z
[ "python" ]
Using other file names than models.py for Django models?
40,061,555
<p>When creating a reusable app, should I put all models I define into single file <code>models.py</code> or can I group the models into several files like <code>topic1.py</code>, <code>topic2.py</code>?</p> <p>Please describe all reasons pro and contra.</p>
0
2016-10-15T16:33:52Z
40,061,691
<p>The <code>models</code> submodule is special in that it is automatically imported at a specific time during the initialization process. All your models should be imported at this time as well. You can't import them earlier than that, and importing them later may cause errors. </p> <p>You can define your models in a different module, but you should always import all your models into your <code>models.py</code> or <code>models/__init__.py</code>. E.g.:</p> <pre><code># models/topic1.py class Topic1(models.Model): ... # models/__init__.py from .topic1 import Topic1 </code></pre> <p>If you import each model into <code>models.py</code> or <code>models/__init__.py</code>, that also allows you to import all the models directly from that file. In the example, that means that you can import <code>Topic1</code> from <code>myapp.models</code>, not just from <code>myapp.models.topic1</code>. This way you can keep your models organized across multiple files without having to remember each model's precise location whenever you need to import them. </p>
1
2016-10-15T16:47:26Z
[ "python", "django", "model" ]
Using other file names than models.py for Django models?
40,061,555
<p>When creating a reusable app, should I put all models I define into single file <code>models.py</code> or can I group the models into several files like <code>topic1.py</code>, <code>topic2.py</code>?</p> <p>Please describe all reasons pro and contra.</p>
0
2016-10-15T16:33:52Z
40,061,752
<p>it depend how much model you define, if you have only 1 to 5 class model, just put it into single file, but if you have more than 5 class model, i suggesting put it on several files,</p> <p>but in my experience, if the model put in a serveral files, it become little cumbersome when it comes to importing stuff,</p>
0
2016-10-15T16:54:35Z
[ "python", "django", "model" ]
Call field from inherited model Odoo v9 community
40,061,786
<p>Let me explain what I'm trying to do.</p> <p>On <code>stock</code> module, when You navigate to whatever operation (picking) type, being it a tree or form view, some of the fields that are shown are from <code>product.product</code>, like, for example <code>name</code>.</p> <p>Now, the model <code>product.product</code> has a field called <code>price</code>, so, I need to show product price on <code>stock.picking</code> movements.</p> <p>Since the <code>stock.picking</code> model doesn't inherit the <code>price</code> field, I'm creating a little module, to inherit <code>price</code> from <code>product.product</code>, and then show it on <code>stock.picking</code>.</p> <p>It is a third module beside <code>stock</code> and <code>product</code>.</p> <p>Now, in my <code>models.py</code> I declare:</p> <pre><code># -*- coding: utf-8 -*- from openerp import models, fields, api class StockMove(models.Model): _inherit = 'stock.move' @api.onchange('name','product_id','move_line_tax_ids','product_uom_qty') price_unit = fields.Float( digits_compute=dp.get_precision('Product Price'), string='Price') </code></pre> <p>In my <code>view.xml</code> I add this field to <code>stock.picking</code>:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;openerp&gt; &lt;data&gt; &lt;record id="view_stock_move_tree" model="ir.ui.view"&gt; &lt;field name="name"&gt;Stock Move Price Tree&lt;/field&gt; &lt;field name="model"&gt;stock.picking&lt;/field&gt; &lt;field name="inherit_id" ref="stock.vpicktree"/&gt; &lt;field name="arch" type="xml"&gt; &lt;field name="state" position="before"&gt; &lt;field name="price_unit"/&gt; &lt;/field&gt; &lt;/field&gt; &lt;/record&gt; &lt;record id="view_stock_move_form" model="ir.ui.view"&gt; &lt;field name="name"&gt;Stock Move Price Form&lt;/field&gt; &lt;field name="model"&gt;stock.picking&lt;/field&gt; &lt;field name="inherit_id" ref="stock.view_picking_form"/&gt; &lt;field name="arch" type="xml"&gt; &lt;field name="state" position="before"&gt; &lt;field name="price_unit"/&gt; &lt;/field&gt; &lt;/field&gt; &lt;/record&gt; &lt;/data&gt; &lt;/openerp&gt; </code></pre> <p>Every time I try to run this, it throws me on console:</p> <pre><code>2016-10-15 05:23:44,821 21578 ERROR argentina werkzeug: Error on request: Traceback (most recent call last): File "/home/kristian/.virtualenvs/odoo_danisan/lib/python2.7/site-packages/werkzeug/serving.py", line 177, in run_wsgi execute(self.server.app) File "/home/kristian/.virtualenvs/odoo_danisan/lib/python2.7/site-packages/werkzeug/serving.py", line 165, in execute application_iter = app(environ, start_response) File "/home/kristian/odoov9/odoo-9.0/openerp/service/server.py", line 246, in app return self.app(e, s) File "/home/kristian/odoov9/odoo-9.0/openerp/service/wsgi_server.py", line 184, in application return application_unproxied(environ, start_response) File "/home/kristian/odoov9/odoo-9.0/openerp/service/wsgi_server.py", line 170, in application_unproxied result = handler(environ, start_response) File "/home/kristian/odoov9/odoo-9.0/openerp/http.py", line 1495, in __call__ return self.dispatch(environ, start_response) File "/home/kristian/odoov9/odoo-9.0/openerp/http.py", line 1644, in dispatch ir_http = request.registry['ir.http'] File "/home/kristian/odoov9/odoo-9.0/openerp/http.py", line 365, in registry return openerp.modules.registry.RegistryManager.get(self.db) if self.db else None File "/home/kristian/odoov9/odoo-9.0/openerp/modules/registry.py", line 355, in get update_module) File "/home/kristian/odoov9/odoo-9.0/openerp/modules/registry.py", line 386, in new openerp.modules.load_modules(registry._db, force_demo, status, update_module) File "/home/kristian/odoov9/odoo-9.0/openerp/modules/loading.py", line 334, in load_modules force, status, report, loaded_modules, update_module) File "/home/kristian/odoov9/odoo-9.0/openerp/modules/loading.py", line 237, in load_marked_modules loaded, processed = load_module_graph(cr, graph, progressdict, report=report, skip_modules=loaded_modules, perform_checks=perform_checks) File "/home/kristian/odoov9/odoo-9.0/openerp/modules/loading.py", line 123, in load_module_graph load_openerp_module(package.name) File "/home/kristian/odoov9/odoo-9.0/openerp/modules/module.py", line 331, in load_openerp_module __import__('openerp.addons.' + module_name) File "/home/kristian/odoov9/odoo-9.0/openerp/modules/module.py", line 61, in load_module mod = imp.load_module('openerp.addons.' + module_part, f, path, descr) File "/home/kristian/odoov9/motostion_addons/stock_move_price/__init__.py", line 7, in &lt;module&gt; from . import models File "/home/kristian/odoov9/motostion_addons/stock_move_price/models/__init__.py", line 1, in &lt;module&gt; from . import models File "/home/kristian/odoov9/motostion_addons/stock_move_price/models/models.py", line 10 price_unit = fields.Float( digits_compute=dp.get_precision('Product Price'), string='Price') ^ SyntaxError: invalid syntax </code></pre> <p>Any ideas on how can I achieve this?</p> <p>I hope I've explained myself, if You need further explanation just ask me please.</p> <p>Thanks in advance!</p>
0
2016-10-15T16:57:00Z
40,062,099
<p>Try with following code:</p> <p>Replace</p> <pre><code>price_unit = fields.Float( digits_compute=dp.get_precision('Product Price'), string='Price') </code></pre> <p>with</p> <pre><code>price_unit = fields.Float(string='Price', digits=dp.get_precision('Product Price')) </code></pre> <p>And write below line in import section</p> <pre><code>import openerp.addons.decimal_precision as dp </code></pre> <p>Afterwards restart Odoo server and upgrade your custom module.</p> <p>EDIT:</p> <p>Replace </p> <pre><code>_inherit = 'stock.move' </code></pre> <p>with</p> <pre><code>_inherit = 'stock.picking' </code></pre>
1
2016-10-15T17:27:57Z
[ "python", "inheritance", "openerp", "odoo-9" ]
Python requests add extra headers to HTTP GET
40,061,869
<p>I am using python 2.7 requests module.</p> <p>I made this HTTP GET with the custom header below;</p> <pre><code>header ={ "projectName": "zhikovapp", "Authorization": "Bearer HZCdsf=" } response = requests.get(bl_url, headers = header) </code></pre> <p>The server returns a response that was not valid. On closer examination of the header that was sent, I discovered python requests module added some extra headers.</p> <pre><code>{ 'Accept-Encoding': 'gzip, deflate', 'projectName': 'zhikovapp', 'Accept': '*/*', 'User-Agent': 'python-requests/2.11.1', 'Connection': 'keep-alive', 'Authorization': 'Bearer HZCdsf=' } </code></pre> <p>The extra headers are <code>Accept-Encoding</code>, <code>Accept</code>, <code>Connection</code>, <code>User-Agent</code>. Is this a bug in python requests module? I am using requests ver 2.11.1</p> <p>How can I remove these extra headers added by python requests module?</p>
0
2016-10-15T17:04:39Z
40,061,938
<p>you can do a prepared request.</p> <p><a href="http://docs.python-requests.org/en/latest/user/advanced/#prepared-requests" rel="nofollow">http://docs.python-requests.org/en/latest/user/advanced/#prepared-requests</a></p> <p>then you can delete the headers manually</p> <pre><code>del prepped.headers['Content-Type'] </code></pre>
1
2016-10-15T17:11:52Z
[ "python", "python-2.7", "http-headers", "python-requests" ]
Read the contents of each file into a separate list in Python
40,061,884
<p>I would like to ready the contents of each file into a separate list in Python. I am used to being able to do something similar with a bash for loop where I can say:</p> <pre><code>for i in file_path; do writing stuff; done </code></pre> <p>With glob I can load each of the files but I want to save the contents in a list for each file to use them for comparison purposes later without hardcoding the names and number of lists. This is how far I have gotten in python:</p> <pre><code>import sys import glob import errno list_$name[] ##&lt;this is not python path = './dir_name/*' files = glob.glob(path) for name in files: try: with open(name) as f: lines = f.read().splitlines() except IOError as exc: if exc.errno != errno.EISDIR: raise </code></pre> <p>Is what I want to do even possible or do I have to use a shell script to process each file as a loop?</p>
0
2016-10-15T17:06:06Z
40,062,023
<pre><code>import sys import glob import errno list_$name[] ##&lt;this is not python path = './dir_name/*' files = glob.glob(path) contents = [] for name in files: try: with open(name) as f: lines = f.read().splitlines() contents.append (lines) except IOError as exc: if exc.errno != errno.EISDIR: raise # Your contents list will now be a list of lists, each list containing the contents of one file. </code></pre>
1
2016-10-15T17:21:35Z
[ "python", "bash", "list", "glob" ]
Problems mapping a series to a min(list, key=lambda x: abs(series)) function
40,061,889
<p>I want to find a number in <code>series</code>, and find which number it's closest to in <code>[1,2,3]</code>. Then use the <code>key</code> to replace the series value with the appropriate letter.</p> <pre><code>key = {1: 'A', 2:'B', 3:'C') series = pd.Series([x*1.2 for x in range(10)]) pd.DataFrame = key[min([1,2,3], key=lambda x: abs(x-series))] </code></pre> <p>The <code>series</code> is a column from the <code>pd.DataFrame</code>, I've just tried to simplify it for here.</p>
1
2016-10-15T17:06:28Z
40,062,008
<p>use the <code>apply</code> method and then <code>map</code> your <code>Series</code> such has:</p> <pre><code>key = {1: 'A', 2:'B', 3:'C'} series = pd.Series([x*1.2 for x in range(10)]) def find(myNumber): return min([1,2,3], key=lambda x:abs(x-myNumber)) series.apply(find).map(key) Out[50]: 0 A 1 A 2 B 3 C 4 C 5 C 6 C 7 C 8 C 9 C dtype: object </code></pre> <p>it also should work if you replace series by the entire dataframe such has:</p> <pre><code>df.apply(find).map(key) </code></pre>
1
2016-10-15T17:19:29Z
[ "python", "pandas", "numpy", "dataframe", "series" ]
Python decorator that returns a function with one or more arguments replaced
40,061,956
<p>I would like to create a decorator to a set of functions that replaces one or more of the arguments of the functions. The first thought that came to my mind was to create a decorator that returns a partial of the function with the replaced arguments. I'm unhappy with the way the decorated function is called, but even when it's being called "properly", i get a TypeError.</p> <p>Here is some example code:</p> <pre><code>def decor(func, *args, **kwargs): def _new_func(*args, **kwargs): return partial(func, *args, **kwargs, v=100) return _new_func @decor def some_function(a, v, c): return a, v, c some_function(1,2,3) # functools.partial(&lt;function some_function at 0x7f89a8bed8c8&gt;, 1, 2, 3, v=100) some_function(1,2,3)(1,2,3) # TypeError: some_function() got multiple values for argument 'v' </code></pre> <p>I'm sure there is an easy way to create a decorator that replaces some of the arguments, but haven't figured it out yet.</p>
0
2016-10-15T17:13:14Z
40,061,972
<p>You'd have to return the partial as the decoration result:</p> <pre><code>def decor(func): return partial(func, v=100) </code></pre> <p>However, this <em>always</em> sets <code>v=100</code>, even if you passed in another value for <code>v</code> by position. You'd still have the same issue.</p> <p>You'd need to create a decorator that knows what positional argument <code>v</code> is, and look for it there <em>and</em> as a keyword argument:</p> <pre><code>from inspect import getargspec def decor(func): vpos = getargspec(func).args.index('v') def wrapper(*args, **kwargs): if len(args) &gt; vpos: args = list(args) args[vpos] = 100 else: kwargs['v'] = 100 return func(*args, **kwargs) return wrapper </code></pre> <p>The above decorator will set the <code>v</code> argument to 100, <em>always</em>. Wether you tried to set <code>v</code> as a positional argument or as a keyword argument, in the end it'll be set to 100 anyway:</p> <pre><code>&gt;&gt;&gt; @decor ... def some_function(a, v, c): ... return a, v, c ... &gt;&gt;&gt; some_function(1, 2, 3) (1, 100, 3) &gt;&gt;&gt; some_function(1, v=2, c=3) (1, 100, 3) </code></pre> <p>If you only wanted to provide a default argument for <code>v</code> if it wasn't explicitly set, you'd have to invert the tests:</p> <pre><code>def decor(func): vpos = getargspec(func).args.index('v') def wrapper(*args, **kwargs): if len(args) &lt;= vpos and 'v' not in kwargs: kwargs['v'] = 100 return func(*args, **kwargs) return wrapper </code></pre> <p>at which point <code>v</code> is only provided if not already set:</p> <pre><code>&gt;&gt;&gt; @decor ... def some_function(a, v, c): ... return a, v, c ... &gt;&gt;&gt; some_function(1, c=3) # v not set (1, 100, 3) &gt;&gt;&gt; some_function(1, 2, c=3) # v is set (1, 2, 3) &gt;&gt;&gt; some_function(1, v=2, c=3) # v is set as keyword argument (1, 2, 3) </code></pre>
2
2016-10-15T17:15:33Z
[ "python", "decorator", "partial", "python-decorators" ]
Patch method only in one module
40,062,073
<p>For example, I have some module(<code>foo.py</code>) with next code:</p> <pre><code>import requests def get_ip(): return requests.get('http://jsonip.com/').content </code></pre> <p>And module <code>bar.py</code> with similiar code:</p> <pre><code>import requests def get_fb(): return requests.get('https://fb.com/').content </code></pre> <p>I just can't understand why next happens:</p> <pre><code>from mock import patch from foo import get_ip from bar import get_fb with patch('foo.requests.get'): print(get_ip()) print(get_fb()) </code></pre> <p>They are two mocked: <code> &lt;MagicMock name='get().content' id='4352254472'&gt; &lt;MagicMock name='get().content' id='4352254472'&gt; </code> It is seemed to patch only <code>foo.get_ip</code> method due to <code>with patch('foo.requests.get')</code>, but it is not. I know that I can just get <code>bar.get_fb</code> calling out of <code>with</code> scope, but there are cases where I just run in context manager one method that calls many other, and I want to patch <code>requests</code> only in one module. Is there any way to solve this? Without changing imports in module</p>
1
2016-10-15T17:25:53Z
40,062,556
<p>The two locations <code>foo.requests.get</code> and <code>bar.requests.get</code> refer to the same object, so mock it in one place and you mock it in the other. </p> <p>Imagine how you might implement patch. You have to find where the symbol is located and replace the symbol with the mock object. On exit from the with context you will need to restore the original value of the symbol. Something like (untested):</p> <pre><code>class patch(object): def __init__(self, symbol): # separate path to container from name being mocked parts = symbol.split('.') self.path = '.'.join(parts[:-1] self.name = parts[-1] def __enter__(self): self.container = ... lookup object referred to by self.path ... self.save = getattr(self.container, name) setattr(self.container, name, MagicMock()) def __exit__(self): setattr(self.container, name, self.save) </code></pre> <p>So your problem is that the you are mocking the object in the request module, which you then are referring to from both foo and bar.</p> <hr> <p>Following @elethan's suggestion, you could mock the requests module in foo, and even provide side effects on the get method:</p> <pre><code>from unittest import mock import requests from foo import get_ip from bar import get_fb def fake_get(*args, **kw): print("calling get with", args, kw) return mock.DEFAULT replacement = mock.MagicMock(requests) replacement.get = mock.Mock(requests.get, side_effect=fake_get, wraps=requests.get) with mock.patch('foo.requests', new=replacement): print(get_ip()) print(get_fb()) </code></pre> <hr> <p>A more direct solution is to vary your code so that <code>foo</code> and <code>bar</code> pull the reference to <code>get</code> directly into their name space.</p> <p>foo.py:</p> <pre><code>from requests import get def get_ip(): return get('http://jsonip.com/').content </code></pre> <p>bar.py:</p> <pre><code>from requests import get def get_ip(): return get('https://fb.com/').content </code></pre> <p>main.py:</p> <pre><code>from mock import patch from foo import get_ip from bar import get_fb with patch('foo.get'): print(get_ip()) print(get_fb()) </code></pre> <p>producing:</p> <pre><code>&lt;MagicMock name='get().content' id='4350500992'&gt; b'&lt;!DOCTYPE html&gt;\n&lt;html lang="en" id="facebook" ... </code></pre> <hr> <p>Updated with a more complete explanation, and with the better solution (2016-10-15)</p> <p>Note: added <code>wraps=requests.get</code> to call the underlying function after side effect. </p>
2
2016-10-15T18:13:25Z
[ "python", "python-3.x", "python-unittest", "python-mock", "python-unittest.mock" ]
Patch method only in one module
40,062,073
<p>For example, I have some module(<code>foo.py</code>) with next code:</p> <pre><code>import requests def get_ip(): return requests.get('http://jsonip.com/').content </code></pre> <p>And module <code>bar.py</code> with similiar code:</p> <pre><code>import requests def get_fb(): return requests.get('https://fb.com/').content </code></pre> <p>I just can't understand why next happens:</p> <pre><code>from mock import patch from foo import get_ip from bar import get_fb with patch('foo.requests.get'): print(get_ip()) print(get_fb()) </code></pre> <p>They are two mocked: <code> &lt;MagicMock name='get().content' id='4352254472'&gt; &lt;MagicMock name='get().content' id='4352254472'&gt; </code> It is seemed to patch only <code>foo.get_ip</code> method due to <code>with patch('foo.requests.get')</code>, but it is not. I know that I can just get <code>bar.get_fb</code> calling out of <code>with</code> scope, but there are cases where I just run in context manager one method that calls many other, and I want to patch <code>requests</code> only in one module. Is there any way to solve this? Without changing imports in module</p>
1
2016-10-15T17:25:53Z
40,062,863
<p>Not to steal <strong>@Neapolitan</strong>'s thunder, but another option would be to simply mock <code>foo.requests</code> instead of <code>foo.requests.get</code>:</p> <pre><code>with patch('foo.requests'): print(get_ip()) print(get_fb()) </code></pre> <p>I think the reason why both methods get mocked in your case is that, since <code>requests.get</code> is not explicitly imported in <code>foo.py</code>, <code>mock</code> will have to look up the method in the <code>requests</code> module and mock it there, rather than mocking it in the <code>requests</code> object already imported into <code>foo</code>, so that when <code>bar</code> later imports <code>requests</code> and accesses <code>requests.get</code> it is geting the mocked version. However, if you <code>patch</code> <code>foo.requests</code> instead, you are just patching the module object already imported into <code>foo</code>, and the original <code>requests</code> module will not be affected.</p> <p>Although not particularly helpful for this particular problem, <a href="https://docs.python.org/3/library/unittest.mock.html#where-to-patch" rel="nofollow">this article</a> is very useful for understanding the subtleties of <code>patch</code></p>
0
2016-10-15T18:44:20Z
[ "python", "python-3.x", "python-unittest", "python-mock", "python-unittest.mock" ]
Mapping in Python
40,062,085
<p>I have at my dispositions a JSON list with all the bike stations called Velib in Paris with their latitude, longitude, number of bikes and capacity. </p> <p>I am trying to calculate proportion <code>averages(number_of_bikes/bike_capacity)</code> of the number of bikes for the bike stations in different districts of Paris. I would like to create a mapping/function of a city that differentiates different districts(= so that when i put coordinates it sends me back the number or the district ) so that when i try to calculate an average per part of the city i can insert coordinates of the bike stations and it goes directly into the average of the number of bikes of the district it is in. </p> <p>I can do it when the districts are parallel one to each other delimited by horizontal/ vertical strait lines. </p> <pre><code>for k in range(len(bike_station_list): if lat(bike_station_k)&lt;lat_district_1 and lng(bike_station_k &lt;lng_disctrict_1 ... and so on </code></pre> <p>However in reality Paris districts are far more complex.</p> <p>How can I create a mapping of the city that can tell me in which district I am.</p> <p>My first idea was to create a huge matrix with all longitudinal and latitudinal coordinates with the number of the district it is in but it looks a bit exaggerated. </p> <p>Thanks for helping !</p>
1
2016-10-15T17:26:30Z
40,062,166
<p>You'll need an approximate contour map of your districts, so the boundaries of the districts as a number of e.g. straight line segments. And then you need a way to find out if you're inside such a closed contour.</p> <p>You'll find how to do that <a href="https://www.quora.com/How-do-I-know-a-point-is-inside-a-closed-curve-or-not" rel="nofollow">here</a></p> <p>Given the complexity of this algorithm, your large matrix isn't too bad an idea, if you're satisfied with a resolution of say 10 * 10 m. If you want to cover an area of say 30 * 30 km that would be 3000 * 3000 == 9,000,000 squares. Nothing a PC can't easily handle, including the searches involved.</p>
1
2016-10-15T17:34:01Z
[ "python", "mapping", "geocoding", "reverse-geocoding" ]
Mapping in Python
40,062,085
<p>I have at my dispositions a JSON list with all the bike stations called Velib in Paris with their latitude, longitude, number of bikes and capacity. </p> <p>I am trying to calculate proportion <code>averages(number_of_bikes/bike_capacity)</code> of the number of bikes for the bike stations in different districts of Paris. I would like to create a mapping/function of a city that differentiates different districts(= so that when i put coordinates it sends me back the number or the district ) so that when i try to calculate an average per part of the city i can insert coordinates of the bike stations and it goes directly into the average of the number of bikes of the district it is in. </p> <p>I can do it when the districts are parallel one to each other delimited by horizontal/ vertical strait lines. </p> <pre><code>for k in range(len(bike_station_list): if lat(bike_station_k)&lt;lat_district_1 and lng(bike_station_k &lt;lng_disctrict_1 ... and so on </code></pre> <p>However in reality Paris districts are far more complex.</p> <p>How can I create a mapping of the city that can tell me in which district I am.</p> <p>My first idea was to create a huge matrix with all longitudinal and latitudinal coordinates with the number of the district it is in but it looks a bit exaggerated. </p> <p>Thanks for helping !</p>
1
2016-10-15T17:26:30Z
40,062,204
<p>If you can find the coordinates for the vertices of a polygon that approximates Paris' districts, then this reduces to a <a href="https://en.wikipedia.org/wiki/Point_in_polygon" rel="nofollow">point-in-polygon</a> problem. You can use the ray-casting or the winding number algorithm to solve it, as mentioned in that article.</p>
1
2016-10-15T17:37:22Z
[ "python", "mapping", "geocoding", "reverse-geocoding" ]
Mapping in Python
40,062,085
<p>I have at my dispositions a JSON list with all the bike stations called Velib in Paris with their latitude, longitude, number of bikes and capacity. </p> <p>I am trying to calculate proportion <code>averages(number_of_bikes/bike_capacity)</code> of the number of bikes for the bike stations in different districts of Paris. I would like to create a mapping/function of a city that differentiates different districts(= so that when i put coordinates it sends me back the number or the district ) so that when i try to calculate an average per part of the city i can insert coordinates of the bike stations and it goes directly into the average of the number of bikes of the district it is in. </p> <p>I can do it when the districts are parallel one to each other delimited by horizontal/ vertical strait lines. </p> <pre><code>for k in range(len(bike_station_list): if lat(bike_station_k)&lt;lat_district_1 and lng(bike_station_k &lt;lng_disctrict_1 ... and so on </code></pre> <p>However in reality Paris districts are far more complex.</p> <p>How can I create a mapping of the city that can tell me in which district I am.</p> <p>My first idea was to create a huge matrix with all longitudinal and latitudinal coordinates with the number of the district it is in but it looks a bit exaggerated. </p> <p>Thanks for helping !</p>
1
2016-10-15T17:26:30Z
40,062,239
<p>You can do get the district information by coordinate using Google's geocoding API</p> <p><a href="https://maps.googleapis.com/maps/api/geocode/json?latlng=48.874809,2.396988" rel="nofollow">https://maps.googleapis.com/maps/api/geocode/json?latlng=48.874809,2.396988</a></p> <p>In the response:</p> <pre><code>{ long_name: "20th arrondissement", short_name: "20th arrondissement", types: [ "political", "sublocality", "sublocality_level_1" ] } </code></pre> <p>See <a href="https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding" rel="nofollow">here</a>. You'll be limited to 2500 free requests per day however (more if you pay) and you'll need to register an API key.</p>
2
2016-10-15T17:41:09Z
[ "python", "mapping", "geocoding", "reverse-geocoding" ]
Can the SoundCloud API be accessed from Windows directly (with a python script, say) or must it be an internet application run from a server?
40,062,189
<p>I'm looking to put together something that automatically uploads songs to SoundCloud and it would be really easy if I could integrate it with my current project by just executing a python script. </p> <p>I don't need an Apache server or something along those lines to run it from, do I?</p>
1
2016-10-15T17:36:15Z
40,062,223
<p>That is possible with Javascript, Python, or ruby (you listed these in the tags, but you can pretty much use anything).</p> <p>To read more about using the API to upload sounds see <a href="https://developers.soundcloud.com/docs/api/guide#uploading" rel="nofollow">this section of the documentation</a>.</p> <p>You don't need to run apache you can access the api directly client-side.</p> <p><a href="https://github.com/soundcloud/soundcloud-python" rel="nofollow">Tool for soundcloud with python.</a></p> <p><a href="https://developers.soundcloud.com/docs/api/sdks" rel="nofollow">SDK for soundcloud with javascript.</a></p> <p><a href="https://github.com/soundcloud/soundcloud-ruby" rel="nofollow">Tool for soundcloud with ruby.</a></p>
1
2016-10-15T17:39:18Z
[ "javascript", "python", "ruby", "apache", "soundcloud" ]
What is difference between if (False,) and True == (False,)
40,062,285
<p>I learned python 3 last year, but I have barely experience.</p> <p>I am reviewing about tuple again.</p> <p>I would like to figure out difference between <code>if (False,)</code> and <code>True == (False,)</code></p> <p>Since <code>if (False,):</code> is true, but <code>True == (False,)</code> is false, I am very confused.</p>
0
2016-10-15T17:46:01Z
40,062,309
<ol> <li><p>The boolean value of a tuple is <code>True</code> if it has contents, if it is empty it is <code>False</code>. Because <code>(False,)</code> is a tuple with one element it's boolean value is <code>True</code>.</p></li> <li><p>You are comparing a <code>tuple</code> to a <code>bool</code>, that will always result in <code>False</code>.</p></li> </ol>
1
2016-10-15T17:48:16Z
[ "python", "tuples" ]
What is difference between if (False,) and True == (False,)
40,062,285
<p>I learned python 3 last year, but I have barely experience.</p> <p>I am reviewing about tuple again.</p> <p>I would like to figure out difference between <code>if (False,)</code> and <code>True == (False,)</code></p> <p>Since <code>if (False,):</code> is true, but <code>True == (False,)</code> is false, I am very confused.</p>
0
2016-10-15T17:46:01Z
40,062,333
<p><code>if</code> does not test for <code>== True</code>. It tests for the <a href="https://docs.python.org/3/library/stdtypes.html#truth-value-testing" rel="nofollow"><em>truth value</em></a> of an object:</p> <blockquote> <p>Any object can be tested for truth value, for use in an <code>if</code> or <code>while</code> condition or as operand of the Boolean operations below.</p> </blockquote> <p>Objects are normally always considered <em>true</em>, except for the <code>False</code> or <code>None</code> objects (on their own), numeric zero, or an <em>empty</em> container.</p> <p><code>(False,)</code> is a tuple with one element, and any tuple that is not empty is considered a <em>true value</em>, because it is not an empty container.</p> <p>You can use the <a href="https://docs.python.org/3/library/functions.html#bool" rel="nofollow"><code>bool()</code> function</a> to get a boolean <code>True</code> or <code>False</code> value for the truth value:</p> <pre><code>&gt;&gt;&gt; tup = (False,) &gt;&gt;&gt; bool(tup) True &gt;&gt;&gt; bool(tup) == True True </code></pre>
5
2016-10-15T17:50:17Z
[ "python", "tuples" ]
What is difference between if (False,) and True == (False,)
40,062,285
<p>I learned python 3 last year, but I have barely experience.</p> <p>I am reviewing about tuple again.</p> <p>I would like to figure out difference between <code>if (False,)</code> and <code>True == (False,)</code></p> <p>Since <code>if (False,):</code> is true, but <code>True == (False,)</code> is false, I am very confused.</p>
0
2016-10-15T17:46:01Z
40,062,362
<p>Perhaps this highlights the difference. </p> <p><code>if (False,):</code> will <em>evaluate</em> because a non-empty tuple is a truth-y value. It is not true itself. And comparing a tuple against a boolean shouldn't be expected to return true in any case, regardless of the content of said tuple. </p> <pre><code>t = (False,) print(bool(t)) # True print(t == True) # False print(bool(t) == True) # True </code></pre>
1
2016-10-15T17:53:16Z
[ "python", "tuples" ]
What is difference between if (False,) and True == (False,)
40,062,285
<p>I learned python 3 last year, but I have barely experience.</p> <p>I am reviewing about tuple again.</p> <p>I would like to figure out difference between <code>if (False,)</code> and <code>True == (False,)</code></p> <p>Since <code>if (False,):</code> is true, but <code>True == (False,)</code> is false, I am very confused.</p>
0
2016-10-15T17:46:01Z
40,062,381
<p>For any <code>x</code> whatsoever,</p> <pre><code>if (x,): </code></pre> <p>succeeds, because <code>(x,)</code> is a non-empty tuple, and all non-empty tuples evaluate to <code>True</code> in a boolean context.</p> <p>And again for any <code>x</code> whatsoever,</p> <pre><code>if True == (x,): </code></pre> <p>cannot succeed, because the things being compared aren't even of the same types (for a start, <code>True</code> isn't a tuple).</p> <p>In your question, what I spelled as <code>x</code> you spelled <code>False</code>, but it makes no difference what value <code>x</code> has: <code>False</code>, <code>True</code>, the integer 42, a file object, ..., it doesn't matter.</p>
0
2016-10-15T17:55:39Z
[ "python", "tuples" ]
What is difference between if (False,) and True == (False,)
40,062,285
<p>I learned python 3 last year, but I have barely experience.</p> <p>I am reviewing about tuple again.</p> <p>I would like to figure out difference between <code>if (False,)</code> and <code>True == (False,)</code></p> <p>Since <code>if (False,):</code> is true, but <code>True == (False,)</code> is false, I am very confused.</p>
0
2016-10-15T17:46:01Z
40,062,499
<p>Not empty values are equivalent to <code>True</code> while empty values are equivalent to <code>False</code>. The tuple <code>(False,)</code> is not an empty tuple so <code>if (False,)</code> always succeeds. On the other hand <code>True</code> is not equal to the singleton tuple <code>(False,)</code> so the logical expression <code>True == (False,)</code> evaluates to <code>False</code>.</p>
1
2016-10-15T18:08:34Z
[ "python", "tuples" ]
How many times a button is clicked?
40,062,388
<p>How to know how many times a button is clicked in pyqt ? where ui is prepared in qt-designer and imported into python as .ui file.</p> <p>Example:</p> <pre><code>self.submit.clicked.connect(self.submit_application) </code></pre> <p>and in </p> <pre><code>def submit_application: </code></pre> <p>how to know that submit.clicked has happened for n number of times ?</p>
0
2016-10-15T17:56:31Z
40,062,522
<p>Assuming your <em>self</em> is a parent widget, you may add a counter member which will be updated any time the slot is called. Something like:</p> <pre><code>class MyWidget(QWidget): def __init__(*args, **kwargs): ... #Your widget initialization, including *sumbit* button self.submit.clicked.connect(self.submit_application) self._submit_counter = 0 def submit_application(self): self._submit_counter += 1 ... # Rest of slot handling </code></pre>
0
2016-10-15T18:10:03Z
[ "python", "pyqt", "pyqt4", "qt-designer" ]
Updating properties of an object in Python OOP
40,062,498
<p>I am trying to create a simple game in Python using the OOP style. The parent class is set up and there are two sub-classes, one for the hero and one for the ork.</p> <p>Basically, when the hero attacks the ork (or vice versa) I want the health to be updated based on the damage done (damage is the amount of power the attacking character has). Currently, every time it loops it resets the health values back to the original of 100.</p> <p>What is the best way of doing this using OOP? I can figure out how to do it in my own procedural and messy way, but I would like to see how it should be done.</p> <pre><code>class Character: '''Blueprint for game characters''' def __init__(self): #default values self.character = "" self.speed = 0 self.power = 0 self.health = 100 def attack(self, attackObj): self.attacker = self.character self.attackerPower = self.power self.victim = attackObj.character self.victimHealth = attackObj.health self.newHealth = self.victimHealth - self.attackerPower print(self.character, "you have chosen to attack", self.victim) print(self.victim, "you have suffered", self.attackerPower, "damage and your health is now", self.newHealth) class Hero(Character): '''Inherits from character to create hero''' def __init__(self): Character.__init__(self) self.character = "Hero" self.speed = 8 self.power = 9 print(self.character, "you have",self.speed, "speed,", self.power, "power and", self.health, "health.") class Ork(Character): '''Inherits from character to create ork''' def __init__(self): Character.__init__(self) self.character = "Ork" self.speed = 2 self.power = 8 print(self.character, "you have",self.speed, "speed,", self.power, "power and", self.health, "health.") def main(): charclass = Character() hero = Hero() ork = Ork() endLoop = False while endLoop == False: print("Please choose your character by typing the corresponding key: ") print("H for hero") print("O for ork") charChoice = input() if charChoice in ("H", "h", "hero", "Hero"): charChoice = hero enemy = ork hero = Hero() elif charChoice in ("O", "o", "ork", "Ork"): charChoice = ork enemy = hero print("Please choose an action by typing the corresponding key: ") print("A to attack") actionChoice = input() if actionChoice in ("A", "a"): charChoice.attack(enemy) else: print("Nothing chosen!") finishedYN = input("Have you finished? Y/N ") if finishedYN in ("Y", "y", "Yes", "yes", "YES"): print("You have chosen to end the game...") endloop = True break else: pass if __name__ == "__main__": main() </code></pre>
-1
2016-10-15T18:08:28Z
40,062,730
<p>A quick fix to your code. Remove all these unecessary attributes, e.g. <code>self.attacker</code> (that's just <code>self</code>), <code>self.attackPower</code> (that's just <code>self.power</code>). <code>self.victim = attackObj.character</code> just gives your object a new attribute that is the same string as whatever <code>attackObj.character</code> is. Similarly, this:<code>self.newHealth = self.victimHealth - self.attackerPower</code> just creates a new attribute each time the method is called that will <em>always</em> be 100 - <code>self.attack</code></p> <pre><code>def attack(self, attackObj): attackObj.health -= self.power print(self.character, "you have chosen to attack", attackObj.character) print(attackObj.character, "you have suffered", self.power, "damage and your health is now", attackObj.health) </code></pre> <p>Really, an even better way is to add methods that mutate your object, that will be used as an interface with how your object interacts with other objects. So, for example:</p> <pre><code>class Character: '''Blueprint for game characters''' def __init__(self): #default values self.character = "" self.speed = 0 self.power = 0 self.health = 100 def attack(self, victim): victim.receive_damage(self.power) def receive_damage(raw_damage): self.health -= raw_damage </code></pre> <p>This improves the extensibility of your code. You could more easily implement a "buffs" system, or add an "armor" element, that affects how you recieve damage, without ever having to change the code in <code>attack</code>. You can override these methods in subclasses. So, perhaps you want all orks to have "thickskin", and in <code>Ork</code>:</p> <pre><code> def receive_damage(raw_damage): self.health -= raw_damage*self.thickskin_modifier </code></pre> <p>Where <code>self.thickskin_modifier</code> was set in the <code>Ork</code> class <code>__init__</code>. It could be something like 0.9.</p>
0
2016-10-15T18:30:16Z
[ "python", "oop" ]
How to convert an input to string
40,062,536
<pre><code>while n == 1: w = inputs.append(input('Enter the product code: ')) with open('items.txt') as f: found = False for line in f: if w in line: </code></pre> <p>So this is the part of the code with the issue. After the last line a bunch of stuff happens which is irrelevant to the question. When i run it, i get the error:<br> if w in line:<br> TypeError: 'in ' requires string as left operand, not NoneType</p> <p>I know it's because i need to convert w to a string somehow but i don't know what to do. Any help is appreciated.</p>
0
2016-10-15T18:11:14Z
40,062,629
<p><a href="https://docs.python.org/3/library/functions.html#input" rel="nofollow"><code>input()</code></a> already returns a string, so there is no need to convert it.</p> <p>You have this:</p> <pre><code>w = inputs.append(input('Enter the product code: ')) </code></pre> <p>You should be doing this in two steps, since you are assigning <code>w</code> to the return value of <code>append()</code>, rather than the return value of <code>input()</code> in this case. <code>append()</code> will always return <code>None</code> regardless of the user input, so <code>w</code> in your program will be assigned to <code>None</code>. Instead, try:</p> <pre><code>w = input('Enter the product code: ') inputs.append(w) </code></pre>
1
2016-10-15T18:20:08Z
[ "python" ]
Simulate Python interactive mode
40,062,539
<p>Im writing a private online Python interpreter for <a href="http://vk.com" rel="nofollow">VK</a>, which would closely simulate IDLE console. Only me and some people in whitelist would be able to use this feature, no unsafe code which can harm my server. But I have a little problem. For example, I send the string with code <code>def foo():</code>, and I dont want to get <code>SyntaxError</code> but continue defining function line by line without writing long strings with use of <code>\n</code>. <code>exec()</code> and <code>eval()</code> doesn't suit me in that case. What should I use to get desired effect? Sorry if duplicate, still dont get it from similar questions. </p>
1
2016-10-15T18:11:33Z
40,074,450
<p>It boils down to reading input, then</p> <pre><code>exec &lt;code&gt; in globals,locals </code></pre> <p>in an infinite loop.</p> <p>See e.g. <a href="https://github.com/ipython/ipython/blob/master/IPython/terminal/interactiveshell.py#L444" rel="nofollow"><code>IPython.frontend.terminal.console.interactiveshell.TerminalInteractiveSh ell.mainloop()</code></a>.</p> <p>Continuation detection is done in <a href="https://github.com/ipython/ipython/blob/master/IPython/core/inputsplitter.py#L330" rel="nofollow"><code>inputsplitter.push_accepts_more()</code></a> by trying <code>ast.parse()</code>.</p> <p>Actually, IPython already has an interactive web console called <a href="https://ipython.org/notebook.html" rel="nofollow">Jupyter Notebook</a>, so your best bet should be to reuse it.</p>
2
2016-10-16T19:22:45Z
[ "python", "read-eval-print-loop", "simulate" ]
Simulate Python interactive mode
40,062,539
<p>Im writing a private online Python interpreter for <a href="http://vk.com" rel="nofollow">VK</a>, which would closely simulate IDLE console. Only me and some people in whitelist would be able to use this feature, no unsafe code which can harm my server. But I have a little problem. For example, I send the string with code <code>def foo():</code>, and I dont want to get <code>SyntaxError</code> but continue defining function line by line without writing long strings with use of <code>\n</code>. <code>exec()</code> and <code>eval()</code> doesn't suit me in that case. What should I use to get desired effect? Sorry if duplicate, still dont get it from similar questions. </p>
1
2016-10-15T18:11:33Z
40,074,632
<p>The Python standard library provides the <a href="https://docs.python.org/2/library/code.html" rel="nofollow"><code>code</code></a> and <a href="https://docs.python.org/2/library/codeop.html" rel="nofollow"><code>codeop</code></a> modules to help you with this. The <code>code</code> module just straight-up simulates the standard interactive interpreter:</p> <pre><code>import code code.interact() </code></pre> <p>It also provides a few facilities for more detailed control and customization of how it works.</p> <p>If you want to build things up from more basic components, the <code>codeop</code> module provides a command compiler that remembers <code>__future__</code> statements and recognizes incomplete commands:</p> <pre><code>import codeop compiler = codeop.CommandCompiler() try: codeobject = compiler(some_source_string) # codeobject is an exec-utable code object if some_source_string was a # complete command, or None if the command is incomplete. except (SyntaxError, OverflowError, ValueError): # If some_source_string is invalid, we end up here. # OverflowError and ValueError can occur in some cases involving invalid literals. </code></pre>
2
2016-10-16T19:39:49Z
[ "python", "read-eval-print-loop", "simulate" ]
sqlalchemy database creation error
40,062,544
<p>I have a project i am working on and i am getting a small error that is preventing me from creating all the tables and my database. I am getting the following error:</p> <pre><code>vagrant@vagrant-ubuntu-trusty-32:/vagrant/PayUp$ python setup_database.py Traceback (most recent call last): File "setup_database.py", line 22, in &lt;module&gt; class Users(Base): File "/usr/lib/python2.7/dist-packages/sqlalchemy/ext/declarative/api.py", line 50, in __init__ _as_declarative(cls, classname, cls.__dict__) File "/usr/lib/python2.7/dist-packages/sqlalchemy/ext/declarative/base.py", line 227, in _as_declarative if not table.c.contains_column(c): AttributeError: 'str' object has no attribute 'c' </code></pre> <p>and the code that i am using is as follows:</p> <pre><code>#The following are all of the standard imports that are needed to run the database import os import sys from sqlalchemy import Column, ForeignKey, Integer, String, Index from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine #The following is what will create the declarative_base base that will be imported to every tables Base = declarative_base() #The following is the user table which will store the users id and username class Users(Base): __table__ = 'users' id = Column(Integer, primary_key = True) user_name = Column(String(16), nullable = False, unique = True, index = True) class User_Auth(Base): __table__ = 'user_auth' id = Column(Integer, primary_key = True) last_name = Column(String(16), nullable = False) first_name = Column(String(16), nullable = False) password = Column(String(225), nullable = False) class User_Info(Base): __table__ = 'user_info' id = Column(Integer, primary_key = True) email = Column(String(50), nullable = False, index = True, unique = True) phone = Column(Integer(12), nullable = True, unique = True) age = Column(Integer(2), nullable = False) gender = Column(String(2), nullable = True) class User_Location(Base): __table__ = 'user_location' id = Column(Integer, primary_key = True) street = Column(String(200), mullable = False) city = Column(String(35), nullable = False) state = Column(String(3), nullable = False) zip_code = Column(Integer(5), nullable = False, index = True) engine = create_engine('sqlite:///payup.db') Base.metadata.create_all(engine) </code></pre>
0
2016-10-15T18:11:54Z
40,062,610
<p>Have you tried replacing __table__ with __tablename__</p> <p><a href="http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/table_config.html" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/table_config.html</a></p>
1
2016-10-15T18:18:33Z
[ "python", "database", "sqlite", "sqlalchemy" ]
CSV to Excel conversion using Python
40,062,576
<p>I wrote a piece of code that parse a .csv and save the data in excel format. The problem is that all my data in excel appear as "number stored as text" and i need the data starting with column 3 to be converted as number type so i can represent it using a chart. My table is looking something like this:</p> <pre><code> C1 C2 C3 R1 BlaBla 36552.00233102 ... R2 App1 3484.000000000 ... R3 App2 3399.000000000 ... ..................................... </code></pre> <p>and this is the code:</p> <pre><code>f = open("csv_file") wb = openpyxl.Workbook() ws = wb.active reader = csv.reader(f, delimiter=',') for i in reader: ws.append(i) f.close() wb.save("excel_file") </code></pre>
0
2016-10-15T18:15:33Z
40,062,801
<p>Does your CSV file contain numeric elements that are in quotation marks? If so, that would result in what you're seeing. For example, consider this:</p> <pre><code>import openpyxl wb = openpyxl.Workbook() ws = wb.active for i in [['100', 100]]: ws.append(i) wb.save("excel_file.xlsx") </code></pre> <p>The <code>str</code> value is written as a text element in Excel while the <code>int</code> value is written as a number. If your CSV file contains</p> <pre><code>"100", 100 </code></pre> <p><code>csv</code> would interpret that as a string and a number.</p> <p>You could convert everything in column three onwards from your <code>csv</code> file by adding:</p> <pre><code>i[2:] = [float(x) for x in i[2:]] </code></pre> <p>to the line right before you append <code>i</code> to your workbook.</p>
0
2016-10-15T18:38:32Z
[ "python", "excel", "csv", "openpyxl" ]
CSV to Excel conversion using Python
40,062,576
<p>I wrote a piece of code that parse a .csv and save the data in excel format. The problem is that all my data in excel appear as "number stored as text" and i need the data starting with column 3 to be converted as number type so i can represent it using a chart. My table is looking something like this:</p> <pre><code> C1 C2 C3 R1 BlaBla 36552.00233102 ... R2 App1 3484.000000000 ... R3 App2 3399.000000000 ... ..................................... </code></pre> <p>and this is the code:</p> <pre><code>f = open("csv_file") wb = openpyxl.Workbook() ws = wb.active reader = csv.reader(f, delimiter=',') for i in reader: ws.append(i) f.close() wb.save("excel_file") </code></pre>
0
2016-10-15T18:15:33Z
40,062,807
<p>I suggest to use pandas pandas.read_csv and pandas.to_excel</p>
-3
2016-10-15T18:38:58Z
[ "python", "excel", "csv", "openpyxl" ]
CSV to Excel conversion using Python
40,062,576
<p>I wrote a piece of code that parse a .csv and save the data in excel format. The problem is that all my data in excel appear as "number stored as text" and i need the data starting with column 3 to be converted as number type so i can represent it using a chart. My table is looking something like this:</p> <pre><code> C1 C2 C3 R1 BlaBla 36552.00233102 ... R2 App1 3484.000000000 ... R3 App2 3399.000000000 ... ..................................... </code></pre> <p>and this is the code:</p> <pre><code>f = open("csv_file") wb = openpyxl.Workbook() ws = wb.active reader = csv.reader(f, delimiter=',') for i in reader: ws.append(i) f.close() wb.save("excel_file") </code></pre>
0
2016-10-15T18:15:33Z
40,062,817
<p>If you haven't defined what column is a float, you can try to convert the value to float with an exception handler. The code could become:</p> <pre><code>reader = csv.reader(f, delimiter=',') for i in reader: try: ws.append(float(i)) except ValueError: ws.append(i) f.close() </code></pre>
1
2016-10-15T18:39:44Z
[ "python", "excel", "csv", "openpyxl" ]
how to print this pattern using python iterator
40,062,584
<pre><code>L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] head = 'head' tail = 'tail' </code></pre> <p>suppose we can and can only get the iterator of some iterable(L). and we can not know the length of L. Is that possible to print the iterable as:</p> <pre><code>'head123tail' 'head456tail' 'head789tail' 'head10tail' </code></pre> <p>My try at it is as follows.</p> <pre><code>L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] head = 'head' tail = 'tail' slice_size = 3 i = iter(L) try: while True: counter = 0 while counter &lt; slice_size: e = next(i) if counter == 0: print(head, end='') print(e, end='') counter += 1 else: print(tail) except StopIteration: if counter &gt; 0: print(tail) </code></pre>
0
2016-10-15T18:16:00Z
40,062,691
<p>Here's one way to do it with <a href="https://docs.python.org/3/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> and <a href="https://docs.python.org/3/library/itertools.html#itertools.count" rel="nofollow"><code>itertools.count</code></a>. </p> <p><code>groupby</code> on the key function <code>lambda _: next(c)//3</code> groups the items in the iterables in <em>threes</em> in successions. The logic uses the integer division of the next object in the count item on 3:</p> <pre><code>from itertools import groupby, count L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] head = 'head' tail = 'tail' c = count() for _, g in groupby(L, lambda _: next(c)//3): item = head + ''.join(map(str, g)) + tail print(item) </code></pre> <p><em>Output</em>:</p> <pre><code>head123tail head456tail head789tail head10tail </code></pre>
2
2016-10-15T18:26:19Z
[ "python" ]
how to print this pattern using python iterator
40,062,584
<pre><code>L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] head = 'head' tail = 'tail' </code></pre> <p>suppose we can and can only get the iterator of some iterable(L). and we can not know the length of L. Is that possible to print the iterable as:</p> <pre><code>'head123tail' 'head456tail' 'head789tail' 'head10tail' </code></pre> <p>My try at it is as follows.</p> <pre><code>L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] head = 'head' tail = 'tail' slice_size = 3 i = iter(L) try: while True: counter = 0 while counter &lt; slice_size: e = next(i) if counter == 0: print(head, end='') print(e, end='') counter += 1 else: print(tail) except StopIteration: if counter &gt; 0: print(tail) </code></pre>
0
2016-10-15T18:16:00Z
40,062,742
<p>You can <a href="http://stackoverflow.com/a/24527424/1639625">split the iterator into chunks</a> of three, using <code>chain</code> and <code>slice</code> from <code>itertools</code> and a <code>for</code> loop, and then join them. The <code>for</code> loop will do most of what your <code>try/while True/except</code> construct is doing.</p> <pre><code>L = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] head = 'head' tail = 'tail' slice_size = 3 iterator = iter(L) from itertools import chain, islice for first in iterator: chunk = chain([first], islice(iterator, slice_size - 1)) print(head, ''.join(str(x) for x in chunk), tail) </code></pre> <p>However, if your iterator is just a <code>list</code>, you can just use <code>range</code> with a <code>step</code> parameter:</p> <pre><code>for start in range(0, len(L), slice_size): chunk = L[start : start + slice_size] print(head, ''.join(str(x) for x in chunk), tail) </code></pre>
1
2016-10-15T18:31:15Z
[ "python" ]
Drop duplicates for rows with interchangeable name values (Pandas, Python)
40,062,621
<p>I have a DataFrame of form</p> <pre><code>person1, person2, ..., someMetric John, Steve, ..., 20 Peter, Larry, ..., 12 Steve, John, ..., 20 </code></pre> <p>Rows 0 and 2 are interchangeable duplicates, so I'd want to drop the last row. I can't figure out how to do this in Pandas.</p> <p>Thanks!</p>
2
2016-10-15T18:19:16Z
40,062,776
<p>Here's a NumPy based solution -</p> <pre><code>df[~(np.triu(df.person1.values[:,None] == df.person2.values)).any(0)] </code></pre> <p>Sample run -</p> <pre><code>In [123]: df Out[123]: person1 person2 someMetric 0 John Steve 20 1 Peter Larry 13 2 Steve John 19 3 Peter Parker 5 4 Larry Peter 7 In [124]: df[~(np.triu(df.person1.values[:,None] == df.person2.values)).any(0)] Out[124]: person1 person2 someMetric 0 John Steve 20 1 Peter Larry 13 3 Peter Parker 5 </code></pre>
2
2016-10-15T18:35:18Z
[ "python", "pandas", "duplicates" ]
Drop duplicates for rows with interchangeable name values (Pandas, Python)
40,062,621
<p>I have a DataFrame of form</p> <pre><code>person1, person2, ..., someMetric John, Steve, ..., 20 Peter, Larry, ..., 12 Steve, John, ..., 20 </code></pre> <p>Rows 0 and 2 are interchangeable duplicates, so I'd want to drop the last row. I can't figure out how to do this in Pandas.</p> <p>Thanks!</p>
2
2016-10-15T18:19:16Z
40,063,593
<p>an approach in pandas</p> <pre><code>df = pd.DataFrame( {'person2': {0: 'Steve', 1: 'Larry', 2: 'John', 3: 'Parker', 4: 'Peter'}, 'person1': {0: 'John', 1: 'Peter', 2: 'Steve', 3: 'Peter', 4: 'Larry'}, 'someMetric': {0: 20, 1: 13, 2: 19, 3: 5, 4: 7}}) print(df) person1 person2 someMetric 0 John Steve 20 1 Peter Larry 13 2 Steve John 19 3 Peter Parker 5 4 Larry Peter 7 df['ordered-name'] = df.apply(lambda x: '-'.join(sorted([x['person1'],x['person2']])),axis=1) df = df.drop_duplicates(['ordered-name']) df.drop(['ordered-name'], axis=1, inplace=True) print df </code></pre> <p>which gives:</p> <pre><code> person1 person2 someMetric 0 John Steve 20 1 Peter Larry 13 3 Peter Parker 5 </code></pre>
0
2016-10-15T19:56:10Z
[ "python", "pandas", "duplicates" ]
Finding values that exist for every dictionary in a list
40,062,650
<p>I have a list of lists that each have several dictionaries. The first list represents every coordinate involved in a triangulation. The second list represents a list of dictionaries associated with that grid coordinate. Each dictionary within the list represents every possible coordinate that is a certain Manhattan distance away from a line point that we are trying to triangulate, our target. Any coordinate that exists within every triangulation list represent the overlapping points from these positions and thus the potential location of our target.</p> <p>Anyway, I gave some background to hopefully add some understanding. I know it probably comes off confusing, but I'll include my data structure to assist in visualizing what is going on. I've tried looping through these and haven't quite found a way to do this efficiently yet. </p> <p>Does anyone know of some Python magic to generate a list of the coordinates that exist in every group of coordinates? </p> <p>So in the example below we are starting with 3 different groups of coordinates. I need to generate a list of any x,y pairs that exists in all 3 groups of coordinates.</p> <p>Example:</p> <pre><code>[ [ {'x': 1, 'y': 0}, {'x': -1, 'y': 0}, {'x': 0, 'y': 1}, {'x': 0, 'y': -1} ], [ {'x': 2, 'y': 0}, {'x': -2, 'y': 0}, {'x': 0, 'y': 2}, {'x': 0, 'y': -2}, {'x': 1, 'y': 1}, {'x': -1, 'y': -1}, {'x': -1, 'y': 1}, {'x': 1, 'y': -1} ], [ {'x': 3, 'y': 0}, {'x': -3, 'y': 0}, {'x': 0, 'y': 3}, {'x': 0, 'y': -3}, {'x': 2, 'y': 1}, {'x': -2, 'y': -1}, {'x': -1, 'y': 2}, {'x': 1, 'y': -2}, {'x': 1, 'y': 2}, {'x': -1, 'y': -2}, {'x': -2, 'y': 1}, {'x': 2, 'y': -1} ] ] </code></pre>
0
2016-10-15T18:22:29Z
40,062,913
<p>There is no magic. You just need to be a bit more careful with your data structures. You are putting coordinates in a dict which are not hashable. So you cannot add them to a set. You need to use tuples. So your data structure should look like this:</p> <pre><code>my_list = [ set([ (1, 0), (-1, 0), (0, 1), (0, -1) ]), set([ (1, 0), (-2, 0), (0, 2), (0, -2), (1, 1), (-1, -1), (-1, 1), (1, -1) ]), set([ (1, 0), (-3, 0), (0, 3), (0, -3), (2, 1), (-2, -1), (-1, 2), (1, -2), (1, 2), (-1, -2), (-2, 1), (2, -1) ]) ] common = my_list[0] for s2 in my_list[1:]: common = common &amp; s2 print common </code></pre>
2
2016-10-15T18:48:41Z
[ "python" ]
cipher encoder in python using dictionaries
40,062,728
<p>I'm trying to practice using dictionaries and functions on python. I am trying to write a program that encrypts a simple phrase or sentence with an encrypted alphabet: </p> <pre><code>Original alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ Encrypted alphabet: TDLOFAGJKRICVPWUXYBEZQSNMH. </code></pre> <p>The user is to enter the phrase or sentence to be encrypted so it could contain upper or lowercase alphabet, spaces, commas, and periods. The output, though, should only be uppercase letters with spaces and punctuation marks. </p> <pre><code>cipher ={"A":"T","a":"T","B":"D","b":"D","C":"L","c":"L","D":"O","d":"O","E":"F","e":"F","F":"A","f":"A","G":"G","g":"G","H":"J","h":"J","I":"K","i":"K","J":"R","j":"R","K":"I","k":"I","L":"C","l":"C","M":"V","m":"V","N":"P","n":"P","O":"W","o":"W","P":"U","p":"U","Q":"X","q":"X","R":"Y","r":"Y","S":"B","s":"B","T":"E","t":"E","U":"Z","u":"Z","V":"Q","v":"Q","W":"S","w":"S","X":"N","x":"N","Y":"M","y":"M","Z":"H","z":"H"} def encode(str,cipher): result="" for c in str: result = result + cipher[c] return result </code></pre>
0
2016-10-15T18:30:05Z
40,063,072
<p>You should exclude those cases with unknown symbols and that could be done by:</p> <pre><code> cipher ={"A":"T","a":"T","B":"D","b":"D","C":"L","c":"L","D":"O","d":"O","E":"F","e":"F","F":"A","f":"A","G":"G","g":"G","H":"J","h":"J","I":"K","i":"K","J":"R","j":"R","K":"I","k":"I","L":"C","l":"C","M":"V","m":"V","N":"P","n":"P","O":"W","o":"W","P":"U","p":"U","Q":"X","q":"X","R":"Y","r":"Y","S":"B","s":"B","T":"E","t":"E","U":"Z","u":"Z","V":"Q","v":"Q","W":"S","w":"S","X":"N","x":"N","Y":"M","y":"M","Z":"H","z":"H"} def encode(words, cipher): result = '' for letter in words: if letter in cipher: result = result + cipher[letter] else: result = result + letter return result phrase = raw_input('Please enter your phrase: ') print encode(phrase, cipher) </code></pre>
0
2016-10-15T19:03:25Z
[ "python", "dictionary", "encryption" ]
cipher encoder in python using dictionaries
40,062,728
<p>I'm trying to practice using dictionaries and functions on python. I am trying to write a program that encrypts a simple phrase or sentence with an encrypted alphabet: </p> <pre><code>Original alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ Encrypted alphabet: TDLOFAGJKRICVPWUXYBEZQSNMH. </code></pre> <p>The user is to enter the phrase or sentence to be encrypted so it could contain upper or lowercase alphabet, spaces, commas, and periods. The output, though, should only be uppercase letters with spaces and punctuation marks. </p> <pre><code>cipher ={"A":"T","a":"T","B":"D","b":"D","C":"L","c":"L","D":"O","d":"O","E":"F","e":"F","F":"A","f":"A","G":"G","g":"G","H":"J","h":"J","I":"K","i":"K","J":"R","j":"R","K":"I","k":"I","L":"C","l":"C","M":"V","m":"V","N":"P","n":"P","O":"W","o":"W","P":"U","p":"U","Q":"X","q":"X","R":"Y","r":"Y","S":"B","s":"B","T":"E","t":"E","U":"Z","u":"Z","V":"Q","v":"Q","W":"S","w":"S","X":"N","x":"N","Y":"M","y":"M","Z":"H","z":"H"} def encode(str,cipher): result="" for c in str: result = result + cipher[c] return result </code></pre>
0
2016-10-15T18:30:05Z
40,065,324
<p>Sometimes it's better to ask forgiveness then permission. You could remove half your key: values and replace them with str.upper(), that way small letters become big letters. If you call dict().get(key) you get the value of the key or you get None. The or operator between the dict and character evaluates to the character if the cipher.get(character) returns None. </p> <pre><code>def get_chiper(plaintext): cipher = {"A": "T", "B": "D", "C": "L", "D": "O", "E": "F", "F": "A", "G": "G", "H": "J", "I": "K", "J": "R", "K": "I", "L": "C", "M": "V", "N": "P", "O": "W", "P": "U", "Q": "X", "R": "Y", "S": "B", "T": "E", "U": "Z", "V": "Q", "W": "S", "X": "N", "Y": "M", "Z": "H"} return "".join(cipher.get(character.upper()) or character for character in plaintext) </code></pre> <hr> <p>And the full encoding and decoding could be done with the same function by reversing the dict. </p> <pre><code>def encode(plaintext, cipher): return "".join(cipher.get(character.upper()) or character for character in plaintext) def decode(secret, encoding_cipher): decode_cipher = {value: key for key, value in encoding_cipher.items()} return encode(secret, decode_cipher) def main(): cipher = {"A": "T", "B": "D", "C": "L", "D": "O", "E": "F", "F": "A", "G": "G", "H": "J", "I": "K", "J": "R", "K": "I", "L": "C", "M": "V", "N": "P", "O": "W", "P": "U", "Q": "X", "R": "Y", "S": "B", "T": "E", "U": "Z", "V": "Q", "W": "S", "X": "N", "Y": "M", "Z": "H"} plaintext = "hello foo from bar" secret = encode(plaintext, cipher) plaintext = decode(secret, cipher) print(secret, plaintext) if __name__ == '__main__': main() </code></pre>
0
2016-10-15T23:37:27Z
[ "python", "dictionary", "encryption" ]
digits to words from sys.stdin
40,062,780
<p>I'm trying to convert digits to words from std input (txt file). If the input is for example : 1234, i want the output to be one two three four, for the next line in the text file i want the output to be on a new line in the shell/terminal: 1234 one two three four 56 five six The problem is that i can't get it to output on the same line. Code so far :</p> <pre><code>#!/usr/bin/python3 import sys import math def main(): number_list = ["zero","one","two","three","four","five","six","seven","eight","nine"] for line in sys.stdin: number = line.split() for i in number: number_string = "".join(i) number2 = int(number_string) print(number_list[number2]) main() </code></pre>
0
2016-10-15T18:35:56Z
40,063,000
<p>Put the words in a list, join them, and print the line.</p> <pre><code>#!/usr/bin/python3 import sys import math def main(): number_list = ["zero","one","two","three","four","five","six","seven","eight","nine"] for line in sys.stdin: digits = list(line.strip()) words = [number_list[int(digit)] for digit in digits] words_line = ' '.join(words) print(words_line) main() </code></pre>
1
2016-10-15T18:57:03Z
[ "python", "words", "digits" ]
print the first item in list of lists
40,062,783
<p>I am trying to print the first item in a list of lists. This is what I have:</p> <p>My list is like this:</p> <pre><code>['32 2 6 6', '31 31 31 6', '31 2 6 6'] </code></pre> <p>My code is:</p> <pre><code>from operator import itemgetter contents = [] first_item = list(map(itemgetter(0), contents)) print first_item </code></pre> <p>but itemgetter only returns: ['3', '3', '3'] istead of ['32', '31', '31'] can I use a delimiter?</p>
1
2016-10-15T18:36:14Z
40,062,811
<p>You are dealing with a list of strings, so you are getting the first index of each string, which is in fact <code>3</code> for all of them. What you should do is a comprehension where you split each string on space (which is the default of split) and get the first index:</p> <pre><code>first_element = [s.split(None, 1)[0] for s in contents] </code></pre> <p>Inside the comprehension, the result of each <code>s.split(None, 1)</code> will actually be => </p> <p><code>['32', '2 6 6']</code> <code>['31', '31 31 6']</code> <code>['31', '2 6 6']</code></p> <p>and you get the first index of that. </p> <p>Output:</p> <pre><code>['32', '31', '31'] </code></pre>
5
2016-10-15T18:39:09Z
[ "python", "list" ]
print the first item in list of lists
40,062,783
<p>I am trying to print the first item in a list of lists. This is what I have:</p> <p>My list is like this:</p> <pre><code>['32 2 6 6', '31 31 31 6', '31 2 6 6'] </code></pre> <p>My code is:</p> <pre><code>from operator import itemgetter contents = [] first_item = list(map(itemgetter(0), contents)) print first_item </code></pre> <p>but itemgetter only returns: ['3', '3', '3'] istead of ['32', '31', '31'] can I use a delimiter?</p>
1
2016-10-15T18:36:14Z
40,066,665
<pre><code>&gt;&gt;&gt; items = ['32 2 6 6', '31 31 31 6', '31 2 6 6'] &gt;&gt;&gt; [s.partition(' ')[0] for s in items] ['32', '31', '31'] </code></pre>
0
2016-10-16T03:58:35Z
[ "python", "list" ]
Save and Load data in Python 3
40,062,790
<p>I have to create a team roster that saves and loads the data. I have it to the point where everything else works but saving and loading.</p> <pre><code>memberList = [] #get first menu selection from user and store in control value variable def __init__(self, name, phone, number): self.__name = name self.__phone = phone self.__number = number def setName(self, name): self.__name = name def setPhone(self, phone): self.__phone = phone def setnumber(self, number): self.__number = number def getName(self): return self.__name def getPhone(self): return self.__phone def getNumber(self): return self.__number def displayData(self): print("") print("Player's Information") print("-------------------") print("Player's Name:", getName) print("Player's Telephone number:", getPhone) print("Player's Jersey number:", getNumber) def displayMenu(): print("==========Main Menu==========") print("1. Display Team Roster") print("2. Add Member") print("3. Remove Member") print("4. Edit Member") print("9. Exit Program") print() return int(input("Selection&gt;")) menuSelection = displayMenu() def printMembers(memberList): print("Current members: ") if len(memberList) == 0: print("No current members in memory.") else: x = 1 while x &lt; len(memberList): print(memberList[x],) x = x + 1 def addPlayer(memberList): # players as an argument newName = input("Add a player's Name: ") newPhone = input("Telephone number: ") newNumber = input("Jersey number: ") memberList.append(newName) return memberList def removePlayer(memberList): removeName = input("What name would you like to remove? ", ) # Don't redefine it! if removeName in memberList: del memberList[removeName] else: print("Sorry", removeName, "was not found!") return memberList def editPlayer(memberList): oldName = input("What name would you like to change? ", ) if oldName in memberList: newName = input("What is the new name? ") print("***", oldName, "has been changed to", newName) else: print("***Sorry", oldName, "was not found!") return memberList def saveData(memberList): filename=input("Filename to save: ", ) print("saving data...") outfile=open(filename, "wt") filename= '/Users\nativ\ Documents' for x in memberList: name = memberList[x].getName() phone = memberList[x].getPhone() number = memberList[x].getNumber() outfile.write("name","age", 'number') print("Data Saved") outfile.close() def loadData(): filename = input("Filename to load: ") inFile = open(filename, "rt") def exitProgram(memberList): print("Exiting Program...") while menuSelection != 9: if menuSelection == 1: printMembers = printMembers(memberList) menuSelection = displayMenu() elif menuSelection == 2: memberList = addPlayer(memberList) menuSelection = displayMenu() elif menuSelection == 3: memberList = removePlayer(memberList) menuSelection = displayMenu() elif menuSelection == 4: memberList = editPlayer(memberList) menuSelection = displayMenu() elif menuSelection == 5: memberList = saveData(memberList) menuSelection = displayMenu() elif menuSelection == 6: memberList = loadData() menuSelection = displayMenu() print('Welcome to the Team Manager') displayMenu() </code></pre> <p>This is the error code that I am getting</p> <pre><code>Traceback (most recent call last): File "C:/Users/nativ/PycharmProjects/Week2/Week 5.py", line 98, in &lt;module&gt; memberList = saveData(memberList) File "C:/Users/nativ/PycharmProjects/Week2/Week 5.py", line 73, in saveData name = memberList[x].getName() TypeError: list indices must be integers or slices, not str </code></pre>
-1
2016-10-15T18:37:07Z
40,064,098
<p>Try <code>name = memberList[int(x)].getName()</code>. When it reads the data from a file it reads a string, and in order to put that into a list you need to make it an integer.</p>
0
2016-10-15T20:52:19Z
[ "python", "file", "save", "load" ]
Scrapy XPath Incorrectly when there is Unicode in the page
40,062,836
<p>I want to get all divs that have category class.</p> <p>Take a look at this page: www.postkhmer.com/ព័ត៌មានជាតិ </p> <p><a href="https://i.stack.imgur.com/WvFAN.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/WvFAN.jpg" alt="enter image description here"></a></p> <p>in scrapy shell: <code>scrapy shell 'www.postkhmer.com/ព័ត៌មានជាតិ'</code></p> <p><a href="https://i.stack.imgur.com/KpZUq.png" rel="nofollow"><img src="https://i.stack.imgur.com/KpZUq.png" alt="enter image description here"></a></p> <p>As you see I got only 2 elements back. </p> <p><code> scrapy fetch --nolog http://www.postkhmer.com/ព័ត៌មានជាតិ &gt; page.html scrapy shell ./page.html response.xpath('//div[@class="category"]') </code> Still got only 2 elements back. But when I open page.html in Sublime. </p> <p>I got 15 matches: <a href="https://i.stack.imgur.com/S9J8u.png" rel="nofollow"><img src="https://i.stack.imgur.com/S9J8u.png" alt="enter image description here"></a></p> <p>The most interesting part is: when I remove the anchor link from the 2nd category: </p> <p><a href="https://i.stack.imgur.com/y1rfG.png" rel="nofollow"><img src="https://i.stack.imgur.com/y1rfG.png" alt="enter image description here"></a></p> <p>and i run <code>response.xpath('//div[@class="category"]')</code> in the scrapy shell again, I got 3 elements:</p> <p><a href="https://i.stack.imgur.com/kGRrS.png" rel="nofollow"><img src="https://i.stack.imgur.com/kGRrS.png" alt="enter image description here"></a></p> <p>I'm like what the hell!? Can someone help me to solve this problem please?</p> <p>I've uploaded the file in <a href="http://www.filedropper.com/scrapypage" rel="nofollow">here</a> incase you want to test locally. </p>
2
2016-10-15T18:42:11Z
40,067,637
<p>when you save the page into a local file <code>page.html</code>, you skip the http header that contains encoding information. Later on, when you open this file , either with scrapy or sublime, they have no clue what was the original encoding of the document.</p> <p><strong>Recommendation</strong>: never used documents saved to a file for parsing.</p>
0
2016-10-16T06:44:26Z
[ "python", "xpath", "scrapy" ]
Scrapy XPath Incorrectly when there is Unicode in the page
40,062,836
<p>I want to get all divs that have category class.</p> <p>Take a look at this page: www.postkhmer.com/ព័ត៌មានជាតិ </p> <p><a href="https://i.stack.imgur.com/WvFAN.jpg" rel="nofollow"><img src="https://i.stack.imgur.com/WvFAN.jpg" alt="enter image description here"></a></p> <p>in scrapy shell: <code>scrapy shell 'www.postkhmer.com/ព័ត៌មានជាតិ'</code></p> <p><a href="https://i.stack.imgur.com/KpZUq.png" rel="nofollow"><img src="https://i.stack.imgur.com/KpZUq.png" alt="enter image description here"></a></p> <p>As you see I got only 2 elements back. </p> <p><code> scrapy fetch --nolog http://www.postkhmer.com/ព័ត៌មានជាតិ &gt; page.html scrapy shell ./page.html response.xpath('//div[@class="category"]') </code> Still got only 2 elements back. But when I open page.html in Sublime. </p> <p>I got 15 matches: <a href="https://i.stack.imgur.com/S9J8u.png" rel="nofollow"><img src="https://i.stack.imgur.com/S9J8u.png" alt="enter image description here"></a></p> <p>The most interesting part is: when I remove the anchor link from the 2nd category: </p> <p><a href="https://i.stack.imgur.com/y1rfG.png" rel="nofollow"><img src="https://i.stack.imgur.com/y1rfG.png" alt="enter image description here"></a></p> <p>and i run <code>response.xpath('//div[@class="category"]')</code> in the scrapy shell again, I got 3 elements:</p> <p><a href="https://i.stack.imgur.com/kGRrS.png" rel="nofollow"><img src="https://i.stack.imgur.com/kGRrS.png" alt="enter image description here"></a></p> <p>I'm like what the hell!? Can someone help me to solve this problem please?</p> <p>I've uploaded the file in <a href="http://www.filedropper.com/scrapypage" rel="nofollow">here</a> incase you want to test locally. </p>
2
2016-10-15T18:42:11Z
40,069,568
<p>Only 2 things can be happening here. Either the html is malformed and scrapy can't parse it or there's some trouble with scrapy and encoding. I think the first one is more likely. <a href="http://www.freeformatter.com/html-validator.html" rel="nofollow">http://www.freeformatter.com/html-validator.html</a> kind of gives it away. </p> <p>Since it works on Chrome what I would suggest is using selenium to make the browser fix the code and scrap the elements from there. I didn't test but maybe scrapy-splash can have the same effect.</p>
0
2016-10-16T11:07:59Z
[ "python", "xpath", "scrapy" ]
Multiprocessing: Use Win32 API to modify Excel-Cells from Python
40,062,841
<p>I'm really looking for a good solution here, maybe the complete concept how I did it or at elast tried to do it is wrong!?</p> <p>I want to make my code capable of using all my cores. In the code I'm modifying Excel Cells using Win32 API. I wrote a small xls-Class which can check whether the desired file is already open (or open it if not so) and set Values to Cells. My stripped down code looks like this:</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import os import win32com.client as win32 from multiprocessing import Pool from time import sleep class xls: excel = None filename = None wb = None ws = None def __init__(self, file): self.filename = file def getNumOpenWorkbooks(self): return self.excel.Workbooks.Count def openExcelOrActivateWb(self): self.excel = win32.gencache.EnsureDispatch('Excel.Application') # Check whether one of the open files is the desired file (self.filename) if self.getNumOpenWorkbooks() &gt; 0: for i in range(self.getNumOpenWorkbooks()): if self.excel.Workbooks.Item(i+1).Name == os.path.basename(self.filename): self.wb = self.excel.Workbooks.Item(i+1) break else: self.wb = self.excel.Workbooks.Open(self.filename) def setCell(self, row, col, val): self.ws.Cells(row, col).Value = val def setLastWorksheet(self): self.ws = self.wb.Worksheets(self.wb.Worksheets.Count) if __name__ == '__main__': dat = zip(range(1, 11), [1]*10) # Create Object xls = xls('blaa.xls') xls.openExcelOrActivateWb() xls.setLastWorksheet() for (row, col) in dat: # Calculate some value here (only depending on row,col): # val = some_func(row, col) val = 'test' xls.setCell(row, col, val) </code></pre> <p>Now as the loop does ONLY depend on the both iterated vars, I wanted to make it run in parallel on many cores. So I've heard of Threading and Multiprocessing, but the latter seemed easier to me so I gave it a go.</p> <p>So I changed the code like this:</p> <pre><code>import os import win32com.client as win32 from multiprocessing import Pool from time import sleep class xls: ### CLASS_DEFINITION LIKE BEFORE ### ''' Define Multiprocessing Worker ''' def multiWorker((row, col)): xls.setCell(row, col, 'test') if __name__ == '__main__': # Create Object xls = xls('StockDatabase.xlsm') xls.openExcelOrActivateWb() xls.setLastWorksheet() dat = zip(range(1, 11), [1]*10) p = Pool() p.map(multiWorker, dat) </code></pre> <p>Didn't seem to work because after some reading, Multiprocessing starts new Processes hence <code>xls</code> is not known to the workers.</p> <p>Unfortunately I can neither pass <code>xls</code> to them as a third parameter as the Win32 can't be pickled :( Like this:</p> <pre><code>def multiWorker((row, col, xls)): xls.setCell(row, col, 'test') if __name__ == '__main__': # Create Object xls = xls('StockDatabase.xlsm') xls.openExcelOrActivateWb() xls.setLastWorksheet() dat = zip(range(1, 11), [1]*10, [xls]*10) p = Pool() p.map(multiWorker, dat) </code></pre> <p>The only way would be to initialize the Win32 for each process right before the definition of the multiWorker:</p> <pre><code># Create Object xls = xls('StockDatabase.xlsm') xls.openExcelOrActivateWb() xls.setLastWorksheet() def multiWorker((row, col, xls)): xls.setCell(row, col, 'test') if __name__ == '__main__': dat = zip(range(1, 11), [1]*10, [xls]*10) p = Pool() p.map(multiWorker, dat) </code></pre> <p>But I don't like it because my constructor of xls has some more logic, which automatically tries to find column ids for known header substrings... So that is a little bit more effort then wanted (and I don't think each process should really open it's own Win32 COM Interface), and this also gives me an error because gencache.EnsureDispatch might not be possible to call so often....</p> <p><strong>What to do? How is the solution? Thanks!!</strong></p>
0
2016-10-15T18:42:37Z
40,068,543
<p>While Excel can use multiple cores when recalculating spreadsheets, its programmatic interface is strongly tied to the UI model, which is single threaded. The active workbook, worksheet, and selection are all singleton objects; this is why you cannot interact with the Excel UI at the same time you're driving it using COM (or VBA, for that matter).</p> <p>tl;dr </p> <p>Excel doesn't work that way.</p>
1
2016-10-16T08:50:26Z
[ "python", "excel", "winapi", "multiprocessing" ]
python: i have an error while trying this on my mac using IDLE on mac or terminal
40,062,854
<p>i want to see some info and get info about my os with python as in my tutorial but actually can't run this code:</p> <pre><code>import os F = os.popen('dir') </code></pre> <p>and this :</p> <pre><code>F.readline() ' Volume in drive C has no label.\n' F = os.popen('dir') # Read by sized blocks F.read(50) ' Volume in drive C has no label.\n Volume Serial Nu' os.popen('dir').readlines()[0] # Read all lines: index ' Volume in drive C has no label.\n' os.popen('dir').read()[:50] # Read all at once: slice ' Volume in drive C has no label.\n Volume Serial Nu' for line in os.popen('dir'): # File line iterator loop ... print(line.rstrip()) </code></pre> <p>this is the the error for the first on terminal, (on IDLE it return just an '</p> <p>f = open('dir') Traceback (most recent call last): File "", line 1, in FileNotFoundError: [Errno 2] No such file or directory: 'dir'</p> <p>I know on mac it should be different but how? to get the same result using macOS sierra.</p>
0
2016-10-15T18:43:52Z
40,062,940
<p>The code you are following looks like it was written for Windows. <code>popen</code> runs a command -- but there is no <code>dir</code> command on a Mac. <code>dir</code> in DOS shows you files in a directory (folder); the equivalent command on a Mac is <code>ls</code>.</p>
0
2016-10-15T18:51:39Z
[ "python", "osx" ]