title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Reading in string of nested JSON lists and dictionaries with Python
38,805,125
<p>I am having trouble reading data in python. A sample of one of the rows is:</p> <pre><code>foo_brackets='{"KEY2":[{"KEY2a":[{"KEY2a1":"4","KEY2a2":"5"},{"KEY2a1":"6","KEY2a2":"7"}],"KEY2b":"8"}],"KEY3":"9"}' </code></pre> <p>When I load with <code>json</code>, the value for <code>KEY2</code> is read in as a list, ...
-1
2016-08-06T14:07:36Z
38,805,160
<p><code>foo_brackets_json['KEY2']</code> references a <em>list</em>, here with one element. </p> <p>You'll have to use integer indices to reference the dictionaries contained in that list:</p> <pre><code>foo_brackets_json['KEY2'][0]['KEY2b'] </code></pre> <p>Don't try to remove the brackets; there could be 0 or mor...
1
2016-08-06T14:10:37Z
[ "python", "json", "python-2.7" ]
Check whether a nested dict is False in the leaf nodes in python
38,805,223
<p>Let's say I have a nested dict, e.g. the following</p> <pre><code>{'agent1': {'status': True}, 'block1': {'status': True, 'number': False, 'usable_by': True, 'location': True, 'skill': {'speed': False, 'flexibility': True}}} </code></pre> <p>At the lowest key level (the leaves) of this dict, the ...
-2
2016-08-06T14:17:16Z
38,805,405
<p>To traverse the nested dict, you can use recursion. See (<a href="http://stackoverflow.com/questions/10756427/loop-through-all-nested-dictionary-values">Loop through all nested dictionary values?</a>)</p> <pre class="lang-py prettyprint-override"><code>def contains_false(d): for k,v in d.iteritems(): if...
1
2016-08-06T14:37:17Z
[ "python", "dictionary", "nested" ]
Check whether a nested dict is False in the leaf nodes in python
38,805,223
<p>Let's say I have a nested dict, e.g. the following</p> <pre><code>{'agent1': {'status': True}, 'block1': {'status': True, 'number': False, 'usable_by': True, 'location': True, 'skill': {'speed': False, 'flexibility': True}}} </code></pre> <p>At the lowest key level (the leaves) of this dict, the ...
-2
2016-08-06T14:17:16Z
38,805,412
<p>A quick solution can be:</p> <pre><code>d = {'block1': {'status': True, 'usable_by': True, 'skill': {'flexibility': True, 'speed': False}, 'number': False, 'location': True}, 'agent1': {'status': True}} values = [] def find_false(d): for k in d.keys(): if isinstance(d[k], dict): find_false...
0
2016-08-06T14:38:11Z
[ "python", "dictionary", "nested" ]
Check whether a nested dict is False in the leaf nodes in python
38,805,223
<p>Let's say I have a nested dict, e.g. the following</p> <pre><code>{'agent1': {'status': True}, 'block1': {'status': True, 'number': False, 'usable_by': True, 'location': True, 'skill': {'speed': False, 'flexibility': True}}} </code></pre> <p>At the lowest key level (the leaves) of this dict, the ...
-2
2016-08-06T14:17:16Z
38,805,443
<p>You'd have to traverse the dictionaries, and you want to exit <em>early</em>:</p> <pre><code>def any_false_leaf(d): if isinstance(d, dict): return any(any_false_leaf(v) for v in d.values()) return not d </code></pre> <p>This <em>recurses</em> through your dictionaries, and returns <code>True</code>...
1
2016-08-06T14:40:29Z
[ "python", "dictionary", "nested" ]
Convert comma to space in list
38,805,232
<p>how can we convert a string <code>[0.0034596999, 0.0034775001, 0.0010091923]</code> to a form <code>[0.0034596999 0.0034775001 0.0010091923]</code> in python. I tried using <code>map</code>, <code>join</code> etc functions but I am unable to do so. Can anyone help?</p>
1
2016-08-06T14:17:49Z
38,805,277
<p><code>"[0.0034596999, 0.0034775001, 0.0010091923]".replace(",", "")</code> returns <code>"[0.0034596999 0.0034775001 0.0010091923]"</code></p> <p>Have a look at the <a href="https://docs.python.org/3/library/stdtypes.html#string-methods" rel="nofollow">string methods</a> - there are many useful ones.</p>
1
2016-08-06T14:22:05Z
[ "python" ]
Convert comma to space in list
38,805,232
<p>how can we convert a string <code>[0.0034596999, 0.0034775001, 0.0010091923]</code> to a form <code>[0.0034596999 0.0034775001 0.0010091923]</code> in python. I tried using <code>map</code>, <code>join</code> etc functions but I am unable to do so. Can anyone help?</p>
1
2016-08-06T14:17:49Z
38,805,291
<p>Just use the string <code>replace()</code> method:</p> <pre><code>s = '[0.0034596999, 0.0034775001, 0.0010091923]' s = s.replace(',', '') print(s) # -&gt; [0.0034596999 0.0034775001 0.0010091923] </code></pre>
0
2016-08-06T14:23:32Z
[ "python" ]
Convert comma to space in list
38,805,232
<p>how can we convert a string <code>[0.0034596999, 0.0034775001, 0.0010091923]</code> to a form <code>[0.0034596999 0.0034775001 0.0010091923]</code> in python. I tried using <code>map</code>, <code>join</code> etc functions but I am unable to do so. Can anyone help?</p>
1
2016-08-06T14:17:49Z
38,805,328
<p>If it's a string you could do as the other suggested. If it is a list of strings you could do:</p> <pre><code>new_list_without_comma = [x.replace(",", "") for x in list_with_comma] </code></pre>
0
2016-08-06T14:27:16Z
[ "python" ]
Convert comma to space in list
38,805,232
<p>how can we convert a string <code>[0.0034596999, 0.0034775001, 0.0010091923]</code> to a form <code>[0.0034596999 0.0034775001 0.0010091923]</code> in python. I tried using <code>map</code>, <code>join</code> etc functions but I am unable to do so. Can anyone help?</p>
1
2016-08-06T14:17:49Z
38,805,716
<p>Using the string method <code>replace()</code> is an efficient solution; however thought I'd offer an alternate using <code>split()</code> and <code>join()</code>:</p> <pre><code>print ''.join(i for i in '[0.0034596999, 0.0034775001, 0.0010091923]'.split(',')) &gt;&gt;&gt; [0.0034596999 0.0034775001 0.0010091923] <...
2
2016-08-06T15:10:37Z
[ "python" ]
Convert sqlite3 to mysql under python
38,805,433
<p>I am converting a python script to use mysql instead of sqlite3 and i am having a lot of issues with mysql syntax errors which have really stumped me to this point. I don't have much experience with databases. It seems the lines will work for a short time then they throw errors.</p> <p>This is the line that gives m...
0
2016-08-06T14:39:44Z
38,807,248
<p>Syntactically, your UPDATE SQL statement is correct according to the <code>SET</code> clause and placement of equal signs and commas. Most likely what's happening is one or more of your 21 variables is returning a zero length string (<code>''</code>) which MySQL cannot set to a numeric column. Consider converting su...
0
2016-08-06T17:59:31Z
[ "python", "mysql", "sqlite3" ]
How to sort contours left to right, while going top to bottom, using Python and OpenCV
38,805,462
<p>I'm finding the contours for an image with digits and characters, for OCR. So, I need the contours to be sorted left to right, while going line to line, i.e. top to bottom. Right now, the contours aren't sorted that way.</p> <p><a href="http://i.stack.imgur.com/DOXds.png" rel="nofollow">PIC: Contours is detected as...
0
2016-08-06T14:42:17Z
38,865,392
<p>I like your trying to solve the problem with a single sorting. But as you said, the variation of y in each line might break your algorithm, plus, the <code>max_line_height</code> is something you probably have to tweak based on different inputs.</p> <p>So instead, I would propose a slightly different algorithm, but...
0
2016-08-10T06:03:26Z
[ "python", "sorting", "opencv", "contour" ]
AWS Lambda Python package - no module named redis
38,805,518
<p>I have a <code>python</code> package that I would like to upload to <code>AWS Lambda</code>. The package works on two different machines with no dependencies issues at all.</p> <p>However, when uploading the same folder to <code>AWS Lambda</code>, I get the following error:</p> <blockquote> <p>Unable to import m...
0
2016-08-06T14:47:58Z
39,664,369
<p>When you run 'lambda_handler.py' locally you are running a main methods within the python file. The lambda function however calls the lambda_handler method within lambda_handler.py directly.</p> <p>Your lambda handler is not configured to run 'lambda_handler.lambda_handler' and is failing on 'tweet_analyzer_python/...
0
2016-09-23T15:23:26Z
[ "python", "amazon-web-services", "aws-lambda" ]
Converting cURL call with encode to python request
38,805,646
<p>Now before this gets marked as duplicate and downvoted, I've tried all the other links like (see below) and they don't help.</p> <p><a href="http://stackoverflow.com/questions/36943604/converting-curl-call-to-python-requests">converting curl call to python requests</a></p> <p><a href="http://stackoverflow.com/ques...
-1
2016-08-06T15:02:13Z
38,805,847
<p>So I managed to get it working, if anyone needs it:</p> <pre><code> payload = { 'userid': USERID, 'password': PASSWORD, '__VIEWSTATE':viewstate # defined earlier } with requests.Session() as s: x = s.get(URL, params=payload,headers=headers) token = x.text </code></pre...
0
2016-08-06T15:27:19Z
[ "python", "curl" ]
Why is my blitted characted not moving in pygame?
38,805,680
<p>I am making an RPG in Python using Pygame. My first step is to create my main character and let it move. But it isn't. This is my code:</p> <pre><code>import pygame,random from pygame.locals import * pygame.init() black = (0,0,0) white = (255,255,255) red = (255,0,0) blue = (0,255,0) green = (0,0,255) global scr...
-2
2016-08-06T15:06:53Z
38,805,808
<p>You will have to update your pressed variable in each run</p> <pre><code>while not gameExit: for event in pygame.event.get(): if event.type == QUIT: gameExit = True pressed = pygame.key.get_pressed() surroundings() move() player() pygame.display.update() </code></pre> ...
1
2016-08-06T15:22:33Z
[ "python", "pygame", "blit" ]
add timedelta data within a group in pandas dataframe
38,805,744
<p>I am working on a dataframe in pandas with four columns of <code>user_id</code>, <code>time_stamp1</code>, <code>time_stamp2</code>, and <code>interval</code>. Time_stamp1 and time_stamp2 are of type datetime64[ns] and interval is of type timedelta64[ns]. </p> <p>I want to sum up interval values for each user_id i...
1
2016-08-06T15:13:54Z
38,805,988
<p><strong>UPDATE:</strong> you can use <code>transform()</code> method:</p> <pre><code>In [291]: df['duration'] = df.groupby('user_id')['interval'].transform('sum') In [292]: df Out[292]: a user_id b interval duration 0 2016-01-01 00:00:00 0.01 2015-11-11...
0
2016-08-06T15:43:36Z
[ "python", "pandas", "dataframe", "group-by", "timedelta" ]
Rosalind Profile and Consensus: Writing long strings to one line in Python (Formatting)
38,805,770
<p>I'm trying to tackle a problem on Rosalind where, given a FASTA file of at most 10 sequences at 1kb, I need to give the consensus sequence and profile (how many of each base do all the sequences have in common at each nucleotide). In the context of formatting my response, what I have as my code works for small seque...
0
2016-08-06T15:16:58Z
38,806,558
<p>Your code is totally fine except for this line:</p> <pre><code>writing_strings=[acgt[i]+' '.join(str(n) for n in ACGT[i] for i in range(0,len(ACGT))) for i in range(0,len(acgt))] </code></pre> <p>You accidentally replicate your data. Try replacing it with:</p> <pre><code>writing_strings=[ACGT[i] + str(ACGT[i...
0
2016-08-06T16:45:25Z
[ "python", "python-3.x", "rosalind" ]
Reading Error Message when Clicking on Python File
38,805,797
<p>If I run the python script file from IDLE or Windows command prompt, I am able to view the error message.</p> <p>Script file:</p> <pre><code>print(3/0) input() </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "...\TEST.py", line 1, in &lt;module&gt; print(3/0) ZeroDivisionErro...
-1
2016-08-06T15:20:44Z
38,805,839
<p>If you just double-click the file, once you hit an error, it terminates the program, thus closing the console window. To see the errors, you should run it from the command prompt.</p>
0
2016-08-06T15:26:04Z
[ "python", "error-handling" ]
Reading Error Message when Clicking on Python File
38,805,797
<p>If I run the python script file from IDLE or Windows command prompt, I am able to view the error message.</p> <p>Script file:</p> <pre><code>print(3/0) input() </code></pre> <p>Error:</p> <pre><code>Traceback (most recent call last): File "...\TEST.py", line 1, in &lt;module&gt; print(3/0) ZeroDivisionErro...
-1
2016-08-06T15:20:44Z
38,805,841
<p>This is how its supposed to work. When you "doubleclick" the <code>.py</code> file windows sees an executable file and invokes a cmd-shell and runs your python executable within (even though its only a text file, its considered as an executable - thats how you have set it in your system - this can be changed, say t...
0
2016-08-06T15:26:35Z
[ "python", "error-handling" ]
Why find_one is returning all documents in my case?
38,805,923
<p>I'm trying to use BCryptAuth to protect resource as well as for login system. I'm trying to fetch only one document based on user's email entered at login page. </p> <pre><code>class BCryptAuth(BasicAuth): def check_auth(self, email, password, allowed_roles, resource, method): account = app.data.driver.db['user...
0
2016-08-06T15:35:35Z
38,830,059
<p>The Auth class you mention will only allow or not the access to the API. It does nothing for resource filtering. </p> <p>If you want resource filtering when getting <code>users</code>, you can create an event hook and make a pre-GET dynamic filter. Check the <a href="http://python-eve.org/features.html#dynamic-look...
0
2016-08-08T13:08:06Z
[ "python", "eve" ]
In Pandas, how can I count consecutive positive and negatives in a row?
38,805,928
<p>In python pandas or numpy, is there a built-in function or a combination of functions that can count the number of positive or negative values in a row? </p> <p>This could be thought of as similar to a roulette wheel with the number of blacks or reds in a row.</p> <p>Example input series data: </p> <pre><code>Dat...
2
2016-08-06T15:36:04Z
38,809,760
<p>You can use <a href="https://docs.python.org/dev/library/itertools.html#itertools.groupby" rel="nofollow">itertools.groupby()</a> function.</p> <pre><code>import itertools l = [-3.550049, 28.609863, -2.189941, 4.419922, 17.690185, 41.219971, 0.000000, -16.330078, 7.950195, 0.000000, 38.370117, 6.060059, 3.57...
1
2016-08-07T00:13:21Z
[ "python", "pandas", "numpy" ]
In Pandas, how can I count consecutive positive and negatives in a row?
38,805,928
<p>In python pandas or numpy, is there a built-in function or a combination of functions that can count the number of positive or negative values in a row? </p> <p>This could be thought of as similar to a roulette wheel with the number of blacks or reds in a row.</p> <p>Example input series data: </p> <pre><code>Dat...
2
2016-08-06T15:36:04Z
38,809,764
<p>Nonnegatives:</p> <pre><code>from functools import reduce # For Python 3.x ser = df['x'] &gt;= 0 c = ser.expanding().apply(lambda r: reduce(lambda x, y: x + 1 if y else x * y, r)) c[ser &amp; (ser != ser.shift(-1))].value_counts() Out: 1.0 2 7.0 1 4.0 1 2.0 1 Name: x, dtype: int64 </code></pre> <p>Ne...
1
2016-08-07T00:13:49Z
[ "python", "pandas", "numpy" ]
In Pandas, how can I count consecutive positive and negatives in a row?
38,805,928
<p>In python pandas or numpy, is there a built-in function or a combination of functions that can count the number of positive or negative values in a row? </p> <p>This could be thought of as similar to a roulette wheel with the number of blacks or reds in a row.</p> <p>Example input series data: </p> <pre><code>Dat...
2
2016-08-06T15:36:04Z
38,829,042
<p>So far this is what I've come up with, it works and outputs a count for how many times each of the negative, positive and zero values occur in a row. Maybe someone can make it more concise using some of the suggestions posted by ayhan and Ghilas above. </p> <pre><code>from collections import Counter ser = [-3.5500...
1
2016-08-08T12:18:14Z
[ "python", "pandas", "numpy" ]
cartesian product of overlapping list of intervals
38,805,963
<p>I have two lists of lists consisting of interval the real line </p> <pre><code>I = [[8,12], [18,24], [3,5]] J = [[7,10], [2,6], [18,22]] </code></pre> <p>I want to to gernerate a list that contains the pairs of intervals from I and J that overlap. For example one element of the list would be [[8,12],[7,10]]. I ha...
0
2016-08-06T15:41:01Z
38,806,684
<p>This shall do</p> <pre><code>import itertools I = [[8,12], [18,24], [3,5]] J = [[7,10], [2,6], [18,22]] z = [] for x,y in itertools.product(I,J): #find intersection via sets if set(range(x[0],x[1])) &amp; set(range(y[0],y[1])): z.append([x,y]) print z </code></pre>
-1
2016-08-06T16:58:15Z
[ "python" ]
cartesian product of overlapping list of intervals
38,805,963
<p>I have two lists of lists consisting of interval the real line </p> <pre><code>I = [[8,12], [18,24], [3,5]] J = [[7,10], [2,6], [18,22]] </code></pre> <p>I want to to gernerate a list that contains the pairs of intervals from I and J that overlap. For example one element of the list would be [[8,12],[7,10]]. I ha...
0
2016-08-06T15:41:01Z
38,808,347
<p>This can be made a little more readable by using <code>enumerate</code> to pull the index and values out at the same time. Also, semantically the number pairs might be better described as tuples. </p> <pre><code>I = [(8,12), (18,24), (3,5)] J = [(7,10), (2,6), (18,22)] def overlap(I, J): res=[] for i, ival...
0
2016-08-06T20:14:39Z
[ "python" ]
Create submodels with pandas groupby and locate each model with test data
38,806,021
<p>I have a pandas dataframe in which values in a column are used as the group-by basis to create submodels.</p> <pre><code>import pandas as pd from sklearn.linear_model import Ridge data = pd.DataFrame({"Name": ["A", "A", "A", "B", "B", "B"], "Score": [90, 80, 90, 92, 87, 80], "Age": [10, 12, 14, 9, 11, 12], "Traini...
0
2016-08-06T15:45:46Z
38,810,102
<p>Consider saving submodels in a dictionary with <em>Name</em> as the key and then run a <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">pandas.DataFrame.apply()</a> to run operations on each row aligning row's <em>Name</em> to corresponding model. </p> <p><s...
0
2016-08-07T01:28:02Z
[ "python", "pandas", "grouping", "prediction" ]
md5 hash of file calculated not correct in Python
38,806,027
<p>I have a function for calculating the md5 hashes of all the files in a drive. A hash is calculated but it's different from the hash I got using other programs or online services that are designed for that.</p> <pre><code>def md5_files(path, blocksize = 2**20): hasher = hashlib.md5() hashes = {} for root...
1
2016-08-06T15:46:31Z
38,806,131
<p>you need to construct a new md5 object for each file and read it completely. eg. like so</p> <pre><code>def md5_files(path, blocksize = 2**20): hashes = {} for root, dirs, files in os.walk(path): for file in files: file_path = os.path.join(root, file) print(file_path) ...
1
2016-08-06T15:58:02Z
[ "python", "hash", "md5", "hashlib" ]
Taking one positional argument but more than one given
38,806,100
<p>I have some code that uses pybing image_search to download pictures but my threading seems to have a problem </p> <pre><code> import pickle from urllib.request import urlretrieve import threading search_terms = ['Clint Eastwood', 'George Clooney'] def downloader(): for search_term in search_terms: ...
0
2016-08-06T15:54:36Z
38,806,129
<p><code>(str(search_term))</code> is not a tuple; <code>(str(search_term),)</code> is. In your code, <code>getter</code> is receiving a list of arguments, one character of <code>search_term</code> per argument.</p>
0
2016-08-06T15:57:54Z
[ "python", "multithreading", "image" ]
Intercept all queries on a model in SQLAlchemy
38,806,196
<p>I need to intercept all queries that concern a model in SQLAlchemy, in a way that I can inspect it at the point where any of the query methods (<code>all()</code>, <code>one()</code>, <code>scalar()</code>, etc.) is executed.</p> <p>I have thought about the following approaches:</p> <h1>1. Subclass the Query class...
1
2016-08-06T16:05:58Z
38,809,415
<p>The <a href="http://docs.sqlalchemy.org/en/latest/orm/events.html#sqlalchemy.orm.events.QueryEvents.before_compile" rel="nofollow"><code>before_compile</code></a> query event might be useful for you.</p> <pre><code>from weakref import WeakSet from sqlalchemy import event from sqlalchemy.orm import Query visited_qu...
1
2016-08-06T22:49:38Z
[ "python", "sqlalchemy" ]
What's the time complexity of functions in heapq library
38,806,202
<p>My question is from the solution in leetcode below, I can't understand why it is <code>O(k+(n-k)log(k))</code>.</p> <p>Supplement: Maybe the complexity isn't that, in fact I don't know the time complexity of <code>heappush()</code> and <code>heappop()</code></p> <pre><code># O(k+(n-k)lgk) time, min-heap def findKt...
0
2016-08-06T16:06:35Z
38,833,175
<p><code>heapq</code> is a binary heap, with O(log n) <code>push</code> and O(log n) <code>pop</code>. See the <a href="https://fossies.org/dox/Python-3.5.2/heapq_8py_source.html" rel="nofollow">heapq source code</a>.</p> <p>The algorithm you show takes O(n log n) to push all the items onto the heap, and then O((n-k) ...
2
2016-08-08T15:29:38Z
[ "python", "heap" ]
Get headlines from web archive
38,806,208
<p>I am trying to get headline from <code>www.bbc.co.uk/news</code>. The code I have works fine and it is as below:</p> <pre><code>from bs4 import BeautifulSoup, SoupStrainer import urllib2 import re opener = urllib2.build_opener() url = 'http://www.bbc.co.uk/news' soup = BeautifulSoup(opener.open(url), "lxml") tit...
0
2016-08-06T16:07:12Z
38,817,485
<p>To see all snapshots for a given URL, replace the timestamp with an asterisk:</p> <blockquote> <p><a href="http://web.archive.org/web/*/http://www.bbc.co.uk" rel="nofollow">http://web.archive.org/web/*/http://www.bbc.co.uk</a></p> </blockquote> <p>then screen scrape that.</p> <p>A few things to consider: </p> ...
1
2016-08-07T18:57:49Z
[ "python", "python-2.7", "web-scraping", "beautifulsoup" ]
Convert lines of a File into CSV
38,806,244
<p>This is an algorithm to get all rows, that begin with "BO_ " in a text-file....</p> <pre><code> with open("FILE.txt") as f: for line in f: if line.startswith('BO_ '): array+=line print(array) </code></pre> <p>this code gives me the following result:</p> <pre><code>BO_ 1 BO_ 2 BO_ 3 BO_...
0
2016-08-06T16:11:17Z
38,806,282
<p>Well, the format you described isn't really CSV format per-say, but:</p> <pre><code>with open("FILE.txt") as f: bo_lines = [line for line in f if line.startswith('BO_')] </code></pre>
0
2016-08-06T16:16:35Z
[ "python", "csv" ]
Convert lines of a File into CSV
38,806,244
<p>This is an algorithm to get all rows, that begin with "BO_ " in a text-file....</p> <pre><code> with open("FILE.txt") as f: for line in f: if line.startswith('BO_ '): array+=line print(array) </code></pre> <p>this code gives me the following result:</p> <pre><code>BO_ 1 BO_ 2 BO_ 3 BO_...
0
2016-08-06T16:11:17Z
38,806,332
<p>You can use the join function like so: </p> <pre><code>string = ','.join(array.split('\n')) </code></pre> <p>this will give you:</p> <pre><code>"BO_1,BO_2,BO_3,..." </code></pre> <p>This could then be saved as a .csv. From the way your question is phrased though, as others have pointed out, you might not be l...
0
2016-08-06T16:22:52Z
[ "python", "csv" ]
Using numpy.fromfile to read scattered binary data
38,806,285
<p>There are different blocks in a binary that I want to read using a single call of <code>numpy.fromfile</code>. Each block has the following format:</p> <pre><code>OES=[ ('EKEY','i4',1), ('FD1','f4',1), ('EX1','f4',1), ('EY1','f4',1), ('EXY1','f4',1), ('EA1','f4',1), ('EMJRP1','f4',1), ('EMNRP1','f4',1), ('EMAX1','...
0
2016-08-06T16:16:47Z
38,806,512
<blockquote> <p>That is, I want to call <code>nparr = np.fromfile(f,dtype=OES)</code> only once. Is there a way to accomplish this goal?</p> </blockquote> <p>No, not with a single call to <code>fromfile()</code>.</p> <p>But if you know the complete layout of the file in advance, you can preallocate the array, and t...
2
2016-08-06T16:41:17Z
[ "python", "numpy", "binary", "records" ]
Python Package ImportError in Windows 10
38,806,288
<p>I am having difficulty installing Python Packages on Windows 10.The package name is Tabular..i have been trying over and over and it doesn't work out.her what i get when I try to install it using pip.Any help about it ?Thanks</p> <pre> C:\Python27\Scripts>pip install tabular Collecting tabular Using cached tabula...
1
2016-08-06T16:17:05Z
38,807,583
<p>Tabular 0.1 has issues with Windows 10. Please fall back to 0.0.8</p> <pre><code>pip install tabular==0.0.8 </code></pre> <p><strong>Edit</strong></p> <p>For scipy installation on Windows 10 with python 2.7, instructions are at <a href="http://stackoverflow.com/a/38618044/5334188">http://stackoverflow.com/a/38618...
0
2016-08-06T18:37:05Z
[ "python" ]
Itertools.product raises "Error in argument"
38,806,295
<p>I am a bit lost here:</p> <p>I can not use <code>itertools.product</code> in my code. This is in a break point in unittest <code>setUp</code> method:</p> <pre><code>ipdb&gt; import itertools ipdb&gt; itertools &lt;module 'itertools' (built-in)&gt; ipdb&gt; itertools.product &lt;class 'itertools.product'&gt; ipdb&g...
1
2016-08-06T16:18:05Z
38,806,337
<p>In this debugger, <code>list</code> is a command. For access to the builtin name you were intending, prepend an exclam:</p> <pre><code>ipdb&gt; list(itertools.product([2,7], [1,4]) *** Error in argument: '(itertools.product([2,7], [1,4])' ipdb&gt; !list(itertools.product([2,7], [1,4])) [(2, 1), (2, 4), (7, 1), (7,...
5
2016-08-06T16:23:32Z
[ "python", "python-3.x", "ipython", "itertools", "ipdb" ]
Web Scraping - No content displayed
38,806,398
<p>I am trying to fetch the stock of a company specified by a user by taking the input. I am using requests to get the source code and BeautifulSoup to scrape. I am fetching the data from <em>google.com</em>. I am trying the fetch only the last stock price (806.93 in the picture). When I run my script, it prints none. ...
1
2016-08-06T16:29:46Z
38,807,846
<p>Looks like that source is from inspecting the element, not the actual source. A couple of suggestions. Use google finance to get rid of some noise - <strong><a href="https://www.google.com/finance?q=googl" rel="nofollow">https://www.google.com/finance?q=googl</a></strong> would be the URL. On that page there is a...
1
2016-08-06T19:09:24Z
[ "python", "web-scraping", "beautifulsoup", "python-requests" ]
Web Scraping - No content displayed
38,806,398
<p>I am trying to fetch the stock of a company specified by a user by taking the input. I am using requests to get the source code and BeautifulSoup to scrape. I am fetching the data from <em>google.com</em>. I am trying the fetch only the last stock price (806.93 in the picture). When I run my script, it prints none. ...
1
2016-08-06T16:29:46Z
38,808,106
<p>I went to <a href="https://www.google.com/?gfe_rd=cr&amp;ei=-AKmV6eqC-LH8AfRqb_4Aw#newwindow=1&amp;safe=off&amp;q=+google+stock" rel="nofollow">https://www.google.com/?gfe_rd=cr&amp;ei=-AKmV6eqC-LH8AfRqb_4Aw#newwindow=1&amp;safe=off&amp;q=+google+stock</a> , did a right click and "View Page Source" but did not...
1
2016-08-06T19:40:38Z
[ "python", "web-scraping", "beautifulsoup", "python-requests" ]
django 404 when opening static folder
38,806,439
<p>I have created a /static/ folder in my project's root and changed the settings thusly:</p> <pre><code>STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, "static")] </code></pre> <p>But when I open my localhost/static, it produces a 404 error. Why is that?</p>
0
2016-08-06T16:34:08Z
38,806,469
<p>You have to run <code>manage.py collectstatic</code> first. </p> <p>Note: It's also possible that going to <code>/static</code> is the cause (missing the trailing slash) though django should redirect. </p>
0
2016-08-06T16:37:15Z
[ "python", "django" ]
django 404 when opening static folder
38,806,439
<p>I have created a /static/ folder in my project's root and changed the settings thusly:</p> <pre><code>STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, "static")] </code></pre> <p>But when I open my localhost/static, it produces a 404 error. Why is that?</p>
0
2016-08-06T16:34:08Z
38,806,476
<p>Are you aiming at a particular file? If not then theres your problem, if you are aiming at a file, are you sure its in the correct directory?</p>
1
2016-08-06T16:37:56Z
[ "python", "django" ]
django 404 when opening static folder
38,806,439
<p>I have created a /static/ folder in my project's root and changed the settings thusly:</p> <pre><code>STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, "static")] </code></pre> <p>But when I open my localhost/static, it produces a 404 error. Why is that?</p>
0
2016-08-06T16:34:08Z
38,806,707
<p>For Django 1.3+:</p> <pre><code>STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] STATIC_ROOT = path.join(TOP_DIR, 'staticfiles') STATIC_URL = '/static/' </...
2
2016-08-06T17:00:37Z
[ "python", "django" ]
How to install gnu gettext (>0.15) on windows? So I can produce .po/.mo files in Django
38,806,553
<p>When runing <code>django make messages</code>:</p> <pre><code>./manage.py makemessages -l pt </code></pre> <p>I get:</p> <pre><code>CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed. </code></pre> <p>I tried to install but the last version I find with an Instalation S...
0
2016-08-06T16:44:51Z
38,806,554
<p>Django removed this explanation from the recent docs and it took me some time to found it so i pasted it here before this old documentation goes offline:</p> <p>Source: <a href="https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#gettext-on-windows" rel="nofollow">Django Docs 1.7</a></p> <p>Download the...
0
2016-08-06T16:44:51Z
[ "python", "django", "windows", "gnu", "gettext" ]
Program error for this solution
38,806,625
<p>This is what is available right now</p> <pre><code>l = [list[0]] list.pop(0) x = len(list) for i in range(x+1): n = len(l) j = 0 if list[j] &gt; l[n-1]: l.append(list[j]) list.pop(j) j = j+1 elif i == len(list): l.append(list[j]) list.pop(j) print(list) print(l) </code></pre> <p>`</p> <p>So...
-1
2016-08-06T16:52:44Z
38,806,817
<p>Make a <code>copy</code> of the list. Iterate through the copy in <em>successions</em> and check for monotonically increasing entries to be added to <code>result</code> in the current iteration of the <code>while</code> loop. Delete the entries as they are added to the <code>result</code>. </p> <p>Repeat the <em>ch...
1
2016-08-06T17:13:14Z
[ "python" ]
Importing from a Package in IDLE vs Shell
38,806,673
<p>Importing a whole package works in IDLE, but not in shell. The following works fine in IDLE:</p> <pre><code>import tkinter as tk tk.filedialog.askopenfilename() </code></pre> <p>In shell, I get this error:</p> <pre><code>AttributeError: 'module' object has no attribute 'filedialog' </code></pre> <p>I understand ...
1
2016-08-06T16:57:23Z
38,808,437
<p>This is an IDLE bug which I fixed for future 3.5.3 and 3.6.0a4 releases. <a href="https://bugs.python.org/issue25507" rel="nofollow">Tracker issue.</a></p> <p>For an existing 3.5 or 3.4 release, add the following to idlelib/run.py just before the LOCALHOST line.</p> <pre><code>for mod in ('simpledialog', 'message...
1
2016-08-06T20:28:49Z
[ "python", "python-import", "python-idle", "python-packaging" ]
"Method Not Allowed The method is not allowed for the requested URL."
38,806,699
<p>I have read through the related posts to this question, but haven't found an answer that fixes or seems to match (apologies if I missed it, I looked through like 10 posts).</p> <p>Writing a search page that looks for entries in a DB. Initially I wrote this as two separate functions. One to display the search box,...
-1
2016-08-06T16:59:39Z
38,807,552
<p>As @dirn already mentioned in his <a href="http://stackoverflow.com/questions/38806699/method-not-allowed-the-method-is-not-allowed-for-the-requested-url#comment64981818_38806699">comment</a>, the <code>methods=['POST']</code> in <code>@app.route('/search', methods=['POST'])</code> means the function <code>SearchFor...
1
2016-08-06T18:34:31Z
[ "python", "methods", "flask", "http-status-code-405" ]
Make console-friendly string a useable pandas dataframe python
38,806,750
<p>A quick question as I'm currently changing from R to pandas for some projects:</p> <p>I get the following print output from <code>metrics.classification_report</code> from <code>sci-kit learn</code>:</p> <pre><code> precision recall f1-score support 0 0.67 0.67 ...
0
2016-08-06T17:04:36Z
38,806,888
<p>Assign it to a variable, <code>s</code>:</p> <pre><code>s = classification_report(y_true, y_pred, target_names=target_names) </code></pre> <p>Or directly:</p> <pre><code>s = ''' precision recall f1-score support class 0 0.50 1.00 0.67 1 class 1 0.00 0...
2
2016-08-06T17:21:34Z
[ "python", "pandas", "dataframe" ]
How to use R's assignment methods in rpy2?
38,806,898
<p>I'm working with rpy2, and I need to use an assignment method on an R object. For example, starting with this object:</p> <pre><code># Python code from rpy2.robjects import r myvar = r('c(a=1,b=2,c=3)') </code></pre> <p>suppose that I want to assign to <code>names(myvar)</code>. (Note: Ignore the fact that rpy2 pr...
0
2016-08-06T17:23:06Z
38,808,519
<p>In R, "setter" functions follow a naming convention that makes the name of the "getter" followed by <code>&lt;-</code>. For example, when doing </p> <pre class="lang-r prettyprint-override"><code>names(myvar) &lt;- c("x", "y", "z") </code></pre> <p>the following is happening:</p> <pre class="lang-r prettyprint-ov...
2
2016-08-06T20:40:37Z
[ "python", "rpy2" ]
How to use R's assignment methods in rpy2?
38,806,898
<p>I'm working with rpy2, and I need to use an assignment method on an R object. For example, starting with this object:</p> <pre><code># Python code from rpy2.robjects import r myvar = r('c(a=1,b=2,c=3)') </code></pre> <p>suppose that I want to assign to <code>names(myvar)</code>. (Note: Ignore the fact that rpy2 pr...
0
2016-08-06T17:23:06Z
38,809,052
<p>Consider importing R's base package and directly use the <code>c()</code> function and to assign names import R's stats package and directly use the <code>setNames()</code> function. Below shows how assigning with <code>r()</code> and <code>base.c()</code> yield equivalent values:</p> <pre><code>from rpy2.robjects ...
0
2016-08-06T21:55:11Z
[ "python", "rpy2" ]
Python __getattr__ to create attr if it does not exist and return it
38,806,907
<p>A little background: You'll notice my comments describe what I'll go through later. Let's say I have the following object...</p> <pre><code>#!/usr/bin/python import os import sys class ContainerField(object): ''' An attribute/object storage device ''' def __init__(self, field=None, value=None): sel...
0
2016-08-06T17:24:08Z
38,807,023
<p>You could consider using the @property decorator with private internal fields. The idea would be something like:</p> <pre><code>class ContainerField(object): def __init__(self, field=None, value=None): self._m_field = field self._m_value = value @property def m_field(self): if s...
1
2016-08-06T17:36:30Z
[ "python", "django" ]
Python __getattr__ to create attr if it does not exist and return it
38,806,907
<p>A little background: You'll notice my comments describe what I'll go through later. Let's say I have the following object...</p> <pre><code>#!/usr/bin/python import os import sys class ContainerField(object): ''' An attribute/object storage device ''' def __init__(self, field=None, value=None): sel...
0
2016-08-06T17:24:08Z
38,807,026
<p>So to answer the first part of the question: how to have <code>__getattr__</code> call <code>self.get()</code> only when the attribute is not defined already. There are two attribute access methods in python classes: <code>__getattribute__</code> and <code>__getattr__</code>. The first is called every time an att...
1
2016-08-06T17:36:49Z
[ "python", "django" ]
Python __getattr__ to create attr if it does not exist and return it
38,806,907
<p>A little background: You'll notice my comments describe what I'll go through later. Let's say I have the following object...</p> <pre><code>#!/usr/bin/python import os import sys class ContainerField(object): ''' An attribute/object storage device ''' def __init__(self, field=None, value=None): sel...
0
2016-08-06T17:24:08Z
38,807,053
<p>Check this out:</p> <pre><code>class Test(object): def __init__(self): self.a = 5 self.b = 6 def __getattr__(self, key): return 'created a new key: {}'.format(key) obj = Test() print(obj.a, obj.b) print(obj.c) </code></pre> <p>Here, instead of returning <code>'created a new key...
0
2016-08-06T17:39:17Z
[ "python", "django" ]
Model field value does not get updated m2m_changed(Django)
38,806,987
<p>I have been searching for an answer for hours, however every answer I found does not work. Also trying to find a bug on my own didn't bring me any results.</p> <p>I have created a <code>receiver function</code> which should update model's <code>total_likes</code> attribute(based on number of <code>users_like</code>...
1
2016-08-06T17:32:42Z
38,815,857
<p>Ok, so the problem was with the custom <code>save()</code> method on the model class.</p> <p>I needed to call the <code>save()</code> method of the parent class like this:</p> <pre><code>def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Image, self).save(*args...
0
2016-08-07T15:50:53Z
[ "python", "django", "django-models", "django-signals" ]
Django 1.9.2 AssertionError: database connection isn't set to UTC
38,807,296
<p>I have setup 3 servers now with PostgreSQL and have so far not seen this issue. I am now setting up the first server which is not running on a danish server, and i start getting errors when accessing the database from the web. </p> <p>I could use createsuperuser without issues and it created my super user. But when...
4
2016-08-06T18:04:22Z
39,649,018
<p>I encountered this same problem, also with a server that is normally running with the UTC+2 (in my case, Europe/Oslo).</p> <p>It turned out that the system zoneinfo files on my server (Centos 7) were corrupted, which became evident in <code>pg_timezone_names</code>.</p> <p><code>postgres=# select * from pg_timezon...
0
2016-09-22T21:16:35Z
[ "python", "django", "postgresql" ]
Why are pool.map() and map() returning varying results?
38,807,432
<p>I have the following program :</p> <pre><code>import string import itertools import multiprocessing as mp def test(word_list): return list(map(lambda xy: (xy[0], len(list(xy[1]))), itertools.groupby(sorted(word_list)))) def f(x): return (x[0], len(list(x[1]))) def test_parallel(word_list): w ...
1
2016-08-06T18:19:57Z
38,807,534
<p><code>groupby()</code> returns <em>iterators</em> per group, and these are <em>not independent</em> from the underlying iterator passed in. You can't independently iterate over these groups in parallel; any preceding group will be prematurely ended the moment you access the next.</p> <p><code>pool.map()</code> will...
2
2016-08-06T18:32:49Z
[ "python", "group-by", "multiprocessing", "itertools", "pool" ]
Why are pool.map() and map() returning varying results?
38,807,432
<p>I have the following program :</p> <pre><code>import string import itertools import multiprocessing as mp def test(word_list): return list(map(lambda xy: (xy[0], len(list(xy[1]))), itertools.groupby(sorted(word_list)))) def f(x): return (x[0], len(list(x[1]))) def test_parallel(word_list): w ...
1
2016-08-06T18:19:57Z
38,807,542
<p>From <a href="https://docs.python.org/3.5/library/itertools.html#itertools.groupby" rel="nofollow">https://docs.python.org/3.5/library/itertools.html#itertools.groupby</a>:</p> <blockquote> <p>The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shar...
3
2016-08-06T18:33:29Z
[ "python", "group-by", "multiprocessing", "itertools", "pool" ]
Can't get a value of a variable from a class
38,807,571
<p>This is some code I wrote to understand how a global variable works.</p> <p>I can't get any value for <code>aaa</code> in <code>print('fuera ' , aaa)</code>. I am not sure how the sequence of execution happens either.</p> <pre><code>import tkinter as tk global aaa def primero(): winda = tk.Toplevel() def ...
-2
2016-08-06T18:36:04Z
38,807,654
<blockquote> <p>I am not sure how the sequence of execution happens </p> </blockquote> <p>Basically, you are starting a window with a button first. Simple enough. Meanwhile, the code after you initialize the window, i.e. the print statement, continues to run, but <code>aaa</code> is only ever initialized when you cl...
0
2016-08-06T18:45:16Z
[ "python" ]
Python3.5 virtual envirement not working ubuntu
38,807,752
<p>I've installed Python 3.5 on my VPS Ubuntu.</p> <p>Command:</p> <pre><code>python3.5 --version </code></pre> <p>Gives:</p> <pre><code>3.5.0+ </code></pre> <p>and then I install simple Flask application and install virtual environment and activate it:</p> <pre><code>virtualenv -p python3.5 envname source envnam...
0
2016-08-06T18:57:07Z
38,808,780
<p>Kind of workaround, but the simplest solution that comes to my mind:</p> <pre><code>cp envname/bin/python3.5 envname/bin/python </code></pre> <p>That way even if Python scripts are executed with <code>python</code> command it will use Python 3.5.</p>
0
2016-08-06T21:16:16Z
[ "python", "python-3.x" ]
Fetching URL and converting to UTF-8 Python
38,807,809
<p>I would like to do my first project in python but I have problem with coding. When I fetch data it shows coded letters instead of my native letters, for example '\xc4\x87' instead of 'ć'. The code is below:</p> <pre><code>import urllib.request import sys page = urllib.request.urlopen("http://olx.pl/") test = page...
0
2016-08-06T19:04:51Z
38,807,852
<p>The data you read from a <code>urlopen()</code> response is <em>encoded data</em>. You'd need to first <em>decode</em> that data using the right encoding.</p> <p>You appear to have downloaded UTF-8 data; you'd have to decode that data first before you had text:</p> <pre><code>test = page.read().decode('utf8') </co...
0
2016-08-06T19:10:20Z
[ "python", "python-3.x", "urllib" ]
Fetching URL and converting to UTF-8 Python
38,807,809
<p>I would like to do my first project in python but I have problem with coding. When I fetch data it shows coded letters instead of my native letters, for example '\xc4\x87' instead of 'ć'. The code is below:</p> <pre><code>import urllib.request import sys page = urllib.request.urlopen("http://olx.pl/") test = page...
0
2016-08-06T19:04:51Z
38,807,968
<p>The <em>urlopen</em> is returning to you a <em>bytes</em> object. That means it's a raw, encoded stream of bytes. Python 3 prints that in a <em>repr</em> format, which uses escape codes for non-ASCII characters. To get the canonical unicode you would have to decode it. The right way to do that would be to inspect th...
0
2016-08-06T19:23:25Z
[ "python", "python-3.x", "urllib" ]
Fetching URL and converting to UTF-8 Python
38,807,809
<p>I would like to do my first project in python but I have problem with coding. When I fetch data it shows coded letters instead of my native letters, for example '\xc4\x87' instead of 'ć'. The code is below:</p> <pre><code>import urllib.request import sys page = urllib.request.urlopen("http://olx.pl/") test = page...
0
2016-08-06T19:04:51Z
38,808,244
<p>The others are correct, but I'd like to offer a simpler solution. Use <a href="http://docs.python-requests.org/en/master/user/quickstart/" rel="nofollow"><code>requests</code></a>. It's 3rd party, so you'll need to install it via pip:</p> <pre><code>pip install requests </code></pre> <p>But it's a lot simpler to u...
0
2016-08-06T20:00:09Z
[ "python", "python-3.x", "urllib" ]
pandas merge dataframes on closest timestamp
38,807,890
<p>I want to merge two dataframes on three columns: email, subject and timestamp. The timestamps between the dataframes differ and I therefore need to identify the closest matching timestamp for a group of email &amp; subject. </p> <p>Below is a reproducible example using a function for closest match suggested for <a...
2
2016-08-06T19:15:57Z
38,807,965
<p>You want to apply the closest timestamp logic to each group of 'email' and 'subject'</p> <pre><code>a = """timestamp,email,subject 2016-07-01 10:17:00,a@gmail.com,subject3 2016-07-01 02:01:02,a@gmail.com,welcome 2016-07-01 14:45:04,a@gmail.com,subject3 2016-07-01 08:14:02,a@gmail.com,subject2 2016-07-01 16:26:35,a@...
1
2016-08-06T19:23:14Z
[ "python", "pandas", "merge" ]
pandas merge dataframes on closest timestamp
38,807,890
<p>I want to merge two dataframes on three columns: email, subject and timestamp. The timestamps between the dataframes differ and I therefore need to identify the closest matching timestamp for a group of email &amp; subject. </p> <p>Below is a reproducible example using a function for closest match suggested for <a...
2
2016-08-06T19:15:57Z
38,808,718
<p>Notice that if you merge <code>df1</code> and <code>df2</code> on <code>email</code> and <code>subject</code>, then the result has all the possible <em>relevant</em> timestamp pairings:</p> <pre><code>In [108]: result = pd.merge(df1, df2, how='left', on=['email','subject'], suffixes=['', '_y']); result Out[108]: ...
2
2016-08-06T21:07:40Z
[ "python", "pandas", "merge" ]
Seaborn multiple barplots
38,807,895
<p>I have a pandas dataframe that looks like this:</p> <pre><code> class men woman children 0 first 0.91468 0.667971 0.660562 1 second 0.30012 0.329380 0.882608 2 third 0.11899 0.189747 0.121259 </code></pre> <p>How would I create a plot using seaborn that looks like this? D...
1
2016-08-06T19:16:05Z
38,808,042
<p>Yes you need to reshape the DataFrame:</p> <pre><code>df = pd.melt(df, id_vars="class", var_name="sex", value_name="survival rate") df Out: class sex survival rate 0 first men 0.914680 1 second men 0.300120 2 third men 0.118990 3 first woman 0.667971 ...
3
2016-08-06T19:32:57Z
[ "python", "pandas", "matplotlib", "seaborn" ]
readlines() error with for-loop in python
38,807,928
<p>This error is hard to describe because I can't figure out how the loop is even affecting the <code>readline()</code> and <code>readlines()</code> Methods. When I try using the former, I get these unexpected Traceback errors. When I try the latter, my code runs and nothing happens. I have determined that the bug is l...
0
2016-08-06T19:20:11Z
38,807,994
<p>Firstly, python conventions are to lowercase all variable names. </p> <p>Secondly, you are exhausting the file pointer when you read all the lines at first, then continue to loop over the file. </p> <p>Try to simply open the file, then loop over it </p> <pre><code>linenumber = 0 with open("Topics.txt") as topicfi...
0
2016-08-06T19:26:19Z
[ "python", "python-3.x", "for-loop", "readlines" ]
readlines() error with for-loop in python
38,807,928
<p>This error is hard to describe because I can't figure out how the loop is even affecting the <code>readline()</code> and <code>readlines()</code> Methods. When I try using the former, I get these unexpected Traceback errors. When I try the latter, my code runs and nothing happens. I have determined that the bug is l...
0
2016-08-06T19:20:11Z
38,808,018
<p>I think there are two issues:</p> <ol> <li>You seem to be iterating over <code>Topicfile</code> instead of <code>Topicfile.readLines()</code>.</li> <li><code>Url.join(Newtopic)</code> isn't returning what you think it is. <code>.join</code> takes a list (in this case, a string is a list of characters) and will inse...
1
2016-08-06T19:29:29Z
[ "python", "python-3.x", "for-loop", "readlines" ]
readlines() error with for-loop in python
38,807,928
<p>This error is hard to describe because I can't figure out how the loop is even affecting the <code>readline()</code> and <code>readlines()</code> Methods. When I try using the former, I get these unexpected Traceback errors. When I try the latter, my code runs and nothing happens. I have determined that the bug is l...
0
2016-08-06T19:20:11Z
38,812,303
<p>What you are attempting to do violates the RiteTag TOS. To get associate4d hashtags from a root hashtag, please use our API: <a href="http://docs.ritekit.apiary.io/#" rel="nofollow">http://docs.ritekit.apiary.io/#</a> and <a href="http://docs.ritekit.apiary.io/#reference/0/ritetag" rel="nofollow">http://docs.ritekit...
0
2016-08-07T08:24:45Z
[ "python", "python-3.x", "for-loop", "readlines" ]
Is there an R/caret equivalent of scikit-learn's labeled kfold cross validation?
38,808,058
<p>I'm augmenting my data and i want to make sure that related data are not separated into different folds during cross validation. </p> <p>I know scikit-learn has a labeled k-fold algorithm that takes in a list of labels along with the data set and assures that the same label is not found in 2 different folds. Is the...
1
2016-08-06T19:34:56Z
38,811,183
<p>The <a href="https://mlr-org.github.io/mlr-tutorial/release/html/index.html" rel="nofollow">mlr package</a> seems to have that sort of functionality. The <a href="https://mlr-org.github.io/mlr-tutorial/release/html/task/index.html#further-settings" rel="nofollow">'blocking'</a> option specifically specifies that all...
0
2016-08-07T05:27:02Z
[ "python", "scikit-learn", "r-caret", "cross-validation" ]
why is function executing twice?
38,808,079
<p>Am experiencing a bizarre problem with my python script the file is being red twice.</p> <p>Script:</p> <pre><code>import platform as serverPlatform class platform: @staticmethod def kernel(): return serverPlatform.release() @staticmethod def cpu(): with open('/proc/cpuinfo', 'r') as f: ...
1
2016-08-06T19:37:11Z
38,808,194
<p>while importing python scripts, it will execute all the statements, like function declaration, class declaration and executable statements (like print). So when you import flatform it will execute <code>flatform.cpu()</code> once. and one more call from the file in which you imported.</p>
2
2016-08-06T19:54:32Z
[ "python" ]
Dictionary: Revert/remove setdefault
38,808,229
<p>I currently have an object passed to my callback which is a dictionary and which I have to return.</p> <p>The invoker called <code>obj.setdefault("Server", "Something")</code> on the dictionary so that it has a default value even if the key/value pair does not exist.</p> <p>How can I revert/remove that <code>setde...
2
2016-08-06T19:58:32Z
38,808,423
<p>Assuming the value is not in the dictionary when passed to the callback, <code>dict.setdefault</code> is not really the problem - this operation is one of many available for changing a python dictionary. Specifically, it ensures SOMETHING is stored for the given key, which can be done directly anyway with an indexed...
0
2016-08-06T20:26:14Z
[ "python", "python-3.x", "dictionary" ]
Dictionary: Revert/remove setdefault
38,808,229
<p>I currently have an object passed to my callback which is a dictionary and which I have to return.</p> <p>The invoker called <code>obj.setdefault("Server", "Something")</code> on the dictionary so that it has a default value even if the key/value pair does not exist.</p> <p>How can I revert/remove that <code>setde...
2
2016-08-06T19:58:32Z
38,808,450
<p>The <code>setdefault</code> method sets the value of the <code>Server</code> key to <code>Something</code> (as long as the <code>Server</code> key is not already in the dictionary). You can simply delete the <code>Server</code> key from the dictionary:</p> <pre><code>if 'Server' in obj: del obj['Server'] </code></p...
5
2016-08-06T20:31:08Z
[ "python", "python-3.x", "dictionary" ]
formatting date, time and string for filename
38,808,311
<p>I want to create a csv file with a filename of the following format:</p> <p>"day-month-year hour:minute-malware_scan.csv"</p> <p>Example:" 6-8-2016 21:45-malware_scan.csv"</p> <p>The first part of the filename is formed by the actual date and time at file creation time, instead "-malware_scan.csv" is a fixed stri...
1
2016-08-06T20:10:31Z
38,808,427
<p>The <code>:</code> character is not allowed for filenames on PC. You could discard the <code>:</code> separator entirely:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; t = datetime.now() &gt;&gt;&gt; formatted_time = t.strftime('%d-%m-%y %H%M') &gt;&gt;&gt; formatted_time '06-08-16 2226' &g...
1
2016-08-06T20:26:36Z
[ "python", "string", "datetime", "formatting", "filenames" ]
formatting date, time and string for filename
38,808,311
<p>I want to create a csv file with a filename of the following format:</p> <p>"day-month-year hour:minute-malware_scan.csv"</p> <p>Example:" 6-8-2016 21:45-malware_scan.csv"</p> <p>The first part of the filename is formed by the actual date and time at file creation time, instead "-malware_scan.csv" is a fixed stri...
1
2016-08-06T20:10:31Z
38,808,496
<p>Thanks to Moses Koledoye for spotting the problem. I was thinking I made a mistake in the Python code, but actually the problem was the characters of the filename.</p> <p>According to <a href="https://msdn.microsoft.com/en-us/library/aa365247" rel="nofollow">MSDN</a> the following are reserved characters that canno...
0
2016-08-06T20:37:10Z
[ "python", "string", "datetime", "formatting", "filenames" ]
How can I find a comment with specified text string
38,808,461
<p>I'm using robobrowser to parse some html content. I has a BeautifulSoup inside. How can I find a comment with specified string inside</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;div&gt; &lt;!-- some commented code here!!!&lt;div&gt;&lt;ul&gt;&lt;li&gt;&lt;div id='ANY_ID'&gt;TEXT_1&lt;/div&gt;&lt;/li&gt; &lt;li&gt;...
0
2016-08-06T20:32:40Z
38,808,493
<p>Use <a class='doc-link' href="http://stackoverflow.com/documentation/beautifulsoup/1940/locating-elements/18725/locating-comments#t=201608062136151957535">the <code>text</code> argument and check the type to be <code>Comment</code></a>. Then, load the contents with <code>BeautifulSoup</code> again and find the desir...
0
2016-08-06T20:36:59Z
[ "python", "beautifulsoup", "robobrowser" ]
Python Error~ List index out of range
38,808,547
<pre><code>def getSublists(L,n): List=L sublists=[] for i in range(len(L)-(n-1)): ii=0 sub=[] while ii&lt;= n: a=List[ii+i] sub.append(a) ii+=1 sublists.append(sub) return sublists </code></pre> <p>I am trying to get all of the possib...
0
2016-08-06T20:45:22Z
38,808,638
<p>your while condition should be modified:</p> <pre><code>def getSublists(L,n): List=L sublists=[] for i in range(len(L)-(n-1)): print ['i: ', i] ii=0 sub=[] while ii&lt;= n-1: print ['ii: ', ii] a=List[ii+i] sub.append(a) ii+...
0
2016-08-06T20:57:07Z
[ "python" ]
Python Error~ List index out of range
38,808,547
<pre><code>def getSublists(L,n): List=L sublists=[] for i in range(len(L)-(n-1)): ii=0 sub=[] while ii&lt;= n: a=List[ii+i] sub.append(a) ii+=1 sublists.append(sub) return sublists </code></pre> <p>I am trying to get all of the possib...
0
2016-08-06T20:45:22Z
38,808,681
<p>You'll want to only append to the sublists array if the sublist is of length n, then break once it is. Otherwise, <code>ii+i</code> could increase beyond <code>len(L) - 1</code>, leading to the index error.</p> <pre><code> if len(sub) == n: sublists.append(sub) break </code></pre> <p>Here's a wo...
0
2016-08-06T21:02:16Z
[ "python" ]
Python Error~ List index out of range
38,808,547
<pre><code>def getSublists(L,n): List=L sublists=[] for i in range(len(L)-(n-1)): ii=0 sub=[] while ii&lt;= n: a=List[ii+i] sub.append(a) ii+=1 sublists.append(sub) return sublists </code></pre> <p>I am trying to get all of the possib...
0
2016-08-06T20:45:22Z
38,808,809
<p>Your code can be fixed changing the while statement to <b>while ii &lt; n</b>, in case you're trying to obtain this result: </p> <pre><code>l = [1, 2, 3, 4] n = 2 nl = [[1, 2], [2, 3], [3, 4]] </code></pre> <p>But I think this is not what you want. Now, if you're lazy as me, you can use itertools.combinations to g...
0
2016-08-06T21:19:24Z
[ "python" ]
Django "./manage.py bower install" tells me bower isn't installed when it is
38,808,548
<p>I'm following the instructions from the django-bower setup readme <a href="https://github.com/nvbn/django-bower" rel="nofollow">here</a>. I've installed django-bower (v5.1.0) via <code>$ pip install -r requirements.txt</code> (django-bower==5.1.0 is in my requirements.txt). Now I'm trying to run <code>$ ./manage.py ...
0
2016-08-06T20:45:23Z
38,808,672
<p>That error message indicates that <code>bower</code> cannot be found. <code>django-bower</code> is properly installed.</p> <p>Check the instructions here: <a href="https://bower.io/#install-bower" rel="nofollow">https://bower.io/#install-bower</a>:</p> <pre><code>npm install -g bower </code></pre>
2
2016-08-06T21:01:33Z
[ "python", "django", "pip", "bower" ]
tf.contrib.layers.embedding_column from tensor flow
38,808,643
<p>I am going through tensorflow tutorial <a href="https://www.tensorflow.org/versions/r0.10/tutorials/wide_and_deep/index.html#tensorflow-wide-deep-learning-tutorial" rel="nofollow">tensorflow</a>. I would like to find description of the following line:</p> <pre><code>tf.contrib.layers.embedding_column </code></pre> ...
2
2016-08-06T20:58:10Z
38,980,687
<p>I've been wondering about this too. It's not really clear to me what they're doing, but this is what I found.</p> <p>In the <a href="http://arxiv.org/pdf/1606.07792v1.pdf" rel="nofollow">paper on wide and deep learning</a>, they describe the embedding vectors as being randomly initialized and then adjusted during t...
2
2016-08-16T17:06:35Z
[ "python", "tensorflow", "embedding" ]
Where can I get pycharm-debug.egg for Idea?
38,808,690
<p>I can't find <code>pycharm-debug.egg</code> in IntelliJ Idea (2016.2) installation directory, where can I get it?</p>
1
2016-08-06T21:03:22Z
38,808,691
<p>It is distributed as part of PyCharm - in directory <code>debug-eggs</code> - that if available at <a href="https://www.jetbrains.com/pycharm/download" rel="nofollow">https://www.jetbrains.com/pycharm/download</a>.</p> <p>The file is also available in <a href="https://github.com/JetBrains/intellij-community" rel="n...
1
2016-08-06T21:03:22Z
[ "python", "debugging", "intellij-idea", "pycharm", "remote-debugging" ]
Why is my 'for' loop not looping?
38,808,739
<p>The following python script should do following:</p> <ul> <li>wait for a key press, then</li> <li>send <code>X1650 Y0 Z0</code> to an embedded device, then</li> <li>fill the variable <code>line</code> byte by byte with the response</li> </ul> <p>Altough <code>print (ser.in_waiting)</code> claims that the input buf...
0
2016-08-06T21:10:14Z
38,808,863
<p>You must specify the number of bytes to be read. But I don't know the return type so when you print a line, you will see :) and then you can convert accordingly </p> <pre><code>line = ser.read(ser.in_waiting) print("%r"%line) </code></pre> <p>Here is a docs <a href="http://pyserial.readthedocs.io/en/latest/pyseri...
2
2016-08-06T21:27:23Z
[ "python", "pyserial" ]
How do I pass the elements of a Python list to HTML for different HREF links?
38,808,759
<p>I have a list of filenames in Python, and I want to pass that to HTML. The HTML page should have different href links for each of the filenames in the list. If I pass the whole list then the href link is again a list (which does not allow me to click on different links), and if I use a for loop to pass the list elem...
0
2016-08-06T21:12:38Z
38,808,896
<p>I'd actually use a <em>template engine</em>, like <a href="http://www.makotemplates.org/" rel="nofollow"><code>Mako</code></a>. Working example:</p> <pre><code>from mako.template import Template def results(docs): template = """ &lt;html&gt; &lt;head&gt; &lt;title&gt; Results &lt;/title&gt; ...
0
2016-08-06T21:32:02Z
[ "python", "html", "python-2.7" ]
How pandas.DataFrame.groupby actually work
38,808,873
<p>I need to group a <code>pandas.DataFrame</code> by one,two and three columns and compute the mean of the "groups".</p> <p>Something like:</p> <pre class="lang-py prettyprint-override"><code> col1 col2 col3 col4 0 A 17 R 3 1 B 5 T 7 2 F 25 R 11 3 A 33 R 15 ...
-1
2016-08-06T21:29:15Z
38,809,401
<p>For your first 2 examples at the top, here is the syntax you are looking for:</p> <pre><code>&gt;&gt;&gt;df.groupby(['col1'])['col2', 'col4'].mean() col2 col4 col1 A 25 9.000000 B 11 13.000000 F 25 20.333333 &gt;&gt;&gt;df.groupby(['col1','col3'])['col2', 'col4']...
1
2016-08-06T22:46:35Z
[ "python", "pandas", "dataframe" ]
Sending Notifications in to multiple users FCM
38,808,880
<p>I am configuring my mobile applications with firebase cloud messaging. I've finally figured out how to send these annoying to configure notifications. My python code looks like this </p> <pre><code>url = 'https://fcm.googleapis.com/fcm/send' body = { "data":{ "title":"mytitle", "body":"mybody", "url":"...
0
2016-08-06T21:30:09Z
38,869,090
<p>Instead of "to":"device_id" you should use "to":"topic" , </p> <p>topic is use from group messaging in FCM or GCM</p> <p><a href="https://developers.google.com/cloud-messaging/topic-messaging" rel="nofollow">https://developers.google.com/cloud-messaging/topic-messaging</a></p>
0
2016-08-10T09:17:15Z
[ "python", "push-notification", "google-cloud-messaging" ]
Sending Notifications in to multiple users FCM
38,808,880
<p>I am configuring my mobile applications with firebase cloud messaging. I've finally figured out how to send these annoying to configure notifications. My python code looks like this </p> <pre><code>url = 'https://fcm.googleapis.com/fcm/send' body = { "data":{ "title":"mytitle", "body":"mybody", "url":"...
0
2016-08-06T21:30:09Z
39,447,372
<p>To send FCM to multiple device you use the key <strong>"registration_ids"</strong> instead of <strong>"to"</strong></p> <pre><code>"registration_ids": ["fcm_token1", "fcm_token2"] </code></pre> <p>Have a look at <a href="https://github.com/olucurious/PyFCM" rel="nofollow">this</a> package and see how they implemen...
0
2016-09-12T09:37:12Z
[ "python", "push-notification", "google-cloud-messaging" ]
Keydown function not working
38,808,937
<p>I have just downloaded pygame 1.9.2 for python 3.3 and the <code>keydown</code> function is not working. The IDLE shell keeps telling me the same error:</p> <pre><code>NameError: name 'KEYDOWN' is not defined </code></pre> <p>How do I solve this problem? I am kinda new to programming so could you please explain t...
-1
2016-08-06T21:38:25Z
38,811,495
<p><strong>NOTE: Sorry for deleting my previous answer but Stack Overflow just randomly posted my answer before I was done.</strong></p> <p>Well, there could be several things wrong. You could be using <code>pygame.key.keydown()</code>, which is wrong, and you should be using <code>pygame.key.get_pressed()</code>. But...
1
2016-08-07T06:18:52Z
[ "python", "python-3.x", "pygame" ]
In a inorder traversal of a binary search tree, where in the code does it traverse up?
38,808,959
<p>I see where how it goes down the tree, but don't see how it traverses back up and onto the right side of the root. Can someone explain? This is fully functional inorder traversal code in Python.</p> <pre class="lang-py prettyprint-override"><code>def inorder(self): if self: if self.leftChild: ...
0
2016-08-06T21:41:46Z
38,811,413
<p>Reaching the end of a function is the same thing as executing <code>return</code> which is the same thing as executing <code>return None</code>.</p> <p>For functions that do not return a meaningful value, it is preferred to let execution reach the end of the function rather than place a superfluous <code>return</co...
1
2016-08-07T06:07:29Z
[ "python", "algorithm", "data-structures", "binary-tree", "binary-search-tree" ]
Remove some x labels with Seaborn
38,809,061
<p>In the screenshot below, all my x-labels are overlapping each other.</p> <pre><code>g = sns.factorplot(x='Age', y='PassengerId', hue='Survived', col='Sex', kind='strip', data=train); </code></pre> <p>I know that I can remove all the labels by calling <code>g.set(xticks=[])</code>, but is there a way to just show s...
3
2016-08-06T21:56:00Z
38,809,632
<p>I am not sure why there aren't sensible default ticks and values like there are on the y-axis. At any rate you can do something like the following:</p> <pre><code>import seaborn as sns import matplotlib.pyplot as plt import matplotlib.ticker as ticker titanic = sns.load_dataset('titanic') sns.factorplot(x='age',y=...
3
2016-08-06T23:40:22Z
[ "python", "seaborn" ]
python variable concatination with different equators
38,809,069
<p>How would I be able to make a variable that contains another = sign in it, like this:</p> <pre><code>newval = dict[key_to_find] = int(change) </code></pre>
0
2016-08-06T21:57:26Z
38,809,132
<p>I'm basing the answer off of</p> <blockquote> <p>variable that <strong>contains</strong> another = sign in it</p> </blockquote> <p>I think you are trying to concatenate <code>dict[key_to_find]</code> and <code>int(change)</code> with an equal sign in the middle. This can be done with the following</p> <pre><co...
0
2016-08-06T22:06:32Z
[ "python" ]
python variable concatination with different equators
38,809,069
<p>How would I be able to make a variable that contains another = sign in it, like this:</p> <pre><code>newval = dict[key_to_find] = int(change) </code></pre>
0
2016-08-06T21:57:26Z
38,809,231
<p>The problem with doing this is that in Python the '=' is an assignment operator rather than a symbol.</p> <p>Python is reading what you wrote as trying to assign to two variables. For example:</p> <p><code>foo = "test"</code> and <code>bar = "test"</code> can be written as <code>foo = bar = "test"</code></p> <p><...
0
2016-08-06T22:20:18Z
[ "python" ]
pyqt QThread and Signal and Emit not working for this answer
38,809,212
<p>So I've been looking around for an answer for how to use QThreads and Signals, and came across an answer from:</p> <p><a href="http://stackoverflow.com/questions/16919472/how-to-access-gui-elements-from-another-thread-in-pyqt?rq=1">How to access GUI elements from another thread in PyQt</a></p> <p>And wondering if ...
0
2016-08-06T22:17:02Z
38,850,118
<p>That code works for me <code>Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32</code>. There is one little bug in that snippet though:</p> <p>You should change this line <code>self.destroy(self, destroyWindow =True, destroySubWindows = True)</code> by this <code>self.d...
0
2016-08-09T11:59:39Z
[ "python", "pyqt" ]
Using comprehensions instead of a for loop
38,809,247
<p>The following is a simplified example of my code.</p> <pre><code>&gt;&gt;&gt; def action(num): print "Number is", num &gt;&gt;&gt; items = [1, 3, 6] &gt;&gt;&gt; for i in [j for j in items if j &gt; 4]: action(i) Number is 6 </code></pre> <p><strong>My question is the following:</strong> is it bad ...
1
2016-08-06T22:21:43Z
38,809,404
<p>This shouldn't use a generator or comprehension at all.</p> <pre><code>def action(num): print "Number is", num items = [1, 3, 6] for j in items: if j &gt; 4: action(i) </code></pre> <p>Generators evaluate lazily. The expression <code>(action(j) for j in items if j &gt; 2)</code> will merely return...
4
2016-08-06T22:46:51Z
[ "python", "list-comprehension" ]
Using comprehensions instead of a for loop
38,809,247
<p>The following is a simplified example of my code.</p> <pre><code>&gt;&gt;&gt; def action(num): print "Number is", num &gt;&gt;&gt; items = [1, 3, 6] &gt;&gt;&gt; for i in [j for j in items if j &gt; 4]: action(i) Number is 6 </code></pre> <p><strong>My question is the following:</strong> is it bad ...
1
2016-08-06T22:21:43Z
38,809,502
<p>While I personally favour <a href="http://stackoverflow.com/a/38809404/1636276">Tigerhawk's solution</a>, there might be a middle ground between his and willywonkadailyblah's solution (now deleted).</p> <p>One of willywonkadailyblah's points was:</p> <blockquote> <p>Why create a new list instead of just using th...
1
2016-08-06T23:06:53Z
[ "python", "list-comprehension" ]
Using comprehensions instead of a for loop
38,809,247
<p>The following is a simplified example of my code.</p> <pre><code>&gt;&gt;&gt; def action(num): print "Number is", num &gt;&gt;&gt; items = [1, 3, 6] &gt;&gt;&gt; for i in [j for j in items if j &gt; 4]: action(i) Number is 6 </code></pre> <p><strong>My question is the following:</strong> is it bad ...
1
2016-08-06T22:21:43Z
38,809,513
<p>This is bad practice. Firstly, your code fragment does not produce the desired output. You would instead get something like: <code>&lt;generator object &lt;genexpr&gt; at 0x03D826F0&gt;</code>. </p> <p>Secondly, a list comprehension is for creating sequences, and generators a for creating streams of objects. Typica...
1
2016-08-06T23:09:00Z
[ "python", "list-comprehension" ]
Python 2.7 check if a file is encoded with UTF-8
38,809,491
<p>My current solution is just read all bytes of a file, try to decode, if any exception, I will say this file is not properly encoded. Any other more elegant ways? Thanks.</p> <pre><code>utfbytes.decode('utf-8') </code></pre> <p>regards, Lin</p>
0
2016-08-06T23:05:36Z
38,809,519
<p><strong><a href="http://stackoverflow.com/a/436299/2483271">No</a></strong>. From that answer:</p> <blockquote> <p>Correctly detecting the encoding all times is impossible.</p> <p>(From chardet FAQ:)</p> <blockquote> <p>However, some encodings are optimized for specific languages, and languages are ...
1
2016-08-06T23:10:35Z
[ "python", "python-2.7", "utf-8" ]
Filling empty DataFrame with numpy structured array
38,809,506
<p>I created an empty <code>DataFrame</code> by doing the following:</p> <pre><code>In [581]: df=pd.DataFrame(np.empty(8,dtype=([('f0', '&lt;i8'), ('f1', '&lt;f8'),('f2', '&lt;i8'), ('f3', '&lt;f8'),('f4', '&lt;f8'),('f5', '&lt;f8'), ('f6', '&lt;f8'),('f7', '&lt;f8')]))) In [582]: df Out[582]: f0 ...
2
2016-08-06T23:07:35Z
39,867,984
<p>The obvious solution is to give pandas a pandas dataframe:</p> <pre><code>df[0:4] = pd.DataFrame(x) </code></pre> <p>This is very performance heavy, but in your example it is probably not noticeable.</p> <p>I would suggest you use the <code>.iloc</code> method as it is more explicit.</p> <pre><code>df.iloc[0:4] ...
0
2016-10-05T07:34:30Z
[ "python", "pandas", "numpy", "dataframe", "structured-array" ]
How to make a test class or function for fibonacci with pytest?
38,809,617
<pre><code>def fibR(n): if n==1 or n==2: return 1 return fib(n-1)+fib(n-2) print (fibR(5)) </code></pre> <p>How could I make a test class for fibonnaci, for example?</p>
1
2016-08-06T23:34:22Z
38,809,670
<p>This is the closed equation for nth fibonnaci</p> <p><a href="http://i.stack.imgur.com/fY87P.png" rel="nofollow"><img src="http://i.stack.imgur.com/fY87P.png" alt="enter image description here"></a></p> <p>You need to create a function that returns that value. Then</p> <pre><code>def fibequation(n): return ((...
2
2016-08-06T23:48:04Z
[ "python", "python-3.x", "fibonacci" ]
How to make a test class or function for fibonacci with pytest?
38,809,617
<pre><code>def fibR(n): if n==1 or n==2: return 1 return fib(n-1)+fib(n-2) print (fibR(5)) </code></pre> <p>How could I make a test class for fibonnaci, for example?</p>
1
2016-08-06T23:34:22Z
38,809,702
<p>I stuck your existing code in a file called <code>fib.py</code>:</p> <pre><code>def fibR(n): if n==1 or n==2: return 1 return fibR(n-1)+fibR(n-2) </code></pre> <p>In the same directory I created a file called <code>test_fib.py</code>:</p> <pre><code>import pytest from fib import fibR def test_fib_1_equals_1(...
2
2016-08-06T23:57:26Z
[ "python", "python-3.x", "fibonacci" ]
Name conversion is not defined
38,809,622
<p>I have an error when running the following in python</p> <blockquote> <p>Runtime error Traceback (most recent call last): File "", line 6, in File "C:\Python27\ArcGIS10.3\Lib\rpy2\robjects__init__.py", line 55, in conversion.ri2py = default_ri2py NameError: name 'conversion' is not defined</p...
-1
2016-08-06T23:35:40Z
38,810,091
<p>Variable simply not defined. Use the snippet below to define it.</p> <pre><code>import rpy2.robjects as robjects robjects.conversion.ri2py = default_ri2py </code></pre> <p><a href="http://rpy.sourceforge.net/rpy2/doc-2.1/html/robjects_convert.html" rel="nofollow">http://rpy.sourceforge.net/rpy2/doc-2.1/html/robje...
0
2016-08-07T01:25:31Z
[ "python" ]
When does ctypes free memory?
38,809,624
<p>In Python I'm using ctypes to exchange data with a C library, and the call interface involves nested pointers-to-structs. </p> <p>If the memory was allocated from in C, then python should (deeply) extract a copy of any needed values and then explicitly ask that C library to deallocate the memory.</p> <p>If the mem...
1
2016-08-06T23:36:18Z
38,826,578
<p>Nested pointers to simple objects seem fine. The documentation is explicit that ctypes doesn't support "original object return", but implies that the pointer does store a python-reference in order to keep-alive its target object (the precise mechanics might be implementation-specific).</p> <pre><code>&gt;&gt;&gt; f...
0
2016-08-08T10:14:42Z
[ "python", "memory-management", "ctypes" ]
Keras import error Nadam
38,809,686
<p>I am getting an import error when trying to import the Keras module Nadam:</p> <pre><code>&gt;&gt;&gt; from keras.optimizers import Nadam Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name Nadam </code></pre> <p>I can import and use SGD, Adam, etc, ...
10
2016-08-06T23:51:51Z
39,250,535
<p>If you can import something in one place but not another, it's definitely an issue with the import system. So, carefully check the relevant variables (<code>sys.path</code>, <code>PYTHON_PATH</code>) and where the modules in each case are being imported from (<code>sys.modules</code>).</p> <p>For a more in-depth re...
3
2016-08-31T13:08:02Z
[ "python", "path", "theano", "keras" ]
Keras import error Nadam
38,809,686
<p>I am getting an import error when trying to import the Keras module Nadam:</p> <pre><code>&gt;&gt;&gt; from keras.optimizers import Nadam Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: cannot import name Nadam </code></pre> <p>I can import and use SGD, Adam, etc, ...
10
2016-08-06T23:51:51Z
39,351,292
<p>It could happen if you're using other version of python. Let's say, you have installed python globally with version 2.7.x, but when running your script, you're using python 3.x. In this case even you'll run python shell, you'll be able to import it, but when running concrete script which uses other version of python...
1
2016-09-06T14:18:06Z
[ "python", "path", "theano", "keras" ]
df.to_dict() only get one row of original dataframe (df)
38,809,705
<p>I have the following dataframe:</p> <p>Note: date is the index</p> <pre><code>city morning afternoon evening midnight date 2014-05-01 YVR 2.32 4.26 -4.87 6.58 2014-05-01 YYZ 24.78 2.90 -50.55 6.64 2014-05-01 DFW 24.78 2.90 -50.55 6.64 2014-05-01 PDX 2.40 4.06 ...
1
2016-08-06T23:59:08Z
38,809,763
<p>The output you're getting is using the index as a key in a dictionary. You have a repeated index, and dictionary keys must be unique, so it's not going to work.</p> <p>You'll have to choose another output format. I find <code>records</code> useful, as in</p> <pre><code>In [65]: df.reset_index().to_dict("records")...
3
2016-08-07T00:13:48Z
[ "python", "pandas", "dictionary" ]