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
Python: Calculating Additions, Deletions, By Date
39,879,857
<p>I have two columns in a dataframe that has date and name. On a daily basis, I would like to count the number of records that enter and are deleted on a daily basis. </p> <pre><code>import numpy as np import pandas as pd df1 = pd.DataFrame({'Name': ['A', 'B', 'C', 'D','E']}) df1['Date'] = '2016-01-01' df2 = pd.DataF...
0
2016-10-05T17:02:01Z
39,882,691
<p>I have an attempt but I cannot say whether it will be as fast or as stable as whatever your full outer join might be but it works with the example above.</p> <p>Carrying from where you left off then,</p> <pre><code>df['Value'] = 1 df = df.set_index(['Date', 'Name']).unstack('Name').fillna(0) df = (df - df.shift(1...
1
2016-10-05T20:00:46Z
[ "python", "pandas", "dataframe" ]
Rotate a rectangle consisting of 4 tuples to left or right
39,879,924
<p>I'm working on a program to manipulate GIS data, but for this precise problem, I'm trying to rotate a rectangle of 4 points around the bottom left corner. I've got 1 tuple describing the bottom left corner: <code>x, y=40000,40000</code> I've also got a length x, and a length y, <code>x_displacement</code>, and <cod...
0
2016-10-05T17:05:46Z
39,880,778
<p>As a few commenters mentioned, you are rotating around the (0, 0) point, rather than the lower left point. As we are constructing the coordinates we can:</p> <ul> <li>First construct the shape at the (0, 0) point</li> <li>Rotate it</li> <li>Translate it out to where it needs to be</li> </ul> <p>The below gives an ...
1
2016-10-05T17:59:11Z
[ "python", "python-3.x", "rotation", "gis" ]
django migrate failing after switching from sqlite3 to postgres
39,879,939
<p>I have been developing a Django project using sqlite3 as the backend and it has been working well. I am now attempting to switch the project over to use postgres as the backend but running into some issues.</p> <p>After modifying my settings file, setting up postgres, creating the database and user I get the error ...
0
2016-10-05T17:06:54Z
40,100,350
<p>This may help you :</p> <p>I think you have pre-stored migration files(migrate for sqlite database). Now you have change the database configuration but still django looking for the existing table according to migration files you have(migrated for previous database). Better you delete all the migration files in mig...
0
2016-10-18T05:40:05Z
[ "python", "django", "postgresql", "django-models", "sqlite3" ]
Chaining functions for cleaner code
39,880,043
<p>I have the following functions that I would like to be able to chain together for usage to have cleaner code:</p> <pre><code>def label_encoder(dataframe, column): """ Encodes categorical variables """ le = preprocessing.LabelEncoder() le.fit(dataframe[column]) dataframe[column] = le.transfor...
0
2016-10-05T17:13:22Z
39,880,738
<p>You could partially evaluate <code>label_encoder</code> first using functools.partial, and then use that version to parse to your lambda. E.g.</p> <pre><code>from functools import partial fixed_col_bound_encoder = partial(label_encoder, column=2) new_df = reduce(lambda x, y: y(x), reversed([fixed_col_bound_encoder,...
3
2016-10-05T17:56:45Z
[ "python" ]
Efficient way to read non-empty cells in a column in CSV file
39,880,069
<p>I have a large python file (>500,000 rows), and would like to read non-empty cells in a column in the dataframe (panda). Right now, I am doing this:</p> <pre><code>df = pd.read_csv(filename) myiter = [] for xiter, x in enumerate(df['Column_name']): if (np.isnan(x) == False): myiter.ap...
0
2016-10-05T17:14:34Z
39,880,572
<p>are they tagged as <code>NaN</code> in your <code>df</code>?</p> <p>if yes then do</p> <pre><code>df.dropna() </code></pre>
0
2016-10-05T17:46:48Z
[ "python", "pandas", "dataframe", "large-files", "import-from-csv" ]
Move multiple elements (based on criteria) to end of list
39,880,110
<p>I have the following 2 Python lists:</p> <pre><code>main_l = ['Temp_Farh', 'Surface', 'Heater_back', 'Front_Press', 'Lateral_Cels', 'Gauge_Finl','Gauge_Relay','Temp_Throw','Front_JL'] hlig = ['Temp', 'Lateral', 'Heater','Front'] </code></pre> <p>I need to move elements from <code>main_l</code> to the end of the li...
1
2016-10-05T17:16:29Z
39,880,202
<p>You could sort <code>main_l</code> using whether each element contains a string from hlig as a key:</p> <pre><code>main_l.sort(key=lambda x: any(term in x for term in hlig)) </code></pre>
4
2016-10-05T17:23:28Z
[ "python", "list", "python-2.7" ]
Move multiple elements (based on criteria) to end of list
39,880,110
<p>I have the following 2 Python lists:</p> <pre><code>main_l = ['Temp_Farh', 'Surface', 'Heater_back', 'Front_Press', 'Lateral_Cels', 'Gauge_Finl','Gauge_Relay','Temp_Throw','Front_JL'] hlig = ['Temp', 'Lateral', 'Heater','Front'] </code></pre> <p>I need to move elements from <code>main_l</code> to the end of the li...
1
2016-10-05T17:16:29Z
39,880,406
<p>I would rewrite what you have to:</p> <pre><code>main_l = ['Temp_Farh', 'Surface', 'Heater_back', 'Front_Press', 'Lateral_Cels', 'Gauge_Finl','Gauge_Relay','Temp_Throw','Front_JL'] hlig = ['Temp', 'Lateral', 'Heater','Front'] found = [i for i in main_l if any(e in i for e in hlig)] </code></pre> <p>Then the solut...
1
2016-10-05T17:36:19Z
[ "python", "list", "python-2.7" ]
numpy.fromfile differences between python 2.7.3 and 2.7.6
39,880,198
<p>I'm having an issue running code between two consoles and I've gotten it down to a difference between the versions of python installed on these computers (2.7.3 and 2.7.6 respectively). </p> <p>Here is the input file found on github (<a href="https://github.com/tkkanno/PhD_work/blob/master/1r" rel="nofollow">https:...
0
2016-10-05T17:23:23Z
39,900,392
<p>Converted from <a href="https://stackoverflow.com/questions/39880198/numpy-fromfile-differences-between-python-2-7-3-and-2-7-6/39900392#comment67047204_39880198">my comment</a>:</p> <p>You're likely running on different Python/OS builds with different notions of how big a <code>long</code> is. C doesn't require a s...
0
2016-10-06T15:46:00Z
[ "python", "arrays", "numpy" ]
Zeroconf not found any service
39,880,204
<p>I started to test zeroconf to implement the discovery feature in a plugin I'm developing. At the beginning it was working good, but a few weeks ago it isn't showing any available service.</p> <p>I thought it was problem of my device, but Arduino IDE is showing the mDNS service (I'm using few nodemcu devices).</p> ...
0
2016-10-05T17:23:41Z
39,899,706
<p>As you can see in <a href="https://github.com/jstasiak/python-zeroconf/issues/85" rel="nofollow">this</a> github issue, the problem was related with <strong>natifaces</strong>, the solution is</p> <p>uninstall netifaces: <code>pip uninstall netifaces</code></p> <p>and install version 0.10.4</p> <p><code>pip insta...
1
2016-10-06T15:13:03Z
[ "python", "iot", "nodemcu", "zeroconf", "mdns" ]
pandas dataseries - How to address difference in days
39,880,209
<p>I have a pandas dataframe navTable whose index is a series of dates.</p> <p>I needed to find the difference between the consecutive dates in index</p> <pre><code> Delta 2016-08-10 0.006619 2016-08-12 0.006595 2016-08-14 0.006595 2016-08-17 0.006595 2016-08-18 ...
3
2016-10-05T17:24:15Z
39,881,020
<p>Normally you will use the <code>diff()</code> function to calculate the adjacent difference and you can convert the index to a normal series and then use the <code>diff()</code> function which gives a series of <code>time delta</code> data type:</p> <pre><code>df.index.to_series().diff() # 2016-08-10 NaT # 20...
2
2016-10-05T18:13:10Z
[ "python", "pandas", "time-series" ]
Kivy App build with Buildozer. APK crash
39,880,264
<p>I am using Oracle VirtualBox running Ubuntu 16. I have been able to build apk files for a while until my latest build. My program will run and keep its functionality when run with python 2.7 on the same Virtual machine. When i install the .apk file on my Samsung S3 it shows the standard kivy loading screen then cras...
-4
2016-10-05T17:26:48Z
39,880,864
<p>Turn USB Debuggin mode on in your device and connect your device to your PC and then run <code>adb logcat</code>. Run the application on your device and see what is going on in your application and what is the reason of crashing. you could also show us the the <code>adb logcat</code> result if you couldn't figure ou...
1
2016-10-05T18:04:26Z
[ "python", "kivy", "android-logcat", "ubuntu-16.04", "buildozer" ]
App Engine development server fails to execute queued task - with no stack trace whatsoever
39,880,267
<p>I'm currently trying to queue tasks in App Engine using the Flask framework, but I'm having some difficulty. I run my code, and it seems like the tasks are queued properly when I check the admin server at localhost:8000/taskqueue. However, the console repeatedly print the following error:</p> <pre><code>WARNING 2...
0
2016-10-05T17:26:58Z
39,880,600
<p>I've found the answer here: <a href="https://stackoverflow.com/a/13552794">https://stackoverflow.com/a/13552794</a></p> <p>Apparently, all I have to do is add the POST method to whichever handler is called for queuing.</p> <p>So</p> <pre><code>@app.route("/sample_task") def sample_task(): ... </code></pre> <p>sh...
0
2016-10-05T17:48:05Z
[ "python", "google-app-engine", "flask", "google-app-engine-python" ]
pyspark: TypeError: condition should be string or Column
39,880,269
<p>I am trying to filter an RDD based like below:</p> <pre><code>spark_df = sc.createDataFrame(pandas_df) spark_df.filter(lambda r: str(r['target']).startswith('good')) spark_df.take(5) </code></pre> <p>But got the following errors:</p> <pre><code>TypeErrorTraceback (most recent call last) &lt;ipython-input-8-86cfb3...
0
2016-10-05T17:27:11Z
39,884,079
<p><code>DataFrame.filter</code>, which is an alias for <code>DataFrame.where</code>, expects a SQL expression expressed either as a <code>Column</code>:</p> <pre><code>spark_df.filter(col("target").like("good%")) </code></pre> <p>or equivalent SQL string:</p> <pre><code>spark_df.filter("target LIKE 'good%'") </code...
2
2016-10-05T21:33:57Z
[ "python", "pandas", "pyspark", "spark-dataframe", "rdd" ]
pyspark: TypeError: condition should be string or Column
39,880,269
<p>I am trying to filter an RDD based like below:</p> <pre><code>spark_df = sc.createDataFrame(pandas_df) spark_df.filter(lambda r: str(r['target']).startswith('good')) spark_df.take(5) </code></pre> <p>But got the following errors:</p> <pre><code>TypeErrorTraceback (most recent call last) &lt;ipython-input-8-86cfb3...
0
2016-10-05T17:27:11Z
39,899,755
<p>I have been through this and have settled to using a UDF:</p> <pre><code>from pyspark.sql.functions import udf from pyspark.sql.types import BooleanType filtered_df = spark_df.filter(udf(lambda target: target.startswith('good'), BooleanType())(spark_df.target)) </code></pre> <p>...
0
2016-10-06T15:15:17Z
[ "python", "pandas", "pyspark", "spark-dataframe", "rdd" ]
Pybot - how to specify an xpath for an "a href" link
39,880,398
<p>I am trying to run a very simple test with pybot using the xpath but for some reason it keeps saying that my xpath is not a valid, even though I am following the documentation straight from <a href="http://robotframework.org/Selenium2Library/Selenium2Library.html" rel="nofollow">http://robotframework.org/Selenium2Li...
-2
2016-10-05T17:35:38Z
39,880,497
<p>Notice how your opening quote is different from the closing one?</p> <p>Change the <code>‘</code> in your syntax to a proper <code>'</code> -- and check that the close-quote in your real code is also a genuine ASCII-character-39 single-quote, not some fancy Unicode curly created by being copied/pasted through Mic...
2
2016-10-05T17:42:28Z
[ "python", "selenium", "xpath", "robotframework" ]
Testing students' code in Jupyter with a unittest
39,880,411
<p>I'd like my students to be able to check their code as they write it in a Jupyter Notebook by calling a function from an imported module which runs a unittest. This works fine unless the function needs to be checked against objects which are to be picked up in the global scope of the Notebook.</p> <p>Here's my <cod...
3
2016-10-05T17:36:56Z
39,880,566
<p>You can <code>import __main__</code> to access the notebook scope:</p> <pre><code>import unittest from IPython.display import Markdown, display import __main__ def printmd(string): display(Markdown(string)) class Tests(unittest.TestCase): def check_add_2(self, add_2): val = 5 self.asser...
2
2016-10-05T17:46:30Z
[ "python", "unit-testing", "python-3.x", "jupyter-notebook" ]
some python exercises and need some input
39,880,495
<p>This is the exercise.</p> <blockquote> <p>Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out a...
-3
2016-10-05T17:42:22Z
39,880,646
<p>You never entered a value for largest and smallest.</p> <pre><code>largest = float('-inf') # Always smaller than any number smallest = float('inf') # Always larger than any number while True: num = raw_input("Enter a number: ") if num == "done" : break if len(num) &lt; 1 : break try ...
0
2016-10-05T17:50:58Z
[ "python", "python-2.7" ]
str.endwith() return false in valid check
39,880,531
<p><strong>I don't need alternate solution.</strong> </p> <p>I'm using Python 2.5.4 and want know why this happens.</p> <p>I write source parser for makefiles.</p> <pre><code>ff = open("module.mk") f = ff.readlines() ff.close() for i in f: if ".o \\" in i[-5:]: print "Is %s for str: %s" %(i.endswith('.o \\'), i)...
-2
2016-10-05T17:44:05Z
39,880,662
<p>When you use <code>.readlines()</code> it includes the newline character in the line, CR-LF in this case.</p> <p>You need to remove that newline before checking <code>.endswith()</code> as such:</p> <pre><code>with open("module.mk") as data: for i in data.readlines(): if ".o \\" in i[-5:]: ...
1
2016-10-05T17:51:39Z
[ "python", "parsing", "windows-xp" ]
Using SoftLayer Python API placeOrder to add disks to vm
39,880,557
<p>I've created a softlayer VM using a custom image template. I am able to add SAN disks to my vm using curl but I'm unsuccessful trying to do this with the Python SoftLayer library. I receive the following error:</p> <pre><code>SoftLayer.exceptions.SoftLayerAPIError: SoftLayerAPIError(SoftLayer_Exception_Order_Inva...
0
2016-10-05T17:45:57Z
39,880,699
<p>yep, because when you are using the Softlayer's python client you do not have to specify the "paramters" property in your order that is only for RESTful request, remove it and it should work.</p> <p>Try this:</p> <pre><code>self.client = SoftLayer.Client(username='myusername@email.com', api_key='key') console_id =...
0
2016-10-05T17:53:59Z
[ "python", "curl", "softlayer" ]
In Pandas, how to delete rows from a Data Frame based on another Data Frame?
39,880,627
<p>I have 2 Data Frames, one named USERS and another named EXCLUDE. Both of them have a field named "email".</p> <p>Basically, I want to remove every row in USERS that has an email contained in EXCLUDE.</p> <p>How can I do it?</p>
2
2016-10-05T17:50:01Z
39,881,230
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> and condition with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a>, inverting boolean <code>Se...
2
2016-10-05T18:26:49Z
[ "python", "pandas" ]
pinging websites from array in a loop
39,880,655
<pre><code>import subproccess import sys mylist= ['google.com','bbc.com','yahoo.com','gmail.com','hotmail.com', 'amazon.com'] for ping in mylist(0,5): result = os.system("ping %s" % ping) result.stdout=open("test.txt","w") result.stdout.close() </code></pre> <p>Can someone please find the mista...
-1
2016-10-05T17:51:28Z
39,880,991
<ul> <li>os not imported</li> <li>mylist = ['google.com','bbc.com','yahoo.com','gmail.com','hotmail.com','amazon.com']</li> <li>for ping in mylist:</li> <li>result = os.system("ping -c 1 %s" % ping)</li> <li><p>f = open("test.txt","w") (open the file before entering the loop, else it would rewrite the file everytime t...
0
2016-10-05T18:11:33Z
[ "python", "arrays", "loops", "cmd", "ping" ]
How to iterate over ResultProxy many times?
39,880,685
<p>Suppose I execute the following query:</p> <pre><code>results = db.engine.execute(sql_query) </code></pre> <p>where it returns rows as expected: </p> <pre><code>&gt;&gt;&gt; for record in results: ... print(record['path']) ... Top.Collections.Pictures.Astronomy.Stars Top.Collections.Pictures.Astronomy.Galaxi...
0
2016-10-05T17:53:17Z
39,880,718
<p>You probably have an <em>iterator</em> object being returned, so once it's exhausted after iterating over it, you can't go over it again. Assuming your results are not extremely large, you can do:</p> <pre><code>results = db.engine.execute(sql_query) results = list(results) </code></pre> <p>That turns the iterato...
1
2016-10-05T17:55:15Z
[ "python", "sqlalchemy", "resultproxy" ]
Python Socket - Networking
39,880,806
<p>I am unable to figure out, whats wrong with my code here. I used pycharm debugger and found out that there is something wrong in my server code - with the command <code>clients_name.append(name)</code>.</p> <p>My server Code: </p> <h1>Server.py</h1> <pre><code>import socket import time import numpy as np import a...
1
2016-10-05T18:01:13Z
39,905,391
<p>This program starts a TCP server that handles each connection in a separate thread. The client connects to the server, gets the client list, and prints it. The client list is transferred as JSON. The receive buffers are set to 1024 bytes, so a client list longer than this will not be completely received.</p> <p><st...
1
2016-10-06T20:50:25Z
[ "python", "multithreading", "sockets" ]
how to count output and make newline every 7 characters?
39,880,880
<p>I just learned the basics of Python , when searching google for cool thing to do with Python found this pdf : <a href="http://usingpython.com/dl/Binary_Images.pdf" rel="nofollow">Binary_Image</a> (converting 1/0 to * and spaces) this pdf has a Challenge section which say's </p> <p>"Modify your program so that it ha...
0
2016-10-05T18:05:18Z
39,880,910
<p>Change:</p> <pre><code>if len(img_out) &gt;= "7": img_out = img_out + "\n" </code></pre> <p>To:</p> <pre><code>if len(img_out) &gt;= 7: img_out = img_out + "\n" </code></pre> <p><strong>UPDATE</strong>:</p> <pre><code>#get a binary number from the user img_in = input("Enter your b&amp;w bitmap i...
0
2016-10-05T18:07:12Z
[ "python", "io", "binary" ]
In-house made package and environmental variables link
39,880,906
<p>I created a python package for in-house use which relies upon some environmental variables (namely, the user and password to enter an online database). for my company, the convenience of installing a package rather than having it in every project is significant as the functions inside are used in completely separat...
0
2016-10-05T18:06:56Z
39,918,729
<p>I think I'll just detail in the readme file what to insert and where. I tried to find a difficult solution when it was really simple and straightforward</p>
0
2016-10-07T13:41:49Z
[ "python", "package", "environment-variables" ]
Compute the median of dynamic time series
39,880,920
<p>If I have a pandas series [a1,a2,a3,a4,...] with length = T. Each value corresponds to one day. For each day, I would like to compute the historical median. For example, the first day compute the median of [a1]; the second day compute the median of [a1,a2]; the nth day compute the median of [a1,a2,...,an]. Finally I...
0
2016-10-05T18:07:46Z
39,881,038
<p>For a Series, <code>ser</code>:</p> <pre><code>ser = pd.Series(np.random.randint(0, 100, 10)) </code></pre> <p>If your pandas version is 0.18.0 or above, use:</p> <pre><code>ser.expanding().median() Out: 0 0.0 1 25.0 2 50.0 3 36.5 4 33.0 5 36.0 6 33.0 7 36.0 8 33.0 9 36.0 dtype: fl...
0
2016-10-05T18:14:11Z
[ "python", "pandas" ]
Append to Numpy Using a For Loop
39,880,938
<p>I am working on a Python script that takes live streaming data and appends it to a numpy array. However I noticed that if I append to four different arrays one by one it works. For example:</p> <pre><code>openBidArray = np.append(openBidArray, bidPrice) highBidArray = np.append(highBidArray, bidPrice) lowBidArray =...
0
2016-10-05T18:08:56Z
39,880,968
<p>In your second example, you have strings, not np.array objects. You are trying to append a number(?) to a string.</p> <p>The string "openBidArray" doesn't hold any link to an array called <code>openBidArray</code>.</p>
1
2016-10-05T18:10:39Z
[ "python", "arrays", "numpy" ]
Append to Numpy Using a For Loop
39,880,938
<p>I am working on a Python script that takes live streaming data and appends it to a numpy array. However I noticed that if I append to four different arrays one by one it works. For example:</p> <pre><code>openBidArray = np.append(openBidArray, bidPrice) highBidArray = np.append(highBidArray, bidPrice) lowBidArray =...
0
2016-10-05T18:08:56Z
39,881,071
<p>Do this instead:</p> <pre><code>arrays = [openBidArray, highBidArray, lowBidArray, closeBidArray] </code></pre> <p>In other words, your list should be a list of arrays, not a list of strings that coincidentally contain the names of arrays you happen to have defined.</p> <p>Your next problem is that <code>np.appen...
2
2016-10-05T18:16:16Z
[ "python", "arrays", "numpy" ]
Can't convert column with pandas.to_numeric
39,880,953
<p>I have a column of data, here is a snip of it:</p> <pre><code>a = data["hs_directory"]["lat"][:5] 0 40.67029890700047 1 40.8276026690005 2 40.842414068000494 3 40.71067947100045 4 40.718810094000446 Name: lat, dtype: object </code></pre> <p>I try to convert it to numerical with python, but fail...
0
2016-10-05T18:09:55Z
39,881,329
<p>As discussed in the comments, let me post the answer for future readers:</p> <p>try:</p> <pre><code>df1=pd.to_numeric(a,errors='coerce') </code></pre>
0
2016-10-05T18:32:42Z
[ "python", "pandas", "converter" ]
Parse XML with using ElementTree library
39,880,964
<p>I am trying to parse an xml data to print its content with ElementTree library in python 3. but when I print lst it returns me an empty list.</p> <blockquote> <p>Error: Returning an empty array of list.</p> </blockquote> <p>My attempt:</p> <pre><code>import xml.etree.ElementTree as ET data = ''' &lt;data&gt...
0
2016-10-05T18:10:21Z
39,881,231
<p>Tree references the root item <code>&lt;data&gt;</code> already so it shouldn't be in your path statement. Just find "country".</p> <pre><code>import xml.etree.ElementTree as ET data = ''' &lt;data&gt; &lt;country name="Liechtenstein"&gt; &lt;rank&gt;1&lt;/rank&gt; &lt;year&gt;20...
1
2016-10-05T18:26:54Z
[ "python", "xml", "python-3.x" ]
Parquet Files from Spark detected as directory in Linux
39,881,051
<p>I am trying to use Python's parquet module to read in some Parquet files written from a local MapR instance.</p> <p>The command I used to output these parquet files is: </p> <pre><code>df.sqlContext.sql("SQL HERE").write.format("parquet").option("mergeSchema", "true").save("/path/to/parquet/test.parquet") </code><...
0
2016-10-05T18:14:53Z
39,881,137
<p>Based on the output of your ls command, itlooks like igayfvpwrs.parquet is actually a directory. Can you check for the data inside? </p>
0
2016-10-05T18:20:36Z
[ "python", "hadoop", "apache-spark", "parquet" ]
Parquet Files from Spark detected as directory in Linux
39,881,051
<p>I am trying to use Python's parquet module to read in some Parquet files written from a local MapR instance.</p> <p>The command I used to output these parquet files is: </p> <pre><code>df.sqlContext.sql("SQL HERE").write.format("parquet").option("mergeSchema", "true").save("/path/to/parquet/test.parquet") </code><...
0
2016-10-05T18:14:53Z
39,881,494
<p>There is no issue with parquet on spark here. The DataFrameWriter writes to parquet format into a directory and partition the output according the number of partition of the DataFrame it is writing. </p> <p>What you are getting is absolutely normal. </p>
0
2016-10-05T18:43:45Z
[ "python", "hadoop", "apache-spark", "parquet" ]
Counting number of characters in a key in a dictionary
39,881,062
<p>For homework I have been set the following:</p> <p>Build a dictionary with the names from myEmployees list as keys and assign each employee a salary of 10 000 (as value). Loop over the dictionary and increase the salary of employees which names have more than four letters with 1000 * length of their name. Print the...
1
2016-10-05T18:15:51Z
39,881,134
<p>You have some indentation problems, clearly, but the main problems are that you are taking the length of the dictionary (getting the number of keys) not taking the length of the key. You also have some bad logic.</p> <pre><code>employeeDict = {"John":'10,000', "Daren":"10,000", "Graham":"10,000", "Steve":"10,000", ...
0
2016-10-05T18:20:19Z
[ "python", "dictionary", "count" ]
Counting number of characters in a key in a dictionary
39,881,062
<p>For homework I have been set the following:</p> <p>Build a dictionary with the names from myEmployees list as keys and assign each employee a salary of 10 000 (as value). Loop over the dictionary and increase the salary of employees which names have more than four letters with 1000 * length of their name. Print the...
1
2016-10-05T18:15:51Z
39,881,162
<p>First, change the values to integers/floats.</p> <pre><code>employeeDict = {"John":10000, "Daren":10000, "Graham":10000, "Steve":10000, "Adren":10000} </code></pre> <p>After doing this, as you know, you need to loop over the items in the dict.</p> <pre><code>for x in employeeDict: x = len(employeeDict) if...
0
2016-10-05T18:22:25Z
[ "python", "dictionary", "count" ]
Counting number of characters in a key in a dictionary
39,881,062
<p>For homework I have been set the following:</p> <p>Build a dictionary with the names from myEmployees list as keys and assign each employee a salary of 10 000 (as value). Loop over the dictionary and increase the salary of employees which names have more than four letters with 1000 * length of their name. Print the...
1
2016-10-05T18:15:51Z
39,881,166
<p>Give this a try and analyse it :</p> <p></p> <pre><code>employees = {"John":10000, "Daren":10000, "Graham":10000} for name in employees: if len(name) &gt; 5: employees[name] += 1000 * len(name) </code></pre> <p>If you have to stick with the string values you can do this :</p> <p></p> <pre><code>emp...
0
2016-10-05T18:22:41Z
[ "python", "dictionary", "count" ]
Counting number of characters in a key in a dictionary
39,881,062
<p>For homework I have been set the following:</p> <p>Build a dictionary with the names from myEmployees list as keys and assign each employee a salary of 10 000 (as value). Loop over the dictionary and increase the salary of employees which names have more than four letters with 1000 * length of their name. Print the...
1
2016-10-05T18:15:51Z
39,881,186
<p>This should give you what your looking for.</p> <pre><code>employeeDict = {"John":10000, "Daren":10000, "Graham":10000, "Steve":10000, "Adren":10000} print "Before increase" print employeeDict for name, salary in employeeDict.items(): if len(name) &gt; 4: employeeDict[name] = salary + len(name) * 1000 ...
0
2016-10-05T18:23:40Z
[ "python", "dictionary", "count" ]
Results for python and MATLAB caffe are different for the same network
39,881,081
<p>I am trying to port MATLAB implementation of <a href="https://github.com/kpzhang93/MTCNN_face_detection_alignment" rel="nofollow">MTCNN_face_detection_alignment</a> to python. I use the same version of caffe bindings for MATLAB and for python.</p> <p>Minimal runnable code to reproduce the issue:</p> <p>MATLAB:</p>...
2
2016-10-05T18:16:55Z
39,892,959
<p>I found the issue source, it is because MATLAB sees image transposed. This python code shows the same result as MATLAB one:</p> <pre><code>import numpy as np import caffe import cv2 caffe.set_mode_gpu() caffe.set_device(0) model = './model/det1.prototxt' weights = './model/det1.caffemodel' PNet = caffe.Net(model...
2
2016-10-06T09:57:57Z
[ "python", "matlab", "caffe", "pycaffe", "matcaffe" ]
How to run SublimeText with visual studio environment enabled
39,881,091
<p><strong>OVERVIEW</strong></p> <p>Right now I got these 2 programs on my windows taskbar:</p> <ul> <li><p>SublimeText3 target: </p> <pre><code>"D:\software\SublimeText 3_x64\sublime_text.exe" </code></pre></li> <li><p>VS2015 x64 Native Tools Command Prompt target: </p> <pre><code>%comspec% /k ""C:\Program Files (...
0
2016-10-05T18:17:49Z
39,883,233
<ol start="2"> <li>exactly as stated is not possible directly but Sublime Text has options for running other programs.</li> </ol> <p>Make a batch file that goes to the directory that vcvarsall.bat wants (it looks at the directory it was run from, so it needs to be started from the proper dir) and runs vcvarsall.bat:</...
0
2016-10-05T20:37:36Z
[ "python", "windows", "visual-studio-2015", "environment-variables", "sublimetext3" ]
Fast way to compress audio data?
39,881,122
<p>I'm trying to build (Inspirated by teamspeak) a voip program that comunicate via UDP.</p> <p>Here is my source (Server):</p> <pre><code>import pyaudio import socket CHUNK = 1024 FORMAT = pyaudio.paInt16 CHANNELS = 1 RATE = 44100 p = pyaudio.PyAudio() stream = p.open(format=FORMAT, channels = CHA...
0
2016-10-05T18:19:44Z
39,882,543
<p>FFmpeg works on Pipe protocols, and the same functionality has been ported to ffmpy so data can be written to stdin and read from stdout. You would likely have to provide some timing constructs as well to handle synchronization and appropriate buffer managment, but I see no reason this couldn't be made to work. </p>...
1
2016-10-05T19:51:39Z
[ "python", "audio", "encoding", "compression" ]
Python access all entrys from one dimension in a multidimensional numpy array
39,881,164
<p>I would like to manipulate the data of all entries of a complicated 3d numpy array. I want all entries of all subarrays in the X-Y-Position. I know Matlab can do something like that (with the variable indicator : for everything) I indicated that below with DARK[:][1][1]. Which basically mean I want the second entry ...
-1
2016-10-05T18:22:28Z
39,881,262
<p>You can do this using slightly different syntax.</p> <pre><code>import numpy as np a = np.arange(27).reshape(3,3,3) # Create a 3x3x3 3d array print("3d Array:") print(a) print("Second Row, Second Column: ", a[:,1,1]) </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; 3d Array: [[[ 0 1 2] [ 3 4 5] [...
1
2016-10-05T18:28:43Z
[ "python", "arrays", "numpy" ]
Python access all entrys from one dimension in a multidimensional numpy array
39,881,164
<p>I would like to manipulate the data of all entries of a complicated 3d numpy array. I want all entries of all subarrays in the X-Y-Position. I know Matlab can do something like that (with the variable indicator : for everything) I indicated that below with DARK[:][1][1]. Which basically mean I want the second entry ...
-1
2016-10-05T18:22:28Z
39,881,535
<p>Found the solution, thanks <strong>Divakar</strong> and <strong>eeScott</strong>:</p> <pre><code>import numpy as np # Creating a dummy variable of the type I deal with (If this looks crappy sorry, the variable actually comes from the output of d = pyfits.getdata()): a = [] for i in range(3): d = np.array([[i, ...
1
2016-10-05T18:46:35Z
[ "python", "arrays", "numpy" ]
Python access all entrys from one dimension in a multidimensional numpy array
39,881,164
<p>I would like to manipulate the data of all entries of a complicated 3d numpy array. I want all entries of all subarrays in the X-Y-Position. I know Matlab can do something like that (with the variable indicator : for everything) I indicated that below with DARK[:][1][1]. Which basically mean I want the second entry ...
-1
2016-10-05T18:22:28Z
39,881,572
<p>The point is you are creating a list of arrays, not a multidimensional array. For this specific example you can use <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehensions</a> to build directly the structure you need and convert it to an array. Then you...
0
2016-10-05T18:48:54Z
[ "python", "arrays", "numpy" ]
How do you run an OR query in Peewee ORM?
39,881,232
<p>I'd like to run a query for a user based on username or email address.</p> <p>I must be missing it, but I can't find how to run an <code>OR</code> query in the peewee documentation. How do you do that?</p>
-1
2016-10-05T18:27:00Z
39,881,259
<p>From the <a href="http://docs.peewee-orm.com/en/latest/peewee/querying.html#filtering-records">documentation</a></p> <blockquote> <p>If you want to express a complex query, use parentheses and python’s bitwise or and and operators:</p> </blockquote> <pre><code>&gt;&gt;&gt; Tweet.select().join(User).where( ... ...
5
2016-10-05T18:28:21Z
[ "python", "peewee" ]
Python Flask Sqlalchemy Subst Query
39,881,240
<p>I am working on an internel search engine at my company written in python utilizing flask and sqlalchemy(sqlite). My current problem is that I would like to.</p> <p>A.) Query on a certain amount of information for the description field B.) Preferable query before it 50 characters and after it.</p> <p>Very similia...
0
2016-10-05T18:27:18Z
39,882,043
<p>This has nothing to do with the <code>mid</code> function. The error message says <code>'BaseQuery' object is not callable.</code> Where are you calling <code>BaseQuery</code>? Here:</p> <pre><code>Item.query(...) </code></pre> <p>The correct incantation is:</p> <pre><code>db.session.query(func.mid(...)) </code><...
2
2016-10-05T19:19:54Z
[ "python", "sql", "sqlalchemy", "flask-sqlalchemy" ]
Sympy on PyPy - Sometimes 6x faster, sometimes 4x slower
39,881,276
<p>Here, pypy is slower in calculating, whether a given number is prime:</p> <pre><code>C:\Users\User&gt;python -m timeit -n10 -s"from sympy import isprime" "isprime(2**521-1)" 10 loops, best of 3: 25.9 msec per loop C:\Users\User&gt;pypy -m timeit -n10 -s"from sympy import isprime" "isprime(2**521-1)" 10 loops, best...
1
2016-10-05T18:29:48Z
39,884,187
<p><code>isprime</code> has a fast path for when <code>gmpy</code> is installed. <code>gmpy</code> has bindings to a highly optimized C library, and is probably only installed on CPython.</p>
2
2016-10-05T21:42:28Z
[ "python", "performance", "sympy", "pypy" ]
GAE python: success message or add HTML class after redirect
39,881,280
<p>I've a website with a contact form running on a google App Engine. After submitting I'd like to redirect and show a message to the user to let him know the message was sent, this can eighter be a alert message or adding a class to a html tag. How can I do that?</p> <p>my python file looks like this:</p> <pre><code...
1
2016-10-05T18:30:01Z
39,881,767
<p>After the redirect a request <strong>different</strong> than the POST one for which the email was sent will be served.</p> <p>So you need to <strong>persist</strong> the information about the email being sent across requests, saving it in the POST request handler code and retrieving it in the subsequent GET request...
0
2016-10-05T19:02:16Z
[ "javascript", "python", "html", "google-app-engine" ]
Threading with subprocess
39,881,356
<p>I am using python 2.7 and new to Threading. I got a class file and run method. But I don't see the run method invoked when I create instances of thread. I am also planning to use <code>subprocess.Popen</code> inside the <code>run</code> method and get <code>stdout</code> of the process for each filename and print th...
1
2016-10-05T18:34:18Z
39,881,398
<p>you're forgetting to call the mother class constructor to specify target. It's not java, and <code>run</code> has no particular meaning. By default, target is <code>None</code> and the thread does nothing.</p> <pre><code>import threading class FileScanThread(threading.Thread): def __init__(self, myFileName): ...
4
2016-10-05T18:37:17Z
[ "python", "multithreading" ]
Threading with subprocess
39,881,356
<p>I am using python 2.7 and new to Threading. I got a class file and run method. But I don't see the run method invoked when I create instances of thread. I am also planning to use <code>subprocess.Popen</code> inside the <code>run</code> method and get <code>stdout</code> of the process for each filename and print th...
1
2016-10-05T18:34:18Z
39,881,492
<p>This will do what you want. You aren't calling <code>__init__</code> from the class Thread.</p> <pre><code>class FileScanThread(threading.Thread): def __init__(self, myFileName): threading.Thread.__init__(self) print("In File Scan Thread") self.mapFile = myFileName #myjar=myFileN...
1
2016-10-05T18:43:36Z
[ "python", "multithreading" ]
BeautifulSoup unable to parse Goa University site
39,881,393
<p>I am working on a parsing project which require me to parse educational website. While doing so, my code is unable to parse <a href="http://unigoa.ac.in" rel="nofollow"><strong>University of Goa</strong></a> site. It does not return as expected. My code:</p> <pre class="lang-py prettyprint-override"><code>from bs4 ...
1
2016-10-05T18:36:51Z
39,881,531
<p>You need to create a session then parse and use the redirect url:</p> <pre><code>with requests.Session() as s: s.headers.update(hdrs) r = s.get("https://www.unigoa.ac.in") result = BeautifulSoup(r.content) redirect = result.find("script").text.split("=")[1].strip('";\r\n') r2 = s.get(redirect) ...
1
2016-10-05T18:46:22Z
[ "python", "python-2.7", "python-3.x", "parsing", "beautifulsoup" ]
tensorflow import error. With /Library/Python/2.7/site-packages not included
39,881,437
<p>Trying to install tensorflow. Tried anaconda, it worked but affected my other program. Then decided to use pip install.</p> <p>But after I installed it, I just can't import it within ipython.</p> <p>Here are the messages: I tried uninstall and reinstall.</p> <pre><code>pip install tensorflow Requirement already s...
2
2016-10-05T18:40:20Z
39,900,144
<p>OK, I got the problem fixed.</p> <p>I am not sure what exactly is causing it. Because I installed all this on my RMBP, nothing wrong. But desktop just won't take it.</p> <p>Solution is:</p> <p>Uninstall all previously installed or half installed tensorflow, and my other packages (just two main packages). And use ...
0
2016-10-06T15:34:01Z
[ "python", "ipython", "tensorflow" ]
best way to transfer data from flask to d3
39,881,571
<p>I have csv tables, processed in Pandas, that I would like to serve from Flask to the browser so that I can use d3 to display the information. How do I transfer the data from Flask to the browser? </p>
0
2016-10-05T18:48:53Z
39,882,115
<p>Use the to_csv method of the Pandas dataframe, and return that from your flask server:</p> <pre><code># app.py @app.route('/my/data/entpoint') def get_d3_data(): df = pandas.DataFrame(...) # Constructed however you need it return df.to_csv() </code></pre> <p>Then on the front end, direct d3.tsv to your end...
0
2016-10-05T19:26:13Z
[ "javascript", "python", "d3.js", "flask", "routing" ]
How to clear pending analysis in Cuckoo sandbox platform
39,881,589
<p>I am testing malware detection on guest VM using Cuckoo sandbox platform. To speed up the analysis, I want to remove pending analysis but keep completed analysis. </p> <p>Cuckoo have --clean option but it will clean all tasks and samples. Can you think of a way to only remove pending analysis? </p> <p>Thanks</p>
0
2016-10-05T18:50:27Z
39,904,650
<p>You can do it by deleting entries from the mysql database for pending analysis.</p>
0
2016-10-06T19:57:19Z
[ "python", "virtual-machine", "sandbox", "antivirus", "malware-detection" ]
Parse one or more expressions with helpful errors
39,881,655
<p>I'm using grako (a PEG parser generator library for python) to parse a simple declarative language where a document can contain one or more protocols.</p> <p>Originally, I had the root rule for document written as:</p> <p><code>document = {protocol}+ ;</code></p> <p>This appropriately returns a list of protocols,...
2
2016-10-05T18:55:03Z
39,886,192
<p>This is the solution:</p> <pre><code>document = {protocol ~ }+ $ ; </code></pre> <p>If you don't add the <code>$</code> for the parser to see the end of file, the parse will succeed with one or more <em>protocol</em>, even if there are more to parse.</p> <p>Adding the <em>cut</em> expression (<code>~</code>) make...
1
2016-10-06T01:39:52Z
[ "python", "parsing", "ebnf", "peg", "grako" ]
Terminate loop at any given time
39,881,660
<p>I have the following code which turns an outlet on/off every 3 seconds.</p> <pre><code> start_time = time.time() counter = 0 agent = snmpy4.Agent("192.168.9.50") while True: if (counter % 2 == 0): agent.set("1.3.6.1.4.1.13742.6.4.1.2.1.2.1.1",1) else: agent.s...
0
2016-10-05T18:55:22Z
39,881,978
<p>You can put the loop in a thread and use the main thread to wait on the keyboard. If its okay for "something to be entered" can be a line with line feed (e.g., type a command and enter), then this will do</p> <pre><code>import time import threading import sys def agent_setter(event): start_time = time.time() ...
0
2016-10-05T19:16:12Z
[ "python", "loops", "break" ]
Jinja2 Environment ImportError in Django 1.10 with Python 3.5
39,881,708
<p>I have a Django 1.10 project (with Python 3.5, and Jinja2 2.8 for templates) setup like this:</p> <p><a href="http://i.stack.imgur.com/QSdtj.png" rel="nofollow"><img src="http://i.stack.imgur.com/QSdtj.png" alt="Directory structure"></a></p> <p>*Consider the red marks as <code>mysite</code></p> <p>File <code>jinj...
0
2016-10-05T18:58:27Z
39,883,270
<p>You've called your own file <code>jinja2</code>. So Python finds that instead of the actual Jinja2 library when you do <code>import jinja2</code>.</p> <p>Call your file something else.</p>
0
2016-10-05T20:40:36Z
[ "python", "django" ]
Jinja2 Environment ImportError in Django 1.10 with Python 3.5
39,881,708
<p>I have a Django 1.10 project (with Python 3.5, and Jinja2 2.8 for templates) setup like this:</p> <p><a href="http://i.stack.imgur.com/QSdtj.png" rel="nofollow"><img src="http://i.stack.imgur.com/QSdtj.png" alt="Directory structure"></a></p> <p>*Consider the red marks as <code>mysite</code></p> <p>File <code>jinj...
0
2016-10-05T18:58:27Z
39,884,017
<p>I think you put the <code>jinja2.py</code> in a wrong position. It should be in the dir <code>mysite/</code>.</p> <p>This is the directory structure of my django project <code>mysite</code>(Jin2 is a app dir), which can run normally:</p> <pre><code>➜ /tmp/jinja/mysite $ tree . -I '*.pyc' . ├── db.sqlite3 â...
0
2016-10-05T21:30:28Z
[ "python", "django" ]
how would i use php to display multiple buttons on a web page (they are going to control a raspberry pi)
39,881,738
<p>i am creating a home automation system, i am using my raspberry pi as a web server to control the gpio ports, p have used some code to turn on the gpio ports. what i want to do is have different php buttons that run different python scripts in turn they turn on different ports. i know lots about python but very litt...
0
2016-10-05T19:00:22Z
39,906,578
<p>One solution would be to add all your html into a php file, add all your php code on top of that and run it in your browser. This assuming that www-data user have correct permissions on your file systems to execute the python scripts. </p> <p>Example:</p> <pre><code>&lt;?php if (isset($_POST['on'])) { exec("sudo ...
0
2016-10-06T22:27:23Z
[ "python", "linux", "raspberry-pi", "composer-php" ]
Correct usage of Decimal objects in this expression
39,881,740
<p>I need to calculate the area of any regular polygon. I acquired this formula from a good ol' google:</p> <pre><code>(n * l**2) / (4 * math.tan((180/n) * (math.pi/180))) </code></pre> <p>No matter how I use <code>decimal.Decimal</code> with these values I can never get it to work as intended. <code>n</code> and <co...
-1
2016-10-05T19:00:29Z
39,881,858
<p>You need to set the precision for the decimal object. Pi is an infinite decimal number, so the precision won't be a whole number.</p> <p>You can do</p> <pre><code>from decimal import * getcontext().prec = 1 </code></pre> <p>or add to the decimal object by rounding down.</p> <pre><code>&gt;&gt;&gt; Decimal('7.32...
1
2016-10-05T19:08:10Z
[ "python", "python-3.x", "decimal" ]
Aws passing credentials to ansible s3 module
39,881,807
<p>In ansible,When I am passing the access key,secret key,token to my aws credentials,it passes the access key to my ansible module s3 ,but when I am passing secret key and token it shows me <code>""VALUE_SPECIFIED_IN_NO_LOG_PARAMETER"</code> like that.So how can I solve this.</p> <p>In accesskey id there is no extra...
0
2016-10-05T19:05:02Z
39,882,855
<p><code>aws_secret_key</code> and <code>security_token</code> are marked as <code>no_log</code> arguments. See <a href="https://github.com/ansible/ansible/blob/devel/lib/ansible/module_utils/ec2.py#L125" rel="nofollow">source</a>.<br> It is sensitive data, so not printed to stdout and you see <code>VALUE_SPECIFIED_IN_...
1
2016-10-05T20:10:48Z
[ "python", "amazon-web-services", "amazon-s3", "ansible", "ansible-playbook" ]
Hide upper/right tick markers using rcparams/mplstyle
39,882,004
<p>I am currently using a variant of <a href="http://stackoverflow.com/a/11417222/2552873">this answer</a> to eliminate the top/right edges on my plots. However, I would like to be able to add this to my .mplstyle file instead of calling this function for every plot I create. Is there a way to achieve this functionalit...
1
2016-10-05T19:17:58Z
39,884,034
<p>You can use:</p> <pre><code>axes.spines.top : False axes.spines.right : False </code></pre> <p>in a mpstyle file to turn off spines. Unfortunately, <a href="http://stackoverflow.com/a/38750147/812786">this recent answer</a> indicates that ticks cannot currently be controlled from an rc or style file like this, and...
1
2016-10-05T21:31:10Z
[ "python", "matplotlib" ]
pip error after upgrading pip & scrapy by "pip install --upgrade"
39,882,200
<p>Using debian 8(jessie) amd64 with python 2.7.9. I tried following commands:</p> <pre><code>pip install --upgrade pip pip install --upgrade scrapy </code></pre> <p>after that, I am getting following pip error</p> <pre><code>root@debian:~# pip Traceback (most recent call last): File "/usr/local/bin/pip", line 11, ...
2
2016-10-05T19:31:23Z
39,882,444
<p>Got the exact same error today, but in a different situation. I suspect this is related to <code>cryptography</code> module.</p> <p>What helped me was to install a specific version of <code>cffi</code> package:</p> <pre><code>pip install cffi==1.7.0 </code></pre>
0
2016-10-05T19:46:34Z
[ "python", "scrapy", "pip" ]
pip error after upgrading pip & scrapy by "pip install --upgrade"
39,882,200
<p>Using debian 8(jessie) amd64 with python 2.7.9. I tried following commands:</p> <pre><code>pip install --upgrade pip pip install --upgrade scrapy </code></pre> <p>after that, I am getting following pip error</p> <pre><code>root@debian:~# pip Traceback (most recent call last): File "/usr/local/bin/pip", line 11, ...
2
2016-10-05T19:31:23Z
39,901,990
<p>i removed cffi and tried this command to install cffi 1.7.0:</p> <pre><code>pip install cffi==1.7.0 </code></pre> <p>it worked, thank you, alecxe and moeseth :)</p>
0
2016-10-06T17:13:03Z
[ "python", "scrapy", "pip" ]
pip error after upgrading pip & scrapy by "pip install --upgrade"
39,882,200
<p>Using debian 8(jessie) amd64 with python 2.7.9. I tried following commands:</p> <pre><code>pip install --upgrade pip pip install --upgrade scrapy </code></pre> <p>after that, I am getting following pip error</p> <pre><code>root@debian:~# pip Traceback (most recent call last): File "/usr/local/bin/pip", line 11, ...
2
2016-10-05T19:31:23Z
40,011,723
<p>My situation was like @alecxe</p> <p>This works:</p> <pre><code>pip install cffi==1.7.0 </code></pre>
0
2016-10-13T03:18:38Z
[ "python", "scrapy", "pip" ]
pip error after upgrading pip & scrapy by "pip install --upgrade"
39,882,200
<p>Using debian 8(jessie) amd64 with python 2.7.9. I tried following commands:</p> <pre><code>pip install --upgrade pip pip install --upgrade scrapy </code></pre> <p>after that, I am getting following pip error</p> <pre><code>root@debian:~# pip Traceback (most recent call last): File "/usr/local/bin/pip", line 11, ...
2
2016-10-05T19:31:23Z
40,056,431
<p>Had the same problem as <em>moeseth</em>: the <code>pip install something</code> answers are pretty useless when all pip commands throw the original exception. Installing cffi v. 1.7.0 also solved the problem and this is how I managed to do it in Debian Jessie without relying on pip:</p> <ol> <li><p>Temporarily add...
0
2016-10-15T07:38:47Z
[ "python", "scrapy", "pip" ]
POST data from modelform_factory generated form
39,882,222
<p>What I'm trying to accomplish is to save the data to the relevant model. Very much looking to mimic the Django admin interface.</p> <p>urls.py </p> <pre><code>url(r'^admin/add/(\w+)', views.admin_add_object, name='admin_add_object'), </code></pre> <p>view.py: </p> <pre><code>def admin_add_object(request, model...
0
2016-10-05T19:33:19Z
39,882,389
<pre><code>def admin_add_object(request, model): model_name = apps.get_model("product", model) ModelFormSet = modelformset_factory(model_name) if request.method == 'POST': formset = ModelFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() # do s...
0
2016-10-05T19:43:55Z
[ "python", "django", "python-2.7", "django-models", "django-forms" ]
ImportError: No module named caffe while running spark-submit
39,882,281
<p>While running a <code>spark-submit</code> on a spark standalone cluster comprised of one master and 1 worker, the <code>caffe</code> python module does not get imported due to error <code>ImportError: No module named caffe</code></p> <p>This doesn't seem to be an issue whenever I run a job locally by <code>spark-s...
1
2016-10-05T19:37:06Z
40,077,765
<p>Please note that the CaffeOnSpark team ported Caffe to a distributed environment backed by Hadoop and Spark. You cannot, I am 99.99% sure, use Caffe alone <em>(without any modifications)</em> in a Spark cluster or any distributed environment per se. (Caffe team is known to be working on this).</p> <p>If you need di...
0
2016-10-17T02:43:10Z
[ "python", "ubuntu", "apache-spark", "caffe", "pycaffe" ]
remove quotes from csv file data in python
39,882,301
<p>I have a csv that is being imported from url and placed into a database, however it imports with quotes around the names and id like to remove them. The originial format of the csv file is</p> <pre><code>"Apple Inc.",113.08,113.07 "Alphabet Inc.",777.61,777.30 "Microsoft Corporation",57.730,57.720 </code></pre> <p...
-1
2016-10-05T19:38:33Z
39,882,598
<p><code>csv.reader</code> removes the quotes properly. You may be viewing a quoted string representation of the text instead of the actual text.</p> <pre><code>&gt;&gt;&gt; new_data = '''"Apple Inc.",113.08,113.07 ... "Alphabet Inc.",777.61,777.30 ... "Microsoft Corporation",57.730,57.720''' &gt;&gt;&gt; &gt;&gt;&gt...
1
2016-10-05T19:54:53Z
[ "python", "mysql", "csv" ]
remove quotes from csv file data in python
39,882,301
<p>I have a csv that is being imported from url and placed into a database, however it imports with quotes around the names and id like to remove them. The originial format of the csv file is</p> <pre><code>"Apple Inc.",113.08,113.07 "Alphabet Inc.",777.61,777.30 "Microsoft Corporation",57.730,57.720 </code></pre> <p...
-1
2016-10-05T19:38:33Z
39,938,223
<p>Figured it out, the problem was as tdelaney mentioned was that the quotes were not acually in the string it was python, so my changing value in </p> <pre><code>cursor.execute('INSERT INTO `trade_data`.`import_data`' '(date, name, price) VALUES(%s, "%s", %s)', row) </cod...
0
2016-10-08T22:56:17Z
[ "python", "mysql", "csv" ]
Django REST framework foreign key with generics.ListCreateAPIView
39,882,314
<p>How it is possible to get foreign key assigned in url with Django REST Framework?</p> <pre><code>class CommentList(generics.ListCreateAPIView): serializer_class = CommentSerializer pagination_class = StandardResultsSetPagination queryset = Comment.objects.all() def get(self, *args, **kwargs): ...
1
2016-10-05T19:39:42Z
39,885,914
<p>If you want to get the pk. You can use <code>lookup_url_kwarg</code> attribute from <code>ListCreateAPIView</code> class.</p> <pre><code>class CommentLikeList(ListCreateAPIView): def get(self, request, *args, **kwargs): key = self.kwargs[self.lookup_url_kwarg] commentLikes = CommentLike.objects...
1
2016-10-06T01:01:33Z
[ "python", "django", "generics", "foreign-keys", "django-rest-framework" ]
Python connect to Teradata in AWS EC2
39,882,352
<p>I want to pull data from a Teradata instance. Client code runs Python2.7+ on AWS EC2 instance.</p> <p>I installed unixODBC driver and <code>sudo pip install teradata</code> but I am still getting the following exception:</p> <pre><code> File "/usr/local/lib/python2.7/site-packages/teradata/tdodbc.py", line 369, i...
0
2016-10-05T19:41:56Z
39,894,883
<p>It sounds like you need to install the Teradata ODBC driver.</p> <p>Available on the Teradata Developer Exchange. <a href="http://downloads.teradata.com/download/connectivity" rel="nofollow">http://downloads.teradata.com/download/connectivity</a></p>
0
2016-10-06T11:32:36Z
[ "python", "python-2.7", "amazon-ec2", "odbc", "teradata" ]
image downloading gets stuck on a link that doesn't exists anymore
39,882,388
<p>So I am not sure how to handle this situation. It almost works on many other broken links but not this one:</p> <pre><code>import datetime import praw import re import urllib import requests from bs4 import BeautifulSoup sub = 'dog' imgurUrlPattern = re.compile(r'(http://i.imgur.com/(.*))(\?.*)?') r = praw.Redd...
0
2016-10-05T19:43:54Z
39,882,797
<p>Use <code>urlopen</code> with <code>timeout</code> argument:</p> <pre><code>&gt;&gt;&gt; import urllib2 &gt;&gt;&gt; modified_url = 'http://cutearoo.com/wp-content/uploads/2011/04/Pomsky.png' &gt;&gt;&gt; try: ... image_file = urllib2.urlopen(modified_url, timeout=5) ... except urllib2.URLError: ... print '...
1
2016-10-05T20:06:36Z
[ "python", "http", "urllib", "information-retrieval" ]
python request payload without sorting
39,882,412
<p>I am trying to use python request module to pass few values to server using the following code, but in the http request its changing the order of the payload values. </p> <pre><code>payload3 = {'OSILA_LinkTo_Site': OSILA_LinkTo_Site, 'OSILA_LinkTo_Service': OSILA_LinkTo_Service, 'OSILA_Locale': OSILA_Locale, 'OSI...
2
2016-10-05T19:44:49Z
39,882,607
<p>You can pass tuples in place of the dict:</p> <pre><code>In [7]: ...: import requests ...: d = {"foo":"bar","bar":"foo","123":"456"} ...: t = (("foo","bar"),("bar","foo"),("123","456")) ...: r1 = requests.post("http://httpbin.org", data=d) ...: r2 = requests.post("http://httpbin.org", data=t) ......
1
2016-10-05T19:55:30Z
[ "python", "python-requests", "unify" ]
django-tables2 flooding database with queries
39,882,504
<p>im using django-tables2 in order to show values from a database query. And everythings works fine. Im now using Django-dabug-toolbar and was looking through my pages with it. More out of curiosity than performance needs. When a lokked at the page with the table i saw that the debug toolbar registerd over 300 queries...
0
2016-10-05T19:49:37Z
39,882,505
<p>Im posting this as a future reference for myself and other who might have the same problem. </p> <p>After searching for a bit I found out that django-tables2 was sending a single query for each row. The query was something like <code>SELECT * FROM "table" LIMIT 1 OFFSET 1</code> with increasing offset. </p> <p>I ...
0
2016-10-05T19:49:37Z
[ "python", "django", "django-tables2" ]
Finding duplicate rows python
39,882,522
<p>I have <code>timestamp</code> and <code>id</code> variables in my dataframe (<code>df</code>)</p> <pre><code>timestamp id 2016-06-09 8:33:37 a1 2016-06-09 8:33:37 a1 2016-06-09 8:33:38 a1 2016-06-09 8:33:39 a1 2016-06-09 8:33:39 a1 2016-06-09 ...
1
2016-10-05T19:50:14Z
39,882,642
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> and get mask of all duplicates values per group by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.duplicated.html" rel="nofollow"><code>Serie...
1
2016-10-05T19:57:15Z
[ "python", "pandas", "timestamp", "duplicates" ]
Finding duplicate rows python
39,882,522
<p>I have <code>timestamp</code> and <code>id</code> variables in my dataframe (<code>df</code>)</p> <pre><code>timestamp id 2016-06-09 8:33:37 a1 2016-06-09 8:33:37 a1 2016-06-09 8:33:38 a1 2016-06-09 8:33:39 a1 2016-06-09 8:33:39 a1 2016-06-09 ...
1
2016-10-05T19:50:14Z
39,883,411
<p>If you wish to find all duplicates then use the <code>duplicated</code> method. It only works on the columns. On the other hand <code>df.index.duplicated</code> works on the index. Therefore we do a quick <code>reset_index</code> to bring the index into the columns.</p> <pre><code>df = df.reset_index() df.ix[df.dup...
0
2016-10-05T20:50:23Z
[ "python", "pandas", "timestamp", "duplicates" ]
Add custom items to QListWidget
39,882,602
<p>How can I add customized items to a QListWidget with a background color that I choose, and add a bottom border to each item, like this draft example in the picture below.</p> <p>This is the code that I wrote:</p> <pre><code>from PyQt5 import QtWidgets, QtGui import sys class CustomListHead(QtWidgets.QWidget): ...
0
2016-10-05T19:55:15Z
39,883,248
<p>I see you have QListWidgetItem with you.</p> <p>From documentation you can customize each widget item, customize it and add to your listwidget:</p> <p>The appearance of the text can be customized with setFont(), setForeground(), and setBackground(). Text in list items can be aligned using the setTextAlignment() fu...
0
2016-10-05T20:39:04Z
[ "python", "qt", "pyqt", "qlistwidget" ]
Managing zipping large number of files in Python using 7zip and subprocess
39,882,604
<p>I have a large amount of files (~100k) moved from a server to a designated folder on a daily basis. I'm running a Python script against these files. At the end of the process I want to create a number of .zip files, each of approximately 2GB.</p> <p>The script will get a list of all files in the folder, get the siz...
0
2016-10-05T19:55:17Z
39,905,145
<p>I ended up finding a workaround, where essentially I write all file names from FilesListBelow2GB to a .txt file, and then ask 7zip to use that to know which files to zip.</p> <pre><code>outf = open('list.txt','w') for fileToZip in FilesListBelow2GB : outf.write(fileToZip+'\n') outf.close() txt = '"C:\\Pro...
0
2016-10-06T20:32:16Z
[ "python", "python-2.7", "zip", "subprocess" ]
How to resolve "ValueError: invalid literal for int() with base 10" in Python?
39,882,621
<p>I'm having a little trouble with a calculator that I'm making. I need to make it where it can add, multiply, divide, and subtract if you put them as the operator then it will follow which one it is. My code looks like this:</p> <pre><code> a= int( input("First Number: ")) int( input("First Operator: ")) b...
-1
2016-10-05T19:56:04Z
39,882,658
<p>The operator is being cast as an int. This should not be the case:</p> <p><code>int( input("First Operator: "))</code></p> <p>Try without the int(...).</p>
0
2016-10-05T19:58:27Z
[ "python" ]
How to resolve "ValueError: invalid literal for int() with base 10" in Python?
39,882,621
<p>I'm having a little trouble with a calculator that I'm making. I need to make it where it can add, multiply, divide, and subtract if you put them as the operator then it will follow which one it is. My code looks like this:</p> <pre><code> a= int( input("First Number: ")) int( input("First Operator: ")) b...
-1
2016-10-05T19:56:04Z
39,882,915
<p>You are trying to turn a char variable, in this case the operator, in an int one. Since the compiler cant turn the operator in int it will return this error. If you just declare a variable called operator it will work, your code will look like this:</p> <pre><code>a= float( input("First Number: ")) operator =input...
0
2016-10-05T20:14:53Z
[ "python" ]
In Tensorflow, how can you check if gradients are correct for your custom operation?
39,882,623
<p>My question is, how backpropatation paths are determined e.g., when using <code>tf.slice</code>? </p> <p>Let me take an example. Let's say, I have a K-classification problem. I can do this in a standard way like</p> <pre><code>conv1 = # conv1+relu1+lrm1+pool1 conv2 = # from conv1 fc1 = # from conv2 to 128D fully c...
0
2016-10-05T19:56:05Z
39,882,694
<p>There is nothing magical about it. You extract a part of the tensor and use for computations, so all the partial derivatives that "flow through" this slice are well defined. From math perspective it is something among the lines of having</p> <pre><code>f([x1,x2,x3,x4]) = f(x) = 2 * sum(slice(x, 2, 2)) + 1 = 2 * (x2...
1
2016-10-05T20:00:50Z
[ "python", "tensorflow", "deep-learning" ]
How would you store a pyramidal image representation in Python?
39,882,632
<p>Suppose I have N images which are a multiresolution representation of a single image (the Nth image being the coarsest one). If my finest scale is a 16x16 image, the next scale is a 8x8 image and so on. How should I store such data to fastly be able to access, at a given scale and for a given pixel, its unique pare...
0
2016-10-05T19:56:45Z
39,883,453
<p>You could just use a list of numpy arrays. Assuming a scale factor of two, for the <em>i,j</em><sup>th</sup> pixel at scale <em>n</em>:</p> <ul> <li>The indices of its "parent" pixel at scale <em>n-1</em> will be <code>(i//2, j//2)</code></li> <li>Its "child" pixels at scale <em>n+1</em> can be indexed by <code>(sl...
2
2016-10-05T20:53:09Z
[ "python", "numpy", "image-processing" ]
Python Requests - add text at the beginning of query string
39,882,644
<p>When sending data through python-requests a GET request, I have a need to specifically add something at the beginning of the query string. I have tried passing the data in through dicts and json strings with no luck.</p> <p>The request as it appears when produced by requests:</p> <pre><code>/apply/.../explain?%7B%...
0
2016-10-05T19:57:18Z
39,882,741
<p>'GET' requests don't have data, that's for 'POST' and friends. </p> <p>You can send the query string arguments using <code>params</code> kwarg instead:</p> <pre><code>&gt;&gt;&gt; params = {'record': '{"'} &gt;&gt;&gt; response = requests.get('http://www.example.com/explain', params=params) &gt;&gt;&gt; response....
0
2016-10-05T20:03:33Z
[ "python", "python-requests" ]
Python Requests - add text at the beginning of query string
39,882,644
<p>When sending data through python-requests a GET request, I have a need to specifically add something at the beginning of the query string. I have tried passing the data in through dicts and json strings with no luck.</p> <p>The request as it appears when produced by requests:</p> <pre><code>/apply/.../explain?%7B%...
0
2016-10-05T19:57:18Z
39,883,003
<p>From the comments i felt the need to explain this. </p> <p><code>http://example.com/sth?key=value&amp;anotherkey=anothervalue</code></p> <p>Let's assume you have a url like the above in order to call with python requests you only have to write </p> <pre><code> response = requests.get('http://example.com/sth', pa...
-1
2016-10-05T20:21:33Z
[ "python", "python-requests" ]
How to grab headers in python selenium-webdriver
39,882,645
<p>I am trying to grab the headers in selenium webdriver. Something similar to the following:</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; res=requests.get('http://google.com') &gt;&gt;&gt; print res.headers </code></pre> <p>I need to use the <code>Chrome</code> webdriver because it supports flash and som...
4
2016-10-05T19:57:26Z
39,882,959
<p>Unfortunately, you <strong>cannot</strong> get this information from the Selenium webdriver, nor will you be able to any time in the near future it seems. An excerpt from <a href="https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/141" rel="nofollow">a very long conversation on the subject</a>:<...
2
2016-10-05T20:17:39Z
[ "python", "selenium" ]
How to grab headers in python selenium-webdriver
39,882,645
<p>I am trying to grab the headers in selenium webdriver. Something similar to the following:</p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; res=requests.get('http://google.com') &gt;&gt;&gt; print res.headers </code></pre> <p>I need to use the <code>Chrome</code> webdriver because it supports flash and som...
4
2016-10-05T19:57:26Z
39,883,010
<p>You are meaning HTTP header data, right? This is not really the scope of Selenium: <a href="http://www.seleniumhq.org/" rel="nofollow">Selenium automates browsers. That's it!</a> So if you cannot do it with your browser (and I don't know of any way), Selenium is the wrong tool to use. However, if you can do it with ...
-1
2016-10-05T20:21:49Z
[ "python", "selenium" ]
Split a pandas dataframe into two by columns
39,882,767
<p>I have a dataframe and I want to split it into two dataframes, one that has all the columns beginning with <code>foo</code> and one with the rest of the columns. Is there a quick way of doing this?</p>
1
2016-10-05T20:05:39Z
39,882,854
<p>You can use <code>list comprehensions</code> for select all columns names:</p> <pre><code>df = pd.DataFrame({'fooA':[1,2,3], 'fooB':[4,5,6], 'fooC':[7,8,9], 'D':[1,3,5], 'E':[5,3,6], 'F':[7,4,3]}) print (df) D E F ...
2
2016-10-05T20:10:47Z
[ "python", "pandas" ]
how to suppress further processing of matplotlib event
39,882,773
<p>I'm building an interactive graphical application with matplotlib. I want it to play nice with the existing "pan" and "zoom" functions of the default matplotlib GUI, but I also want to overshadow some keystrokes. My problem is that I don't know to suppress the GUI's default response to those keystrokes. For exampl...
1
2016-10-05T20:05:47Z
39,901,886
<p>From tacaswell's comments above:</p> <p>Callbacks are stored in a dictionary so the order in which they get called cannot be guaranteed. Callback return values are ignored.</p> <p>The solution is to change <code>matplotlib.rcParams['keymap.back']</code> so that it does not include <code>'backspace'</code>.</p>
0
2016-10-06T17:06:52Z
[ "python", "matplotlib" ]
How can I get a list of the days in a year and follow this form?
39,882,809
<p>This code not work at all, and I'm still confusing with the pandas datetime method...</p> <pre><code>def date_list(): list = [] for i in pd.date_range(datetime(2016, 1, 1), datetime(2016, 12, 31)): list.append(datetime[1], datetime[2]) return list </code></pre> <p>This is the example for the...
0
2016-10-05T20:07:39Z
39,883,081
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.strftime.html" rel="nofollow"><code>strftime</code></a> to directly do the formatting:</p> <pre><code>dt_list = pd.date_range('2016-01-01', '2016-12-31').strftime('%m%d') </code></pre> <p>Use <a href="http://docs.scipy....
1
2016-10-05T20:26:22Z
[ "python", "python-3.x", "pandas", "anaconda", "miniconda" ]
After override the field as compute it's not working
39,882,822
<p>I did some changes in product.template and override the field like this</p> <pre><code>list_price = fields.Float(copy=False, string='Sale Price', store=True,compute='_calculate_sale_price', help='compute cost as per gun_dealer', default=0.00) </code></pre> <p>and the compute methods ...
0
2016-10-05T20:08:38Z
39,883,798
<p>THIS IS NOT A SOLUTION. But I cant really put this suggestion in a comment.</p> <p>I am not sure if you should use list_price in your depends decorator arguments. Try placing some logging in and see what is happening when you load the page.</p> <pre><code>import logging _logger = logging.getLogger(__name__) @api....
0
2016-10-05T21:15:55Z
[ "python", "odoo-9" ]
Replacing a node in graph with custom op having variable dependency in tensorflow
39,882,956
<p>I am trying to replace the computation done in the graph with a custom op that does the same. </p> <p>Lets say the graph has a constant <code>A</code> and weight variable <code>W</code>, I create the custom op to take these two inputs and do the entire computation (except the last step of weight update):</p> <pre>...
2
2016-10-05T20:17:30Z
40,136,131
<p>Could you precise which version of Tensorflow you use : r0.08, r0.09, r0.10, r0.11 ?</p> <p>That is impossible to change an op in the graph with another op. But If you may access W, you can still make a backup copy of W (using deepcopy() <a href="https://docs.python.org/2/library/copy.html" rel="nofollow">from cop...
0
2016-10-19T15:47:06Z
[ "python", "graph", "tensorflow", "custom-operator" ]
How can I pause a long running loop?
39,882,967
<p>I have a question about pausing / resuming a long running program. I'll use Python in this example, but it could be for any programming language really.</p> <p>Let's say I want to sum up all the numbers to a billion for example</p> <pre><code>results = [] for i in range(1000000000): results.append(i + i*2) w...
0
2016-10-05T20:19:09Z
39,883,237
<p>Ctrl+C won't corrupt the file. I'm not sure how sophisticated you need to be, but a simple solution would be to be able to give the program an input of where to resume from:</p> <pre><code>def main(start=0): with open('./sum.txt', 'w') as outfile: for i in range(start, 10000000): outfile.wri...
1
2016-10-05T20:38:00Z
[ "python", "loops", "for-loop", "long-running-processes", "pause" ]
How can I pause a long running loop?
39,882,967
<p>I have a question about pausing / resuming a long running program. I'll use Python in this example, but it could be for any programming language really.</p> <p>Let's say I want to sum up all the numbers to a billion for example</p> <pre><code>results = [] for i in range(1000000000): results.append(i + i*2) w...
0
2016-10-05T20:19:09Z
39,889,147
<h3>Create a condition for the loop to either continue or hold</h3> <p>A possible solution would be in the script, periodically checking for a "trigger" file to exist. In the example below, the loop checks once in hundred cycles, but you could make it 500 for example.</p> <p><strong><em>If</em></strong> and as long a...
1
2016-10-06T06:38:55Z
[ "python", "loops", "for-loop", "long-running-processes", "pause" ]
tearDown not called after timeout in twisted trial?
39,883,058
<p>I'm seeing an issue in my test suite in trial where everything works fine until I get a timeout. If a test fails due to a timeout, the tearDown function never gets called, leaving the reactor unclean which in turn causes the rest of the tests to fail. I believe tearDown should be called after a timeout, does anyone ...
0
2016-10-05T20:24:44Z
39,883,194
<p>You are correct that <code>tearDown()</code> should be called regardless of what happens in your test. From <a href="https://docs.python.org/2/library/unittest.html#unittest.TestCase.tearDown" rel="nofollow">the documentation</a> for <code>tearDown()</code>:</p> <blockquote> <p>This is called even if the test met...
1
2016-10-05T20:34:48Z
[ "python", "testing", "twisted", "trial" ]
tearDown not called after timeout in twisted trial?
39,883,058
<p>I'm seeing an issue in my test suite in trial where everything works fine until I get a timeout. If a test fails due to a timeout, the tearDown function never gets called, leaving the reactor unclean which in turn causes the rest of the tests to fail. I believe tearDown should be called after a timeout, does anyone ...
0
2016-10-05T20:24:44Z
39,888,137
<p>It's rather strange because on my box, the teardown executes even if a timeout occurs. The tests should stop running if the reactor is not in a clean state, unless you use the <code>--unclean-warnings</code> flag. Does the test runner stop after the timeout for you? What version of Python and Twisted are you running...
1
2016-10-06T05:26:44Z
[ "python", "testing", "twisted", "trial" ]
How to create and set variables as classes from a list of tuples?
39,883,083
<p>I am trying to figure out how to create variables from a list of tuple and assign them to a class. </p> <p>I have data organized like this</p> <pre><code> Name Age Status John 30 Employed </code></pre> <p>That I have created a list of tuple like this</p> <pre><code> employeelist = [(John, 30, Employed), (S...
2
2016-10-05T20:26:31Z
39,883,127
<p>You just need</p> <pre><code>employees = [Employee(*v) for v in employee_list] </code></pre> <p>Note that <code>employees</code> and <code>Employee.elist</code> are essentially the same once each <code>Employee</code> object has been created.</p>
4
2016-10-05T20:30:11Z
[ "python", "class", "loops", "tuples" ]
scipy minimization/optimization of simple function
39,883,173
<p>I'm having trouble optimizing a very simple function I'm using as a test case before moving on to something more complex. I've tried different optimization methods, giving the method a bound and even giving the exact solution as the initial guess.</p> <p>Function I'm trying to optimize: <code>f(x) = 1 / x - x</code...
0
2016-10-05T20:33:31Z
39,883,720
<p>As Victor mentioned, the optimization function is working correctly,</p> <p>I was looking to solve <code>f(x) --&gt; 0</code> which requires a root finding method rather than an optimization routine.</p> <p>for example: </p> <p><code>scipy.optimize.root(testfun, 1)</code> or <code>scipy.optimize.Newton(testfun, 1...
0
2016-10-05T21:10:06Z
[ "python", "optimization" ]
Game timer in pygame
39,883,175
<p>I'm trying to implement a game timer for a word memory game. The game has a start screen, so the time should be calculated from when the user presses "play", paused when the user presses "pause" mid game and continued when the user presses "continue" on the pause screen. I understand that the correct implementation ...
0
2016-10-05T20:33:34Z
39,883,405
<p>Create your own timer class. Use <code>time.time()</code> (from the regular python <code>time</code> module). </p> <pre><code>import time class MyTimer: def __init__(self): self.elapsed = 0.0 self.running = False self.last_start_time = None def start(self): if not self.runn...
2
2016-10-05T20:50:09Z
[ "python", "timer", "pygame" ]
Append a column to a dataframe in Pandas
39,883,182
<p>I am trying to append a numpy.darray to a dataframe with little success. The dataframe is called user2 and the numpy.darray is called CallTime.</p> <p>I tried:</p> <pre><code>user2["CallTime"] = CallTime.values </code></pre> <p>but I get an error message:</p> <pre><code>Traceback (most recent call last): File "&...
-2
2016-10-05T20:33:45Z
39,883,467
<p><code>pandas DataFrame</code> is a 2-dimensional data structure, and each column of a <code>DataFrame</code> is a 1-dimensional <code>Series</code>. So if you want to add one column to a DataFrame, you must first convert it into <code>Series</code>. np.ndarray is a multi-dimensional data structure. From your code, I...
0
2016-10-05T20:53:48Z
[ "python", "numpy" ]
Append a column to a dataframe in Pandas
39,883,182
<p>I am trying to append a numpy.darray to a dataframe with little success. The dataframe is called user2 and the numpy.darray is called CallTime.</p> <p>I tried:</p> <pre><code>user2["CallTime"] = CallTime.values </code></pre> <p>but I get an error message:</p> <pre><code>Traceback (most recent call last): File "&...
-2
2016-10-05T20:33:45Z
39,889,564
<p>I think instead to provide only documentation, I will try to provide a sample:</p> <pre><code>import numpy as np import pandas as pd data = {'A': [2010, 2011, 2012], 'B': ['Bears', 'Bears', 'Bears'], 'C': [11, 8, 10], 'D': [5, 8, 6]} user2 = pd.DataFrame(data, columns=['A', 'B', 'C', 'D']) #creating t...
0
2016-10-06T07:03:26Z
[ "python", "numpy" ]
Pandas - Self reference of instances in column
39,883,232
<p>I have the following DF</p> <pre><code> SampleID ParentID 0 S10 S20 1 S10 S30 2 S20 S40 3 S30 4 S40 </code></pre> <p>How can I put the id of the other row in the column 'ParentID' instead of the string?</p> <p>Expected result:</p> <pre><code> SampleID P...
0
2016-10-05T20:37:35Z
39,883,603
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.merge.html" rel="nofollow"><code>merge</code></a> and then assign column <code>index</code>:</p> <pre><code>df1 = pd.merge(df[['SampleID']].reset_index(), df[['ParentID']], left_on='SampleID', ...
2
2016-10-05T21:01:48Z
[ "python", "pandas" ]