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
Multiple matches on split-string
38,121,082
<p>I'm using the split()-function on an hexlified string in Python. This string is containing a marker (0xffffffffffffffff) which I want to split out. After this marker there is hexadecimal data. There can be multiple "markers" in the hexlified string.</p> <p>Now I found out that there is a problem when my first data-...
2
2016-06-30T10:55:40Z
38,121,727
<p>You could convert your string to <code>bytes</code>/<code>bytearray</code> and split it</p> <pre><code>In [2]: b = bytes.fromhex(s).split(b'\xff'*8) In [3]: b Out[3]: [b'\n\x0b\x0c\r\x0e\x0f', b'\n\x0b\x0c'] </code></pre> <p>Then convert each element of the list back to <code>str</code></p> <pre><code>In [4]: [x...
2
2016-06-30T11:24:57Z
[ "python", "regex", "string", "split" ]
Multiple matches on split-string
38,121,082
<p>I'm using the split()-function on an hexlified string in Python. This string is containing a marker (0xffffffffffffffff) which I want to split out. After this marker there is hexadecimal data. There can be multiple "markers" in the hexlified string.</p> <p>Now I found out that there is a problem when my first data-...
2
2016-06-30T10:55:40Z
38,127,390
<p>To parse a hexadecimal 8-bit number sequence properly, you simply must treat it as characters pairs.</p> <p>The following simple split function splits a string on a fixed substring, but only at even positions. It preserves the pairs of chars that form the hex numbers.</p> <pre><code>def split_even(string, sep): ...
0
2016-06-30T15:22:12Z
[ "python", "regex", "string", "split" ]
Config for ubuntu 14.04, eclipse Neon, python 2.7, Django 1.9, Pydev and virtualenv doesn't create src folder
38,121,376
<p>Coming from PHP, I'm an absolute beginner with Python/Django. I have successfully installed a virtual environment. So I can see a result with localhost:8000 and localhost:8000/admin. (Standard SQLITE)</p> <p>The folders lie with user rights in /home/.../django-test. The python environment is in folder django-test/s...
0
2016-06-30T11:08:26Z
38,122,017
<p>Sorry for any inconvenience, found now the solution myself! The usual problems as beginner: I did not know about the naming conventions, so I used - instead _. After finding the error.log from eclipse (I usually use netbeans) I saw the problem. Solution: 2 min, finding the problem: 1 day! </p> <p>Will be funny the ...
0
2016-06-30T11:38:37Z
[ "python", "django", "eclipse", "python-2.7", "ubuntu" ]
which argtypes for NetShareAdd
38,121,435
<p>The win32 function NetShareDel takes three arguments, LPCWSTR LPCWSTR and DWORD.</p> <p>So I use the following list for argtypes:</p> <pre><code>C.windll.Netapi32.NetShareDel.argtypes = [LPCWSTR, LPCWSTR, c_int] C.windll.Netapi32.NetShareDel.restype = c_int C.windll.Netapi32.NetShareDel(server, shareName, 0) </co...
1
2016-06-30T11:11:29Z
38,141,041
<p>Got it working finally</p> <p>First the line </p> <pre><code>bytearray = buffer(info)[:] </code></pre> <p>was changed into byte pointer type</p> <pre><code>byteptr = C.POINTER(C.wintypes.BYTE)(info) </code></pre> <p>and then the argtypes and call will become POINTER(BYTE) too of course:</p> <pre><code>C.wind...
1
2016-07-01T08:51:22Z
[ "python", "ironpython", "pywin32" ]
Tensorflow error using my own data for text classification
38,121,451
<p>I've been playing with the Tensorflow library doing the tutorials. Now I wanted to play with my own data, but I fail horribly. This is perhaps a noob question but I can't figure it out.</p> <p>I'm using this <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/examples/skflow/text_classification...
1
2016-06-30T11:12:26Z
38,127,232
<p>The "axis" parameter was just added to tf.unpack on June 23, and the example you're looking at was changed to use it:</p> <p><a href="https://github.com/tensorflow/tensorflow/commit/eff93149a6dc8e6826898fd9f9c28c81e21c9836" rel="nofollow">https://github.com/tensorflow/tensorflow/commit/eff93149a6dc8e6826898fd9f9c28...
1
2016-06-30T15:15:07Z
[ "python", "machine-learning", "tensorflow", "text-classification" ]
Why does paypal-ipn still return INVALID to my POST?
38,121,463
<p>i have build a simple paypal-ipn listener: it listens for paypal sending me a http POST, reads its data out and sends it back to paypal, which should answer VALID if the data received matches the data send.</p> <p>i am using the Paypal IPN-Simulator to send the IPNs. </p> <p>i basically copied the code from <a hre...
0
2016-06-30T11:12:55Z
38,125,764
<p>i found it via the answer <a href="http://stackoverflow.com/questions/37505969/paypal-ipn-always-return-invalid-even-when-i-follow-paypal-sample-code-to-the-wo?lq=1">PayPal IPN always return INVALID even when I follow PayPal sample code to the word?</a></p> <p>turns out: the ipn-simulator does not (or does not alwa...
0
2016-06-30T14:14:26Z
[ "python", "paypal", "paypal-ipn", "urlencode", "server-side-scripting" ]
How to write numpy where condition based on indices and not values?
38,121,584
<p>I have a 2d numpy array and I need to extract all elements <code>array[i][j]</code> if the conditions </p> <p><code>x1range &lt; i &lt; x2range</code> and <code>y1range &lt; j &lt; y2range</code> are satisfied.</p> <p>How do I write such conditions? Do I need to use mgrid/ogrid?</p> <p>Edit: Should have written m...
0
2016-06-30T11:18:10Z
38,121,711
<p>just a guess.</p> <pre><code>x=array[x1range:x2range,y1range:y2range] </code></pre>
0
2016-06-30T11:24:31Z
[ "python", "numpy" ]
How to write numpy where condition based on indices and not values?
38,121,584
<p>I have a 2d numpy array and I need to extract all elements <code>array[i][j]</code> if the conditions </p> <p><code>x1range &lt; i &lt; x2range</code> and <code>y1range &lt; j &lt; y2range</code> are satisfied.</p> <p>How do I write such conditions? Do I need to use mgrid/ogrid?</p> <p>Edit: Should have written m...
0
2016-06-30T11:18:10Z
38,121,747
<p>What about slicing?</p> <pre><code>array[x1range:x2range,y1range:y2range] </code></pre> <p>Example:</p> <pre><code>numpy.array([[1,2,3],[4,5,6],[7,8,9]])[0:2,0:2] array([[1, 2], [4, 5]]) </code></pre>
0
2016-06-30T11:25:47Z
[ "python", "numpy" ]
How to write numpy where condition based on indices and not values?
38,121,584
<p>I have a 2d numpy array and I need to extract all elements <code>array[i][j]</code> if the conditions </p> <p><code>x1range &lt; i &lt; x2range</code> and <code>y1range &lt; j &lt; y2range</code> are satisfied.</p> <p>How do I write such conditions? Do I need to use mgrid/ogrid?</p> <p>Edit: Should have written m...
0
2016-06-30T11:18:10Z
38,121,878
<p><strong>Problem #1: Getting indices within the range</strong></p> <p>You could use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow"><code>np.meshgrid</code></a> to get those indices -</p> <pre><code>In [145]: x1range,x2range = 2,5 ...: y1range,y2range = 1,4 ...
0
2016-06-30T11:32:05Z
[ "python", "numpy" ]
Multiply NumPy ndarray with every element in another binary ndarray of different size
38,121,665
<p>I have two ndarrays :</p> <pre><code>a = [[30,40], [60,90]] b = [[0,0,1], [1,0,1], [1,1,1]] </code></pre> <p>please notice that a shape might be larger but always square array (50,50) , (100,100) The wanted result is :</p> <pre><code>Result = [[a*0,a*0,a*1], [[a*1,a*0,a*1], [[a*1,a*...
2
2016-06-30T11:21:56Z
38,121,714
<p>Indeed there's a NumPy built-in <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.kron.html" rel="nofollow"><code>np.kron</code></a> for such block-based elementwise multiplication problems. To solve your case, it could be used like so -</p> <pre><code>np.kron(b,a) </code></pre> <p>Sample run -</p...
2
2016-06-30T11:24:33Z
[ "python", "numpy" ]
hglib: show patches for a revision, possible?
38,121,696
<p>I'm trying to get the patches for a given revision using hglib. I know the hg command is</p> <p><code>hg log -pr rev</code> </p> <p>but I can't find how to do this or equivalent with hglib. It seems there is not functionality to do that, unless I hack the code myself to run the above command. Any help would be gre...
0
2016-06-30T11:23:37Z
38,164,093
<p>The hglib client.log() interface doesn't support what I wanted to do, but I found a simple way to run an arbitrary hg command. This two lines print the patch of revision rev:</p> <pre><code> out = client.rawcommand([b'log', b'-pr', b'%i'%rev]) print(str(out, 'utf-8')) </code></pre>
0
2016-07-02T20:12:13Z
[ "python", "mercurial", "hglib" ]
Python: reflect positions in a 2D grid graph
38,121,860
<p>In a 2D graph with 10x10 nodes, I realized I want the nodes to be labelled starting from the upper left corner, downwards and column-wise: </p> <pre><code>1st column -&gt; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 2nd column -&gt; [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] </code></pre> <p>and so forth until I reach the 10th c...
0
2016-06-30T11:31:22Z
38,123,923
<p>You could just change the labels when you draw the graph like this</p> <pre><code>import networkx as nx import matplotlib.pyplot as plt #n=100 Num...
1
2016-06-30T13:01:11Z
[ "python", "grid", "position", "networkx", "cartesian-coordinates" ]
Python: reflect positions in a 2D grid graph
38,121,860
<p>In a 2D graph with 10x10 nodes, I realized I want the nodes to be labelled starting from the upper left corner, downwards and column-wise: </p> <pre><code>1st column -&gt; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 2nd column -&gt; [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] </code></pre> <p>and so forth until I reach the 10th c...
0
2016-06-30T11:31:22Z
38,123,929
<p>The following worked for me: delete the line <code>vals=sorted(vals, reverse=False)</code>, and replace the line <code>inds=sorted(inds,reverse=False)</code> with <code>inds=[(N-j-1,N-i-1) for i,j in inds]</code>.<a href="http://i.stack.imgur.com/IjlCj.png" rel="nofollow"><img src="http://i.stack.imgur.com/IjlCj.png...
1
2016-06-30T13:01:36Z
[ "python", "grid", "position", "networkx", "cartesian-coordinates" ]
Convert Outlook PST to json using libpst
38,122,047
<p>I have an Outlook PST file, and I'd like to get a json of the emails, e.g. something like</p> <pre><code>{"emails": [ {"from": "alice@example.com", "to": "bob@example.com", "bcc": "eve@example.com", "subject": "mitm", "content": "be careful!" }, ...]} </code></pre> <p>I've thought using <code>readpst</code> to...
0
2016-06-30T11:40:06Z
38,125,887
<p>I found a way to do it in 2 stages, first convert to mbox and then to json:</p> <pre><code># requires installing libpst pst2json my.pst # or you can specify a custom output dir and an outlook mail folder, # e.g. Inbox, Sent, etc. pst2json -o email/ -f Inbox my.pst </code></pre> <p>Where <code>pst2json</code> is my...
0
2016-06-30T14:18:36Z
[ "python", "ruby", "json", "email", "pst" ]
Gui for a simple chat in PyQt5 using QGridLayout
38,122,052
<p>I have been studying PyQt5 and recenlty decided to make a gui for a simple chat client. This is my mockup: </p> <p><a href="http://i.stack.imgur.com/8e6kZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/8e6kZ.png" alt="PyQt5 simple chat GUI mockup"></a></p> <p>I used QGridLayout, and this is what I got:</p>...
1
2016-06-30T11:40:11Z
38,125,070
<p>I guess you are looking after <a href="http://doc.qt.io/qt-5/qwidget.html#setFixedSize" rel="nofollow">setFixedSize(QSize size)</a> of <a href="http://doc.qt.io/qt-5/qwidget.html" rel="nofollow">QWidget</a>.</p>
1
2016-06-30T13:48:22Z
[ "python", "user-interface", "pyqt", "pyqt5", "qgridlayout" ]
Gui for a simple chat in PyQt5 using QGridLayout
38,122,052
<p>I have been studying PyQt5 and recenlty decided to make a gui for a simple chat client. This is my mockup: </p> <p><a href="http://i.stack.imgur.com/8e6kZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/8e6kZ.png" alt="PyQt5 simple chat GUI mockup"></a></p> <p>I used QGridLayout, and this is what I got:</p>...
1
2016-06-30T11:40:11Z
38,130,865
<p>You first need to set a fixed height for the bottom text-edit based on the number of lines you want shown. This also needs to take account of the frame and document margin:</p> <pre><code> def initUI(self): ... chat.setFixedHeight( (chat.fontMetrics().lineSpacing() * 3) + ...
1
2016-06-30T18:37:14Z
[ "python", "user-interface", "pyqt", "pyqt5", "qgridlayout" ]
Web2Py Multiple Smartgrids in a view
38,122,060
<p>I am trying to build a view in web2py that has multiple smartgrid objects served from the same controller. It displays them absolutely fine, but whenever I try to create a new record on the second table it doesn't allow entry, it just seems to refresh the page. Also trying to search on the second table actually fi...
0
2016-06-30T11:40:50Z
38,127,972
<p>As you have noted, you cannot have two grids on the same page in this manner, as the grid makes use of the URL to determine its current state. Instead of the iframe approach, though, you might consider putting each grid in an Ajax component. In the main view file:</p> <pre><code>{{=LOAD('default', 'grid1.load', aja...
0
2016-06-30T15:49:59Z
[ "python", "web2py" ]
how to take input in different lines in python?
38,122,230
<p>I am new to python language.</p> <p>I dont know how to take input in different lines in python??</p> <p>So i would like to take n number of inputs like this using loop:</p> <pre><code>4 #first line input 3 2 #second line input 5 3 6 #third line input 1 2 3 4 #fouth line input # and so on.... </code></pre> ...
-3
2016-06-30T11:48:52Z
38,122,344
<p>I suppose the first line is your number of lines, i.e, your <code>n</code>.</p> <p>So you can do it like this :</p> <pre><code>for i in range(int(input())): line = input() #process your input </code></pre> <p>else you can do it like :</p> <pre><code>n = #your number of lines for i in range(n): line =...
0
2016-06-30T11:53:46Z
[ "python", "python-3.x" ]
SQL Server Error converting data type nvarchar to date python
38,122,260
<p>I am getting an error while calling a SQL Server stored procedure in python.</p> <blockquote> <p>Error converting data type nvarchar to date.</p> </blockquote> <p>My code is as below.</p> <pre><code>from datetime import datetime OnlyDate=datetime.now().date() # I got date in OnlyDate in this formate :-2016-06...
0
2016-06-30T11:50:05Z
38,122,335
<p><code>@Date=OnlyDate</code></p> <p>You are trying to insert the string <code>OnlyDate</code> into the <code>Date</code> column, therefore ending up with an error that nvarchar (<code>"OnlyDate"</code>) can't be converted to date.</p> <p>You should use a parameterized query:</p> <pre><code>query = "exec dbo.Scrape...
0
2016-06-30T11:53:17Z
[ "python", "date", "stored-procedures" ]
Performing Login with Python requests (Cookies not activated)
38,122,379
<p>I'm trying to perform a login with the python requests module. I first post to the login-page with my user name and password to save the cookie from the response. After that I try to enter the password protected page. The problem is that the response page says I have to activate cookies to login to this page, but I ...
1
2016-06-30T11:55:22Z
38,122,826
<p>Try an initial <code>GET</code> of the login page with <code>r = session.get(login)</code>. Then check <code>session.cookies</code> - it should contain a session cookie. You will also need to extract the various values for <code>security_token</code>, <code>login_ticket</code> and the other fields so that you can in...
0
2016-06-30T12:15:53Z
[ "python", "python-2.7", "authentication", "cookies", "python-requests" ]
copy file name and certain text string then place it into a specific part of all files in subdirectories
38,122,435
<p>I have many files in subdirectories eg. UCE-1…UCE-2000, which all contain the same two file types (a <code>.cfg</code> file and a <code>.phylip</code> file).</p> <pre><code>UCEs UCE-13 partition_finder.cfg UCE-13.phylip </code></pre> <p>I need to modify the .cfg file in all of these UCE-1...UCE-2000 folders....
0
2016-06-30T11:57:43Z
38,133,211
<p>start in “All-UCEs"<br> the info is all common to a subdir so<br> go to that dir first<br> get the phylip name<br> get the last field of the first row of the phylip file<br> stick them in the .cfg file<br> (use double quote to allow expansion of shell var in sed)<br> change back out of the dir</p> <pre><code>for ...
0
2016-06-30T21:02:29Z
[ "python", "regex", "unix", "bioinformatics" ]
catch exception and return empty dataframe
38,122,456
<p>I query a database and save result as a dataframe which I then transform by <code>factorize</code> with <code>pivot_table</code>. This works fine when database query returns data but it throws an error when no data is returned(this is to be expected). How to catch this exception and return empty dataframe? </p> <pr...
2
2016-06-30T11:58:42Z
38,122,798
<p>You should probably check whether the dataframe is empty or not</p> <pre><code>if df.empty: return df </code></pre> <p>before calling <code>pivot_table</code></p>
0
2016-06-30T12:14:31Z
[ "python", "pandas" ]
catch exception and return empty dataframe
38,122,456
<p>I query a database and save result as a dataframe which I then transform by <code>factorize</code> with <code>pivot_table</code>. This works fine when database query returns data but it throws an error when no data is returned(this is to be expected). How to catch this exception and return empty dataframe? </p> <pr...
2
2016-06-30T11:58:42Z
38,122,802
<pre><code>try: df1 = df.pivot_table(index='name', columns='name', values=['sale', 'year']) except pd.core.groupby.DataError: df1 = pd.DataFrame() except: raise </code></pre> <p>Credits to brenbarn who found the error name for dataerror at <a href="http://stackoverflow.com/questions/29500778/how-can-i-catc...
2
2016-06-30T12:14:37Z
[ "python", "pandas" ]
Individual datatsore query oder for large number of properties
38,122,466
<p>I have an entity with more than 25 properties. Out of these 25, 15 properties are displayed in the frontend table. These table will allow to do a sorting (both ASC &amp; DESC) on each properties.</p> <p>To handle this in backend, I'm checking the order type and writing query on each property for both ASC and DESC o...
1
2016-06-30T11:59:00Z
38,127,782
<p><strong>No, you are handling indexing in the correct manner.</strong></p> <p>If your data is smaller in size and relatively bounded in growth, you could switch to client-side sorting if you want to avoid creating 15*2 indexes.</p> <p>Alternatively, if the number of parents (Entity-groups) is small and you can live...
1
2016-06-30T15:41:23Z
[ "python", "google-app-engine", "optimization", "query-optimization", "google-cloud-datastore" ]
Individual datatsore query oder for large number of properties
38,122,466
<p>I have an entity with more than 25 properties. Out of these 25, 15 properties are displayed in the frontend table. These table will allow to do a sorting (both ASC &amp; DESC) on each properties.</p> <p>To handle this in backend, I'm checking the order type and writing query on each property for both ASC and DESC o...
1
2016-06-30T11:59:00Z
38,131,591
<p>If the parameters you're passing always match your property names then you can replace your if statements with something like:</p> <pre><code>desc = False if order[0] == '-': order = order[1:] desc = True query = cls.query(ancestor=parent) order = getattr(cls, order) if desc: order = -order query = query.or...
2
2016-06-30T19:19:22Z
[ "python", "google-app-engine", "optimization", "query-optimization", "google-cloud-datastore" ]
Tkinter - What is the time item, stored in the event object
38,122,503
<p>In Tkinter there is an object called event, usually passed to functions, which are called by buttons (or similar objects) in Tkinter.</p> <pre><code>tkinter.Event </code></pre> <p>This event.object has a bunch of items, like x-position or y-position, and also a time-stamp of sorts.</p> <p>What does this time-stam...
-1
2016-06-30T12:00:44Z
38,123,011
<p>The documentation of the <code>Event</code> class in tkinter source code only says this:</p> <blockquote> <p>time - when the event occurred</p> </blockquote> <p>I assume this comes from the <code>%t</code> substitution provided by the underlying tcl/tk interpreter, which is documented to be the following:</p> <...
1
2016-06-30T12:24:08Z
[ "python", "tkinter" ]
Loading of text data file
38,122,639
<p>I have a text file in below format </p> <pre><code>id x, y 0[0.0, 1.0] 1[0.0, 2.0] 2[0.1, 2.5] : : </code></pre> <p>I need to load this text file. I have tried:</p> <pre><code>numpy.genfromtxt('FileName', delimiter=",", names=True) </code></pre> <p>but the existence of <code>[</code> prevents it from reading the...
4
2016-06-30T12:06:40Z
38,122,913
<p>'try this</p> <pre><code>import numpy as np X=[] # keep x, y id=[] # keep ids file_toload=open('FileName',"r") # start reading a file file_toload.readline()# get rid of headers for line in file_toload: # loop through all remaining lines line =line.replace("[",",") # replace [ with comma first row becomes '0,0.0,...
1
2016-06-30T12:19:42Z
[ "python", "numpy", "text-files" ]
Loading of text data file
38,122,639
<p>I have a text file in below format </p> <pre><code>id x, y 0[0.0, 1.0] 1[0.0, 2.0] 2[0.1, 2.5] : : </code></pre> <p>I need to load this text file. I have tried:</p> <pre><code>numpy.genfromtxt('FileName', delimiter=",", names=True) </code></pre> <p>but the existence of <code>[</code> prevents it from reading the...
4
2016-06-30T12:06:40Z
38,123,349
<p>You need to convert the file to the format that NumPy expects, before feeding it to <code>genfromtxt()</code>. Fortunately, you can do that in Python itself.</p> <pre><code>f1 = open("file.txt", "rU") f2 = open("output.txt", "wt") for line in f1: line = line.replace("[", ",") line = line.replace("]", "") ...
3
2016-06-30T12:38:10Z
[ "python", "numpy", "text-files" ]
fabfile user information requirement
38,122,696
<p>The remote server is disabling authentication by ssh keys, so when I deploy a new version I need to enter my password (some LDAP authentication).</p> <p>However, my <code>fabfile</code> script will be used by many developers. So, everyone must somehow provide his username to the script.</p> <p>I thought of this:</...
0
2016-06-30T12:09:22Z
38,125,181
<p>If your problem is DRY you could use a decorator</p> <pre><code>def authenticate(f): @functools.wraps(f) def wrapper(login, *args, **kwargs): if login is None: abort('You must provide your username') return f(*args, **kwargs) return wrapper </code></pre> <p>and then</p> <pre><...
2
2016-06-30T13:52:29Z
[ "python", "fabric" ]
Django Admin how to change text in relations field
38,122,829
<p>I have the following code:</p> <p>models.py</p> <pre><code>from django.db import models from parler.models import TranslatableModel, TranslatedFields class Federation(TranslatableModel): translations = TranslatedFields( name = models.CharField('name', max_length=50) ) created_at = models.DateT...
1
2016-06-30T12:16:00Z
38,123,115
<p>By default it uses the <code>__str__()</code> method of the object. So the easiest way to change this is to set this method. For instance:</p> <pre><code>class Federation(models.Model): ... def __str__(self): return "{0} ({1})".format(self.translation, self.created_at) </code></pre> <p>Another way...
1
2016-06-30T12:28:54Z
[ "python", "django", "django-parler" ]
Heroku migrate app from cedar-10 to cedar-14
38,122,870
<p>I am just having an issue to push my changes after I followed steps to upgrade my heroku instance from cedar-10 to cedar-14. Although it works if I create new app and apply existing code, it doesn't work to on production app.</p> <blockquote> <p>Error</p> </blockquote> <pre><code>-----&gt; Python app detected ER...
0
2016-06-30T12:17:34Z
38,260,567
<p>I ended up opening a ticket directly through support on Heroku platform. </p> <p>Obviously, it was a bug on their side. So, an Engineer from Heroku needed to <strong>purge build cache</strong> for my application. After that action, I was able to push new changes and deploy new release.</p>
0
2016-07-08T06:51:38Z
[ "python", "django", "heroku", "heroku-toolbelt" ]
Heroku migrate app from cedar-10 to cedar-14
38,122,870
<p>I am just having an issue to push my changes after I followed steps to upgrade my heroku instance from cedar-10 to cedar-14. Although it works if I create new app and apply existing code, it doesn't work to on production app.</p> <blockquote> <p>Error</p> </blockquote> <pre><code>-----&gt; Python app detected ER...
0
2016-06-30T12:17:34Z
38,596,071
<p>Heroku support told me: </p> <blockquote> <p>This is not exactly a bug, moving between cedar-10 and cedar-14 is an entire operating system upgrade and creating a disk image with completely parity is nearly impossible. You can purge the build cache on your own with the <code>repo:purge_cache</code> command via <a ...
2
2016-07-26T17:11:30Z
[ "python", "django", "heroku", "heroku-toolbelt" ]
How to remove an item from a "collections.defaultdict"?
38,122,926
<p>I have a <code>collections.defaultdict</code> as follows:</p> <pre><code>mydict = defaultdict(lambda:0) mydict['stock1'] = 1.11 mydict['stock2'] = 2.22 mydict['stock3'] = 3.33 </code></pre> <p>Now I want to remove the second item completely, how can I do that?</p> <p>Maybe there is little seens to remove that but...
-3
2016-06-30T12:20:18Z
38,122,990
<p><a href="https://docs.python.org/2/library/stdtypes.html#mapping-types-dict" rel="nofollow">See the documentation</a>, it's just like the ordinary dictionary. You can use either:</p> <ul> <li><code>del mydict['stock2']</code></li> <li><code>mydict.pop('stock2')</code></li> </ul>
0
2016-06-30T12:23:01Z
[ "python" ]
w, h = template.shape[::-1] results in Value Error too many values to unpack
38,122,948
<p>Im on <code>Python 2.7 (x86) ,Open CV 3.1.0, Windows 7 (x64)</code></p> <p>Trying some simple template matching on Open CV</p> <p><strong>The image</strong></p> <p><a href="http://i.stack.imgur.com/oJCuI.png" rel="nofollow"><img src="http://i.stack.imgur.com/oJCuI.png" alt="enter image description here"></a></p> ...
2
2016-06-30T12:20:55Z
38,123,027
<p>Your image shape returns 3 dimensions</p> <pre><code>im.shape &gt;&gt;&gt; (24, 28, 3) </code></pre> <p>If you only want the first 2 do:</p> <pre><code>w, h = im.shape[:-1] &gt;&gt;&gt; (24, 28) </code></pre> <p>or </p> <pre><code>w, h, _ = im.shape # w is 24, h is 28 </code></pre> <p>Because otherwise, you ar...
3
2016-06-30T12:24:49Z
[ "python", "opencv" ]
COPY command in psycopg2
38,123,049
<p>I have a process which is reading from 4 databases with 4 tables each. I am consolidating that data into 1 postgres database with 4 tables total. (Each of the original 4 databases have the same 4 tables which need to be consolidated).</p> <p>The way I am doing it now works using pandas. I read one table from all 4 ...
3
2016-06-30T12:25:40Z
38,123,394
<p>psycopg2 offers a number of specific <code>copy</code> related apis. If you want to use csv, you have to use <code>copy_expert</code> (which allows you to specify a fully <code>copy</code> statement).</p> <p>Normally when I have done this, I have used <code>copy_expert()</code> and a file-like object which iterate...
2
2016-06-30T12:40:15Z
[ "python", "postgresql", "pandas" ]
How to change position of dragable child elements with in same parent using selenium python
38,123,179
<p>Suppose I have this html. <br></p> <pre><code>&lt;div name="parent"&gt; &lt;div name="child one"&gt; &lt;/div&gt; &lt;div name="child two"&gt; &lt;/div&gt; &lt;div name="child three"&gt; &lt;/div&gt; &lt;div name="child four"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>All of these child element...
3
2016-06-30T12:31:37Z
38,125,539
<p>Have you looked into <a href="http://selenium-python.readthedocs.io/api.html#module-selenium.webdriver.common.action_chains" rel="nofollow"><code>ActionChains</code></a>? It allows for drag and drop.</p> <pre><code>childOne = driver.find_element_by_css_selector("div.child.one") childFour = driver.find_element_by_cs...
0
2016-06-30T14:05:34Z
[ "python", "selenium", "selenium-webdriver" ]
How to change position of dragable child elements with in same parent using selenium python
38,123,179
<p>Suppose I have this html. <br></p> <pre><code>&lt;div name="parent"&gt; &lt;div name="child one"&gt; &lt;/div&gt; &lt;div name="child two"&gt; &lt;/div&gt; &lt;div name="child three"&gt; &lt;/div&gt; &lt;div name="child four"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>All of these child element...
3
2016-06-30T12:31:37Z
38,187,211
<p>In case of JAVA, this is the solution, can you look up for the same in python ? </p> <pre><code>Action dragAndDrop = builder.clickAndHold(from web element) .moveToElement(toElement) .release(To) .build(); dragAndDrop.perform(); </code></pre>
0
2016-07-04T14:35:03Z
[ "python", "selenium", "selenium-webdriver" ]
Match shortest substring in list using for loop
38,123,454
<p>I am trying to match items (single words) from one list with items (full sentences) from a second list. This is my code: </p> <pre><code>tokens=['Time','Fun','Python'] sentences=['Time is High', "Who's Funny", 'Pythons', 'Python is Nice', "That's Fun!"] for word in tokens: for line in sentences: if w...
0
2016-06-30T12:42:44Z
38,123,719
<p>It is not as easy (requires more lines of code) to achieve retrieving "Fun!" for <code>Fun</code> and at the same time not "Pythons" for <code>Python</code>.. It can be done of course but your rules are not very clear to me at this point. Have a look at this though:</p> <pre><code>tokens = ['Time', 'Fun', 'Python']...
0
2016-06-30T12:53:30Z
[ "python", "string" ]
Match shortest substring in list using for loop
38,123,454
<p>I am trying to match items (single words) from one list with items (full sentences) from a second list. This is my code: </p> <pre><code>tokens=['Time','Fun','Python'] sentences=['Time is High', "Who's Funny", 'Pythons', 'Python is Nice', "That's Fun!"] for word in tokens: for line in sentences: if w...
0
2016-06-30T12:42:44Z
38,123,898
<p>You might want to use dynamically generated regular expressions, ie for "Python" the regexp will look like '\bPython\b'. '\b' is a word boundary.</p> <pre><code>tokens=['Time','Fun','Python'] sentences=['Time is High', "Who's Funny", 'Pythons', 'Python is Nice', "That's Fun!"] import re for word in tokens: reg...
0
2016-06-30T13:00:23Z
[ "python", "string" ]
Match shortest substring in list using for loop
38,123,454
<p>I am trying to match items (single words) from one list with items (full sentences) from a second list. This is my code: </p> <pre><code>tokens=['Time','Fun','Python'] sentences=['Time is High', "Who's Funny", 'Pythons', 'Python is Nice', "That's Fun!"] for word in tokens: for line in sentences: if w...
0
2016-06-30T12:42:44Z
38,123,953
<p>Since you want exact matches, it'd be better to use <code>==</code> instead of <code>in</code>. </p> <pre><code>import string tokens=['Time','Fun','Python'] sentences=['Time is High', "Who's Funny", 'Pythons', 'Python is Nice', "That's Fun!"] for word in tokens: for line in sentences: for wrd in l...
0
2016-06-30T13:02:31Z
[ "python", "string" ]
Match shortest substring in list using for loop
38,123,454
<p>I am trying to match items (single words) from one list with items (full sentences) from a second list. This is my code: </p> <pre><code>tokens=['Time','Fun','Python'] sentences=['Time is High', "Who's Funny", 'Pythons', 'Python is Nice', "That's Fun!"] for word in tokens: for line in sentences: if w...
0
2016-06-30T12:42:44Z
38,124,851
<p>tokenized sentence is better then split it by space, since tokenize will separate punctuation.</p> <p>for example:</p> <pre><code>sentence = 'this is a test.' &gt;&gt;&gt; 'test' in 'this is a test.'.split(' ') False &gt;&gt;&gt; nltk.word_tokenize('this is a test.') ['this', 'is', 'a', 'test','.'] </code></pre> ...
0
2016-06-30T13:40:05Z
[ "python", "string" ]
Python subprocess call hungs when running rpm2cpio
38,123,480
<p>I'm running the below command using python subprocess to extract files from rpm. But the command failes when the rpm size is more than 25 - 30 MB. Tried the command using <code>Popen</code>, <code>call</code>, with <code>stdout</code> as <code>PIPE</code> and <code>os.system</code> as well. This command is working f...
0
2016-06-30T12:43:54Z
38,141,616
<p>If all you want is the payload of a *.rpm package, then do the computations to find the beginning of the compressed cpio payload and do the operations directly in python.</p> <p>See <a href="http://stackoverflow.com/questions/18787375/how-do-i-extract-the-contents-of-an-rpm/28440918#28440918">How do I extract the c...
0
2016-07-01T09:17:30Z
[ "python", "process", "rpm", "strace", "cpio" ]
Python subprocess call hungs when running rpm2cpio
38,123,480
<p>I'm running the below command using python subprocess to extract files from rpm. But the command failes when the rpm size is more than 25 - 30 MB. Tried the command using <code>Popen</code>, <code>call</code>, with <code>stdout</code> as <code>PIPE</code> and <code>os.system</code> as well. This command is working f...
0
2016-06-30T12:43:54Z
38,543,130
<p>Your output pipe is full. The <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">python docs</a> note in many places <strong>not</strong> to do what you are doing:</p> <blockquote> <p>Do not use stdout=PIPE or stderr=PIPE with this function as that can deadlock based on the child process o...
0
2016-07-23T14:59:02Z
[ "python", "process", "rpm", "strace", "cpio" ]
Boto2 file upload does not works
38,123,504
<p>I am trying to upload files to S3 bucket using code from this question: <a href="http://stackoverflow.com/a/15087468/291372">http://stackoverflow.com/a/15087468/291372</a>. I am using boto2 (boto3 has too many dependencies). I tried many methods, but no one works for me. CORS was checked for bucket and set to allow ...
1
2016-06-30T12:44:49Z
38,252,179
<p>Try this code, I'm using it to upload a lot of files (most of them are > 1MB):</p> <pre><code>from boto.s3.connection import S3Connection from contextlib import contextmanager @contextmanager def connect_to_s3(): conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) try: yield conn fin...
1
2016-07-07T17:54:43Z
[ "python", "amazon-s3", "boto" ]
Performance hit from if: pass statements
38,123,568
<p>I am writing a script that parses user input, reads a file, does some work, and then sends an html POST request. </p> <p>There is one section of the code that requires me to do a different action based on the interaction of three variables, but some of the cases are handled with 'do nothing' i.e. <code>pass</code>....
2
2016-06-30T12:47:30Z
38,123,698
<p>The only real performance hit will be if you have to evaluate a complex conditional going into the statement. I'd have to see a snippet of your code, but you may be able to save some time by checking the simplest / most common conditions near the top of the block and using continue vs. pass (if it's an iterable) or ...
0
2016-06-30T12:52:49Z
[ "python", "performance", "if-statement" ]
Performance hit from if: pass statements
38,123,568
<p>I am writing a script that parses user input, reads a file, does some work, and then sends an html POST request. </p> <p>There is one section of the code that requires me to do a different action based on the interaction of three variables, but some of the cases are handled with 'do nothing' i.e. <code>pass</code>....
2
2016-06-30T12:47:30Z
38,123,906
<p>In many cases if conditions actually speed up the program (because we are skipping over blocks of code). But that is not the case as nothing is done inside the blocks.</p> <p>The only time large numbers of if statements will slow down the code execution is if the condition you're checking requires processing. An ex...
1
2016-06-30T13:00:31Z
[ "python", "performance", "if-statement" ]
Performance hit from if: pass statements
38,123,568
<p>I am writing a script that parses user input, reads a file, does some work, and then sends an html POST request. </p> <p>There is one section of the code that requires me to do a different action based on the interaction of three variables, but some of the cases are handled with 'do nothing' i.e. <code>pass</code>....
2
2016-06-30T12:47:30Z
38,123,950
<p>My advice would be to go for readability: if your code will be read by many people, make it as simple and as comprehensible as you can. Anything else would be premature optimization.</p> <p>You can actually do tests with <a href="https://docs.python.org/2/library/timeit.html" rel="nofollow">the <code>timeit</code> ...
2
2016-06-30T13:02:23Z
[ "python", "performance", "if-statement" ]
How to connect to the mongodb-cluster using mongoengine
38,123,843
<p>I'm build mongodb-cluster with replication and sharding. I'm set x509-based authentication. I'm connect to database (mongos) by mongo as:</p> <pre><code>mongo admin --ssl --sslCAFile mongoCA.pem \ --sslPEMKeyFile client.pem -u user -p password --host my.host.com --port 27017 </code></pre> <p>How do I connect to th...
1
2016-06-30T12:58:09Z
38,181,352
<p>I looked dokstring "register_connection" and I found:</p> <pre><code>:param kwargs: allow ad-hoc parameters to be passed into the pymongo driver </code></pre> <p>And I use this as:</p> <pre><code>import os import ssl from mongoengine import DEFAULT_CONNECTION_NAME, register_connection from pymongo import ReadPref...
1
2016-07-04T09:34:33Z
[ "python", "mongodb", "database-connection", "x509", "mongoengine" ]
How to nicely measure runs of same-data in a pandas dataframe
38,123,904
<p>I want to give a function an arbitrary dataframe, dateindex, and column and ask it to return how many continuous preceding rows (including itself) had the same value. I've been able to keep most of my pandas code vectorized. Struggling to think how I can do this cleanly though.</p> <p>Below is a small toy datase...
4
2016-06-30T13:00:29Z
38,124,790
<p>try this:</p> <pre><code>In [135]: %paste def consec(df, col, d): return (df[:d].groupby((df[col] != df[col].shift()) .cumsum())[col] .transform('size').tail(1)[0]) ## -- End pasted text -- In [137]: consec(df, 'foo', '2016-06-09') Out[137]: 4 In [138]: consec(df, ...
1
2016-06-30T13:37:40Z
[ "python", "pandas" ]
How to nicely measure runs of same-data in a pandas dataframe
38,123,904
<p>I want to give a function an arbitrary dataframe, dateindex, and column and ask it to return how many continuous preceding rows (including itself) had the same value. I've been able to keep most of my pandas code vectorized. Struggling to think how I can do this cleanly though.</p> <p>Below is a small toy datase...
4
2016-06-30T13:00:29Z
38,124,886
<p>You can use:</p> <pre><code>#reorder index in df df = df[::-1] def consec(col, date): #select df by date df1 = df.ix[date:,:] #get first group == 1 colconsec = (df1[col] != df1[col].shift()).cumsum() == 1 return 'Value is ' + str(df1.ix[0,col]) + ', Len is: '+ str(len(df1[colconsec])) print (c...
1
2016-06-30T13:41:23Z
[ "python", "pandas" ]
How to nicely measure runs of same-data in a pandas dataframe
38,123,904
<p>I want to give a function an arbitrary dataframe, dateindex, and column and ask it to return how many continuous preceding rows (including itself) had the same value. I've been able to keep most of my pandas code vectorized. Struggling to think how I can do this cleanly though.</p> <p>Below is a small toy datase...
4
2016-06-30T13:00:29Z
38,125,649
<p>Here's an alternative method which creates a new column with the relevant consecutive count for each row. I tested this when the dataframe has 10000 rows and it took 24 ms. It uses <code>groupby</code> from <a href="https://docs.python.org/2.7/library/itertools.html" rel="nofollow"><code>itertools</code></a>. It tak...
1
2016-06-30T14:09:29Z
[ "python", "pandas" ]
UnicodeDecodeError when add new list to excel using python
38,124,065
<p>I try to add new sheet to excel file with</p> <pre><code>def add_xlsx_sheet(df, sheet_name=u'Десктопы кратко', index=True, digits=2, path=None): book = load_workbook(path) writer = pd.ExcelWriter(path, engine='openpyxl') writer.book = book writer.sheets = dict((ws.title, ws) for ws in book.worksheets)...
0
2016-06-30T13:06:45Z
38,126,444
<p>Try the following:</p> <pre><code>df.groupby('member_id').apply(lambda x: add_xlsx_sheet(x, u'Десктопы полно', path='u{}.xlsx'.format(x.name))) </code></pre> <p>If this doesn't work you may need to decode <code>x.name</code>. Or switch to Python 3.</p>
0
2016-06-30T14:41:37Z
[ "python", "excel", "pandas", "openpyxl" ]
Django, rendering a view from another view (call a specific URL)
38,124,335
<p>simple question, i'm a Django and Pyhton noob...</p> <p>I'm trying to do a really simple thing, at least i think so:</p> <p>I've a little form:</p> <pre><code>&lt;form action="#" method="post"&gt; {% csrf_token %} &lt;label&gt;Company Number:&lt;/label&gt; &lt;input type="text" name="company" placehol...
0
2016-06-30T13:16:53Z
38,124,687
<p>Does the following code solve your problem?</p> <p>In your template:</p> <pre><code>&lt;form action="{% url 'userfilt' %}" method="post"&gt; </code></pre>
0
2016-06-30T13:33:11Z
[ "python", "django", "forms", "redirect", "post" ]
Django, rendering a view from another view (call a specific URL)
38,124,335
<p>simple question, i'm a Django and Pyhton noob...</p> <p>I'm trying to do a really simple thing, at least i think so:</p> <p>I've a little form:</p> <pre><code>&lt;form action="#" method="post"&gt; {% csrf_token %} &lt;label&gt;Company Number:&lt;/label&gt; &lt;input type="text" name="company" placehol...
0
2016-06-30T13:16:53Z
38,124,827
<p>You should always redirect, not render, after a successful post. Doing <code>return redirect(url)</code> is the correct thing to do, and it's not clear why you're not happy with this.</p> <p>Note that <code>redirect</code> <a href="https://docs.djangoproject.com/en/1.9/topics/http/shortcuts/#redirect" rel="nofollow...
0
2016-06-30T13:39:06Z
[ "python", "django", "forms", "redirect", "post" ]
DASK : IOError: [Errno 13] Permission denied:
38,124,425
<p>I am using <code>Dask 0.10</code> with the latest <code>Anaconda</code> distribution and I run into the following error after calling <code>.compute(get=dask.multiprocessing.get)</code> : </p> <pre><code> File "&lt;ipython-input-8-cd6a1c9a02b6&gt;", line 309, in find_matches merged = data.merge(matches, on='u...
0
2016-06-30T13:21:14Z
38,154,531
<blockquote> <p>Does Dask needs to write on the root directory? </p> </blockquote> <p>No, Dask operates entirely within userspace, as does Anaconda generally. In the traceback provided it looks like the error is coming from trying to open a file named <code>"log"</code> in the local directory. Perhaps you're runni...
1
2016-07-01T22:20:59Z
[ "python", "pandas", "anaconda", "dask" ]
Python numpy difference between reshape(v.shape) & reshape(*v.shape)
38,124,433
<p>I found myself struggled in the following two region of codes(which exactly did the same job),can anyone tell me what the difference?</p> <p>Code1: </p> <pre><code>v = np.zeros((2,5)) value_one = np.linspace(-1.4, 1.3, num=v.size).reshape(*v.shape) </code></pre> <p>Code2:</p> <pre><code>v = np.zeros((2,5)) value...
0
2016-06-30T13:21:45Z
38,125,587
<p>Since <code>reshape</code> can accept either ints or tuple of ints both version are ok. You can verify by</p> <pre><code>value_one = np.linspace(-1.4, 1.3, num=10).reshape(2,5) value_one = np.linspace(-1.4, 1.3, num=10).reshape((2,5)) </code></pre> <p>The stared version <code>*v.shape</code> will strip the tuple ...
1
2016-06-30T14:07:24Z
[ "python", "numpy" ]
Why does the function fail to parse the data from a csv file when another function works to parse the csv file
38,124,463
<pre><code>def participated(): part_counters = {} for line in reader: if int(line[6]) &gt; 0: primary = line[7].strip() part_counters.setdefault(primary, 0) part_counters[primary] += 1 return part_counters data_out.seek(0) reader = csv.reader(data_out) next(reade...
0
2016-06-30T13:23:05Z
38,124,884
<p>Short answer: don't do global resources.</p> <p>Long answer: <code>reader</code> is an iterator, which iterates over the lines in your csv. That is, whenever a new line has been provided, the iterator skips on to the next line. That implies that it will reach the last line somewhen, and cannot provide any more line...
1
2016-06-30T13:41:19Z
[ "python", "python-2.7", "csv" ]
Sample code for listing a FixedPriceItem with ebay
38,124,679
<p>I'm working with Python 2.7 on a Linux environment, my app working with the ebay trading API with the sdk: <a href="https://github.com/timotheus/ebaysdk-python" rel="nofollow">ebaysdk-python</a>. My goal is to list a fixedpriceitem, I didn't found a correct way to do it...</p> <p>It seems the example on the ebay we...
12
2016-06-30T13:32:53Z
38,307,167
<p>finally ebay answer to the question and solve the problem.</p> <p>The call was failing because the mandatory ItemSpecifics Brand(Marca for Italy site) &amp; MPN was missing. It'll work fine if you use the following parameters. </p> <pre><code>&lt;ItemSpecifics&gt; &lt;NameValueList&gt; &lt;Name&gt;Marca&lt;...
0
2016-07-11T12:38:59Z
[ "python", "python-2.7", "ebay-api" ]
How to pass id argument while calling an old api method from a new api method in odoo
38,124,689
<p>Currently i am working on odoo8. I have a function written in new API as,</p> <pre><code>@api.onchange('scheme','product_id','product_uos_qty') @api.constrains('scheme','product_id','product_uos_qty') def change_sale_price_scheme(self): if self.scheme: get_product_wise_tax = self.pool.get('sale.order.li...
1
2016-06-30T13:33:16Z
38,195,128
<p>Finally after a long search I found the answer. What I did is..</p> <pre><code>@api.onchange('scheme','product_id','product_uos_qty') @api.constrains('scheme','product_id','product_uos_qty') def change_sale_price_scheme(self): if self.scheme: self.foo() @api.cr_uid_ids_context def foo(self,cr,uid,ids,c...
0
2016-07-05T04:21:03Z
[ "python", "api", "odoo-8" ]
Speed SELECT SQlite Python very unstable
38,124,810
<p>I'm using a reasonably large SQLite database (300 - 400 MB) together with a Python 3 program , it has two columns, which I call key and value. The key column is indexed, but not unique. Sometimes there is no or small amounts of values for a certain key, sometimes several hundreds. </p> <p>For some reason, the follo...
-1
2016-06-30T13:38:25Z
38,124,955
<p>It seems you have all the information you need: if performance is restored by rebuilding the index then the poor performance is likely due to index fragmentation due to updates, though you don't mention that you <em>are</em> updating it. Without changes to the database content I can't think of any reason why perform...
1
2016-06-30T13:44:05Z
[ "python", "performance", "sqlite" ]
Setting up and sending data over a serial connection in Python
38,124,840
<p>I have code written in C++ that I am translating to Python. The C++ code is:</p> <pre><code> WriteBuffer[0] = unsigned char (0xc0 + (Steer &amp; 0x1F)); // change the signal to conform to jrk motor controller WriteBuffer[1] = unsigned char (Steer &gt;&gt; 5) &amp; 0x7F; // two-word f...
0
2016-06-30T13:39:37Z
38,277,962
<p>The problem was in my first line of code. I had this:</p> <pre><code>rightWheel = bytearray(b'\xc000') </code></pre> <p>But that was making rightWheel into 3 bytes, taking the rightmost two 0s as one-byte ASCII characters for 0 each. So rightWheel became b'\xc0\x30\x30'.</p> <p>This modified first line of code wo...
1
2016-07-09T03:23:16Z
[ "python", "serial-communication" ]
Connecting to the Tor network with Python without getting "Proxy server is refusing connection"
38,125,000
<p>I've been trying to use Tor via Python only to come across the "Proxy server is refusing connection" error.</p> <p>I've trying this method using the Stem library: <a href="http://www.thedurkweb.com/automated-anonymous-interactions-with-websites-using-python-and-tor/" rel="nofollow">http://www.thedurkweb.com/automat...
1
2016-06-30T13:45:51Z
38,444,846
<p>I deleted the SSL and FTP proxy and port settings and it worked. I also used port 9150.</p> <p>Here is the working code:</p> <pre><code>import stem.process from stem import Signal from stem.control import Controller from splinter import Browser proxyIP = "127.0.0.1" proxyPort = 9150 proxy_settings = {"network.pr...
1
2016-07-18T19:47:28Z
[ "python", "tor" ]
ValueError: I/O operation on closed file (Using two txt files)
38,125,039
<p>I'm getting this error in my coding and I'm not sure what it means. The code uses different files to compare the 4th column and check if they are the same. I'm very new to coding using Python, I have a week worth of experience. Any help is much appreciated.</p> <pre><code>from tkFileDialog import askopenfilename fr...
-1
2016-06-30T13:47:21Z
38,125,159
<p>After going over its <a href="http://tkinter.unpythonic.net/wiki/tkFileDialog" rel="nofollow">documentation</a>, <code>tkFileDialog.askopenfilename</code> doesn't seem to actually open the file, so you should open it on your own. </p> <pre><code>a = askopenfilename() b = askopenfilename() with open(a) as file_a, o...
1
2016-06-30T13:51:34Z
[ "python", "tkinter" ]
Raspberry Pi RuntimeError: Conflicting edge detection already enabled for this GPIO channel
38,125,047
<p>I was following a tutorial found here: <a href="https://www.linkedin.com/pulse/prepare-your-raspberry-pi-work-aws-iot-kay-lerch" rel="nofollow">https://www.linkedin.com/pulse/prepare-your-raspberry-pi-work-aws-iot-kay-lerch</a></p> <p>I have not even begun the internet part of it as I was having issues with the cir...
1
2016-06-30T13:47:36Z
38,126,203
<p>The code you have is adding an event detection callback constantly (in the <code>while(True)</code> loop). What you want is to add the event detection callback once and then wait for an edge.</p> <p>This <a href="http://raspi.tv/2014/rpi-gpio-update-and-detecting-both-rising-and-falling-edges" rel="nofollow" title=...
2
2016-06-30T14:31:06Z
[ "python", "python-2.7", "raspberry-pi", "gpio", "raspberry-pi3" ]
Python - Using Pandas to eliminated curly brackets and output floats
38,125,060
<p>Having this large csv data set, that essentially has x and y values in each column.</p> <pre><code>"{733.15, 179.5}", "{565.5, 642.5}", "{172.5, 375.5}", "{223.5, 554.5}",.... ...., "{213.5, 666.5}", "{851.5, 323.5}", "{498.5, 638.5}", "{763.5, 102.5}" </code></pre> <p>or by a table,</p> <p><a href="http://i.st...
2
2016-06-30T13:48:06Z
38,125,357
<p>You can use a regex against the string, then parse it to a float.</p> <pre><code>import re # Returns 733.15 float(re.match(r'\{(.*),\s*(.*)\}', '{733.15, 179.5}').group(1)) # Returns 179.5 float(re.match(r'\{(.*),\s*(.*)\}', '{733.15, 179.5}').group(2)) </code></pre>
1
2016-06-30T13:58:24Z
[ "python", "csv", "numpy", "pandas" ]
Python - Using Pandas to eliminated curly brackets and output floats
38,125,060
<p>Having this large csv data set, that essentially has x and y values in each column.</p> <pre><code>"{733.15, 179.5}", "{565.5, 642.5}", "{172.5, 375.5}", "{223.5, 554.5}",.... ...., "{213.5, 666.5}", "{851.5, 323.5}", "{498.5, 638.5}", "{763.5, 102.5}" </code></pre> <p>or by a table,</p> <p><a href="http://i.st...
2
2016-06-30T13:48:06Z
38,125,405
<p><strong>UPDATE:</strong></p> <pre><code>def str2coords(df, col, new_cols): df[new_cols] = df[col].str.extract(r'\{([\d\.]+),\s*([\d\.]+)\}', expand=True).astype(np.float64) return df.drop(col, axis=1) In [204]: df Out[204]: coord1 coord2 0 {733.15, 179.5} {33.15, 79.5} 1 {565.5, 642...
2
2016-06-30T13:59:53Z
[ "python", "csv", "numpy", "pandas" ]
Python - Using Pandas to eliminated curly brackets and output floats
38,125,060
<p>Having this large csv data set, that essentially has x and y values in each column.</p> <pre><code>"{733.15, 179.5}", "{565.5, 642.5}", "{172.5, 375.5}", "{223.5, 554.5}",.... ...., "{213.5, 666.5}", "{851.5, 323.5}", "{498.5, 638.5}", "{763.5, 102.5}" </code></pre> <p>or by a table,</p> <p><a href="http://i.st...
2
2016-06-30T13:48:06Z
38,125,479
<p>Or you can <code>extract</code> then <code>split</code>.</p> <pre><code>df.col1.str.extract(r'{(.*)}', expand=False).str.split(', ', expand=True) </code></pre> <hr> <h3>Timing</h3> <p>MaxU's solution is quicker as it does more in one step as opposed to mine that takes two steps.</p> <p><a href="http://i.stack.i...
3
2016-06-30T14:02:40Z
[ "python", "csv", "numpy", "pandas" ]
Tests fails with TransactionTestCase and pytest
38,125,218
<p>I have an issue with a my unit tests and the way django manages transactions.</p> <p>In my code I have a function:</p> <pre><code>def send(): autocommit = transaction.set_autocommit(False) try: # stuff finally: transaction.rollback() transaction.set_autocommit(autocommit) </c...
4
2016-06-30T13:53:44Z
38,125,494
<p>The <a href="https://docs.djangoproject.com/en/1.9/topics/testing/tools/#testcase" rel="nofollow"><code>TestCase</code></a> class wraps the tests inside two atomic blocks. Therefore it is not possible to use <code>transaction.set_autocommit()</code> or <code>transaction.rollback()</code> if you are inheriting from <...
4
2016-06-30T14:03:37Z
[ "python", "django", "py.test", "django-1.8" ]
Tests fails with TransactionTestCase and pytest
38,125,218
<p>I have an issue with a my unit tests and the way django manages transactions.</p> <p>In my code I have a function:</p> <pre><code>def send(): autocommit = transaction.set_autocommit(False) try: # stuff finally: transaction.rollback() transaction.set_autocommit(autocommit) </c...
4
2016-06-30T13:53:44Z
38,197,709
<p>having <code>autocommit = transaction.set_autocommit(False)</code> inside the <code>send</code> function feels wrong. Disabling the transaction is done here presumably for testing purposes, but the rule of thumb is to keep your test logic outside your code.</p> <p>As @Alasdair has pointed out, <a href="https://doc...
3
2016-07-05T07:34:09Z
[ "python", "django", "py.test", "django-1.8" ]
DataFrame sorting unwanted using Pandas
38,125,231
<p>Consider a basic data frame (using Pandas):</p> <pre><code>testDf = pandas.DataFrame({'c':[1,2],'b':[2,2],'a':[3,4]}) </code></pre> <p>The result gives:</p> <pre><code> a b c 0 3 2 1 1 4 2 2 </code></pre> <p>Instead of:</p> <pre><code> c b a 0 1 2 3 1 2 2 4 </code></pre> <p>Why is it sorted...
3
2016-06-30T13:54:03Z
38,125,279
<p>A dictionary is unsorted, therefor you cannot expect the ordering to be the same as in the initialization. </p>
0
2016-06-30T13:55:43Z
[ "python", "pandas" ]
DataFrame sorting unwanted using Pandas
38,125,231
<p>Consider a basic data frame (using Pandas):</p> <pre><code>testDf = pandas.DataFrame({'c':[1,2],'b':[2,2],'a':[3,4]}) </code></pre> <p>The result gives:</p> <pre><code> a b c 0 3 2 1 1 4 2 2 </code></pre> <p>Instead of:</p> <pre><code> c b a 0 1 2 3 1 2 2 4 </code></pre> <p>Why is it sorted...
3
2016-06-30T13:54:03Z
38,125,280
<p>You passed a dict as the data param so the order is not the same as the order of key creation as the order is not the same, you can specify the column order by passing a list of the columns as the arg for <code>columns</code> param:</p> <pre><code>In [307]: testDf = pd.DataFrame({'c':[1,2],'b':[2,2],'a':[3,4]}, col...
2
2016-06-30T13:55:45Z
[ "python", "pandas" ]
DataFrame sorting unwanted using Pandas
38,125,231
<p>Consider a basic data frame (using Pandas):</p> <pre><code>testDf = pandas.DataFrame({'c':[1,2],'b':[2,2],'a':[3,4]}) </code></pre> <p>The result gives:</p> <pre><code> a b c 0 3 2 1 1 4 2 2 </code></pre> <p>Instead of:</p> <pre><code> c b a 0 1 2 3 1 2 2 4 </code></pre> <p>Why is it sorted...
3
2016-06-30T13:54:03Z
38,125,284
<p>You need add parameter <code>columns</code> to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html" rel="nofollow"><code>DataFrame</code></a> constructor, because <code>dict</code> is unordered:</p> <pre><code>print (pd.DataFrame({'c':[1,2],'b':[2,2],'a':[3,4]}, columns=['c','b','a'...
3
2016-06-30T13:55:50Z
[ "python", "pandas" ]
Please correct my code Python
38,125,244
<p>I am trying to read from a file and return solutions based on the problem that the user inputs. I have saved the text file in the same location, that is not an issue. At the moment, the program just crashes when I run it and type a problem eg "screen".</p> <p>Code</p> <pre><code> file = open("solutions.txt", 'r...
-2
2016-06-30T13:54:33Z
38,126,680
<p>When I change the line "for i in file:" to "for i in read:" everything works well. </p>
0
2016-06-30T14:52:05Z
[ "python" ]
Please correct my code Python
38,125,244
<p>I am trying to read from a file and return solutions based on the problem that the user inputs. I have saved the text file in the same location, that is not an issue. At the moment, the program just crashes when I run it and type a problem eg "screen".</p> <p>Code</p> <pre><code> file = open("solutions.txt", 'r...
-2
2016-06-30T13:54:33Z
38,131,267
<p>Your question reminds me a lot of my learning, so I will try give an answer to expand on your learning with lots of <code>print</code> statements to consider how it works carefully. It's not the most efficient or stable approach but hopefully of some use to you to move forwards. </p> <pre><code>print "LOADING RAW ...
1
2016-06-30T19:00:29Z
[ "python" ]
Please correct my code Python
38,125,244
<p>I am trying to read from a file and return solutions based on the problem that the user inputs. I have saved the text file in the same location, that is not an issue. At the moment, the program just crashes when I run it and type a problem eg "screen".</p> <p>Code</p> <pre><code> file = open("solutions.txt", 'r...
-2
2016-06-30T13:54:33Z
38,140,017
<p>To output only the line starting with "screen" just forget the probs variable and change the last for statement to</p> <pre class="lang-py prettyprint-override"><code>for line in advice: if line.startswith( favcol ) : print line break </code></pre> <p>For the <code>startswith()</code> function...
0
2016-07-01T07:55:20Z
[ "python" ]
cannot get pip to be recognized as a command
38,125,246
<p>I am trying to install <strong>matplotlib</strong> into <strong>python27</strong> but am running into issues with pip. As stated when I try any 'pip' command I get </p> <blockquote> <p>'pip' is not recognized as an internal or external command. </p> </blockquote> <p>I checked my path variables and they point to ...
0
2016-06-30T13:54:38Z
38,127,300
<p>You need to add <code>C:\Python27\Scripts</code> to your path as well. That is where the pip executable lives by default. </p> <p>Also, remember to close and reopen your command shell after you change your path variable to make sure that the update is loaded.</p>
0
2016-06-30T15:18:19Z
[ "python", "pip" ]
Extending or overwriting a docstring when composing classes
38,125,271
<p>I have a class <code>MyClass</code>:</p> <pre><code>class MyClass(object): def __init__(self): pass def my_function(self, x): # MyClass.my_function.__doc__ is not writable! # Otherwise, I could just set it here. Origin.func(self, x) </code></pre> <p>The class borrows from <...
1
2016-06-30T13:55:25Z
38,126,619
<p>I'm not clear on exactly how Sphinx works, but assuming it reads from <code>__doc__</code> rather than parsing the source, there are a number of options.</p> <hr> <p>Consider the simpler example...</p> <pre><code>def add(x, y): return x + y </code></pre> <p>...which is virtually identical to...</p> <pre><co...
3
2016-06-30T14:49:40Z
[ "python", "python-sphinx", "composition", "docstring" ]
split sentence without space in python (nltk?)
38,125,281
<p>I have a set of concatenated word and i want to split them into arrays</p> <p>For example : </p> <pre><code>split_word("acquirecustomerdata") =&gt; ['acquire', 'customer', 'data'] </code></pre> <p>I found <code>pyenchant</code>, but it's not available for 64bit windows. </p> <p>Then i tried to split each string ...
2
2016-06-30T13:55:46Z
38,125,893
<p>If you have a list of all possible words, you can use something like this:</p> <pre><code>import re word_list = ["go", "walk", "run", "jump"] # list of all possible words pattern = re.compile("|".join("%s" % word for word in word_list)) s = "gowalkrunjump" result = re.findall(pattern, s) </code></pre>
0
2016-06-30T14:18:42Z
[ "python", "nltk", "spell-checking", "wordnet" ]
split sentence without space in python (nltk?)
38,125,281
<p>I have a set of concatenated word and i want to split them into arrays</p> <p>For example : </p> <pre><code>split_word("acquirecustomerdata") =&gt; ['acquire', 'customer', 'data'] </code></pre> <p>I found <code>pyenchant</code>, but it's not available for 64bit windows. </p> <p>Then i tried to split each string ...
2
2016-06-30T13:55:46Z
38,291,700
<p>Check - <a href="http://nbviewer.jupyter.org/url/norvig.com/ipython/How%20to%20Do%20Things%20with%20Words.ipynb" rel="nofollow">Word Segmentation Task</a> from <a href="http://norvig.com/" rel="nofollow">Norvig</a>'s work.</p> <pre><code>from __future__ import division from collections import Counter import re, nlt...
1
2016-07-10T12:07:48Z
[ "python", "nltk", "spell-checking", "wordnet" ]
Using execute()/executemany() for SQL statements in python
38,125,308
<p>I am using the MySQLdb module in python to write SQL statements. I am having a difficult time using variables in the way I'd like to. Here's my work:</p> <pre><code>stmt = "\ INSERT INTO Table1\ (name, status)\ SELECT (:name1, :status1)\ FROM dual\ WHERE NOT EXISTS (\ SELECT 1 FROM Table1\ W...
0
2016-06-30T13:56:52Z
38,125,407
<p><code>executemany()</code> takes a <em>sequence</em> of parameter objects (dictionaries), but you are passing in just <strong>one</strong>. Either use <code>dbcursor.execute()</code>, or pass in a sequence of dictionaries. Since you only have one dictionary, just use <code>dbcursor.execute()</code>:</p> <pre><code>...
0
2016-06-30T14:00:02Z
[ "python", "mysql", "sql", "python-2.7", "mysql-python" ]
nvcc fatal : Value 'sm_61' is not defined for option 'gpu-architecture' error with theano
38,125,310
<p>I was setting up python and theano for use with gpu on; ubunutu 14.04, GeForce GTX 1080 already installed NVIDIA driver (367.27) and CUDA toolkits (7.5) successfully for the system, but on testing with theano gpu implementation i get the above error (for example; when importing theano with gpu enabled) I have tried...
3
2016-06-30T13:56:54Z
38,161,800
<p>As Robert Crovella said, SM 6.1 (sm_61) is only supported in CUDA 8.0 and above, and thus you should download CUDA 8.0 Release Candidate from <a href="https://developer.nvidia.com/cuda-toolkit" rel="nofollow">https://developer.nvidia.com/cuda-toolkit</a></p> <p>Ubuntu 14.04 is supported, and the instructions on the...
4
2016-07-02T15:41:33Z
[ "python", "cuda", "gpu", "theano", "nvcc" ]
python divide by zero encountered in log - logistic regression
38,125,319
<p>I'm trying to implement a multiclass logistic regression classifier that distinguishes between <code>k</code> different classes.</p> <p>This is my code.</p> <pre><code>import numpy as np from scipy.special import expit def cost(X,y,theta,regTerm): (m,n) = X.shape J = (np.dot(-(y.T),np.log(expit(np.dot(X,...
0
2016-06-30T13:57:13Z
38,125,456
<p>I'm guessing your data has negative values in it. You can't log a negative.</p> <pre><code>import numpy as np np.log(2) &gt; 0.69314718055994529 np.log(-2) &gt; nan </code></pre> <p>There are a lot of different ways to transform your data that should help, if this is the case.</p>
0
2016-06-30T14:01:52Z
[ "python", "machine-learning", "logistic-regression", "logarithm", "divide-by-zero" ]
python divide by zero encountered in log - logistic regression
38,125,319
<p>I'm trying to implement a multiclass logistic regression classifier that distinguishes between <code>k</code> different classes.</p> <p>This is my code.</p> <pre><code>import numpy as np from scipy.special import expit def cost(X,y,theta,regTerm): (m,n) = X.shape J = (np.dot(-(y.T),np.log(expit(np.dot(X,...
0
2016-06-30T13:57:13Z
38,127,042
<p>Not an answer to your question, but too long for a comment.</p> <p>You can clean up the formula by appropriately using broadcasting, the operator <code>*</code> for dot products of vectors, and the operator <code>@</code> for matrix multiplication &mdash; and breaking it up as suggested in the comments. Here is you...
2
2016-06-30T15:07:01Z
[ "python", "machine-learning", "logistic-regression", "logarithm", "divide-by-zero" ]
Adding progressbar to pop up kv language
38,125,356
<p>I am trying to add <code>ProgressBar</code> to <code>PopUp</code> using the kv language.<br> As per the docs I have to pass the <code>ProgressBar</code> to it as <code>content</code>.</p> <p>But it gives error.</p> <pre><code>&lt;DownPop&gt;: size_hint: .5, .5 auto_dismiss: False title: 'Downloading' ...
0
2016-06-30T13:58:24Z
38,125,916
<p>Yup, that's not going to happen. <code>content</code> is mainly for python side if I'm right.</p> <p>It's used for <code>add_widget(content)</code> in <code>__init__()</code> of a widget, because it needs to be placed somewhere inside the widget e.g. Popup is built with Label, Button, some strip etc + blank space i...
0
2016-06-30T14:19:38Z
[ "python", "kivy" ]
Find and adjust date and timestamp in XML using python
38,125,411
<p>I'm trying to change all date values in an XML and subsequently add or subtract an user specified amount of time from the time stamps.</p> <p>The timestamps are all of the format 2016-06-29T17:03:39.000Z However, they are not all enclosed in the same tags</p> <p>My XML looks something like this:</p> <pre><code>&l...
0
2016-06-30T14:00:13Z
38,125,712
<p>You can use this:</p> <pre><code>(?P&lt;YEAR&gt;[\d]{4})-(?P&lt;MONTH&gt;([0][1-9])|([1][0-2]))-(?P&lt;DAY&gt;([0][1-9])|([12][0-9])|([3][01]))T(?P&lt;HOUR&gt;([01][0-9])|([2][0-3])):(?P&lt;MINUTES&gt;([0-5][0-9])):(?P&lt;SECONDS&gt;([0-5][0-9])).(?P&lt;MILLIS&gt;[0-9]{3})Z </code></pre> <p>And then you can access...
0
2016-06-30T14:12:08Z
[ "python", "regex", "xml", "timestamp", "datestamp" ]
Find and adjust date and timestamp in XML using python
38,125,411
<p>I'm trying to change all date values in an XML and subsequently add or subtract an user specified amount of time from the time stamps.</p> <p>The timestamps are all of the format 2016-06-29T17:03:39.000Z However, they are not all enclosed in the same tags</p> <p>My XML looks something like this:</p> <pre><code>&l...
0
2016-06-30T14:00:13Z
38,125,777
<p>use this regex to find the all date :</p> <blockquote> <p>\d{4}[-/]\d{2}[-/]\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z</p> </blockquote> <pre><code>filedata = filedata.split() for line in filedata: cur_date = re.findall('\d{4}[-/]\d{2[-/]\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z', line) print cur_date for match in cur_dat...
0
2016-06-30T14:15:03Z
[ "python", "regex", "xml", "timestamp", "datestamp" ]
Find and adjust date and timestamp in XML using python
38,125,411
<p>I'm trying to change all date values in an XML and subsequently add or subtract an user specified amount of time from the time stamps.</p> <p>The timestamps are all of the format 2016-06-29T17:03:39.000Z However, they are not all enclosed in the same tags</p> <p>My XML looks something like this:</p> <pre><code>&l...
0
2016-06-30T14:00:13Z
38,144,720
<p>Assuming we can ignore that the timestamps are embedded in XML in this case, you could adjust them using <code>re.sub()</code>:</p> <pre><code>#!/usr/bin/env python2 import datetime as DT import fileinput import re timestamp_regex = '(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).(\d{3})Z' def add_two_days(m): ...
0
2016-07-01T11:50:41Z
[ "python", "regex", "xml", "timestamp", "datestamp" ]
Find and adjust date and timestamp in XML using python
38,125,411
<p>I'm trying to change all date values in an XML and subsequently add or subtract an user specified amount of time from the time stamps.</p> <p>The timestamps are all of the format 2016-06-29T17:03:39.000Z However, they are not all enclosed in the same tags</p> <p>My XML looks something like this:</p> <pre><code>&l...
0
2016-06-30T14:00:13Z
38,197,328
<p>I finally solved the issue with the following code (it might not be 100% optimal, but it works..):</p> <pre><code>import re import xml.etree.ElementTree as et import datetime name_file = 'test.gpx' #raw_input("Naam van file incl .txt op het einde: ") nieuwe_datum = '2016-06-30' #raw_input("Nieuwe datum format YYYY...
0
2016-07-05T07:12:49Z
[ "python", "regex", "xml", "timestamp", "datestamp" ]
NodeJS Selenium using WebElements returned from findElements
38,125,421
<p>I am completely new to Node.js and am currently trying to re-write some of my Python code into it.</p> <p>I have the following snippet in Python where <code>driver</code> is my <code>webdriver</code> instance.</p> <pre><code>tabs = driver.find_elements_by_xpath('//div[@class="className"]') for tab in tabs: ...
0
2016-06-30T14:00:41Z
38,125,866
<p>If I dig into the selenium source code for <a href="https://github.com/SeleniumHQ/selenium/blob/master/javascript/webdriver/atoms/inject/find_element.js#L41" rel="nofollow"><code>findElement()</code></a> I see it can take an <code>opt_root</code> as parameter. The doc about it says:</p> <blockquote> <p>@param {?{...
0
2016-06-30T14:18:07Z
[ "python", "node.js", "selenium" ]
TensorFlow - how to evaluate all test set with every example once and only once
38,125,436
<p>I am running <a href="https://www.tensorflow.org/versions/r0.9/tutorials/deep_cnn/index.html" rel="nofollow">cifar10</a> example from TensorFlow. But there is a problem for evaluation.</p> <p>I have a test set and I want to evaluate every example from it once and only once. But the code (<a href="https://github.com...
0
2016-06-30T14:01:11Z
38,125,661
<p>The function <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/io_ops.html#string_input_producer" rel="nofollow"><code>tf.train.string_input_producer</code></a> that creates the queue of filenames <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/image/cifar10/cifar10_in...
0
2016-06-30T14:10:02Z
[ "python", "machine-learning", "tensorflow" ]
TensorFlow - how to evaluate all test set with every example once and only once
38,125,436
<p>I am running <a href="https://www.tensorflow.org/versions/r0.9/tutorials/deep_cnn/index.html" rel="nofollow">cifar10</a> example from TensorFlow. But there is a problem for evaluation.</p> <p>I have a test set and I want to evaluate every example from it once and only once. But the code (<a href="https://github.com...
0
2016-06-30T14:01:11Z
38,187,462
<p>I have figured a solution but rather imperfect. The clue is exclude it from variables to load and then initialize the <code>limit_epochs</code> by one's own. Following is the detailed step:</p> <p>Add the code <code>del variables_to_restore['input_producer/limit_epochs/epochs']</code> after <code>variables_to_resto...
0
2016-07-04T14:50:12Z
[ "python", "machine-learning", "tensorflow" ]
printing output in python to txt file
38,125,446
<p>wrote a simple program and would like to print the output to a text file. I'm trying the following at the very top of my script:</p> <pre><code>python SagicorPremiumCalculator2.py &gt; textfile.txt </code></pre> <p>But this is giving me a syntax error in idle. How is my syntax incorrect?</p> <pre><code>python Sag...
-5
2016-06-30T14:01:29Z
38,125,809
<p>If you want to write the output of your script in a file I see two options. The first one is to handle the writing in the python script :</p> <pre><code>#!/usr/bin/python #I am here assuming that you use a Unix-like system (i.e. Not Windows ) file = open('textfile.txt','w') ... some code ... file.write(myData +...
0
2016-06-30T14:16:17Z
[ "python" ]
Writing integers into a new file
38,125,453
<p>So I am trying to open a new file, and write in to that file all the values of <code>n</code>.</p> <pre><code>for n in [4, 7, 8, 10, 6, 3, 5, 13]: if n &gt; 5: print(n) b = open('new', 'w') b.write(n) </code></pre> <p>It writes the numbers in as a string and only writes in <code>13</code>, the last <co...
-5
2016-06-30T14:01:43Z
38,125,532
<p>Modified code:</p> <pre><code>with open('new', 'w') as outfile: for n in [4, 7, 8, 10, 6, 3, 5, 13]: if n &gt; 5: print(n) outfile.write(str(n)) </code></pre> <p>or (Not recommended)</p> <pre><code>for n in [4, 7, 8, 10, 6, 3, 5, 13]: if n &gt; 5: print(n) b...
1
2016-06-30T14:05:06Z
[ "python", "file", "file-writing" ]
Writing integers into a new file
38,125,453
<p>So I am trying to open a new file, and write in to that file all the values of <code>n</code>.</p> <pre><code>for n in [4, 7, 8, 10, 6, 3, 5, 13]: if n &gt; 5: print(n) b = open('new', 'w') b.write(n) </code></pre> <p>It writes the numbers in as a string and only writes in <code>13</code>, the last <co...
-5
2016-06-30T14:01:43Z
38,125,610
<p>You are printing the last value only. So you are getting the result only 13.You have to write the value in the for loop.</p> <pre><code>b = open('new', 'w') for n in [4, 7, 8, 10, 6, 3, 5, 13]: if n &gt; 5: print(n) b.write(n) </code></pre>
-1
2016-06-30T14:08:01Z
[ "python", "file", "file-writing" ]
how to write setup.py to install python extention (xxx.so file) built by SWIG?
38,125,588
<p>Using SWIG to build python extensions (xxx.so) is easier than <a href="https://docs.python.org/2/distutils/apiref.html#distutils.core.Extension" rel="nofollow">distutils</a>. You don't need to write a wrap.c program to wrap your original c program. So I'd like using SWIG than Distutils. But There is no methods to ...
0
2016-06-30T14:07:24Z
38,128,994
<p>Distutils is not about <em>writing</em> extensions, but about compiling and installing them. SWIG can help you creating the Python wrappers for your C/C++ code, but does <em>not</em> handle compiling and installing them.</p> <p>So, distutils can (and should) be used to install the SWIG generated extensions. See the...
0
2016-06-30T16:43:00Z
[ "python", "swig", "setup.py", "python-extensions" ]
Time data does not match format python
38,125,606
<p>I'm having troubles converting a time string to datetime object:</p> <p>time data 'June 30, 2016, 11:44 a.m.' does not match format '%B %d, %Y, %I:%M %p'</p> <pre><code>object = datetime.strptime('June 30, 2016, 11:44 a.m.', '%B %d, %Y, %I:%M %p') </code></pre> <p>Am I missing something? </p>
0
2016-06-30T14:07:56Z
38,125,723
<p>Are you sure that 'a.m.' matches your locale for AM/PM?</p> <p>what happens if you do</p> <pre><code>object = datetime.strptime('June 30, 2016, 11:44 am', '%B %d, %Y, %I:%M %p') </code></pre> <p>?</p>
0
2016-06-30T14:12:37Z
[ "python", "django" ]
Time data does not match format python
38,125,606
<p>I'm having troubles converting a time string to datetime object:</p> <p>time data 'June 30, 2016, 11:44 a.m.' does not match format '%B %d, %Y, %I:%M %p'</p> <pre><code>object = datetime.strptime('June 30, 2016, 11:44 a.m.', '%B %d, %Y, %I:%M %p') </code></pre> <p>Am I missing something? </p>
0
2016-06-30T14:07:56Z
38,125,847
<p><a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">Python docs</a></p> <blockquote> <p>%p Locale’s equivalent of either AM or PM. AM, PM (en_US); am, pm (de_DE)</p> </blockquote> <p>You need to change "a.m." for am</p> <p>Maybe:</p> <pre><code>date = 'June 30, 2016, 11:44 a.m.'....
0
2016-06-30T14:17:27Z
[ "python", "django" ]
Python Tkinter multiple line input as integer in list
38,125,644
<p>I have a problem reading multiple lines of coordinates (like x,y) from a Tkinter Textbox. The user input will be this:</p> <pre><code>41,3 21,12 68,10 etc. </code></pre> <p>Each Line represents an x,y coordinate. X and Y are seperated by ,. I need to read this coordinates from the text box and process it in a way ...
0
2016-06-30T14:09:16Z
38,126,315
<p>You have to <code>split</code> again at the <code>','</code> and convert to <code>int</code> (or <code>float</code>):</p> <pre><code>def get_Data(): text_from_Box = Text_Entry.get("1.0", 'end-1c').split("\n") numbers = [[int(x) for x in pair.split(",")] for pair in text_from_Box] print numbers </code></pre...
1
2016-06-30T14:35:51Z
[ "python", "tkinter", "python-2.x" ]
Pandas filter rows using multiple fields together
38,125,699
<p>I have a pandas <code>DataFrame</code> like this:</p> <pre><code>In [34]: people = pandas.DataFrame({'name' : ['John', 'John', 'Mike', 'Sarah', 'Julie'], 'age' : [28, 18, 18, 2, 69]}) people = people[['name', 'age']] people Out[34]: name age 0 John 28 1 John 18 2 Mike 1...
2
2016-06-30T14:11:44Z
38,125,967
<p>This should work:</p> <pre><code>people.set_index(people.columns.tolist(), drop=False).loc[filter].reset_index(drop=True) </code></pre> <h3>Cleaned up and with explanation</h3> <pre><code># set_index with the columns you want to reference in tuples cols = ['name', 'age'] people = people.set_index(cols, drop=False...
5
2016-06-30T14:21:33Z
[ "python", "pandas" ]
Importing external package once in my module without it being added to the namespace
38,125,727
<p>I apologize for not being able to phrase my question more easily. I am writing a large package that makes extensive use of pandas in almost every function. My first instinct, naturally, was to create an <code>__init__.py</code> as</p> <pre><code>import pandas # then import my own submodules and other things </code>...
2
2016-06-30T14:12:52Z
38,127,797
<blockquote> <p>...by <code>import</code>ing <code>pandas</code> from the <code>__init__.py</code> call I can define some <code>pandas</code>' options there (like <code>pandas.options.display.expand_frame_repr</code>) and it will be valid throughout the module.</p> </blockquote> <p>They will be anyway. The module is...
2
2016-06-30T15:42:26Z
[ "python", "python-2.7", "python-import" ]