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
What format should I use to store timestamp in JSON for mongodb queries used in nodejs?
38,936,739
<p>I am currently using python to preprocess my data into JSON and insert my data into the collection via nodejs: <code>collection.insert(data, {safe:true}, function(err, result) {});</code> My queries will be executed using nodejs as well.</p> <p>I previously used python <code>datetime.datetime</code> to format my t...
2
2016-08-13T20:31:19Z
38,937,390
<p>The following <a href="http://stackoverflow.com/questions/3778428/best-way-to-store-date-time-in-mongodb">answer</a> suggests that the best way is to use the JavaScript <code>Date</code> (constructed also via <code>ISODate</code>), which is native to Mongo. Digging into the <a href="https://docs.mongodb.com/manual/r...
1
2016-08-13T22:04:28Z
[ "python", "json", "node.js", "mongodb", "isodate" ]
How to find the correlation between two lists when one list consists of date values?
38,936,752
<p>I'm trying to calculate the correlation between two lists every 30 days using the <em>pearsonr</em> function from scipy.</p> <p>One list consists of dates (called <strong>dateValues</strong>), and the other one consists of sales (called <strong>saleNumbers</strong>). I already extracted the dates using datetime.str...
0
2016-08-13T20:32:29Z
38,936,772
<p>Convert them to numeric values first:</p> <pre><code>arbitrary_date = datetime(1970,1,1) pearsonr([(d - arbitrary_date).total_seconds() for d in dateValues], saleNumbers) </code></pre> <p>Perason correlation is unaffected by scaling or translation in either axis (affine transformations)</p>
1
2016-08-13T20:35:38Z
[ "python", "numpy", "scipy", "data-analysis", "python-datetime" ]
How to find the correlation between two lists when one list consists of date values?
38,936,752
<p>I'm trying to calculate the correlation between two lists every 30 days using the <em>pearsonr</em> function from scipy.</p> <p>One list consists of dates (called <strong>dateValues</strong>), and the other one consists of sales (called <strong>saleNumbers</strong>). I already extracted the dates using datetime.str...
0
2016-08-13T20:32:29Z
38,936,889
<p>You might try something like this:</p> <pre><code>import numpy as np pearsonr(np.array(dateValues, dtype=np.datetime64).astype("int"), np.array(saleNumbers)) </code></pre>
1
2016-08-13T20:49:28Z
[ "python", "numpy", "scipy", "data-analysis", "python-datetime" ]
Categorize Data in a column in dataframe
38,936,854
<p>I have a column of numbers in my dataframe, i want to categorize these numbers into e.g high , low, excluded. How do i accomplish that. I am clueless , i have tried looking at the cut function and category datatype.</p>
-1
2016-08-13T20:45:18Z
38,936,967
<p>This question is pretty broad, but a good place to start might be this page in the documentation:</p> <p><a class='doc-link' href="http://stackoverflow.com/documentation/pandas/1751/indexing-and-selecting-data/6784/boolean-indexing#t=201608132054126569217">Boolean indexing</a></p> <p>Or you could look into numpy.w...
0
2016-08-13T20:59:03Z
[ "python", "pandas", "machine-learning", "data-analysis" ]
Categorize Data in a column in dataframe
38,936,854
<p>I have a column of numbers in my dataframe, i want to categorize these numbers into e.g high , low, excluded. How do i accomplish that. I am clueless , i have tried looking at the cut function and category datatype.</p>
-1
2016-08-13T20:45:18Z
38,987,747
<p>A short example with <code>pd.cut</code>.</p> <p>Let's start with some data frame:</p> <pre><code>df = pd.DataFrame({'A': [0, 8, 2, 5, 9, 15, 1]}) </code></pre> <p>and, say, we want to assign the numbers to the following categories: <code>'low'</code> if a number is in the interval <code>[0, 2]</code>, <code>'mid...
1
2016-08-17T03:41:09Z
[ "python", "pandas", "machine-learning", "data-analysis" ]
(Python) Passing multiple changes to URL
38,936,855
<p>I have a list of several stock tickers:</p> <pre><code>ticker = (GE,IBM,GM,F,PG,CSCO) </code></pre> <p>That I want to pass to the URL in my python program. </p> <pre><code>url = "https://www.quandl.com/api/v3/datasets/WIKI/FB.json" </code></pre> <p>I'm trying to pass a new ticker into the URL on each subsequent...
-1
2016-08-13T20:45:18Z
38,936,917
<pre><code>import requests url_tpl = "https://www.quandl.com/api/v3/datasets/WIKI/{ticker}.json" # Here your results will be stored jsons = {} for ticker in ('FB', 'GE', 'IBM', 'GM', 'F' , 'PG', 'CSCO'): res = requests.get(url_tpl.format(ticker=ticker)) if res.status_code == 200: jsons[ticker] = res.json...
2
2016-08-13T20:53:09Z
[ "python" ]
Concatenate lines of form input into a single line
38,936,861
<p>I have a HTML form, user will input here text (with lines), like this : </p> <pre><code>How are you? I am fine. Thank you! </code></pre> <p>In the server side, I will get that input by :</p> <pre><code>input = request.POST['input'] </code></pre> <p>And then I will to concatenate them into a single line like thi...
1
2016-08-13T20:46:34Z
38,936,933
<p><code>newstring = input.replace('\n', '')</code> should work</p>
1
2016-08-13T20:55:23Z
[ "python", "django", "concatenation" ]
Concatenate lines of form input into a single line
38,936,861
<p>I have a HTML form, user will input here text (with lines), like this : </p> <pre><code>How are you? I am fine. Thank you! </code></pre> <p>In the server side, I will get that input by :</p> <pre><code>input = request.POST['input'] </code></pre> <p>And then I will to concatenate them into a single line like thi...
1
2016-08-13T20:46:34Z
38,937,145
<p>Use</p> <pre><code>" ".join(input.split("\n")) </code></pre>
1
2016-08-13T21:26:33Z
[ "python", "django", "concatenation" ]
Concatenate lines of form input into a single line
38,936,861
<p>I have a HTML form, user will input here text (with lines), like this : </p> <pre><code>How are you? I am fine. Thank you! </code></pre> <p>In the server side, I will get that input by :</p> <pre><code>input = request.POST['input'] </code></pre> <p>And then I will to concatenate them into a single line like thi...
1
2016-08-13T20:46:34Z
38,937,274
<p>Thank you Harrison and Cychih for your answer, I tried however, they don't work. The solution I found is this : </p> <pre><code>newstring = input1.replace('\r\n', ' ') </code></pre> <p>It's </p> <pre><code>'\r\n' </code></pre> <p>not </p> <pre><code>'\n' </code></pre> <p>When I put in the form 3 lines like thi...
0
2016-08-13T21:45:52Z
[ "python", "django", "concatenation" ]
Dynamically create methods for an instance in Python
38,937,123
<p>I have a class called 'Movable Piece'. Of course, I want every instance of this class to move. For that, I thought another class called 'Movement' would be nice, and reusable in case I need other stuff to move. Besides, I quite like how <code>my_piece.move.up</code> looks in the code. </p> <p>The problem comes when...
-2
2016-08-13T21:22:59Z
38,937,299
<p>IMHO you should have provided a <a href="http://stackoverflow.com/help/mcve">mvce</a> in the question that way this answer could add some additional tips, in any case, here's a working example guessing the missing bits of your code:</p> <pre><code>class Piece(object): def __init__(self, letter, name, walkable)...
1
2016-08-13T21:50:06Z
[ "python", "class", "python-3.x" ]
Dynamically create methods for an instance in Python
38,937,123
<p>I have a class called 'Movable Piece'. Of course, I want every instance of this class to move. For that, I thought another class called 'Movement' would be nice, and reusable in case I need other stuff to move. Besides, I quite like how <code>my_piece.move.up</code> looks in the code. </p> <p>The problem comes when...
-2
2016-08-13T21:22:59Z
38,943,759
<p>This is how I finally ended up doing it. I'm sorry this example is not reproducible, but there are just too many classes involved in the mix and I think it would just tamper with readability and comprehension for this precise problem. You can nevertheless peep the code at <a href="https://github.com/Mellatrix/escape...
0
2016-08-14T15:34:30Z
[ "python", "class", "python-3.x" ]
python issues with csv
38,937,187
<p>I just started leaning python while taking an udacity course for data analytics, and am having problems with my code in pyCharm. To preface this, the code works when used in the udacity shell and the file locations changed to instructed location for the udacity website. Below is the code and the 2 errors I'm getting...
-2
2016-08-13T21:32:26Z
38,937,261
<p>I'll note your errors with inline comments. Basically, you seem to have trouble keeping track of objects and their names.</p> <pre><code>import csv daily_engagements = [] # this is never used project_submissions = [] # you never add anything to this list with open(r'C:\Users\austi\Downloads\daily_engagement.csv',...
1
2016-08-13T21:42:40Z
[ "python", "csv", "pycharm" ]
Custom class which is a dict, but initialized without dict copy?
38,937,227
<p>For legibility purposes, I would like to have a custom class that behaves exactly like a dict (but carries a meaningful type instead of the more general dict type):</p> <pre><code>class Derivatives(dict): "Dictionary that represents the derivatives." </code></pre> <p>Now, is there a way of building new objects...
2
2016-08-13T21:38:02Z
38,937,654
<p>TL;DR: There's not general-purpose way to do it unless you do it in C.</p> <p>Long answer: The <code>dict</code> class is implemented in C. Thus, there is no way to access it's internal properties - and most importantly, it's internal hash table, unless you use C.</p> <p>In C, you could simply copy the pointer rep...
0
2016-08-13T22:53:06Z
[ "python", "dictionary", "inheritance" ]
Custom class which is a dict, but initialized without dict copy?
38,937,227
<p>For legibility purposes, I would like to have a custom class that behaves exactly like a dict (but carries a meaningful type instead of the more general dict type):</p> <pre><code>class Derivatives(dict): "Dictionary that represents the derivatives." </code></pre> <p>Now, is there a way of building new objects...
2
2016-08-13T21:38:02Z
38,937,844
<p>By inheriting from <code>dict</code> you are given three possibilities for constructor arguments: (baring the <code>{}</code> literal)</p> <pre><code>class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg) </code></pre> <p>This means that, in order to instantiate your instance you <strong>mu...
0
2016-08-13T23:28:50Z
[ "python", "dictionary", "inheritance" ]
Python 3.4: After popen.communicate() program is lost
38,937,238
<p>I'll try to connect a button on my RPi to control mplayer, first button press shall start the player, and each later button press shall play another entry in the playlist. As a minimal example I created following script on Linux Mint 18 and Python3.4.3:</p> <pre><code>from time import sleep from subprocess import P...
0
2016-08-13T21:39:43Z
38,942,094
<p>I solved it with mplayer slave:</p> <pre><code>from time import sleep from subprocess import Popen pathtoControlFile = "/home/immi/mplayer-control" cmd = ["mplayer", "-slave", "-input", "file="+pathtoControlFile, "-shuffle", "-playlist", "/media/immi/9A005723005705A3/Musik/playlist.m3u"] if __name__ == '__main__'...
0
2016-08-14T12:09:18Z
[ "python", "python-3.x", "subprocess", "popen" ]
two dataframes into one
38,937,245
<p>Not sure if this is possible. I have two dataframes df1 and df2 which are presented like this:</p> <pre><code>df1 df2 id value id value a 5 a 3 c 9 b 7 d 4 c 6 f 2 d 8 ...
0
2016-08-13T21:40:39Z
38,937,284
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow"><code>combine_first</code></a>, provided that you first make the DataFrame index <code>id</code> (so that the <code>values</code> get aligned by <code>id</code>):</p> <pre><code>In [80]: ...
1
2016-08-13T21:47:19Z
[ "python", "pandas" ]
How to take input in single line in python and storing it into list
38,937,301
<p>I am getting <strong>Runtime Error - NZEC</strong> while running this code online. I searched.. it is because of input format. Please help me out.</p> <pre><code>import math a=input() b=int(a) e=list() answer=1 for c in range(0,b): d=input() e.append(d) for c in range(0,b): g=e[c] answer=math.fmod(f...
0
2016-08-13T21:50:10Z
38,937,535
<p>if you want to take the second and following inputs in a single line (I guess separated by spaces), you can do the following:</p> <pre><code>import math a=input() b=int(a) answer=1 e = raw_input().split(" ")[:b] for c in range(0,b): g=e[c] answer=math.fmod(float(float(answer) * float(g)),float((10**9)+7))...
0
2016-08-13T22:31:24Z
[ "python", "python-3.x" ]
Incorrect display of major and minor ticks on matplotlib plot
38,937,363
<p>I have the foll. dataframe:</p> <pre><code>Version A2011 v1.0h Decade 1510 - 1500 -3.553251 -0.346051 1520 - 1510 -2.797978 -0.356409 1530 - 1520 -2.194027 -0.358922 1540 - 1530 -1.709211 -0.329759 1550 - 1540 -1.354583 -0.308463 1560 - 1550 -1.062436 -0.305...
1
2016-08-13T21:59:37Z
38,937,796
<p>From a bit of looking around it seems that pandas doesn't play well with locators. It seems that the preferred method of setting ticklabels is automatic. The problem seems to be that the implicit coupling of data vs index, used when automatically setting the tick labels, gets mixed up with a different number of tick...
1
2016-08-13T23:20:33Z
[ "python", "pandas", "matplotlib" ]
logged out users are accessing views which logged in users can only access in django
38,937,380
<p>I am quite new to Django and came across this error. When ever I input a url directly ( '/accounts/admin2@outlook.com/'), django shows the user the view which only logged in users can see. I am using LoginRequiredMixin but it is not helping. </p> <p>My view file is : `</p> <pre><code>from django.shortcuts import r...
0
2016-08-13T22:02:11Z
38,945,227
<p>Please correct following things first.</p> <ul> <li>Whenever you are using class based view you must use request object via <code>self</code>.</li> <li>Check auth use with the following<code>self.request.user.is_authenticated()</code>(It will return the what request does have)</li> <li>If you want to use an automat...
0
2016-08-14T18:20:35Z
[ "python", "django", "authentication" ]
regarding understanding a python function using logical operators
38,937,461
<p>I once read the following python function,</p> <pre><code>def f1(i, num_digits): return np.array([i &gt;&gt; d &amp; 1 for d in range(num_digits)]) </code></pre> <p>I am not very clear on how does the part of <code>i &gt;&gt; d &amp; 1</code> work. Running <code>f1(2,5)</code> will return <code>[0,1,0,0,0]</co...
0
2016-08-13T22:16:33Z
38,937,586
<p>This function creates a list containing the last bit of <code>i</code> after it got shifted <code>index</code> times to the right.</p> <p>Sounds cryptic? It is.</p> <p>Here is what happens:</p> <p>The list comprehension creates a list of size <code>num_digits-1</code>, using the values of the range expression (wh...
0
2016-08-13T22:40:58Z
[ "python", "numpy", "scipy" ]
regarding understanding a python function using logical operators
38,937,461
<p>I once read the following python function,</p> <pre><code>def f1(i, num_digits): return np.array([i &gt;&gt; d &amp; 1 for d in range(num_digits)]) </code></pre> <p>I am not very clear on how does the part of <code>i &gt;&gt; d &amp; 1</code> work. Running <code>f1(2,5)</code> will return <code>[0,1,0,0,0]</co...
0
2016-08-13T22:16:33Z
38,937,783
<p><code>numpy</code> lets us demonstrate this action in a nice table:</p> <pre><code>In [1633]: np.arange(10)[:,None]&gt;&gt;np.arange(5) Out[1633]: array([[0, 0, 0, 0, 0], [1, 0, 0, 0, 0], [2, 1, 0, 0, 0], [3, 1, 0, 0, 0], [4, 2, 1, 0, 0], [5, 2, 1, 0, 0], [6, 3, 1, 0, 0], ...
0
2016-08-13T23:18:48Z
[ "python", "numpy", "scipy" ]
MultiValueDictKeyError on Django View with GET
38,937,506
<p>Trying to build a facebook bot with Django. I get a <code>MultiValueDictKeyError</code> when I do <code>except ValueError:</code>. I am using ngrok to hook Django up to facebook.</p> <p>Here is the code:</p> <pre><code>class PPBChatBotView(generic.View): def get(self, request, *args, **kwargs): try: ...
0
2016-08-13T22:25:25Z
39,446,429
<p>Try <code>if request.GET.get('hub.verify_token') == '10101100':</code></p>
0
2016-09-12T08:46:01Z
[ "python", "facebook", "python-3.x", "hash", "django-views" ]
Parsing Successfully Until IndexError?
38,937,518
<p>I have a script that's parsing for the first upper-case words in this file:</p> <pre><code>IMPORT fs IF fs.exists("fs.pyra") THEN PRINT "fs.pyra Exists!" END </code></pre> <p>The script looks like this:</p> <pre><code>file = open(sys.argv[1], "r") file = file.read().split("\n") while '' in file: findIt...
0
2016-08-13T22:28:24Z
38,937,583
<p>You don't need to increment the index on spaces - <code>line.strip()</code> will remove leading and trailing spaces. </p> <p>You could <code>split()</code> the line on spaces to get words. </p> <p>Then you can iterate over those strings and use <code>isupper()</code> to check whole words, rather than individual ch...
0
2016-08-13T22:40:33Z
[ "python" ]
Parsing Successfully Until IndexError?
38,937,518
<p>I have a script that's parsing for the first upper-case words in this file:</p> <pre><code>IMPORT fs IF fs.exists("fs.pyra") THEN PRINT "fs.pyra Exists!" END </code></pre> <p>The script looks like this:</p> <pre><code>file = open(sys.argv[1], "r") file = file.read().split("\n") while '' in file: findIt...
0
2016-08-13T22:28:24Z
38,937,645
<p>If the file you're trying to process is compatible with Python's built in tokenizer, you can use that so it'll also handle stuff within quotes, then take the very first name token it finds in capitals from each line, eg:</p> <pre><code>import sys from itertools import groupby from tokenize import generate_tokens, N...
0
2016-08-13T22:51:40Z
[ "python" ]
How do I fix an error in my python code where it is complaining about a string being wanted?
38,937,545
<p>I was actually using code from a course at Udacity.com on Data Wrangling. The code file is very short so I was able to copy what they did and I still get an error. They use python 2.7.x. The course is about a year old, so maybe something about the functions or modules in the 2.7 branch has changed. I mean the co...
0
2016-08-13T22:33:20Z
38,946,383
<p>You don't have matching characters in your csv file and the dictionaries in your test function. In particular, in your csv file you are using an <em>em dash</em> (U+2014) and in your <code>firstline</code> and <code>tenthline</code> dictionaries you are using a <em>hyphen-minus</em> (U+002D).</p> <pre><code>hex(ord...
1
2016-08-14T20:35:47Z
[ "python", "python-2.7", "csv" ]
list index out of range error while using if statement in for loop
38,937,621
<p>I'm new to python; I've been coding in javascript so I'm not used to all the errors I'm getting.</p> <p>I'm trying to add properties to an empty object with a for loop, but I get an error saying list index out of range. The error seems to be happening when I add an if statement inside my for loop. I'm not using an ...
0
2016-08-13T22:46:49Z
38,962,564
<p>Insert a blank line in the data file to reproduce the error.</p> <pre><code>section_id = one_seat[0][1:] one_seat[0] = section_id </code></pre> <p>At this point, one_seat = [''], so there is no one_seat[1]</p> <pre><code>if one_seat[1] ... </code></pre> <p>Thus list index out of range is correctly raised.</p> <...
0
2016-08-15T20:29:11Z
[ "python", "python-2.7" ]
list index out of range error while using if statement in for loop
38,937,621
<p>I'm new to python; I've been coding in javascript so I'm not used to all the errors I'm getting.</p> <p>I'm trying to add properties to an empty object with a for loop, but I get an error saying list index out of range. The error seems to be happening when I add an if statement inside my for loop. I'm not using an ...
0
2016-08-13T22:46:49Z
38,963,069
<p>Although the solution by Kenny Ostrom is well, I would actually suggest pre-processing the data file after reading it in. This way, you don't have to constantly check assumptions and it simplifies the code. Specifically, I had the following in mind:</p> <pre><code>seats_info = ['\n', '\n1,133,0,A', '\n1,133,2,C', '...
-1
2016-08-15T21:06:33Z
[ "python", "python-2.7" ]
Pandas rank by column value with conditions
38,937,652
<p>I have the following dataset <strong>(non-unique id)</strong> :</p> <pre><code>id data country 1 8 B 2 15 A 3 14 D 3 19 D 3 8 C 3 20 A </code></pre> <p>For rows with <strong>country ANYTHING BUT "A"</strong>, I want to add a "rank" column.</p> <p>For rows with <strong>coun...
1
2016-08-13T22:52:49Z
38,937,838
<p><strong>EDIT: Written before an edit to the question so doesn't do exactly what the OP wants.</strong></p> <pre><code>df['rank_A'] = df.data[df['country']=='A'].rank(ascending=True) </code></pre> <p>Tested on this </p> <pre><code> import pandas as pd from pandas import DataFrame import numpy as np df2 = DataFr...
2
2016-08-13T23:27:20Z
[ "python", "sorting", "pandas" ]
python loops without index
38,937,663
<p>I'm learning python and I love that you can loop through iterable objects without constantly creating index variables. </p> <p>But I keep finding myself creating index variables anyway so I can reference them in calls from parallel objects. Like when I'm comparing two lists, or a list and a dictionary. </p> <p>As ...
-1
2016-08-13T22:54:54Z
38,937,674
<p>Use enumerate...</p> <pre><code>for i, item in enumerate(myList): foo = parallelList[i] </code></pre> <p>or zip...</p> <pre><code>for item, foo in zip(myList, parallelList): ... </code></pre>
1
2016-08-13T22:57:14Z
[ "python", "loops", "indexing" ]
python loops without index
38,937,663
<p>I'm learning python and I love that you can loop through iterable objects without constantly creating index variables. </p> <p>But I keep finding myself creating index variables anyway so I can reference them in calls from parallel objects. Like when I'm comparing two lists, or a list and a dictionary. </p> <p>As ...
-1
2016-08-13T22:54:54Z
38,938,653
<p>It sounds like you write code like this:</p> <pre><code>for i, item in enumerate(list1): if item == list2[i]: ... </code></pre> <p>You still don't need an explicit index, because you can zip the two lists and iterate over a list of tuples.</p> <pre><code>for item1, item2 in zip(list1, list2): if i...
1
2016-08-14T02:34:09Z
[ "python", "loops", "indexing" ]
I need help in understanding the function of the number "1" and the word 'sum' in the code below
38,937,685
<p>This is the solution to counting upper and lower case letters in a sentence that my friend gave to me without explaining the use of 1 in the statements.</p> <pre><code>x = raw_input('Enter the word') print ("Capital Letters: ", sum(1 for d in x if d.isupper())) print ("Small letters:" , sum(1 for d in x if d.isl...
0
2016-08-13T22:59:59Z
38,937,717
<p>He's filtering all the capital letters in a string and building a list of 1's for each item in the remaining list. Then he's summing that list. Since the list comprehension is building a generator and not a list, <code>len</code> cannot be used.</p> <p>(Edited. Previous version said <code>len</code> could be used e...
0
2016-08-13T23:04:57Z
[ "python" ]
I need help in understanding the function of the number "1" and the word 'sum' in the code below
38,937,685
<p>This is the solution to counting upper and lower case letters in a sentence that my friend gave to me without explaining the use of 1 in the statements.</p> <pre><code>x = raw_input('Enter the word') print ("Capital Letters: ", sum(1 for d in x if d.isupper())) print ("Small letters:" , sum(1 for d in x if d.isl...
0
2016-08-13T22:59:59Z
38,937,756
<p>The <code>sum</code> function takes in a container as its arguments and returns the sum of its elements.</p> <p>This line, <code>sum(1 for d in x if d.isupper())</code>, feeds a generator expression to the <code>sum</code> function, consisting of ones, which in effect counts the number of upper case words in the st...
1
2016-08-13T23:13:40Z
[ "python" ]
global frame vs. stack frame
38,937,721
<p><em>Everything below is from the main page of <a href="http://www.pythontutor.com" rel="nofollow">www.pythontutor.com</a> (a fantastic tool and website by the way).</em></p> <p>Here's some code (image file):</p> <p><a href="http://i.stack.imgur.com/cfGvY.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/cfGvY...
1
2016-08-13T23:05:24Z
38,938,014
<p><a href="https://docs.python.org/2/library/inspect.html#inspect.currentframe" rel="nofollow"><code>frames</code></a> are actual python objects that you can interact with:</p> <pre><code>import inspect my_frame = inspect.currentframe() print(my_frame) #&lt;frame object at MEMORY_LOCATION&gt; print(my_frame.f_line...
1
2016-08-14T00:00:52Z
[ "python", "python-2.7", "stack", "global", "stack-trace" ]
First Digits of a number
38,937,776
<p>I want the first 9 digits and last 9 digits of a fibonocci series for an infinite loop. Running the tests individually, I get better result for the last 9 digits using modulo operator no where comparable to the first 9 digits. I ran different tests like <code>int(str(b)[::-1])%10**9, b/(10**(len(str(b))-9))</code> b...
2
2016-08-13T23:16:22Z
38,938,240
<p>Here are a few versions and timings for getting the first 30000 prefixes. I left out the first two yields and the last digits for simplicity.</p> <ul> <li><code>fibby1</code> is the original way just using <code>str(b)[:9]</code>.</li> <li><code>fibby2</code> keeps track of the appropriate power of 10 to divide by....
1
2016-08-14T00:48:38Z
[ "python" ]
python write to file does not write
38,937,777
<p>I have found similar questions, and tried the solutions proposed within, and none seem to solve my problem. What I am attempting to do is in essence copy the data from one file to another, and even though it does not error our and I have verified the 'line' variable is a string and contains the correct data, it simp...
0
2016-08-13T23:16:38Z
38,937,798
<p>You could just write to the data file in your first loop.</p> <pre><code>with open("data/data.csv", 'w+') as data_file, open("data/raw/" + data_point + ".csv", 'r') as raw_file: for line in raw_file: line = line.split(',') temp_date = datetime(int(line[0]), int(line[1]), int(line[2])) if...
1
2016-08-13T23:20:51Z
[ "python" ]
Word Search on Python 2.7.4
38,937,814
<p><a href="http://i.stack.imgur.com/YlYzp.png" rel="nofollow">The image shows the output. You can clearly see how the letters are not perfectly aligned. </a>We are trying to make a game for a school project and chose Word Search. We researched and have found a piece of coding that helps us make the grid as well as pla...
0
2016-08-13T23:23:13Z
38,937,932
<p>Seems to be printing fine to me... Maybe you should use a Monospaced font in your terminal / wherever you are printing out the grid. </p> <pre><code>grid = [['_' for _ in range(width)] for _ in range(height)] def print_grid(): global grid for row in grid: print " ".join(row) put_word("hello", grid...
2
2016-08-13T23:43:33Z
[ "python", "python-2.7" ]
Auto creating instances of class
38,937,891
<p>I'm trying to create instances of a class by loading a textfile and using some strings from that as input.</p> <p>This is supposed to spit out all the scene headers from a film manuscript and create an instance of a Scene class for every time it reads a scene header that is characterized by starting with either INT...
0
2016-08-13T23:35:51Z
38,937,962
<p>Your function shouldn't be a method of <code>Scene</code>, since it doesn't actually do anything but create a bunch of objects. You can use generators to emit your <code>Scene</code> instances as you parse the file:</p> <pre><code>def read_scenes(filename): with open(filename, 'r') as handle: scene = Sc...
0
2016-08-13T23:49:26Z
[ "python" ]
pySerial: how to check the current baud rate
38,937,903
<p>I have a device (<a href="http://www.robotshop.com/media/files/pdf/datasheet-sen-11792.pdf" rel="nofollow">GT511C3 fingerprint scanner</a>) that I am connecting to Raspberry Pi and programming it using <a href="http://pyserial.readthedocs.io/en/stable/index.html" rel="nofollow">Python Serial module</a>. The GT511 de...
0
2016-08-13T23:38:08Z
38,941,001
<p>Maybe you shoul use <code>stty</code> until you find a better alternative. You can call it from Python code and parse the result to obtain what you need. Here is a basic example (not tested):</p> <pre><code>import subprocess import shlex def get_baudrate(device): command = 'stty &lt; {0}'.format(device) pr...
0
2016-08-14T09:45:43Z
[ "python", "serial-port", "pyserial" ]
Python thread in socket chat application won't start
38,937,917
<p>I'm new to python, and I'm trying to write a simple chat application, featuring a server which runs a thread that accepts from and transmits messages to connected clients, and a client which runs two threads that send messages to and accept messages from the server respectively. Here's the code</p> <p>Server:</p> ...
-1
2016-08-13T23:40:25Z
38,938,091
<p>You swallow the original exception and print out a custom message so it's hard to determine what's causing the issue. So I am going to provide some tips around debugging the issue. </p> <pre><code> try: thread.start_new_thread(receiveAndDeliverMessage, (connection)) except: print ("Error: una...
1
2016-08-14T00:18:34Z
[ "python", "multithreading", "sockets", "networking", "chat" ]
distributed tensorflow on localhosts failed by "socket error, connection refused"
38,937,984
<p>I am experimenting distributed tensorflow using a slight modification of an <a href="https://www.tensorflow.org/versions/r0.10/how_tos/distributed/index.html" rel="nofollow">official example</a>.</p> <p>My experiment code is (you can skip this for now and scroll down to the problem),</p> <pre><code>import tensorfl...
0
2016-08-13T23:54:44Z
39,805,195
<p>The error message tells you where the problem is ---- the worker1 can't connect to worker2. The reason for this problem is you <strong>didn't</strong> start the worker2 server.</p> <p>So execute the fourth command even if there are connection failure messages after executing the third one. Then you will find everyt...
0
2016-10-01T09:51:51Z
[ "python", "tensorflow" ]
Performing Power Operations in Dictionaries
38,938,001
<pre><code> dict1 = {'A': 2,'B': 4,'C': 6} </code></pre> <p>I want a new dictionary to be the values of dict1 squared.</p> <pre><code> dict2 = {'A': 4,'B': 16,'C': 36} </code></pre> <p>A tried using </p> <pre><code>for k in dict1.keys(): value = dict[k] for k1 in value.keys(): value[k1] = value**2 ...
2
2016-08-13T23:58:40Z
38,938,036
<p>You first need to create <code>dict2</code>:</p> <pre><code>dict2 = {} </code></pre> <p>Then, you can populate it using the keys and values of <code>dict1</code>:</p> <pre><code>for key in dict1.keys(): dict2[key] = dict1[key] ** 2 </code></pre> <p>Or in one line:</p> <pre><code>dict2 = {key: value ** 2 for...
3
2016-08-14T00:06:36Z
[ "python", "dictionary" ]
Performing Power Operations in Dictionaries
38,938,001
<pre><code> dict1 = {'A': 2,'B': 4,'C': 6} </code></pre> <p>I want a new dictionary to be the values of dict1 squared.</p> <pre><code> dict2 = {'A': 4,'B': 16,'C': 36} </code></pre> <p>A tried using </p> <pre><code>for k in dict1.keys(): value = dict[k] for k1 in value.keys(): value[k1] = value**2 ...
2
2016-08-13T23:58:40Z
38,938,041
<p>You can just iterate through your old dictionary using a dictionary comprehension like so (python 2):</p> <pre><code>&gt;&gt;&gt; dict1 = {'A': 2,'B': 4,'C': 6} &gt;&gt;&gt; dict2 = {k:v**2 for k,v in dict1.iteritems()} &gt;&gt;&gt; dict2 {'A': 4, 'C': 36, 'B': 16} </code></pre> <p>Note that for python 3:</p> <pr...
3
2016-08-14T00:07:28Z
[ "python", "dictionary" ]
I want get the sum of integers?
38,938,048
<p>I am a beginner and I wrote this code, but how can I make it output the sum of the integers?</p> <pre><code>a=100 b=200 for a in range (b): if a%2==1: print a </code></pre>
-5
2016-08-14T00:09:04Z
38,938,067
<p>If you mean the sum of all the numbers <code>a &lt; x &lt; b</code>, then this will do it.</p> <pre><code>a = 100 b = 200 total = 0 for i in range(a,b+1): total += i print total </code></pre> <p>In this case it will print <code>15150</code>.</p> <p>As per your question, if you want just odd numbers:</p> <p...
-3
2016-08-14T00:13:15Z
[ "python" ]
libxml2-dev not installing on raspbian/debian
38,938,055
<p>When I <code>sudo apt-get install libxml2-dev</code> I receive the error <code>libxml2-dev : Depends: libxml2 (= 2.9.4+dfsg1-1+b1) but 2.9.4+dfsg1-1 is to be installed E: Unable to correct problems, you have held broken packages.</code></p> <p>I tried to follow this guide: <a href="https://www.raspberrypi.org/forum...
0
2016-08-14T00:10:59Z
38,949,270
<p>Ended up downloading from source: <a href="https://packages.debian.org/search?keywords=libxml2" rel="nofollow">https://packages.debian.org/search?keywords=libxml2</a></p> <p>And then installing manually via <code>sudo dpkg -i /path/to/deb/file</code></p>
0
2016-08-15T04:19:58Z
[ "python", "raspberry-pi", "debian", "raspbian", "libxml2" ]
libxml2-dev not installing on raspbian/debian
38,938,055
<p>When I <code>sudo apt-get install libxml2-dev</code> I receive the error <code>libxml2-dev : Depends: libxml2 (= 2.9.4+dfsg1-1+b1) but 2.9.4+dfsg1-1 is to be installed E: Unable to correct problems, you have held broken packages.</code></p> <p>I tried to follow this guide: <a href="https://www.raspberrypi.org/forum...
0
2016-08-14T00:10:59Z
38,977,880
<p>"784 not upgraded."</p> <p>Are you updated whenever your raspian? Maybe you can't install this because you haven't stable packages. </p>
0
2016-08-16T14:41:31Z
[ "python", "raspberry-pi", "debian", "raspbian", "libxml2" ]
Why can't python recognize my month column in a dataset?
38,938,064
<p>This is what the dataframe looks like:</p> <pre><code>Date Time (HHMM) Site Plot Replicate Temperature \ 0 2002-05-01 600 Barre Woods 16 5 4.5 1 2002-05-01 600 Barre Woods 21 7 4.5 2 2002-05-01 600 Barre Woods 31 ...
0
2016-08-14T00:12:40Z
38,938,313
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow">set_index</a> first:</p> <pre><code>dfx = df.set_index('Date') </code></pre> <p>Then, you can <code>groupby</code>:</p> <pre><code>dfx.groupby(lambda x : x.month).mean() #just for an example ...
1
2016-08-14T01:04:31Z
[ "python", "datetime", "pandas", "group-by" ]
Why can't python recognize my month column in a dataset?
38,938,064
<p>This is what the dataframe looks like:</p> <pre><code>Date Time (HHMM) Site Plot Replicate Temperature \ 0 2002-05-01 600 Barre Woods 16 5 4.5 1 2002-05-01 600 Barre Woods 21 7 4.5 2 2002-05-01 600 Barre Woods 31 ...
0
2016-08-14T00:12:40Z
38,938,821
<p>Group by <code>df['Date'].dt.month</code>. For example, to compute the average temperature you can do the following.</p> <pre><code>import io import pandas as pd data = io.StringIO('''\ Date,Time (HHMM),Site,Plot,Replicate,Temperature 0,2002-05-01,600,Barre Woods,16,5,4.5 1,2002-05-01,600,Barre Woods,21,7,4.5 2,20...
1
2016-08-14T03:14:27Z
[ "python", "datetime", "pandas", "group-by" ]
What's the equivalent of peewee's DoesNotExist in SQLAlchemy?
38,938,116
<p>I've been using peewee with SQLite for some time and now I'm switching to SQLAlchemy with Postgres and I can't find equivalent of DoesNotExist (see example) </p> <pre><code>try: return models.User.get(models.User.id == userid) except models.DoesNotExist: return None </code></pre> <p>Do you know how to achi...
0
2016-08-14T00:23:51Z
38,938,155
<p>The closest could be this one: - <a href="http://docs.sqlalchemy.org/en/latest/orm/exceptions.html#sqlalchemy.orm.exc.NoResultFound" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/exceptions.html#sqlalchemy.orm.exc.NoResultFound</a> </p> <p><strong>Code Sample:</strong></p> <pre><code>from sqlalchemy.orm....
-1
2016-08-14T00:32:00Z
[ "python", "postgresql", "flask-sqlalchemy", "peewee" ]
What's the equivalent of peewee's DoesNotExist in SQLAlchemy?
38,938,116
<p>I've been using peewee with SQLite for some time and now I'm switching to SQLAlchemy with Postgres and I can't find equivalent of DoesNotExist (see example) </p> <pre><code>try: return models.User.get(models.User.id == userid) except models.DoesNotExist: return None </code></pre> <p>Do you know how to achi...
0
2016-08-14T00:23:51Z
39,113,947
<p>Peewee <em>does</em> work with Postgresql, you know. ;)</p>
-1
2016-08-24T03:31:07Z
[ "python", "postgresql", "flask-sqlalchemy", "peewee" ]
Simplifying, printing text instead of boolean value, Python
38,938,182
<p>Using python to grade student scores. Trying to simplify from</p> <pre><code>A = ((float(scptratio)) &gt;= (0.9) and (float(scptratio) &lt;= 1)) B = ((float(scptratio)) &gt;= (0.8) and (float(scptratio) &lt;= (0.89))) if A == True: print (studentname, (" has scored an A on the test.")) elif B == True: print (stud...
2
2016-08-14T00:38:20Z
38,938,225
<p>I'd suggest making an easily-editable list containing the minimum score required for a specific grade, from high to low:</p> <pre><code>minimum_scores = [("A", 9), ("B", 8), ("C", 7), ("D", 6)] </code></pre> <p>Then go through this list and print the first grade for which the student passed.</p> <pre><code>for gr...
1
2016-08-14T00:45:35Z
[ "python" ]
Separate by threshold
38,938,189
<p>I am trying to take the value of <code>c_med</code> one value as threshold from input:1 and separate the above and below values in two different outputs from input:2. Write <code>above.csv</code> &amp; <code>below.csv</code> with reference to column <code>c_total</code>.</p> <p>Read the <code>above.csv</code> as in...
1
2016-08-14T00:39:07Z
38,940,990
<p>assuming you have the following DFs:</p> <pre><code>In [7]: df1 Out[7]: date_count all_hours c_min c_max c_med c_med_med u_min u_max u_med u_med_med 0 2 12 2309 19072 12515 13131 254 785 686 751 In [8]: df2 Out[8]: date startTime endTime day c_to...
1
2016-08-14T09:44:24Z
[ "python", "csv", "pandas", "numpy" ]
Why WSGI Server need reload Python file when modified but PHP not need?
38,938,191
<p>I'm confused about this question. When do Django development, if I have modified the <code>py</code> file or static file, the build-in server will reload. But on PHP app development, if I have modified the files, the Apache Server do not need reload and the modified content will show on browser.</p> <p>Why?</p>
0
2016-08-14T00:39:47Z
38,941,344
<p>Django used to do the same back when CGI was the most common way to run dynamic web applications. It would create a new python process on each request, which would load all the files on the fly. But while PHP is optimized for this use-case with a fast startup time, Python, as a general purpose language, isn't, and t...
1
2016-08-14T10:30:40Z
[ "php", "python", "django" ]
How to override the pip command to Python3.x instead of Python2.7?
38,938,205
<p>I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command <code>pip2</code> to use Python2 and when I use the command <code>pip3</code> Python3.x will be used. The problem is that the default of <code>pip</code> is set to Python2.7 and I want it to be Python3.x.</p> <p>...
3
2016-08-14T00:42:32Z
38,938,246
<p>I always just run it via Python itself, this way:</p> <pre><code>python3 -m pip install some_module </code></pre> <p>or</p> <pre><code>python2 -m pip install some_module </code></pre> <p>The <code>-m</code> calls the <code>__main__.py</code> module of a specified package. Pip supports this.</p>
0
2016-08-14T00:50:00Z
[ "python", "python-3.x", "pip" ]
How to override the pip command to Python3.x instead of Python2.7?
38,938,205
<p>I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command <code>pip2</code> to use Python2 and when I use the command <code>pip3</code> Python3.x will be used. The problem is that the default of <code>pip</code> is set to Python2.7 and I want it to be Python3.x.</p> <p>...
3
2016-08-14T00:42:32Z
38,938,280
<p>For your projects, you should be using a <a href="http://docs.python-guide.org/en/latest/dev/virtualenvs/" rel="nofollow">virtualenv</a>.</p> <p>You can choose which python will be that of the virtualenv at creation time, by specifying it on the command line:</p> <pre><code>virtualenv -p python3 env # then . env/b...
2
2016-08-14T00:57:13Z
[ "python", "python-3.x", "pip" ]
How to override the pip command to Python3.x instead of Python2.7?
38,938,205
<p>I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command <code>pip2</code> to use Python2 and when I use the command <code>pip3</code> Python3.x will be used. The problem is that the default of <code>pip</code> is set to Python2.7 and I want it to be Python3.x.</p> <p>...
3
2016-08-14T00:42:32Z
38,938,282
<p>Although <a href="https://www.python.org/dev/peps/pep-0394/" rel="nofollow">PEP 394</a> does not specifically mention <code>pip</code>, it does discuss a number of other Python-related commands (including <code>python</code> itself). The short version is that, for reasons of backwards compatibility, the unversioned...
0
2016-08-14T00:57:36Z
[ "python", "python-3.x", "pip" ]
How to override the pip command to Python3.x instead of Python2.7?
38,938,205
<p>I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command <code>pip2</code> to use Python2 and when I use the command <code>pip3</code> Python3.x will be used. The problem is that the default of <code>pip</code> is set to Python2.7 and I want it to be Python3.x.</p> <p>...
3
2016-08-14T00:42:32Z
38,938,367
<p>Can't you <code>alias pip='pip3'</code> in your <code>~/.bash_profile</code>?</p> <p>In Terminal, run <code>nano ~/.bash_profile</code>, then add a line to the end that reads <code>alias pip='pip3'</code>. This is safe; it won't affect system processes, only your terminal.</p>
1
2016-08-14T01:16:43Z
[ "python", "python-3.x", "pip" ]
How to override the pip command to Python3.x instead of Python2.7?
38,938,205
<p>I am using OSX and I have pip installed for both Python3.5 and Python2.7. I know I can run the command <code>pip2</code> to use Python2 and when I use the command <code>pip3</code> Python3.x will be used. The problem is that the default of <code>pip</code> is set to Python2.7 and I want it to be Python3.x.</p> <p>...
3
2016-08-14T00:42:32Z
38,943,188
<p>Since you have specified in the comments you want syntax like <code>pip install [package]</code> to work, here is a solution:</p> <ol> <li><p>Install <code>setuptools</code> for <code>Python3</code>: <code>apt-get install python3-setuptools</code></p></li> <li><p>Now <code>pip</code> for <code>Python3</code> could ...
1
2016-08-14T14:26:47Z
[ "python", "python-3.x", "pip" ]
AttributeError: 'module' object has no attribute 'SFrame'
38,938,236
<p>I am taking ML course in Coursera and I have installed GraphLab Create and ipython notebook.I am new to ML and python.</p> <p>I get the following error,</p> <pre><code>import graphlab sf = graphlab.SFrame('people-example.csv') </code></pre> <blockquote> <p>AttributeError Traceback (most recent call last) in ...
1
2016-08-14T00:48:17Z
38,938,251
<p>Change it to:</p> <pre><code>sf = graphlab.SFrame.read_csv('people-example.csv') </code></pre>
0
2016-08-14T00:50:42Z
[ "python", "graphlab" ]
AttributeError: 'module' object has no attribute 'SFrame'
38,938,236
<p>I am taking ML course in Coursera and I have installed GraphLab Create and ipython notebook.I am new to ML and python.</p> <p>I get the following error,</p> <pre><code>import graphlab sf = graphlab.SFrame('people-example.csv') </code></pre> <blockquote> <p>AttributeError Traceback (most recent call last) in ...
1
2016-08-14T00:48:17Z
38,939,305
<p>Make sure the library <code>graphlab</code> is updated and works with your current python version. Changes on built-in libraries from python 2x to 3x are likely to cause issues like this one.</p>
0
2016-08-14T05:02:33Z
[ "python", "graphlab" ]
AttributeError: 'module' object has no attribute 'SFrame'
38,938,236
<p>I am taking ML course in Coursera and I have installed GraphLab Create and ipython notebook.I am new to ML and python.</p> <p>I get the following error,</p> <pre><code>import graphlab sf = graphlab.SFrame('people-example.csv') </code></pre> <blockquote> <p>AttributeError Traceback (most recent call last) in ...
1
2016-08-14T00:48:17Z
38,955,228
<p>You need to restart the ipython kernel on your iPython/Jupyter notebook for graphlab to see the dependencies in the correct locations.</p> <p>menu options:</p> <p><code>Kernel &gt; Restart</code></p> <p>and try again. Worked for me.</p>
0
2016-08-15T12:37:23Z
[ "python", "graphlab" ]
AttributeError: 'module' object has no attribute 'SFrame'
38,938,236
<p>I am taking ML course in Coursera and I have installed GraphLab Create and ipython notebook.I am new to ML and python.</p> <p>I get the following error,</p> <pre><code>import graphlab sf = graphlab.SFrame('people-example.csv') </code></pre> <blockquote> <p>AttributeError Traceback (most recent call last) in ...
1
2016-08-14T00:48:17Z
38,971,441
<p>In your iPython/Jupyter notebook follow these steps in this particular order.</p> <ol> <li>This will download and install dependencies. <code>graphlab.get_dependencies()</code> </li> <li><p>Restart Kernel : <code>Kernel &gt; Restart</code></p></li> <li><p>Now import graphlab: <code>import graphlab</code></p></li>...
2
2016-08-16T09:38:33Z
[ "python", "graphlab" ]
Cleaning data more efficiently in Pandas
38,938,254
<p>I have a python script that pulls EPS information from streetinsider.com. Currently I'm cleaning the data using an entirely inefficient method as seen below. Wondering if someone can show how this can be done more efficiently. </p> <p>The following example is very very scaled down, there are many more columns and m...
0
2016-08-14T00:51:07Z
38,938,731
<p>This is probably the easiest way to do it:</p> <pre><code>eps_table.replace('\+', '', regex=True).replace('%', '', regex=True).replace(',', '', regex=True) </code></pre> <p>output:</p> <pre><code> % Beat % Week 0 1405 123 </code></pre>
0
2016-08-14T02:51:14Z
[ "python", "pandas", "data-cleaning" ]
Cleaning data more efficiently in Pandas
38,938,254
<p>I have a python script that pulls EPS information from streetinsider.com. Currently I'm cleaning the data using an entirely inefficient method as seen below. Wondering if someone can show how this can be done more efficiently. </p> <p>The following example is very very scaled down, there are many more columns and m...
0
2016-08-14T00:51:07Z
38,938,748
<p>Do it all at once:</p> <pre><code>eps_table.replace(r'[%+,]', '', regex=True) </code></pre>
3
2016-08-14T02:54:42Z
[ "python", "pandas", "data-cleaning" ]
Why apply sometimes isn't faster than for-loop in pandas dataframe?
38,938,318
<p>It seems <code>apply</code> could accelerate the operation process on dataframe in most cases. But when I use <code>apply</code> I doesn't find the speedup. Here comes my example, I have a dataframe with two columns</p> <pre><code>&gt;&gt;&gt;df index col1 col2 1 10 20 2 20 30 3 30 40 </code></pre> <p>What I want ...
1
2016-08-14T01:05:50Z
38,938,507
<p>It is my understanding that <code>.apply</code> is <strong>not</strong> generally faster than iteration over the axis. I believe underneath the hood it is merely a loop over the axis, except you are incurring the overhead of a function call each time in this case. </p> <p>If we look at the <a href="https://github.c...
2
2016-08-14T01:52:31Z
[ "python", "pandas" ]
urllib3 segfault (core dumped)
38,938,381
<p>I'm getting a segfault ("Illegal operation (core dumped)") for a python program that I've run every week without fault for ages. I'm also running Ubuntu on Nitrous. I recall dealing with these yonks ago when coding in C, and I haven't had to deal with them very much recently.</p> <p>Importing the library urllib3 se...
1
2016-08-14T01:20:02Z
38,939,568
<blockquote> <p>"Illegal operation"</p> </blockquote> <p>This <em>usually</em> means that you are running code compiled for a more capable processor (e.g. <a href="https://en.wikipedia.org/wiki/Haswell_(microarchitecture)" rel="nofollow">Haswell</a>) on a less capable one (e.g. <a href="https://en.wikipedia.org/wiki...
0
2016-08-14T05:53:09Z
[ "python", "linux", "segmentation-fault", "urllib3" ]
Tweepy Django redirect
38,938,409
<p>I am working on a project with tweepy and django for some reason I cannot get the site to stop going to example.com with the response. I have tried deleteting example.com from the admin site and adding my host, as well as changing the default domain and the allowed hosts to my site. This is running on an ec2 instanc...
1
2016-08-14T01:26:58Z
38,938,690
<p>When we send the user to Twitter for authentication, Twitter redirects the user to the url we set as call back url in the app settings. </p> <p>You can however, override this callback url when sending the user to twitter for authorization. </p>
0
2016-08-14T02:42:21Z
[ "python", "django", "tweepy" ]
How to filter objects in django by hyperlink related field
38,938,421
<p>I have a model called car which contains a property <code>session</code> which is a HyperLinkRelatedField</p> <p>I am trying to filter the objects by that hyperlinkrelated field</p> <p>I tried something like this:</p> <pre><code>session_url = "http://localhost:8000/v1/sessions/"+uuid+"/" print cars.objects.filter...
0
2016-08-14T01:29:39Z
38,938,673
<p>You field <code>session</code> is a serializer field, not a model field. In the DRF these fields are usually computed based on the model data. The <code>HyperlinkedRelatedField</code> offers an easy way of putting URLs to ressourses into a response. On the other other hand it contais too much hard to parse data to ...
1
2016-08-14T02:38:40Z
[ "python", "django" ]
how to solve ? x and y must have same first dimension
38,938,437
<pre><code>from sklearn.neighbors import KNeighborsClassifier import pandas as pd from sklearn import metrics from sklearn.cross_validation import train_test_split import matplotlib.pyplot as plt r = pd.read_csv("vitalsign_test.csv") clm_list = [] for column in r.columns: clm_list.append(column) X = r[clm_list[1...
-1
2016-08-14T01:34:22Z
38,941,788
<p>It has nothing to do with your <code>X</code> and <code>y</code>, it is about <code>x</code> and <code>y</code> arguments to <strong>plot</strong>, since your <code>scores</code> has one element, and <code>k_range</code> has 25. The error is incorrect indentation:</p> <pre><code>for k in k_range: clf = KNeighbo...
0
2016-08-14T11:30:44Z
[ "python", "matplotlib", "machine-learning" ]
python saving multiple subplot figures to pdf
38,938,454
<p>I am new with python I am trying to save a huge bunch of data into a pdf with figures using PdfPages of matplotlib and subplots. Problem is that I found a blottleneck I dont know how to solve, the code goes something like:</p> <pre><code>import matplotlib.pyplot as plt from matplotlib.backends.backend_pdf import Pd...
1
2016-08-14T01:39:29Z
38,943,527
<p>To contain large numbers of subplots as multipage output inside a single pdf, all you need to do is create a new page immediately after detecting that the most recent subplot addition has maxed out the available space in the current page's subplot-array layout. Here's a way to do it where the dimensions controlling ...
1
2016-08-14T15:09:26Z
[ "python", "pdf", "matplotlib" ]
Simple Python documentation exception
38,938,457
<p>My code returns an exception from a documentation string, and I can't see the issue:</p> <pre><code>def printBreak(title): """Prints a dotted line""" print("------" + title + "------") def printWords(theWords): """Prints the passed array with word length and word""" for w in theWords: print...
0
2016-08-14T01:40:13Z
38,938,502
<p>You've mixed tabs and spaces, causing Python to get confused about what statements are at what indentation level. On Python 3, you're supposed to get an error specifically notifying you of inconsistent mixing of tabs and spaces, but it looks like that's not happening for some reason.</p> <p>Stop mixing tabs and spa...
4
2016-08-14T01:51:14Z
[ "python", "python-3.x" ]
Python - Pass a variable to lambda if it exists
38,938,464
<p>I'm curious about how to make code more efficient in Python, I've got to execute an action, which may or may not have a payload attached depending on the length of a list.</p> <p>Right now, I'm using an if statement to determine if there is a payload. Is there a better or cleaner way to find this?</p> <pre><code> ...
1
2016-08-14T01:41:26Z
38,938,477
<p>The code is efficient as is - instead of optimising for efficiency, try optimising for clarity first. If the code then becomes a performance hotspot... think about looking at the efficiency.</p> <hr> <p>Remembering that a <code>return</code> ends a function; this is a slightly cleaner alternative:</p> <pre><code>...
3
2016-08-14T01:45:38Z
[ "python", "lambda" ]
Python - Pass a variable to lambda if it exists
38,938,464
<p>I'm curious about how to make code more efficient in Python, I've got to execute an action, which may or may not have a payload attached depending on the length of a list.</p> <p>Right now, I'm using an if statement to determine if there is a payload. Is there a better or cleaner way to find this?</p> <pre><code> ...
1
2016-08-14T01:41:26Z
38,938,503
<p>Python comes with vararg syntax you can use for this directly.</p> <pre><code>return mec.action(*data[1:]) </code></pre> <p>(I'm assuming here that <code>data[2]</code> onwards aren't meaningful, or you could use <code>mec.action(*data[1:2])</code>)</p>
1
2016-08-14T01:51:42Z
[ "python", "lambda" ]
How to find the n-largest edge weights in a network matrix (networkx)?
38,938,571
<p>I have the following code that I attempt to use to generate a network matrix. With this matrix, I would like to find the 20 highest-weighted edges that ARE NOT on the diagnal (<em>i.e.</em> <code>i!=j</code> in the matrix). I also would like to get the names of the nodes (in pairs) composed of these edges.</p> <p...
1
2016-08-14T02:11:24Z
38,940,008
<p>The issue with this line:</p> <pre><code>heapq.nlargest(20, A_square) </code></pre> <p>Is that <code>nlargest</code> does not expect an iterable of iterables, but an interable of numbers.</p> <p>So you could do this instead:</p> <pre><code>heapq.nlargest(20, itertools.chain.from_iterable(A_square)) </code></pre>...
1
2016-08-14T07:14:13Z
[ "python", "matrix", "heap", "networkx" ]
String variable doesn't print correctly
38,938,629
<p>So I am writing a multi-client chat and I would like to display the name of every client in front of the message. when I print the variable "client_name" in the main function (the line "clients_dictionary[current_socket.getpeername()]" returns the value it's supposed to, doesn't return None) by itself it shows up fi...
1
2016-08-14T02:28:15Z
38,939,944
<p>anyway you better be use python string formatting: </p> <pre><code>chat_msg = '{}: {}'.format(client_name, data) </code></pre>
3
2016-08-14T07:01:53Z
[ "python", "python-2.7", "sockets", "chat" ]
Different renders of RGB data in scipy vs pyplot
38,938,640
<p>I'm implementing a fractal-flame renderer for kicks and giggles, and got hung up on a silly little color problem. After running the algorithm, I get a RGBA matrix (HxWxC, specifically I have 1080x1440x4), but I get different results when rendering it with pyplot than I do with scipy. Here's the output code:</p> <pr...
1
2016-08-14T02:30:37Z
38,939,075
<p>When saving a floating point array, <code>scipy.misc.imsave()</code> (which uses Pillow to do the actual work) effectively scales the values in the array to the interval [0, 1]. <code>plt.imsave()</code>, on the other hand, appears to <em>clip</em> the values to the interval [0, 1], without changing the values that...
0
2016-08-14T04:17:18Z
[ "python", "numpy", "matplotlib", "colors", "scipy" ]
Django Flatpages Using: Site matching query does not exist
38,938,649
<p>I'm a noob at Django.</p> <p>I've created a flatpages object in my admin console when I visit the url which I run on a local server, I get a "Site Matching query does not exist" error. Can someone help me?</p> <pre><code>urlpatterns = [ url(r'^', include('main.urls')), url(r'^home/', include('django.contri...
1
2016-08-14T02:33:08Z
38,939,515
<p>Perhaps you have not defined <a href="https://docs.djangoproject.com/en/1.10/ref/settings/#std:setting-SITE_ID" rel="nofollow">SITE_ID</a> in settings.</p>
0
2016-08-14T05:43:28Z
[ "python", "django" ]
Django .all() query on a unique_together model
38,938,655
<p>I have a model with two fields that are unique together:</p> <pre><code>class Servers(models.Model): server_id = models.IntegerField(db_column='server_id') nodename = models.CharField(max_length=40) tag_name = models.CharField(max_length=180) customer = models.ForeignKey(Customers, on_delete=models....
0
2016-08-14T02:34:47Z
38,938,710
<p>You have <code>managed</code> set to <code>False</code>. So, Django is not creating the default primary key (<code>id</code>) on the table. </p> <p>When you're later trying to query it, Django ORM looks for the <code>id</code> and it fails. </p> <p>You need to have at least one primary key. So create a new field o...
2
2016-08-14T02:47:20Z
[ "python", "mysql", "django", "django-forms" ]
Why does cos(x) give me a result of x as x was in radians?
38,938,664
<p>I am using Python but there is something strange. Why does cos(x) give me a result of x as was in radians? while cos(radians(x)) gives the answer as x was in degree</p> <p>for example :</p> <pre><code>&gt;&gt;&gt; cos(75) 0.9217512697247493 </code></pre> <p>but the truth is if 75 is in degree, then cos(75) = 0.2...
-1
2016-08-14T02:37:05Z
38,938,685
<ul> <li><code>cos(75)</code> means "the cosine of 75 radians". (See <a href="https://docs.python.org/3/library/math.html#trigonometric-functions">documentation</a>.)</li> <li><code>radians(75)</code> means "convert 75&deg; to radians", i.e. "the number of radians that's equivalent to 75&deg;". (See <a href="https://do...
5
2016-08-14T02:41:19Z
[ "python", "math", "cos" ]
Convert list of Dictionaries of lists to DataFrame Table in Python
38,938,680
<p>I have a list of dictionaries that i'd like to convert into a data frame table. I know the question in the title is a little confusing, so ill post the dictionary:</p> <pre><code>[{'MESSAGE': ['RECEIVED SUCCESSFULLY AWAITING STOCKING PROCESS'], 'BIN': ['8FHA9D83H 82HG7D9F'], 'INV': 'SSXR 98-20LM NM CORN CREAM'}, ...
-1
2016-08-14T02:40:16Z
38,942,473
<p>Assuming L is your list of dicts:</p> <pre><code>pd.concat(pd.DataFrame(l) for l in L) Out: BIN INV \ 0 8FHA9D83H 82HG7D9F SSXR 98-20LM NM CORN CREAM 0 HA8DHWO2H HAHD0138 FPBC *SOUP CANS LENTILS 1 8SHDNAIDU 00AD0123 FPBC *SOUP CANS LENTILS 2 ...
2
2016-08-14T12:58:02Z
[ "python", "pandas", "dictionary" ]
Python: Generating list of numbers 1-10, but 1 ends up at the end of the list?
38,938,688
<p>I have just started learning how to program using Python, and have been going through some exercises to help me improve. For one of the exercises, I have to program a Sieve of Eratosthenes, and as part of doing this, I wanted to generate a list of numbers 1 through <em>n</em>. </p> <p>My code is as follows:</p> <p...
1
2016-08-14T02:41:28Z
38,938,730
<p>I don't know why it's backwards, but your code is not the way to add elements to a list. Also you don't use the variable <code>n</code> in your code (probably a typo), so I will just add the function to generate a list through 1 to <code>n</code>.</p> <pre><code>def primelist(n): grid=[] for k in range(1,n+...
0
2016-08-14T02:51:13Z
[ "python", "list" ]
Python: Generating list of numbers 1-10, but 1 ends up at the end of the list?
38,938,688
<p>I have just started learning how to program using Python, and have been going through some exercises to help me improve. For one of the exercises, I have to program a Sieve of Eratosthenes, and as part of doing this, I wanted to generate a list of numbers 1 through <em>n</em>. </p> <p>My code is as follows:</p> <p...
1
2016-08-14T02:41:28Z
38,938,749
<p>In Python, <code>list.insert(index, item)</code> actually inserts <code>item</code> BEFORE <code>index</code>. </p> <p>So <code>list.insert(-1, k)</code>inserts <code>k</code> before -1. Hence your results.</p> <p>To do what you want to do properly, the following two lines are equivalent</p> <pre><code>list.inser...
3
2016-08-14T02:55:00Z
[ "python", "list" ]
Python: Generating list of numbers 1-10, but 1 ends up at the end of the list?
38,938,688
<p>I have just started learning how to program using Python, and have been going through some exercises to help me improve. For one of the exercises, I have to program a Sieve of Eratosthenes, and as part of doing this, I wanted to generate a list of numbers 1 through <em>n</em>. </p> <p>My code is as follows:</p> <p...
1
2016-08-14T02:41:28Z
38,938,831
<p>xrange can do this for you, remember to give xrange a end value that is one more than the one you want. </p> <p>So to generate numbers from 1 to n : xrange(1,n+1)</p> <p>The example below will give you a list from 1 to 10.</p> <pre><code>&gt;&gt;&gt; primelist=list(xrange(1,11)) &gt;&gt;&gt; primelist [1, 2, 3, 4...
0
2016-08-14T03:17:33Z
[ "python", "list" ]
Python: Generating list of numbers 1-10, but 1 ends up at the end of the list?
38,938,688
<p>I have just started learning how to program using Python, and have been going through some exercises to help me improve. For one of the exercises, I have to program a Sieve of Eratosthenes, and as part of doing this, I wanted to generate a list of numbers 1 through <em>n</em>. </p> <p>My code is as follows:</p> <p...
1
2016-08-14T02:41:28Z
38,938,881
<p><code>insert</code> method for list inserts the element at the index before the first argument. <code>-1</code> is the index of last element. So, when you are inserting at <code>-1</code>, you are always inserting just before the last element. For example you have a list <code>a</code> as:</p> <pre><code>a = [1,2,3...
1
2016-08-14T03:30:53Z
[ "python", "list" ]
Why does virtualenv create the environments with Python2.7 if I installed it using pip3?
38,938,700
<p>I installed virtualenv using <code>sudo pip3 install virtualenv --upgrade</code>, and yet every time I create a new environment (<code>virtualenv test</code>) it's running python2.7... </p> <p>I know I can create the env. via <code>virtualenv -p python3 test</code>, but I don't want to do that. Virtualenv states th...
0
2016-08-14T02:45:00Z
38,938,770
<p>On my machine, when I do this:</p> <pre><code>$ virtualenv[hit-tab-now-for-autocomplete] virtualenv virtualenv-2.7 virtualenv-3.4 </code></pre> <p>So, I can simply do:</p> <pre><code>$ virtualenv-3.4 test </code></pre>
1
2016-08-14T02:59:54Z
[ "python", "pip", "virtualenv" ]
How can i print the square roots of odd numbers in a given list by using lis comprehension only?
38,938,811
<p>The below gives only the odd numbers, but not the square roots. How can I add additional features like writing the square roots for the odd numbers?</p> <pre><code>my_list=[x for x in range(1,10) if x%2!=0] print my_list </code></pre>
-1
2016-08-14T03:11:31Z
38,938,815
<p>Where you insert the value of <code>x</code> into the array, take the square root of it.</p> <pre><code>my_list=[x**.5 for x in range(1,10) if x%2!=0] </code></pre> <p>You can also use the <strong><a href="https://docs.python.org/2/library/math.html" rel="nofollow"><code>math</code></a></strong> module, and specif...
2
2016-08-14T03:13:23Z
[ "python" ]
Pycharm can't change interpreter from python 2.7 to 3.4
38,938,830
<p>Im currently working on an open source Python project on Xubuntu Linux 3.19.0-51-generic x86_64 using Pycharm. Even though I my project requires Python 3.4 or greater, the IDE seems to force the project to use Python 2.7. I've tried to change the interpreter from the Project Interpreter menu (see screenshot), and we...
0
2016-08-14T03:17:28Z
38,939,339
<p>Try to setup different interpreter in run/debug configuration in the same manner as suggested in <a href="https://stackoverflow.com/a/23524553/5485944">this answer</a>.</p> <p>Main Menu -> Run -> Edit Configurations...</p> <p><a href="http://i.stack.imgur.com/gpnJp.png" rel="nofollow"><img src="http://i.stack.imgu...
2
2016-08-14T05:09:24Z
[ "python", "pycharm", "jetbrains", "anki" ]
script to split file name into part1 and part2 and create directory part1 and put file part2 into part1 directory
38,938,908
<p>I have bunch of files of the form st_hwk.txt If you must know, this is how Moodle downloads assignments for grading. It takes the name of the hwk and prepands the user name. This solution needs to work on Linux bc that is what I am working on. Ex: I download j smith_hwk1a.txt, j smith_hwk1b.txt, m wong_hwk1a.txt, m ...
-2
2016-08-14T03:38:32Z
39,032,194
<pre><code>for f in *_hwk*.txt; do n=$(echo "$f"|tr -d ' '|tr _ /); # delete spaces, convert _ to / mkdir -p "$(dirname "$n")"; # make directory if needed mv "$f" "$n"; # move the file done </code></pre>
0
2016-08-19T06:11:48Z
[ "python", "linux", "bash", "split", "directory" ]
Installing weblate 2.3: from django.db.models.sql.aggregates ImportError: No module named aggregates
38,938,947
<p>While installing <a href="https://weblate.org/en/" rel="nofollow">weblate</a> 2.3 (older version), I had the following error:</p> <blockquote> <p>File "/srv/weblate/weblate/trans/boolean_sum.py", line 27, in from django.db.models.sql.aggregates import Sum as BaseSQLSum ImportError: No module named aggreg...
0
2016-08-14T03:46:40Z
38,938,948
<p>I took a look at my django version, and it was the latest one, which doesn't have a <code>aggregates.py</code> in <a href="https://github.com/django/django/tree/master/django/db/models/sql" rel="nofollow"><code>django/db/models/sql/</code></a>. I took a look at <a href="https://github.com/nijel/weblate/blob/weblate-...
1
2016-08-14T03:46:40Z
[ "python", "django", "pip", "importerror", "weblate" ]
Python - Convert a list to a list of lists
38,938,957
<p>I'm trying to create a list of lists, such that each inner list has 8 elements, in a python one-liner.</p> <p>So far I have the following:</p> <pre><code>locations = [[alphabet.index(j) for j in test]] </code></pre> <p>That maps to one big list inside of a list:</p> <pre><code>[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,...
1
2016-08-14T03:48:50Z
38,938,981
<p>Use list slicing with <code>range()</code> to get the starting indexes:</p> <pre><code>In [3]: test = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] In [4]: [test[i:i+8] for i in range(0, len(test), 8)] Out[4]: [[1, 2, 3, 4, 5, 6, 7, 8], [9, 10, 11, 12, 13, 14, 15, 16]] </code></pre> <p>As a function:</p> <pre><code>I...
1
2016-08-14T03:55:17Z
[ "python", "list", "nested-lists" ]
Python - Convert a list to a list of lists
38,938,957
<p>I'm trying to create a list of lists, such that each inner list has 8 elements, in a python one-liner.</p> <p>So far I have the following:</p> <pre><code>locations = [[alphabet.index(j) for j in test]] </code></pre> <p>That maps to one big list inside of a list:</p> <pre><code>[[1,2,3,4,5,6,7,8,9,10,11,12,13,14,...
1
2016-08-14T03:48:50Z
38,939,534
<p>Another solution could be to use NumPy</p> <pre><code>import numpy as np data = [x for x in xrange(0, 64)] data_split = np.array_split(np.asarray(data), 8) </code></pre> <p>Output:</p> <pre><code>for a in data_split: print a [0 1 2 3 4 5 6 7] [ 8 9 10 11 12 13 14 15] [16 17 18 19 20 21 22 23] [24 25 26 27 ...
0
2016-08-14T05:46:09Z
[ "python", "list", "nested-lists" ]
within python for loop calling more than one functions
38,938,992
<p>the following code filters images, now I would like to call two functions for each image in a for loop one by one; first <code>check_image_size</code> and then <code>binarization</code>. I am having trouble figuring out the correct syntax. </p> <pre><code>import os, sys check_image_size(pic) binarization(pic) fol...
1
2016-08-14T03:57:29Z
38,939,004
<p>What you are doing here is not the actual way to define a for loop. What you are using is list comprehension.</p> <h1>What is list comprehension?</h1> <p>List comprehension is used to quickly equate values for loops. For example:</p> <pre><code>x = [] for i in range(10): if i % 2 == 0: x.append(i) </c...
1
2016-08-14T04:01:44Z
[ "python" ]
python split string that by space and new line character
38,939,022
<p>I have this code:</p> <pre><code>f1=open('test.txt','r') d={} line = f1.read().replace('\n',' ') line2= line.split("\n") </code></pre> <p><code>line = "This is line1\nthis isline2\nthis is line3"</code></p> <p>My question is: can I do a split with multiple delimiters rather than replace first, then do a split?</p...
1
2016-08-14T04:06:01Z
38,939,049
<p>Use <a href="https://docs.python.org/2/library/re.html#re.split" rel="nofollow"><code>re.split()</code></a>.</p> <p>Splitting on <code>\n</code> and <code>\t</code>:</p> <pre><code>In [23]: line = "This is line1\nthis isline2\tthis is line3" In [24]: re.split(r'[\n\t]', line) Out[24]: ['This is line1', 'this isli...
2
2016-08-14T04:11:31Z
[ "python", "split" ]
Vim & GAE - Is there anyway to debug python gae applications using vim?
38,939,029
<p>I know that there are plugins to debugging python in vim like this one:<a href="https://github.com/joonty/vdebug" rel="nofollow">https://github.com/joonty/vdebug</a></p> <p>What I'm struggling is to find a way to debug GAE apps, is that even possible? If so what steps should I take to make it work?</p> <p>Thanks</...
2
2016-08-14T04:08:07Z
38,947,127
<p>If you're running the GAE app locally with the development server, you should be able to debug the python runtime the same way that you'd debug other local processes.</p> <p>You can't use vim to debug processes running on the Google runtimes in Google's datacenters. You might be able to use the <a href="https://clo...
1
2016-08-14T22:21:06Z
[ "python", "google-app-engine", "debugging", "vim" ]
Saving model in tensorflow
38,939,081
<p>Tensorflow allows us to save/load model's structure, using method tf.train.write_graph, so that we can restore it in the future to continue our training session. However, I'm wondering that if this is necessary because I can create a module, e.g GraphDefinition.py, and use this module to re-create the model. So, whi...
0
2016-08-14T04:19:20Z
38,951,015
<p>First of all you have to understand, that tensorflow graph does not have current weights in it (until you save them manually there) and if you load model structure from graph.pb, you will start you train from the very beginning. But if you want to continue train or use your trained model, you have to save checkpoint...
0
2016-08-15T07:33:05Z
[ "python", "python-2.7", "tensorflow" ]
Spotify - access token from command line
38,939,085
<p>I am testing my <code>app</code> using the <code>terminal</code>, which is quite handy in a pre-development phase.</p> <p>so far, I have used <code>spotipy.Spotify(client_credentials_manager=client_credentials_manager)</code> within my <code>python</code> scripts in order to access data. </p> <p><code>SpotifyClien...
0
2016-08-14T04:19:58Z
39,049,945
<p>Copy and paste the entire redirect URI from your browser to the terminal (when prompted) after successful authentication. Your access token will be cached in the directory (look for <code>.cache.&lt;username&gt;</code>) </p>
0
2016-08-20T02:41:02Z
[ "python", "command-line", "spotify", "spotipy" ]
How to effectively update the attributes of an object
38,939,096
<p>I am creating a "pet game" in order to train my computing skills in python (that is just an excuse: it is because it is fun).</p> <p>I decided to do a simple RPG game. For that, I defined the class <em>hero</em>:</p> <pre><code>class hero: #Common class for the main character def __init__(self, name, lvl, ...
0
2016-08-14T04:22:27Z
38,939,120
<p>Make <code>dmg</code> a property instead of setting in the <code>__init__</code> function. The <code>__init__</code> only runs when the instance is initialized, which is why things aren't updating. However, making it a property runs the method whenever the property is accessed.</p> <pre><code>@property def dmg(self...
1
2016-08-14T04:26:18Z
[ "python", "object" ]
How to effectively update the attributes of an object
38,939,096
<p>I am creating a "pet game" in order to train my computing skills in python (that is just an excuse: it is because it is fun).</p> <p>I decided to do a simple RPG game. For that, I defined the class <em>hero</em>:</p> <pre><code>class hero: #Common class for the main character def __init__(self, name, lvl, ...
0
2016-08-14T04:22:27Z
38,939,213
<p>It's better to use inheritance in your case:</p> <pre><code>class Hero(object): def __init__(self, name, lvl, _str, agi, vit, _int, luk): self.name = name self.lvl = lvl self._str = _str # Should not use "str" because of reserved keyword of the same name self.agi = agi s...
1
2016-08-14T04:47:00Z
[ "python", "object" ]
Random picking 3 chosen numbers
38,939,129
<p>Ok, I am creating a game and no matter what I do, it just isn't working. So I have 3 numbers chosen, 25,50,75. I want to be able to random pick one of them. Then I will need to be able to add it to a total making it obviously an integer. I have imported random. I have tried random.sample but I can't get that one to ...
1
2016-08-14T04:28:22Z
38,939,137
<p>Use <a href="https://docs.python.org/2/library/random.html#random.choice" rel="nofollow"><code>random.choice</code></a>:</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; random.choice([25,50,75]) 25 &gt;&gt;&gt; random.choice([25,50,75]) 25 &gt;&gt;&gt; random.choice([25,50,75]) 75 </code></pre>
4
2016-08-14T04:30:09Z
[ "python" ]
Random picking 3 chosen numbers
38,939,129
<p>Ok, I am creating a game and no matter what I do, it just isn't working. So I have 3 numbers chosen, 25,50,75. I want to be able to random pick one of them. Then I will need to be able to add it to a total making it obviously an integer. I have imported random. I have tried random.sample but I can't get that one to ...
1
2016-08-14T04:28:22Z
38,939,196
<p><a href="https://docs.python.org/3/library/random.html#random.choice" rel="nofollow"><code>random.choice()</code></a> is the way to go, however, <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow"><code>random.sample()</code></a> will also work if you use a sample size of 1 <em>and</...
0
2016-08-14T04:41:59Z
[ "python" ]
Simple TensorFlow Neural Network minimizes cost function yet all results are close to 1
38,939,221
<p>So I tried implementing the neural network from:</p> <p><a href="http://iamtrask.github.io/2015/07/12/basic-python-network/" rel="nofollow">http://iamtrask.github.io/2015/07/12/basic-python-network/</a></p> <p>but using TensorFlow instead. I printed out the cost function twice during training and the error is appe...
0
2016-08-14T04:48:06Z
38,939,400
<p>First of all: you have no hidden layer. As far as I remember basic perceptrons could possibly model the XOR problem, but it needed some adjustments. However, AI is just invented by biology, but it does not model real neural networks exactly. Thus, you have to at least build an MLP (<a href="https://en.wikipedia.org/...
1
2016-08-14T05:19:55Z
[ "python", "machine-learning", "neural-network", "tensorflow" ]