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
Divide date as day,month and year
39,301,871
<p>l have 41 year-dataset and l would like to do some calculations by using these dataset but for this, l need to divide the date into day, month and year respectively.</p> <p>example dataset(csv file data)</p> <pre><code> date stations pcp 1.01.1979 6 1.071 2.01.1979 6 5.909 3.01.1979 6 9.134 1....
0
2016-09-02T23:31:49Z
39,302,249
<p>this script will get you a list of lists with your values and will also write the final list into a csv.</p> <pre><code>import csv with open('p2.csv') as csvfile: x=[] reader = csv.reader(csvfile,delimiter=',', quotechar='|') for num, row in enumerate(reader): for i, item in enumerate(row): ...
0
2016-09-03T00:40:18Z
[ "python", "date", "csv" ]
numpy.unique gives non-unique output?
39,301,882
<p>I am trying to get the indices of unique elements of a numpy array (long vector of 3628621 elements). However, I must do something wrong, because when I try to select the unique elements I am still finding duplicates:</p> <pre><code>Vector Out[165]: array([712450, 714390, 718560, ..., 384390, 992041, 94852]) Loc ...
-1
2016-09-02T23:33:42Z
39,302,318
<p><code>np.unique</code> has several parameters that can be activated and will give you the needed information. It's calling signature is:</p> <pre><code>np.unique(ar, return_index=False, return_inverse=False, return_counts=False) </code></pre> <p>read the docs.</p> <pre><code>In [50]: keys Out[50]: array([1, 3, ...
1
2016-09-03T00:55:05Z
[ "python", "numpy", "unique" ]
What is the difference between 'with open(...)' and 'with closing(open(...))'
39,301,983
<p>From my understanding,</p> <pre><code>with open(...) as x: </code></pre> <p>is supposed to close the file once the <code>with</code> statement completed. However, now I see</p> <pre><code>with closing(open(...)) as x: </code></pre> <p>in one place, looked around and figured out, that <code>closing</code> is supp...
4
2016-09-02T23:53:17Z
39,302,016
<p>Assuming that's <code>contextlib.closing</code> and the standard, built-in <code>open</code>, <code>closing</code> is redundant here. It's a wrapper to allow you to use <code>with</code> statements with objects that have a <code>close</code> method, but don't support use as context managers. Since the file objects r...
14
2016-09-02T23:57:41Z
[ "python" ]
Submitting Python Application with Apache Spark Submit
39,302,113
<p>I am trying to follow the examples on the Apache Spark documentation site: <a href="https://spark.apache.org/docs/2.0.0-preview/submitting-applications.html" rel="nofollow">https://spark.apache.org/docs/2.0.0-preview/submitting-applications.html</a></p> <p>I started a Spark standalone cluster and want to run the ex...
0
2016-09-03T00:15:08Z
39,347,226
<p>The <code>PYSPARK_DRIVER_PYTHON</code> and <code>PYSPARK_DRIVER_PYTHON_OPTS</code> are meant for running the ipython/jupyter shell when opening the pyspark shell ( More info at <a href="http://stackoverflow.com/questions/31862293/how-to-load-ipython-shell-with-pyspark">How to load IPython shell with PySpark</a> ).</...
0
2016-09-06T10:51:25Z
[ "python", "apache-spark", "pyspark" ]
Getting Flask to Run on Apache on Ubuntu
39,302,129
<p>Having trouble getting Flask to run on Apache. Followed the directions <a href="https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps" rel="nofollow">here</a> to setup mod_wsgi. I put my desired python code into the <code>/var/www/TDAA_reminder/TDAA_reminder/__init__.py<...
0
2016-09-03T00:17:48Z
39,419,555
<p>Answered in comments via following discussion: </p> <blockquote> <p>what was the error from the Apache error log file? If the guide says to have it twice, the guide is technically wrong. It has to be /var/www/TDAA_reminder as that is the directory the WSGI script file is in. Without it, Apache shouldn't be ...
0
2016-09-09T20:54:03Z
[ "python", "apache", "ubuntu", "flask", "mod-wsgi" ]
Python: Ignore case sensitivity for MYSQL column names
39,302,170
<p>I am querying my MySQL DB with following code. </p> <pre><code>import MySQLdb db = MySQLdb.connect("localhost","user","password","test" ) cursor = db.cursor(MySQLdb.cursors.DictCursor) sql = "select * from student" try: cursor.execute(sql) results = cursor.fetchall() for row in results: print r...
0
2016-09-03T00:26:08Z
39,302,305
<p>you can use this:</p> <pre><code>sequence = cursor.column_names </code></pre> <p><a href="https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html" rel="nofollow">https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-column-names.html</a></p> <p>The...
1
2016-09-03T00:51:57Z
[ "python", "mysql" ]
Django ORM query for empty FileFields
39,302,175
<p>It's not clear to me whether this is possible through the ORM - it doesn't appear so, but maybe I'm missing something?</p> <pre><code> class ApplicationInstitution(models.Model): ... transcript_file = FileField(upload_to=...) </code></pre> <p>Some of those <code>ApplicationInstitution</code> object...
0
2016-09-03T00:26:46Z
39,302,287
<pre><code>transcript_file = FileField(upload_to=..., null=True) </code></pre> <p>and try this for <code>ApplicationInstitution</code> without file:</p> <pre><code>ApplicationInstitution.objects.filter(transcript_file__isnull=True) </code></pre> <p>for <code>ApplicationInstitution</code> with file:</p> <pre><code>A...
-1
2016-09-03T00:48:56Z
[ "python", "django", "orm" ]
Django ORM query for empty FileFields
39,302,175
<p>It's not clear to me whether this is possible through the ORM - it doesn't appear so, but maybe I'm missing something?</p> <pre><code> class ApplicationInstitution(models.Model): ... transcript_file = FileField(upload_to=...) </code></pre> <p>Some of those <code>ApplicationInstitution</code> object...
0
2016-09-03T00:26:46Z
39,307,388
<p>You can query for empty strings:</p> <pre><code># instances with empty FileField ApplicationInstitution.objects.filter(transcript_file='') # and with a file already uploaded ApplicationInstitution.objects.exclude(transcript_file='') </code></pre>
1
2016-09-03T13:22:25Z
[ "python", "django", "orm" ]
Python background shell script communication
39,302,190
<p>I have 2 python scripts, <code>foo.py</code> and <code>bar.py</code>. I am running foo.py in the background using</p> <pre><code>python foo.py &amp; </code></pre> <p>Now I want to run <code>bar.py</code> and use the stdout from this file to trigger script inside foo.py. Is this possible? I'm using Ubuntu 16.04 LTS...
1
2016-09-03T00:28:53Z
39,302,263
<p>There is a system that actually comes from UNIX world that creates <code>pipes</code> between processes. A pipe is basically a pair of file descriptors, each program having access to one of them. One program writes to the pipe, while the other reads:</p> <p><a href="https://docs.python.org/2/library/subprocess.html...
0
2016-09-03T00:43:15Z
[ "python", "shell", "background-process" ]
Python background shell script communication
39,302,190
<p>I have 2 python scripts, <code>foo.py</code> and <code>bar.py</code>. I am running foo.py in the background using</p> <pre><code>python foo.py &amp; </code></pre> <p>Now I want to run <code>bar.py</code> and use the stdout from this file to trigger script inside foo.py. Is this possible? I'm using Ubuntu 16.04 LTS...
1
2016-09-03T00:28:53Z
39,302,292
<p>You could use <a href="https://en.wikipedia.org/wiki/Named_pipe" rel="nofollow">UNIX named pipe</a> for that.</p> <p>First, you create named pipe object by executing <code>mkfifo named_pipe</code> in the same directory, where you have your python files.</p> <p>Your <code>foo.py</code> then could look like this:</p...
1
2016-09-03T00:49:50Z
[ "python", "shell", "background-process" ]
Getting a cropped combination of 9 2D numpy arrays (only want boundaries of middle array)
39,302,252
<p>I have 9 individual 2D numpy arrays that are each 3x3, I want to join at the edges like example:</p> <p><code> 111222333 111222333 111222333 444555666 444555666 444555666 777888999 777888999 777888999 </code></p> <p>Except I only want the nearby boundaries of any array that isn't the middle one, like example:</p> ...
0
2016-09-03T00:41:01Z
39,302,304
<p>Since you know you want to drop the first and last two columns of your 9x9 array, I would just use NumPy's indexing:</p> <pre><code>&gt;&gt;&gt; x = np.arange(81).reshape((9,9)) &gt;&gt;&gt; x array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8], [ 9, 10, 11, 12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23, 2...
1
2016-09-03T00:51:41Z
[ "python", "arrays", "numpy" ]
Reducing the brightness of an LED Strip (Adafruit Dotstar RGB Strip) using Python
39,302,267
<p>I have this code below piping data to a strip of RGB LEDs. The code works fine. The Adafruit Dotstar libray (<a href="https://github.com/adafruit/Adafruit_DotStar" rel="nofollow">https://github.com/adafruit/Adafruit_DotStar</a>) also has a strandtest.py example in addition to the code below. In the test example i...
0
2016-09-03T00:44:18Z
39,309,152
<p>Here is a solution to reducing pixel brightness provided by Adafruit Industries. Thanks Adafruit!</p> <pre><code> column[x][y4 + rOffset] = gamma[value[0]/2] # Gamma-corrected R column[x][y4 + gOffset] = gamma[value[1]/2] # Gamma-corrected G column[x][y4 + bOffset] = gamma[value[2]/2] # Gamma-corrected B </co...
0
2016-09-03T16:39:16Z
[ "python", "debugging", "raspberry-pi", "led" ]
concatinate pandas dataframe to multiindex
39,302,275
<p>I have a pandas dataframe like this </p> <pre><code>df1=pd.DataFrame(np.random.randint(0,10,size=(3,3)),columns=list('ABC')) df1.index.name="ID1" df2=pd.DataFrame(np.random.randint(0,10,size=(3,3)),columns=list('ABC')) df2.index.name="ID2" </code></pre> <p>so,How can I concatinate like below,this dataframe have...
2
2016-09-03T00:46:25Z
39,302,293
<p>Concat is correct</p> <pre><code>pd.concat([df1,df2], keys=['id1', 'id2']) </code></pre>
2
2016-09-03T00:50:03Z
[ "python", "pandas" ]
Datetime object with timezone
39,302,385
<p>How do I get an aware datetime object using the modified timestamp from a file? I've done it this way:</p> <pre><code>modified = datetime.datetime.fromtimestamp(os.path.getmtime(myfile)) isotime = modified.strftime('%Y-%m-%d %H:%M:%S %z') </code></pre> <p>but this just gets me a naive time, so %z is a blank string...
1
2016-09-03T01:10:16Z
39,302,542
<p>It is pain in the ass to get the current time zone using python standart library.</p> <p>Just install <a href="https://dateutil.readthedocs.io/en/stable/tz.html" rel="nofollow"><code>dateutil</code></a> package:</p> <pre><code>$ sudo pip install python-dateutil </code></pre> <p>and you can do the following:</p> ...
1
2016-09-03T01:51:15Z
[ "python", "datetime" ]
String not in string
39,302,405
<p>So I have two strings</p> <p><code>a = "abc"</code> and <code>b = "ab"</code></p> <p>Now I am trying to find the characters in a which are not present in b</p> <p>The code that I have is : </p> <pre><code>for element in t: if element not in s: print element </code></pre> <p>This is giving some err...
-1
2016-09-03T01:15:24Z
39,302,410
<p>This is the sort of thing that a <code>set</code> is really good for:</p> <pre><code>&gt;&gt;&gt; a = "abc" &gt;&gt;&gt; b = "abd" &gt;&gt;&gt; set(a).difference(b) set(['c']) </code></pre> <p>This gives you items in <code>a</code> that aren't in <code>b</code>. If you want the items that only appear in one or th...
3
2016-09-03T01:17:07Z
[ "python", "string", "python-2.7" ]
How do I get a datetime object out of a YYYY-Q string?
39,302,412
<p>The <a href="https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior" rel="nofollow">datetime.strptime</a> reference does not provide an option for the YYYY-Qx (with x = {1,...,4}) date format. Do I need the <a href="http://dateutil.readthedocs.io/en/stable/parser.html" rel="nofollow">dateutil.par...
0
2016-09-03T01:19:08Z
39,302,458
<p>You could simply hard-code the relationship between quarters and dates, and use <code>re.sub</code> to replace <code>Q(\d)</code> with the appropriate value:</p> <pre><code>import re def df_quarter(date): q = {'1':'02-15', '2':'05-15', '3':'08-15', '4':'11-15'} return re.sub('Q(\d)', lambda match, q=q: q[ma...
0
2016-09-03T01:29:16Z
[ "python", "date", "datetime" ]
Invalid Syntax Error - Average Calculator "IF" and "WHILE"
39,302,442
<p>I have no idea what I'm doing wrong, but this is driving me up a wall. Why am I getting a Syntax error? I have to code an average calculator using a while statement, where "0" defines that the program needs to perform the calculation.</p> <p><a href="http://i.stack.imgur.com/umYUV.png" rel="nofollow"><img src="http...
-3
2016-09-03T01:26:19Z
39,302,470
<p>I've fixed your code for you. For future questions, please post your code directly in your question and indent it all by 4 spaces to properly format it. </p> <pre><code>addition_integer = 0 divison_integer = 0 while True: test = int(input("Enter test score: ")) if test == 0: break else: ...
1
2016-09-03T01:34:31Z
[ "python", "if-statement", "while-loop", "syntax-error", "average" ]
Invalid Syntax Error - Average Calculator "IF" and "WHILE"
39,302,442
<p>I have no idea what I'm doing wrong, but this is driving me up a wall. Why am I getting a Syntax error? I have to code an average calculator using a while statement, where "0" defines that the program needs to perform the calculation.</p> <p><a href="http://i.stack.imgur.com/umYUV.png" rel="nofollow"><img src="http...
-3
2016-09-03T01:26:19Z
39,302,482
<p>The <code>if</code> statement in the image (please post the actual code in your question) is invalid. It needs a colon, i.e. <code>if test == '0':</code>. It also needs a body.</p> <p>The sample output suggests that <code>0</code> is to terminate the loop. Check for that first, before you modify <code>division_inte...
2
2016-09-03T01:37:53Z
[ "python", "if-statement", "while-loop", "syntax-error", "average" ]
Invalid Syntax Error - Average Calculator "IF" and "WHILE"
39,302,442
<p>I have no idea what I'm doing wrong, but this is driving me up a wall. Why am I getting a Syntax error? I have to code an average calculator using a while statement, where "0" defines that the program needs to perform the calculation.</p> <p><a href="http://i.stack.imgur.com/umYUV.png" rel="nofollow"><img src="http...
-3
2016-09-03T01:26:19Z
39,302,531
<p>Alternative answer </p> <p>Use a list, sum and divide. Same concept, compare test inside the while loop in order to break out of it. Also check if you get valid input that can be made an integer with a try/except. </p> <p>Additionally, beware of the division by zero </p> <pre><code>values = [] while True: t...
0
2016-09-03T01:50:00Z
[ "python", "if-statement", "while-loop", "syntax-error", "average" ]
How to redirect a Django template and use the 'Next' variable?
39,302,467
<p>I am using Django's built in login view as can be seen in the following snippets:</p> <p><strong>urls.py</strong></p> <pre><code> url(r'^login$',login,{'template_name': 'login.html'},name="login"), </code></pre> <p><strong>template.html</strong></p> <pre><code>&lt;form method="post" action="{% url 'login' %}"...
0
2016-09-03T01:34:07Z
39,341,203
<p>if you are using django login view ie,</p> <pre><code>from django.contrib.auth.views import login </code></pre> <p>you just need to pass the next url to the template. so when the request is sent to the login view , the code is in place to redirect to that url. is no next url is found</p> <pre><code>settings.LOGIN...
0
2016-09-06T05:26:40Z
[ "python", "django", "django-forms", "django-templates", "django-views" ]
How to access DataFrame column created with DataFrame.groupby
39,302,498
<p>After creating a DataFrame with a column 'a' having the duplicated cell values:</p> <pre><code>import pandas as pd df = pd.DataFrame({'a': [1,2,2,3,3,3,3], 'b':[1,2,3,4,5,6,7], 'c':[8,9,10,11,12,13,14]}) </code></pre> <p><a href="http://i.stack.imgur.com/OlBbV.png" rel="nofoll...
1
2016-09-03T01:41:21Z
39,302,552
<p>After the <code>groupby</code>, the grouped column turns into an index, you can access it either by call <code>.index</code> or <code>reset_index</code> and then access it as a normal column, i.e the following two methods:</p> <pre><code>df.groupby('a', axis=0).sum().reset_index() # a b c # 0 1 1 8 # 1 2...
4
2016-09-03T01:53:15Z
[ "python", "pandas" ]
Adding URL parameters to form action in flask
39,302,500
<p>Is there a way to pass an additional list of parameters outside of a form when the form is submit? </p> <p>I know I can create a new hidden input field in the form for each parameter I want to pass through the form, but is there another way? I tried to add parameters directly to the form action but that doesn't wor...
1
2016-09-03T01:41:40Z
39,302,846
<p>I think you should show what you input and what you want output.</p> <p>In your code, the <code>index()</code> function default accept the <code>GET</code> method, so if you want to post data from form add the <code>methods</code> to the <code>@app.route()</code>.</p> <pre><code>@app.route('/', methods=['GET', 'PO...
0
2016-09-03T03:00:53Z
[ "python", "forms", "flask" ]
Time formats match but still getting error. ValueError: time data 'Time' does match format specified pd.to_datetime
39,302,508
<p>my data column looks like this:</p> <pre><code>0 Time 1 2014-07-28 00:17:35 2 2014-07-28 00:18:05 3 2014-07-28 01:50:54 4 2014-07-28 01:51:24 5 2014-07-28 01:53:57 6 2014-07-28 01:54:56 </code></pre> <p>my code looks like this:</p> <pre><code>df['Epoch'] = pd.to_datetime(df['Time'], format = "%Y-%m-%d %H:%M...
-1
2016-09-03T01:44:37Z
39,302,807
<p>Your dataframe is wrongly loaded: your header is interpreted as a row and is the first row of your dataframe. <code>pd.to_datetime</code> tries to transform the string 'Time' found row 0.</p> <p>Load correctly your dataframe by getting the row 0 loaded as a header instead.</p> <p>Something like this can move the f...
0
2016-09-03T02:53:35Z
[ "python", "pandas", "time", "python-datetime" ]
Django, send dictionary to template
39,302,512
<p>Is it possible to send a dictionary to a template. And use the django/python magic to work on it client side?</p> <p>The view function</p> <pre><code>def index(request): context = { 'users' : users, 'investments' : { 'one' : 1, 'two' : 2 }, } return render(request, 'index...
1
2016-09-03T01:46:19Z
39,302,536
<p>The code below works in Flask-Jinja, and I believe should work in Django:</p> <pre><code>{% if investments %} &lt;h1&gt;{{ investments.one }}&lt;/h1&gt; {% endif %} </code></pre>
3
2016-09-03T01:50:36Z
[ "python", "django" ]
Decode a hex string into Chinese characters
39,302,515
<p>I have a hex code: %E7%B5%99. I want to convert it into Chinese characters.</p> <pre><code>print ("%E7%B5%99".decode('utf-8')) </code></pre> <p>This doesn't seem to work.</p> <p>It should give the answer: 絙</p>
0
2016-09-03T01:46:47Z
39,302,533
<p>You need to "unquote" the percent encoded string first. Then decode from UTF8:</p> <pre><code>&gt;&gt;&gt; s = "%E7%B5%99" &gt;&gt;&gt; print urllib.unquote(s).decode('utf8') 絙 </code></pre>
3
2016-09-03T01:50:10Z
[ "python", "python-2.7" ]
Time-based sliding window and measuring (change of) data arrival rate
39,302,567
<p>I'm trying to implement a time-based sliding window (in Python), i.e., a data sources inserts new data items, and items older than, say, 1h are automatically removed. On top of that, I need to measures the rate, or rather the change of rate the data sources inserts items.</p> <p>My question is kind of two-fold. Fir...
0
2016-09-03T01:57:31Z
39,304,218
<p>For the first part, it is more efficient to check for expired items and remove them when you receive a new item to add. That is, don't bother with a timer which wakes up the process for no reason once a second--just piggyback the maintenance work when real work is happening.</p> <p>For the second part, the entire ...
0
2016-09-03T07:04:53Z
[ "python", "list", "queue", "sliding-window" ]
python - Mount EBS volume using boto3
39,302,594
<p>I want to use AWS Spot instances to train Neural Networks. To prevent loss of the model when the spot instance is terminated, I plan to create a snapshot of the EBS volume, make a new volume and attach it to a reserved instance. How can I mount, or make the EBS volume available using python &amp; boto3. </p> <p>The...
1
2016-09-03T02:04:10Z
39,302,706
<p>You have to perform those steps in the operating system. You can't perform those steps via the AWS API (Boto3). Your best bet is to script those steps and then kick off the script somehow via Boto3, possibly using the AWS SSM service.</p>
1
2016-09-03T02:28:17Z
[ "python", "linux", "amazon-web-services", "boto3" ]
python - Mount EBS volume using boto3
39,302,594
<p>I want to use AWS Spot instances to train Neural Networks. To prevent loss of the model when the spot instance is terminated, I plan to create a snapshot of the EBS volume, make a new volume and attach it to a reserved instance. How can I mount, or make the EBS volume available using python &amp; boto3. </p> <p>The...
1
2016-09-03T02:04:10Z
39,326,511
<p>What's wrong with sending and execute ssh script remotely? Assume you are using ubuntu , i.e. </p> <pre><code>ssh -i your.pem ubuntu@ec2_name_or_ip 'sudo bash -s' &lt; mount_script.sh </code></pre> <p>If you attach tag to those resources, you can later use boto3 to inquired the resources by universal tag name, ...
0
2016-09-05T08:26:43Z
[ "python", "linux", "amazon-web-services", "boto3" ]
How to decode a text file
39,302,602
<p>I have this code here and it work perfectly.</p> <pre><code># encoding=utf8 #Import the necessary methods from tweepy library import sys from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener reload(sys) sys.setdefaultencoding('utf8') #Variables that contains the u...
0
2016-09-03T02:06:09Z
39,302,755
<p>The reason of only getting 291 is the <code>json.loads()</code> throw some errors and <code>except</code> continue it.</p> <p>I suggest you print the error just like:</p> <pre><code>except Exception as err: print err continue </code></pre> <p>now you know the error reason, and solve it.</p> <p>Are you su...
2
2016-09-03T02:40:00Z
[ "python", "twitter", "encoding", "tweepy" ]
How to decode a text file
39,302,602
<p>I have this code here and it work perfectly.</p> <pre><code># encoding=utf8 #Import the necessary methods from tweepy library import sys from tweepy import OAuthHandler from tweepy import Stream from tweepy.streaming import StreamListener reload(sys) sys.setdefaultencoding('utf8') #Variables that contains the u...
0
2016-09-03T02:06:09Z
39,302,895
<p>As agnewee said, I also recommend:</p> <pre><code>try: tweet = json.loads(line) except Exception as err: print err # or use log to see what happen else: tweets_data.append(tweet) </code></pre>
2
2016-09-03T03:14:45Z
[ "python", "twitter", "encoding", "tweepy" ]
how to add column by using other column's conditions
39,302,666
<p>I have a dataframe.</p> <pre><code>df=pd.DataFrame({'month':np.arange(1,8)}) </code></pre> <p>So,I would like to add column by using 'month' columns</p> <pre><code>if 'month'=1,2,3 the elements = 'term1' 'month'=4,5 the elements = 'term2' 'month'=6,7 the elements = 'term3' </code></pre> <p>I wou...
0
2016-09-03T02:19:52Z
39,302,722
<p>Use <code>numpy.where</code> and <code>Series.isin()</code> method could be one of the options to do it:</p> <pre><code>import numpy as np import pandas as pd df["term"] = np.where(df.month.isin([1,2,3]), "term1", \ np.where(df.month.isin([4,5]), "term2", "term3")) df # month term #0 1 te...
1
2016-09-03T02:32:25Z
[ "python", "pandas" ]
how to add column by using other column's conditions
39,302,666
<p>I have a dataframe.</p> <pre><code>df=pd.DataFrame({'month':np.arange(1,8)}) </code></pre> <p>So,I would like to add column by using 'month' columns</p> <pre><code>if 'month'=1,2,3 the elements = 'term1' 'month'=4,5 the elements = 'term2' 'month'=6,7 the elements = 'term3' </code></pre> <p>I wou...
0
2016-09-03T02:19:52Z
39,302,910
<p>I would go for a declarative way through a dict, simple to read and easy to apply. You can generate your replace condition dictionary programmatically if the replacement conditions become large or depends on other inputs:</p> <pre><code>conditions = {1:'term1', 2:'term1', 3:'term1', 4:'term2', 5:'term...
1
2016-09-03T03:18:31Z
[ "python", "pandas" ]
How to copy one DataFrame column in to another Dataframe if their indexes values are the same
39,302,670
<p>After creating a DataFrame with some duplicated cell values in column with the name 'keys':</p> <pre><code>import pandas as pd df = pd.DataFrame({'keys': [1,2,2,3,3,3,3],'values':[1,2,3,4,5,6,7]}) </code></pre> <p><a href="http://i.stack.imgur.com/M9c0P.png" rel="nofollow"><img src="http://i.stack.imgur.com/M9c0P....
2
2016-09-03T02:20:23Z
39,302,752
<p>There are several ways to do this. Using the <code>merge</code> function off the dataframe is the most efficient.</p> <pre><code>df_both = df_sum.merge(df_mean, how='left', on='keys') df_both Out[1]: keys sums means 0 1 1 1.0 1 2 5 2.5 2 3 22 5.5 </code></pre>
3
2016-09-03T02:38:43Z
[ "python", "pandas" ]
How to copy one DataFrame column in to another Dataframe if their indexes values are the same
39,302,670
<p>After creating a DataFrame with some duplicated cell values in column with the name 'keys':</p> <pre><code>import pandas as pd df = pd.DataFrame({'keys': [1,2,2,3,3,3,3],'values':[1,2,3,4,5,6,7]}) </code></pre> <p><a href="http://i.stack.imgur.com/M9c0P.png" rel="nofollow"><img src="http://i.stack.imgur.com/M9c0P....
2
2016-09-03T02:20:23Z
39,302,777
<p>I think <code>pandas.merge()</code> is the function you are looking for. Like <code>pd.merge(df_sum, df_mean, on = "keys")</code>. Besides, this result can also be summarized on one <code>agg</code> function as following:</p> <pre><code>df.groupby('keys')['values'].agg(['sum', 'mean']).reset_index() # keys sum mea...
2
2016-09-03T02:45:51Z
[ "python", "pandas" ]
SyntaxError: non-keyword arg after keyword arg, with no apparent reason
39,302,705
<p>I have a .dat file which I first want to convert into a .csv file and then plot some of the rows against time, my scripts is as follows :</p> <pre><code>import pandas as pd import numpy as np from sys import argv from pylab import * import csv script, filename = argv txt = open(filename) print "Here's your f...
2
2016-09-03T02:28:16Z
39,302,727
<p>It's just what it says. You can't pass non-keyword arguments after keyword arguments. If you have something like x='#time', that's a keyword argument, and all of those have to come at the end of the argument list.</p>
4
2016-09-03T02:34:04Z
[ "python", "csv", "pandas" ]
SyntaxError: non-keyword arg after keyword arg, with no apparent reason
39,302,705
<p>I have a .dat file which I first want to convert into a .csv file and then plot some of the rows against time, my scripts is as follows :</p> <pre><code>import pandas as pd import numpy as np from sys import argv from pylab import * import csv script, filename = argv txt = open(filename) print "Here's your f...
2
2016-09-03T02:28:16Z
39,302,729
<p>The argument 'Nuclear_Burning' follows a keyword argument <code>x</code>. Once you start using keywords in an argument list, you have to keep on using keyword arguments.</p>
3
2016-09-03T02:34:09Z
[ "python", "csv", "pandas" ]
Tkinter TypeError: setvar() takes exactly 1 argument (2 given)
39,302,813
<p>I am writing a GUI program with Tkinter. Everything runs smoothly except for the key bindings. When I test themI get</p> <blockquote> <p>"TypeError: setvar() takes exactly 1 argument (2 given)"</p> </blockquote> <p>The problem is that I am passing no arguments in these instances so I don't understand where the i...
0
2016-09-03T02:54:22Z
39,302,909
<p>When you bind an event to an object-oriented handler:</p> <pre><code>PN_in.bind('&lt;1&gt;', do.setvar) </code></pre> <p>it will call the handler with two arguments <code>(self, event)</code></p> <p>But you've only defined the hander to take one:</p> <pre><code>def setvar(self): </code></pre> <p>If you don't ne...
1
2016-09-03T03:17:56Z
[ "python", "tkinter" ]
Bash script running python scripts
39,302,842
<p>I new to bash script, and found one of the code from stackoverflow. I merge it with my script, it doesn't run python. When I try to echo, it is always going to "Good". When I tried to run <code>ps -ef | grep runserver*</code> this always came out and causing the python script not running. </p> <pre><code>root ...
0
2016-09-03T02:59:56Z
39,303,159
<p>If you are more familiar with python, try this instead:</p> <pre><code>#!/usr/bin/python import os import sys process = os.popen("ps aux | grep -v grep | grep WHATEVER").read().splitlines() if len(process) == 2: print "WHATEVER is running - nothing to do" else: os.system("WHATEVER &amp;") </code></pre>
0
2016-09-03T04:12:58Z
[ "python", "linux", "bash", "shell" ]
Bash script running python scripts
39,302,842
<p>I new to bash script, and found one of the code from stackoverflow. I merge it with my script, it doesn't run python. When I try to echo, it is always going to "Good". When I tried to run <code>ps -ef | grep runserver*</code> this always came out and causing the python script not running. </p> <pre><code>root ...
0
2016-09-03T02:59:56Z
39,303,357
<p>Is the following code what you want?</p> <pre><code>#!/bin/sh SERVER='runserver*' CC=`ps ax|grep -v grep|grep "$SERVER"` if [ "$CC" = "" ]; then python /var/www/html/rest/runserver.py python /var/www/html/rest2/runserver.py else echo "good" fi </code></pre>
0
2016-09-03T04:51:25Z
[ "python", "linux", "bash", "shell" ]
Bash script running python scripts
39,302,842
<p>I new to bash script, and found one of the code from stackoverflow. I merge it with my script, it doesn't run python. When I try to echo, it is always going to "Good". When I tried to run <code>ps -ef | grep runserver*</code> this always came out and causing the python script not running. </p> <pre><code>root ...
0
2016-09-03T02:59:56Z
39,307,720
<p>@NickyMan, the problem is related to the logic in the shell script. Your program don't find <em>runserver</em> and always says "Good". In this code, if you don't find the server, then exec <em>runserver</em>.</p> <pre><code>#!/bin/sh SERVICE='runserver*' if ps ax | grep -v grep | grep $SERVICE &gt; /dev/null then ...
0
2016-09-03T13:57:56Z
[ "python", "linux", "bash", "shell" ]
Getting the root word using the Wordnet Lemmatizer
39,302,880
<p>I need to find a common root word matched for all related words for a keyword extractor.</p> <p>How to convert words into the same root using the python nltk lemmatizer? </p> <ul> <li>Eg: <ol> <li>generalized, generalization -> general </li> <li>optimal, optimized -> optimize (maybe) </li> <li>configure, configu...
0
2016-09-03T03:10:45Z
39,303,494
<p>Use SnowballStemmer:</p> <pre><code>&gt;&gt;&gt; from nltk.stem.snowball import SnowballStemmer &gt;&gt;&gt; stemmer = SnowballStemmer("english") &gt;&gt;&gt; print(stemmer.stem("generalized")) general &gt;&gt;&gt; print(stemmer.stem("generalization")) general </code></pre> <blockquote> <p>Note: Lemmatisation is...
2
2016-09-03T05:15:46Z
[ "python", "nlp", "nltk", "wordnet", "lemmatization" ]
Pandas plot series with series names in one row
39,302,945
<p>I have a csv file like this</p> <pre><code>date, name, value 2016-09-01, alice, 10 2016-09-02, alice, 11 2016-09-01, bob, 8 2016-09-02, bob, 14 </code></pre> <p>With pandas can I plot as a line chart? Or must I change the structure of the file to something similar to </p> <pre><code>date, alice, bob 2016-09-01, 1...
0
2016-09-03T03:24:30Z
39,303,169
<p>Pivot your dataframe to plot one curve per column:</p> <pre><code>df.pivot(index='date', columns='name').plot() </code></pre>
1
2016-09-03T04:15:30Z
[ "python", "pandas", "plot", "time-series" ]
Load an opencv video frame by frame using PyQT
39,303,008
<p>I am trying to load a mat file ( has position coordinates of object whichis tracked) and load a video file. To load a video file I am using opencv. I made a GUI to load both of them. As soon as someone presses start button the video starts playing and Pause stops it. </p> <p>Here is the gui for that:</p> <p><a hre...
0
2016-09-03T03:39:12Z
39,434,210
<p>Here is the link for the solved answer to the above asked question:</p> <p><a href="https://github.com/rajatsaxena/IISc_Neuroscience/blob/master/Miscellaneous/pyqt_opencv.py" rel="nofollow">https://github.com/rajatsaxena/IISc_Neuroscience/blob/master/Miscellaneous/pyqt_opencv.py</a></p>
0
2016-09-11T08:24:32Z
[ "python", "opencv", "pyqt", "pyqt4" ]
python sqlite3 unrecognized token
39,303,010
<p>I am trying to do some simple operations in sqlite with python. I have the test database created and have created a table but when I try to insert my data into it I get an 'unrecognized token' error. </p> <blockquote> <p>c.execute("create table node(changeset int, uid int, timestamp text, lon real, visible int, v...
-1
2016-09-03T03:39:38Z
39,303,631
<p>The line</p> <pre><code>c.execute("insert into node values(8581395,451048,2011-0629T14:14:14Z,-87.6939548,true,5,bbmiller,41.9729565,261114299)") </code></pre> <p>should be</p> <pre><code>c.execute("insert into node values(8581395, 451048, '2011-0629T14:14:14Z', -87.6939548, 1, 5, 'bbmiller', 41.9729565, 26111429...
0
2016-09-03T05:40:26Z
[ "python", "sqlite3" ]
How do I evaluate xe^x/(e^x-1) with numerical stability in Python?
39,303,052
<p>How do I evaluate xe^x/(e^x-1) with numerical stability around zero and when x is very positive or negative? I have access to all the usual mathematical functions in <code>numpy</code> and <code>scipy</code>.</p>
1
2016-09-03T03:48:11Z
39,303,428
<pre><code>def f(x): if abs(x) &gt; 0.1: return x*exp(x)/(exp(x)-1) else: return 1/(1.-x/2.+x**2/6.-x**3/24.) </code></pre> <p>The expansion in the last line can be extended in the obvious fashion if more precision is required, and can be made faster by re-phrasing. As it stands, it errs by as much as 1e-6.</p>
2
2016-09-03T05:03:40Z
[ "python", "numerical-stability" ]
Creating a python calculator using for loop
39,303,056
<p>so I have been asked to write a Python assignment for a basic calculator. It needs to include the operation I want to use (e.g. 1+1=, 2*2=). I am not so shabby at the keywords but when it comes to the construction from below the for i in range(1, 12, 1) statement I kinda falter. Im a bit fuzzy about how the data fro...
-4
2016-09-03T03:49:11Z
39,303,100
<pre><code>print ("Welcome to my Calculator") x = int(input('Please enter first number: ')) y = int(input('Please enter a second number: ')) equation = x + y s = input("Choose an equation: (+) Add, (*) Multiplaction, (-) Subtract, (/) Divide") if s == '+': print x + y if s == '*': print x * y if s == '-': ...
-1
2016-09-03T04:00:52Z
[ "python", "for-loop", "range" ]
Creating a python calculator using for loop
39,303,056
<p>so I have been asked to write a Python assignment for a basic calculator. It needs to include the operation I want to use (e.g. 1+1=, 2*2=). I am not so shabby at the keywords but when it comes to the construction from below the for i in range(1, 12, 1) statement I kinda falter. Im a bit fuzzy about how the data fro...
-4
2016-09-03T03:49:11Z
39,303,120
<p>I feel like the other answer lacks indicators to what you do wrong. You will need to look further into Python's grammar before going further. Basically you have some things problematic :</p> <p><code>equation = x + y</code> computes the sum of x + y. To create an equation to which you can send x and y, you could cr...
0
2016-09-03T04:05:38Z
[ "python", "for-loop", "range" ]
Paramiko won't install with Pip
39,303,095
<p>Trying to use <code>paramiko</code> and Python tells me it's not found, so I try to install with <code>sudo pip install paramiko</code> and get this awful error: <a href="http://pastebin.com/GFpgXB07" rel="nofollow">http://pastebin.com/GFpgXB07</a></p> <p>On OS X. Thanks!</p>
0
2016-09-03T04:00:09Z
39,303,172
<p>The system Python in OSX is used for various tasks by the operating system, so modifying its packages is generally a very bad idea. This error looks like the operating system preventing you from doing something potentially very harmful – in general, doing <code>sudo pip install</code> <em>anything</em> within your...
1
2016-09-03T04:15:58Z
[ "python", "pip", "paramiko" ]
Paramiko won't install with Pip
39,303,095
<p>Trying to use <code>paramiko</code> and Python tells me it's not found, so I try to install with <code>sudo pip install paramiko</code> and get this awful error: <a href="http://pastebin.com/GFpgXB07" rel="nofollow">http://pastebin.com/GFpgXB07</a></p> <p>On OS X. Thanks!</p>
0
2016-09-03T04:00:09Z
39,303,318
<p>It seems that you have permissions problem. I agree with jakevdp but in that case virtualenv is nut your solution. Try the install with --user option. Doc says (<a href="https://pip.pypa.io/en/stable/reference/pip_install/" rel="nofollow">https://pip.pypa.io/en/stable/reference/pip_install/</a>): </p> <pre><code>--...
1
2016-09-03T04:45:34Z
[ "python", "pip", "paramiko" ]
ValueError: too many values to unpack Multiprocessing Pool
39,303,117
<p>I have the following 'worker' that initially returned a single JSON object, but I would like it to return multiple JSON objects:</p> <pre><code>def data_worker(data): _cats, index, total = data _breeds = {} try: url = _channels['feedUrl'] r = get(url, timeout=5) rss = etree.XML(...
0
2016-09-03T04:05:05Z
39,303,154
<p>First of all I think you meant to write this:</p> <pre><code>cats, breeds = pool.map(data_worker, data, chunksize=1) </code></pre> <p>But anyway this won't work, because <code>data_worker</code> returns a pair, but <code>map()</code> returns a list of whatever the worker returns. So you should do this:</p> <pre>...
1
2016-09-03T04:12:38Z
[ "python", "json", "multiprocessing" ]
How to install flaskext.mysql with yum/centos?
39,303,157
<p>While running a program, I get the error <code>ImportError: No module named flaskext.mysql</code>. How can I fix this with yum?</p>
-1
2016-09-03T04:12:50Z
39,303,207
<p>You can install <code>flaskext.mysql</code> using <code>pip</code></p> <p><code>pip install flask-mysql</code></p> <p>If you don't have <code>pip</code> you can install that using the instructions here: <a href="https://packaging.python.org/install_requirements_linux/#centos-rhel" rel="nofollow">https://packaging....
1
2016-09-03T04:23:12Z
[ "python", "mysql", "flask", "centos", "yum" ]
Correct way of writing two floats into a regular txt
39,303,218
<p>I am running a big job, in cluster mode. However, I am only interested in two floats numbers, which I want to read somehow, when the job succeeds.</p> <p>Here what I am trying:</p> <pre><code>from pyspark.context import SparkContext if __name__ == "__main__": sc = SparkContext(appName='foo') f = open('fo...
1
2016-09-03T04:25:00Z
39,370,817
<p>At the first glance there is nothing particularly (you should context manager in case like this instead of manually closing but it is not the point) wrong with your code. If this script is passed to <code>spark-submit</code> file will be written to the directory local to the driver code. </p> <p>If you submit your ...
1
2016-09-07T13:09:14Z
[ "python", "apache-spark", "io", "bigdata", "distributed-computing" ]
Pandas 'read_csv' giving an error, in one specific directory only.
39,303,287
<p>I was attempting to follow a <a href="http://ahmedbesbes.com/how-to-score-08134-in-titanic-kaggle-challenge.html" rel="nofollow">pandas/sklearn/kaggle tutorial</a>, and barely got a dozen lines when I stumbled over over one of the simplest commands in python:</p> <p>Code:</p> <pre><code>import warnings warnings.fi...
1
2016-09-03T04:40:18Z
39,303,394
<p>Write:</p> <pre><code>import matplotlib.pyplot as plt </code></pre> <p>By reimporting as <code>pd</code> you overwrite <code>import pandas as pd</code></p>
2
2016-09-03T04:58:41Z
[ "python", "csv", "pandas", "module", "attributeerror" ]
OpenCV Python Feature detection examples extension
39,303,315
<p>I'm chasing a little assistance with an idea I'm playing with. I want to take the features located in an image with code similar to the example on</p> <p><a href="http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_matcher/py_matcher.html" rel="nofollow">See sample image at bottom of page here</a> Last...
1
2016-09-03T04:44:23Z
39,311,462
<p>You need to find the prescriptive transform between the two images.</p> <p>Create a set of corresponding coordinates according to the matched features. </p> <p>For example you find that the feature FtI1 in image 1 corresponds to FtJ1 in image 2 so you know that coordinate of FtI1 (xi,yi) corresponds to the coordin...
0
2016-09-03T21:21:47Z
[ "python", "image-processing", "opencv3.0" ]
Problems extending python array declared outside of scope
39,303,338
<p>This is a very basic question, but I can't seem to extend an array with a new item that is added within a function. I haven't gotten push to work either, so I think my array is just not being addressed by the other functions. </p> <p>The array is declared as a global because otherwise function(s) do not appear to ...
1
2016-09-03T04:48:01Z
39,304,546
<p>A working example of all mentioned functions. <code>global</code> is not required, because the <code>tasklist</code> is not re-assigned in the function, only its methods are called.</p> <pre><code>tasklist = ['one'] def testfunc(): # no global required tasklist.append('two') tasklist.extend(['three', '...
3
2016-09-03T07:45:05Z
[ "python", "arrays", "python-3.x" ]
Problems extending python array declared outside of scope
39,303,338
<p>This is a very basic question, but I can't seem to extend an array with a new item that is added within a function. I haven't gotten push to work either, so I think my array is just not being addressed by the other functions. </p> <p>The array is declared as a global because otherwise function(s) do not appear to ...
1
2016-09-03T04:48:01Z
39,304,828
<p>Here's the working solution in python 3.2 to add items to list in function:</p> <pre><code>weeklyTasks = ['No work Sunday'] def AddWeeklyTask(): weeklyTasks.extend(['Work On']) weeklyTasks.append('Do not work on weekends') weeklyTasks.insert(2,'Friday') print(weeklyTasks) AddWeeklyTask() print(weeklyTa...
1
2016-09-03T08:22:58Z
[ "python", "arrays", "python-3.x" ]
How to detect own files name
39,303,375
<p>I have some code, which I will rather not share but this a portion</p> <pre><code>try_again = input ("Try again?") if answer == "Y" or answer == "y": clear() file_path = os.path.dirname(os.path.realpath(__file__)) open file_path + "maze_game.exe" exit() else: exit() </code></pre> <p>...
2
2016-09-03T04:55:09Z
39,303,522
<p>Maybe I am misunderstanding what you want, but I think <code>os.path.basename(__file__)</code> will do the trick. </p> <p>This will give you just the file part of your path, so if you have a file<code>foo/bar/baz.py</code> and pass that path like <code>os.path.basename('foo/bar/baz.py')</code>, it will return the s...
2
2016-09-03T05:21:16Z
[ "python" ]
Fastest way to process a python list of tuples
39,303,484
<p>In a Django project, I have a python list of tuples like so:</p> <pre><code>users_and_values = [(user_id,value),(user_id,value),......] </code></pre> <p>where <code>value</code> can either be 0.0 or 1.0 (float). Given this list, I need to create a new one, which is like so:</p> <pre><code>[(user_object,value),(us...
0
2016-09-03T05:13:33Z
39,303,545
<p><code>user_objs</code> is an unordered collection of users. You have to manually map the user ids to the corresponding values by iterating over it:</p> <pre><code>user_ids = [user_id for user_id, value in users_and_values] user_objs = User.objects.filter(id__in=user_ids) ids_to_values = dict(users_and_values) # {...
2
2016-09-03T05:25:30Z
[ "python", "django" ]
Django upload only csv file
39,303,488
<p>I am trying to import csv file i am able to import without any problem but the present functionality accepts all file types, i want the functionality to accept only csv file. below is the view.py and template file.</p> <p>myapp/views.py</p> <pre><code>def list(request): # Handle file upload if request.meth...
0
2016-09-03T05:14:42Z
39,304,039
<p>added code snippet to the forms.py file to validate file extension and now it is working fine.</p> <pre><code>def validate_file_extension(value): if not value.name.endswith('.csv'): raise forms.ValidationError("Only CSV file is accepted") class DocumentForm(forms.Form): docfile = forms.File...
0
2016-09-03T06:43:08Z
[ "python", "django", "csv" ]
Web2py DAL find the record with the latest date
39,303,554
<p>Hi I have a table with the following structure.</p> <p>Table Name: DOCUMENTS</p> <p>Sample Table Structure:</p> <pre><code>ID | UIN | COMPANY_ID | DOCUMENT_NAME | MODIFIED_ON | ---|----------|------------|---------------|---------------------| 1 | UIN_TX_1 | 1 | txn_summary | 2016-09-02 1...
0
2016-09-03T05:26:49Z
39,335,401
<p>Your approach will not return complete row, it will only return last modified_on value.</p> <p>To fetch last modified record for the company whose id is 1 and document_name "txn_summary", query will be</p> <pre><code>query = (db.documents.company_id==1) &amp; (db.documents.document_name=='txn_summary') row = db(qu...
0
2016-09-05T17:37:44Z
[ "python", "postgresql", "web2py", "data-access-layer" ]
Cannot install Keras on Pycharm on Macbook
39,303,623
<p>Macbook.</p> <p>I can perform "pip install Keras==1.0.8" successfully on terminal though.</p> <p><strong>Problem: Installing Keras to Pycharm, cannot make it.</strong></p> <p>Error as shown by screenshots below: <a href="http://i.stack.imgur.com/7ORA6.png" rel="nofollow"><img src="http://i.stack.imgur.com/7ORA6.p...
0
2016-09-03T05:38:55Z
39,303,904
<p>There are some non-python dependencies for Keras, so pip won't install them and fails if they are not found. The error here is related to fortran compiler and can be resolved by installing for example <code>gfortran</code>. But there would be probably other packages that you miss.</p> <p>I recommend taking steps in...
1
2016-09-03T06:25:31Z
[ "python", "pycharm", "keras" ]
python 3.5 for loop defined functions placed in the loop
39,303,685
<p>Ok I have been trying to use a input Int function to set how many questions are asked at the start however the input doesn't seem to want to go through. It can be done right? I all I want is to be be able to alter the start_test() value. While when the user enter a inter correct answer I want the error message to...
-2
2016-09-03T05:49:06Z
39,303,860
<pre><code>import random import string import sys vowels = ['a', 'e', 'i', 'o', 'u'] consonants = [x for x in string.ascii_lowercase if x not in vowels] candidateWords = ['HELLO', 'GOODBYE', 'NAME', 'DAY', 'NIGHT', 'HOUR', 'POTATO', 'BIG', 'SMALL', 'GOOD', 'BAD', 'YES', 'NO', 'HOUSE', 'QUESTION', 'BALLOON', 'CAT', '...
2
2016-09-03T06:17:57Z
[ "python", "python-3.x", "python-3.5" ]
How do i work out this date time issue in python
39,303,710
<p>I am new to Python and machine learning and i am trying to work out how to fix this issue with date time. next_unix is 13148730, because that is how many seconds are in five months, which is the time in between my dates. I have searched and i can't seem to find anything that works.</p> <pre><code>last_date = df.ilo...
-1
2016-09-03T05:54:11Z
39,304,571
<p>If <code>pd.to_datetime</code> returns a python <code>datetime</code> object, then you should look at using a <code>timedelta</code> object for your 5 month interval:</p> <p><a href="https://docs.python.org/2/library/datetime.html#timedelta-objects" rel="nofollow">https://docs.python.org/2/library/datetime.html#tim...
0
2016-09-03T07:47:50Z
[ "python", "pandas" ]
How do i work out this date time issue in python
39,303,710
<p>I am new to Python and machine learning and i am trying to work out how to fix this issue with date time. next_unix is 13148730, because that is how many seconds are in five months, which is the time in between my dates. I have searched and i can't seem to find anything that works.</p> <pre><code>last_date = df.ilo...
-1
2016-09-03T05:54:11Z
39,304,713
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/timedeltas.html" rel="nofollow">pd.Timedelta()</a> method:</p> <pre><code>In [20]: pd.to_datetime('2015-01-31 00:00:00') + pd.Timedelta(seconds=13148730) Out[20]: Timestamp('2015-07-02 04:25:30') </code></pre> <p>if we try to add number of seconds to...
0
2016-09-03T08:08:30Z
[ "python", "pandas" ]
Flask testing keeps failing
39,303,754
<p>So I have web app where if the user is logged in, he cannot sign up. Instead he is redirected and a message saying he cannot sign up is flashed.</p> <p>The problem is I can't test it for some reason.</p> <p>Here is the view</p> <pre><code>@users_template.route('/signup', methods=['GET', 'POST']) def signup(): ...
0
2016-09-03T06:00:27Z
39,303,916
<p>Suggestion no:</p> <ol> <li><p>Because of this line:</p> <pre><code>if current_user.is_authenticated and current_user.is_active: </code></pre> <p>current_user has his <code>is_active</code> flag set as <code>False</code>. If I'm not right, then please paste test error.</p></li> <li><p>Another clue could be lack o...
1
2016-09-03T06:26:50Z
[ "python", "flask", "flask-testing" ]
How to count the number of vowels in a string without a function wrapper
39,303,789
<p>I've currently solving a MIT undergrad problem in Python 3.5. The goal is to write a Python script counting and printing the number of vowels in a string containing only lower-case letters without using a function wrapper or even a function definition (stated in the assignment, weird ?).</p> <pre><code>def vowels_c...
-1
2016-09-03T06:06:09Z
39,303,880
<p>You can use the condition of <code>i</code> being less than the length of your string to break out of the while loop. I also recommend the easier approach of just checking if the letter at <code>s[i]</code> is in a string composed of vowels:</p> <pre><code>def vowels_count(s): i = 0 counter = 0 while i ...
5
2016-09-03T06:22:05Z
[ "python", "string" ]
How to count the number of vowels in a string without a function wrapper
39,303,789
<p>I've currently solving a MIT undergrad problem in Python 3.5. The goal is to write a Python script counting and printing the number of vowels in a string containing only lower-case letters without using a function wrapper or even a function definition (stated in the assignment, weird ?).</p> <pre><code>def vowels_c...
-1
2016-09-03T06:06:09Z
39,303,946
<p>As you learn more and more you'll be able to count the vowels in one line using <code>sum</code> and a generation expression.</p> <p>You could fix your loop <code>while i &lt; len(s)</code>, i.e. up to the length of the string, but much better is just to <em>iterate</em> over the sequence of characters we call "str...
1
2016-09-03T06:30:38Z
[ "python", "string" ]
How to count the number of vowels in a string without a function wrapper
39,303,789
<p>I've currently solving a MIT undergrad problem in Python 3.5. The goal is to write a Python script counting and printing the number of vowels in a string containing only lower-case letters without using a function wrapper or even a function definition (stated in the assignment, weird ?).</p> <pre><code>def vowels_c...
-1
2016-09-03T06:06:09Z
39,307,132
<p>Here is an one line solution:</p> <pre><code>reduce(lambda t, c : (t + 1) if c in 'aeiou' else t, s.lower(), 0) </code></pre>
0
2016-09-03T12:55:26Z
[ "python", "string" ]
TfidfVectorizer in scikit-learn : ValueError: np.nan is an invalid document
39,303,912
<p>I'm using TfidfVectorizer from scikit-learn to do some feature extraction from text data. I have a CSV file with a Score (can be +1 or -1) and a Review (text). I pulled this data into a DataFrame so I can run the Vectorizer.</p> <p>This is my code: </p> <pre><code>import pandas as pd import numpy as np from sklear...
1
2016-09-03T06:26:03Z
39,308,809
<p>You need to convert the dtype <code>object</code> to <code>unicode</code> string as is clearly mentioned in the traceback.</p> <pre><code>x = v.fit_transform(df['Review'].values.astype('U')) ## Even astype(str) would work </code></pre> <p>From the Doc page of TFIDF Vectorizer:</p> <blockquote> <p>fit_transform...
2
2016-09-03T16:01:07Z
[ "python", "machine-learning", "scikit-learn", "tf-idf", "text-classification" ]
Convert time decimal to datetime object python
39,304,024
<p>I am trying to convert a decimal time to a datetime object to look for the months in order to later divide the time into seasons. I did some research and stumbled upon datetime.datetime.fromtimestamp but everything I have tried produces the following error:</p> <pre><code> TypeError: 'datetime.datet...
1
2016-09-03T06:41:16Z
39,304,528
<p>The error message is because of your use of <code>extend</code>:</p> <pre><code>annual_time = [] for i in raw_time[time]: annual_time.extend(datetime.datetime.fromtimestamp(i)) </code></pre> <p><em>list</em><code>.extend()</code> is used to take another list or iterable and add its contents to the end of the l...
1
2016-09-03T07:43:49Z
[ "python", "datetime" ]
Convert time decimal to datetime object python
39,304,024
<p>I am trying to convert a decimal time to a datetime object to look for the months in order to later divide the time into seasons. I did some research and stumbled upon datetime.datetime.fromtimestamp but everything I have tried produces the following error:</p> <pre><code> TypeError: 'datetime.datet...
1
2016-09-03T06:41:16Z
39,332,582
<p>You should use <a href="http://unidata.github.io/netcdf4-python/#netCDF4.num2date" rel="nofollow">netCDF4 num2date</a> to convert <code>time</code> from numeric values to datetime objects. </p> <pre><code>import netCDF4 ncfile = netCDF4.Dataset('./foo.nc', 'r') time = ncfile.variables['time'] # do not cast to nump...
0
2016-09-05T14:18:30Z
[ "python", "datetime" ]
Code debugging, why leds won't turn off after operation?
39,304,052
<p>I wroted a code, whitch turns on leds by the date and color from the txt file. If the date is correct leds turns on, but when correct time passes leds wont turn off, they still glowing until next date. So, why leds won't turn off, where is the problem? Please help, I have tried almost everything. </p> <pre><code>...
1
2016-09-03T06:45:15Z
39,304,248
<p>Hey brother I believe I have found the answer to your problem. Okay here is what you will do. <a href="https://learn.adafruit.com/debugging-with-the-raspberry-pi-webide/debug-a-blinking-led" rel="nofollow">THIS IS A THOROUGH GUIDE ON DEBUGGING A BLINKING LED</a></p> <p>Endeavour to go through the guide as it contai...
0
2016-09-03T07:07:55Z
[ "python", "raspberry-pi", "raspbian", "led", "raspberry-pi3" ]
Code debugging, why leds won't turn off after operation?
39,304,052
<p>I wroted a code, whitch turns on leds by the date and color from the txt file. If the date is correct leds turns on, but when correct time passes leds wont turn off, they still glowing until next date. So, why leds won't turn off, where is the problem? Please help, I have tried almost everything. </p> <pre><code>...
1
2016-09-03T06:45:15Z
39,306,026
<p>What a nice opportunity to use the <a href="https://docs.python.org/3.5/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops" rel="nofollow">for-else construct</a>.</p> <p>If an instruction to turn LED lights on is found, turn the LEDs on and then break from the loop, because the task i...
2
2016-09-03T10:44:26Z
[ "python", "raspberry-pi", "raspbian", "led", "raspberry-pi3" ]
how to call a member function in python by its function instance?
39,304,103
<p>Suppose we have the following code:</p> <pre><code>class T(object): def m1(self, a): ... f=T.m1 </code></pre> <p>How to call f on an instance of T?</p> <pre><code>x=T() x.f(..)? f(x, ..)? </code></pre>
1
2016-09-03T06:51:05Z
39,304,145
<p>Hopefully this explains it!</p> <pre><code>class T(object): def m1(self, a): return a f=T().m1 #must initialize the class using '()' before calling a method of that class f(1) f = T() f.m1(1) f = T().m1(1) f = T f().m1(1) f = T.m1 f(T(), 1) #can call the method without first initializing the class b...
0
2016-09-03T06:55:33Z
[ "python" ]
how to call a member function in python by its function instance?
39,304,103
<p>Suppose we have the following code:</p> <pre><code>class T(object): def m1(self, a): ... f=T.m1 </code></pre> <p>How to call f on an instance of T?</p> <pre><code>x=T() x.f(..)? f(x, ..)? </code></pre>
1
2016-09-03T06:51:05Z
39,304,574
<p>A member function is just like any other function, except it takes <code>self</code> as the first argument and there is a mechanism which passes that argument automatically.</p> <p>So, the short answer is, use it ths way:</p> <pre><code>class T(object): def m1(self, a): pass f=T.m1 x = T() f(x, 1234) </co...
0
2016-09-03T07:48:10Z
[ "python" ]
python pdf (PyPDF2 module) - How to split/merge this?
39,304,167
<p>I was trying to split &amp; merge pdf files so that i can remove the first page of each pdf files.. Here's the code.</p> <pre><code> #python3 #split and merge pdf files! import os, PyPDF2 pdfFiles = [] os.chdir('C:\\Users\\Cyber\\Downloads\\5-111-fall-2008\\5-111-fall-2008\\contents\\readings...
0
2016-09-03T06:58:01Z
39,305,139
<p>This warning means that the first section of the xref table does not begin with object zero. There may have been an error in writing the PDF. If strict = False, PyPDF2 will try to correct the object ID numbers. If strict = True, they will not be corrected.The default is True. Try <code>PyPDF2.PdfFileReader(pdfFileOb...
1
2016-09-03T09:01:32Z
[ "python", "pypdf2" ]
How do I deal with Pandas Series data type that has NaN?
39,304,173
<p>What happens when using max() and min() on pandas.core.series.Series type that has NaN in it? Is this a bug? See below,</p> <hr> <pre><code>%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt mydata = pd.DataFrame(np.random.standard_normal((100,1)), columns=['No NaN']) mydata...
2
2016-09-03T06:58:16Z
39,304,634
<p>you should use Pandas or NumPy functions instead of vanilla Python ones:</p> <pre><code>In [7]: mydata['Has NaN'].min(), mydata['Has NaN'].max() Out[7]: (-46.00309057827485, 62.430829637766671) In [8]: min(mydata['Has NaN']), max(mydata['Has NaN']) Out[8]: (nan, nan) In [125]: mydata.plot.hist(alpha=0.5) Out[125]...
3
2016-09-03T07:57:19Z
[ "python", "pandas", "matplotlib", "dataframe" ]
How do I deal with Pandas Series data type that has NaN?
39,304,173
<p>What happens when using max() and min() on pandas.core.series.Series type that has NaN in it? Is this a bug? See below,</p> <hr> <pre><code>%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt mydata = pd.DataFrame(np.random.standard_normal((100,1)), columns=['No NaN']) mydata...
2
2016-09-03T06:58:16Z
39,304,658
<p>First, you shouldn't use the Python built-in <code>max</code> or <code>min</code> when dealing with <code>pandas</code> or <code>numpy</code>, especially when you are working with <code>nan</code>.</p> <p>Since 'nan' is the first item of <code>mydata['Has NaN']</code>, it is never replaced in either <code>max</code...
3
2016-09-03T08:00:55Z
[ "python", "pandas", "matplotlib", "dataframe" ]
Why is there a difference in format of encrypted passwords in Django
39,304,190
<p>I am using Django 1.97. The encrypted passwords are significantly different (in terms of the format).</p> <p>Some passwords are of format $$$: </p> <pre><code>pbkdf2_sha256$24000$61Rm3LxOPsCA$5kV2bzD32bpXoF6OO5YuyOlr5UHKUPlpNKwcNVn4Bt0= </code></pre> <p>While others are of format :</p> <pre><code>!9rPYViI1oqrSMf...
0
2016-09-03T07:00:51Z
39,304,294
<p>There is no significant difference between <code>User.objects.create_user()</code> and <code>user.set_password()</code> since first uses second.</p> <p>Basically, passwords are in string with format <code>&lt;algorithm&gt;$&lt;iterations&gt;$&lt;salt&gt;$&lt;hash&gt;</code> according to <a href="https://docs.django...
0
2016-09-03T07:14:20Z
[ "python", "django" ]
Why is there a difference in format of encrypted passwords in Django
39,304,190
<p>I am using Django 1.97. The encrypted passwords are significantly different (in terms of the format).</p> <p>Some passwords are of format $$$: </p> <pre><code>pbkdf2_sha256$24000$61Rm3LxOPsCA$5kV2bzD32bpXoF6OO5YuyOlr5UHKUPlpNKwcNVn4Bt0= </code></pre> <p>While others are of format :</p> <pre><code>!9rPYViI1oqrSMf...
0
2016-09-03T07:00:51Z
39,306,071
<p>You'll be fine. You just have some blank passwords in your database. </p> <p>Going back as far as <a href="https://github.com/django/django/blob/stable/0.95.x/django/contrib/auth/models.py#L13" rel="nofollow">V0.95</a>, django used the <code>$</code> separators for delimiting algorithm/salt/hash. These days, dja...
1
2016-09-03T10:48:51Z
[ "python", "django" ]
QObject::startTimer: QTimer can only be used with threads started with QThread?
39,304,366
<p>I have given the model a parent, but it still shows error message when exiting, what was wrong in the following code</p> <pre><code>#!/usr/bin/env python2 import os import sys from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4 import uic import re CODE = 'xxx' class MyWindow(QDialog): def __in...
0
2016-09-03T07:22:29Z
39,311,662
<p>after adding this call, it doesn't error out anymore</p> <pre><code>self.setAttribute(Qt.WA_DeleteOnClose) </code></pre>
0
2016-09-03T21:53:50Z
[ "python", "qt", "pyqt", "qcompleter" ]
execute time period in python
39,304,472
<p>I want to run the script in shell by sending time period like</p> <pre><code>./test.py 20160830000 201608311100 </code></pre> <p>How can I do this for the following python script? <code>s</code> and <code>t</code> are UNIX timestamp.</p> <pre><code>#!/usr/bin/python import requests from pprint import pprint impor...
0
2016-09-03T07:36:21Z
39,304,635
<p>Take a look at the <a href="https://docs.python.org/2/library/time.html" rel="nofollow">time</a> python module, specifically the <a href="https://docs.python.org/2/library/time.html#time.strptime" rel="nofollow">time.strptime</a> function for parsing human-readable time strings into a time structure and the <a href=...
0
2016-09-03T07:57:31Z
[ "python", "json", "linux" ]
execute time period in python
39,304,472
<p>I want to run the script in shell by sending time period like</p> <pre><code>./test.py 20160830000 201608311100 </code></pre> <p>How can I do this for the following python script? <code>s</code> and <code>t</code> are UNIX timestamp.</p> <pre><code>#!/usr/bin/python import requests from pprint import pprint impor...
0
2016-09-03T07:36:21Z
39,304,743
<p>If I understand correctly, you want to get the timestamps to use in your jsonrpc call from the command line arguments, rather than using hardcoded dates (which for some reason you're processing through the command line too <code>date</code> using the deprecated <code>commands</code> module, rather than using Python'...
1
2016-09-03T08:11:34Z
[ "python", "json", "linux" ]
Python coding exercise
39,304,512
<p>I have a function named orderInt passed three integers and returns true if the three int are in ascending order, otherwise false. Here's my code so far:</p> <pre><code>def orderInt(a, b, c): print "Enter 3 integers: " a = input() b = input() c = input() </code></pre> <p>How do I compare the variables? </p>
-7
2016-09-03T07:41:29Z
39,304,637
<p>First of all, your indentation is wrong.</p> <pre><code>def orderInt(): print "Enter 3 integers: " a = input() b = input() c = input() if a&lt;b&lt;c: return True else: return False print orderInt() </code></pre> <p>Second, your function is taking three arguments and also t...
0
2016-09-03T07:58:23Z
[ "python", "python-2.7" ]
Python Cryptography: Cannot sign with RSA private key using PKCS1v15 padding
39,304,533
<p>I'm trying to implement a functionally equivalent signing with Python and the Cryptography library to PHP's <code>openssl_pkey_get_private</code> and <code>openssl_sign</code> using a SHA1 hash. I've read that PHP uses PKCS1v15 padding, so that's what I'm trying to use as well. My code is:</p> <pre><code>from crypt...
3
2016-09-03T07:44:13Z
39,305,312
<p>The operator <code>isinstance</code> indicates that <code>padding.PKCS1v15</code> needs to be an instance instead of the type (class) itself. That means that the object instance should be created by calling the constructor.</p> <p>To do this add parentheses, i.e. <code>padding.PKCS1v15()</code>.</p>
2
2016-09-03T09:22:02Z
[ "php", "python", "cryptography", "pkcs#1" ]
should I store all encrypted password to database using generate_password_hash()
39,304,650
<p>When I use <code>generate_password_hash()</code> function, I get a encrypted password string which contains a random salt.</p> <pre><code>&gt;&gt;&gt; from werkzeug.security import generate_password_hash, check_password_hash &gt;&gt;&gt; generate_password_hash('password') &gt;&gt;&gt; 'pbkdf2:sha1:1000$3j8Brovx$9ac...
0
2016-09-03T08:00:10Z
39,304,969
<blockquote> <p>it's easy to get the origin password using brute force cracking because the encrypted password contains the salt.</p> </blockquote> <p>No, it's "easy" to brute force, because you're having a low iteration count of 1000.</p> <blockquote> <p>Should I encrypt the origin password using my own salt fir...
2
2016-09-03T08:41:25Z
[ "python", "encryption", "flask" ]
should I store all encrypted password to database using generate_password_hash()
39,304,650
<p>When I use <code>generate_password_hash()</code> function, I get a encrypted password string which contains a random salt.</p> <pre><code>&gt;&gt;&gt; from werkzeug.security import generate_password_hash, check_password_hash &gt;&gt;&gt; generate_password_hash('password') &gt;&gt;&gt; 'pbkdf2:sha1:1000$3j8Brovx$9ac...
0
2016-09-03T08:00:10Z
39,306,671
<p>When you store password hashes, the main assumption is that it is too difficult to retrieve the password using brute force. If you want it to be safer, go for slower hash algorithims and longer passwords.</p> <p>Encryption is worse than a hash because hash is irreversible and brute force is the only way to retrieve...
2
2016-09-03T12:02:33Z
[ "python", "encryption", "flask" ]
Why is Django reporting inconsistent values for this instance attribute?
39,304,819
<p>I have the following simple Django model class:</p> <pre><code>from django.db import models class MyClassA(models.Model): name = models.CharField(max_length=254) parent_a = models.IntegerField() def update_names(self, name, other_a_list): a_set = set([self] + other_a_list) for curr_a i...
0
2016-09-03T08:21:39Z
39,304,879
<p>Because you haven't refreshed m3 from the database. <code>related_a_instances</code> fetches brand new objects from the database; even though those items refer to the same db rows as m1 to m3, they are not the same objects and updates to one do not affect the other.</p> <p>If you did <code>m3 = MyClassA.objects.get...
2
2016-09-03T08:29:58Z
[ "python", "django", "django-models", "django-queryset" ]
Python list to sqlite
39,304,872
<pre><code>from bs4 import BeautifulSoup import requests import sqlite3 conn = sqlite3.connect('stadiumsDB.db') c = conn.cursor() c.executescript(''' DROP TABLE IF EXISTS Stadium; CREATE TABLE Stadium ( id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, Stadium TEXT UNIQUE, Club Text UNIQUE, ...
0
2016-09-03T08:29:22Z
39,316,118
<p>For your table definition you can insert <code>stadium_data</code> best with <a href="https://docs.python.org/2.7/library/sqlite3.html#sqlite3.Cursor.executemany" rel="nofollow">executemany</a> like</p> <pre><code>cn=column_names stadium=cn.index("Stadium") club=cn.index("Club") location=cn.index("Location") # thi...
0
2016-09-04T10:50:15Z
[ "python", "sqlite" ]
Python threading with PyQt as decorator
39,304,951
<p>Hello fellow Overflowers, here's another code I've stuck in. I am using decorator to run some functions asycronously.</p> <p>file: async.py</p> <pre><code>from threading import Thread from functools import wraps def run(func): @wraps(func) def async_func(*args, **kwargs): func_hl = Thread(target=...
0
2016-09-03T08:38:59Z
39,386,669
<p>First here: <a href="http://stackoverflow.com/questions/1595649/threading-in-a-pyqt-application-use-qt-threads-or-python-threads">Threading in a PyQt application: Use Qt threads or Python threads?</a>, for some usufull advise.</p> <p>A simple "refactoring" of your code, to make it cleaner:</p> <pre><code>class Run...
1
2016-09-08T08:58:29Z
[ "python", "multithreading", "qt", "pyqt", "qthread" ]
Element-wise comparison of vector and scalar fails in rpy2 with Python 3
39,304,977
<p>It looks like rpy2 doesn't behave exactly the same in Python3 and Python2. In particular, in Python 2.7.x, I am able to compare a <a href="http://rpy2.readthedocs.io/en/version_2.8.x/vector.html" rel="nofollow">Vector</a> with a scalar, whereas in Python 3.5.x, if I try to do that, the following error is raised: </p...
1
2016-09-03T08:41:58Z
39,310,160
<p>If a bug, I would think that it was with Python 2.</p> <p>An R vector is a sequence and the default Python behavior does not make such comparisons possible. For example:</p> <pre><code>&gt;&gt;&gt; [1,2,3] &lt; 2 --------------------------------------------------------------------------- TypeError ...
1
2016-09-03T18:33:39Z
[ "python", "python-3.x", "numpy", "rpy2" ]
Reuse large dequeued variable in Tensorflow
39,304,995
<p>I have a large tensor (some hundreds of megabytes) that is dequeued.</p> <pre><code>small_queue = tf.FIFOQueue(10, [tf.float64, tf.float64, tf.float64]) big_queue = tf.FIFOQueue(10, [tf.float64]) .... small1, small2, small3 = small_queue.dequeue() large = big_queue.dequeue() result = process(small1, small2, small...
1
2016-09-03T08:43:48Z
39,312,666
<p>I don't sure that I understand your question. </p> <p>If you just want to get <code>Tensor</code> variable you need <code>tf.get_variable</code> after <code>scope.reuse_variables()</code>:</p> <pre><code>with tf.scope('my_scope') as scope: scope.reuse_variables() large_var = tf.get_variable('my_large_var')...
0
2016-09-04T01:02:55Z
[ "python", "tensorflow" ]
How to call a function in a function in python
39,305,002
<p>I have a problem about function in python, and i'm pretty new in programming, so please giving your examples in the simplest way, thanks</p> <p>I want to call a function in a function like this:</p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b...
-1
2016-09-03T08:44:26Z
39,305,045
<p>Have You tried to call it ? And TIPs : Remember about indent </p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c funct2() #function called , WORKS ! </code></pre> <h1> </h1>
1
2016-09-03T08:49:26Z
[ "python", "function", "nested" ]
How to call a function in a function in python
39,305,002
<p>I have a problem about function in python, and i'm pretty new in programming, so please giving your examples in the simplest way, thanks</p> <p>I want to call a function in a function like this:</p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b...
-1
2016-09-03T08:44:26Z
39,305,072
<pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c return func2,func3 </code></pre> <p><strong>Closure may works</strong></p>
0
2016-09-03T08:51:58Z
[ "python", "function", "nested" ]
How to call a function in a function in python
39,305,002
<p>I have a problem about function in python, and i'm pretty new in programming, so please giving your examples in the simplest way, thanks</p> <p>I want to call a function in a function like this:</p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b...
-1
2016-09-03T08:44:26Z
39,305,077
<p>Although you don't really need new functions to do such simple tasks, calling functions in another function would be something like this:</p> <pre><code>def func2(b): return b*3 def func3(b): return b/5 def func1(a): b = a + 1 c = func2(b) print c c = func3(b) print c </code></pre> <p...
0
2016-09-03T08:52:32Z
[ "python", "function", "nested" ]
How to call a function in a function in python
39,305,002
<p>I have a problem about function in python, and i'm pretty new in programming, so please giving your examples in the simplest way, thanks</p> <p>I want to call a function in a function like this:</p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b...
-1
2016-09-03T08:44:26Z
39,305,345
<p>There is a way to achieve the syntax you want but it is <strong>highly irregular</strong> and I would <strong>strongly</strong> advise against using it. It is hacky.</p> <pre><code>def func1(a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b/5 print c func1.fun...
0
2016-09-03T09:25:54Z
[ "python", "function", "nested" ]
How to call a function in a function in python
39,305,002
<p>I have a problem about function in python, and i'm pretty new in programming, so please giving your examples in the simplest way, thanks</p> <p>I want to call a function in a function like this:</p> <pre><code>def func1 (a): b = a + 1 def func2(): c = b*3 print c def func3(): c = b...
-1
2016-09-03T08:44:26Z
39,305,368
<p>The function objects <code>func2</code> and <code>func3</code> are local to the function <code>func1</code>, which means they do not exist outside of <code>func1</code> unless <code>func1</code> explicitly returns them to the calling environment. </p> <p>So if you want to call those functions <em>outside</em> of <c...
0
2016-09-03T09:29:00Z
[ "python", "function", "nested" ]
django rest framework multiple url arguments
39,305,135
<p>In rest api view I need to have 2 objects. For example:</p> <pre><code>class Foo(models.Model): .... class Bar(models.Model): .... </code></pre> <p>What is correct way to get them? I mean how should I configure urls? I think this is not really good practice: <code>url(r'^foo/(?P&lt;pk&gt;\d+)/bar/(?P&lt;p...
1
2016-09-03T09:00:22Z
39,305,548
<p>For django >= 1.5 You could pass parameters to class view doing somethin like this:</p> <pre><code>class Foo(TemplateView): template_name = "yourtemplatesdir/template.html" # Set any other attributes here # dispatch is called when the class instance loads def dispatch(self, request, *args, **kwarg...
0
2016-09-03T09:49:02Z
[ "python", "django", "django-rest-framework" ]
django rest framework multiple url arguments
39,305,135
<p>In rest api view I need to have 2 objects. For example:</p> <pre><code>class Foo(models.Model): .... class Bar(models.Model): .... </code></pre> <p>What is correct way to get them? I mean how should I configure urls? I think this is not really good practice: <code>url(r'^foo/(?P&lt;pk&gt;\d+)/bar/(?P&lt;p...
1
2016-09-03T09:00:22Z
39,306,929
<p>I think it is more like a design problem.</p> <p>Which one is better? I will say it depends on what is the relationship between model foo and model bar.</p> <p>If you get model <strong>Class</strong> and model <strong>student</strong>, and you want to get student info and base on which class and relative student_n...
0
2016-09-03T12:33:38Z
[ "python", "django", "django-rest-framework" ]
multiclass classification with double values and scikit
39,305,189
<p>I would like to train a programm to give dicts various tags depending on the numeric values they contain - with scikit. My problem is, that I only seem to understand how to classify text (sentences) or just number variables (and not variables that contain mulitple numbers).</p> <p>Here is what I am trying to do:</p...
1
2016-09-03T09:07:26Z
39,311,420
<p>You need to train two classifiers and fit them to your data twice. Suppose your data is (you can convert your dicts to a dataframe using <code>Pandas</code>):</p> <pre><code>| "temp" | "airpressure" | "airmoisture"| "target1" | "target2" | |:------:|:-------------:|:------------:|:---------:|:---------:| | 30 ...
0
2016-09-03T21:17:20Z
[ "python", "scikit-learn", "classification" ]