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
Bug with a program for a guessing game
39,902,412
<p>I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a ...
1
2016-10-06T17:39:52Z
39,902,537
<p>The simplest way to stop a loop when some condition becomes true is to use <code>break</code>. So when the player guesses correctly, the code would look like</p> <pre><code>if inp == x: guess = True print "Correct! You won" break </code></pre> <p>Additionally, you should break the loop when you run out...
3
2016-10-06T17:47:36Z
[ "python", "python-2.7" ]
Bug with a program for a guessing game
39,902,412
<p>I am creating a program where a user had to guess a random number in a specific range and has 3 tries to do so. After each try, if the guess is correct you tell the user they won and if the guess is wrong you tell them its wrong and how many tries they have got remaining. When the number of tries exceed 3 without a ...
1
2016-10-06T17:39:52Z
39,903,070
<p>this is a slightly different version to your problem:</p> <pre><code>import random def play(): x = round(random.random()*5) guess = False tries = 0 while guess is False and tries &lt; 3: inp = raw_input("Guess the number: ") if int(inp) == x: guess = True pri...
2
2016-10-06T18:20:06Z
[ "python", "python-2.7" ]
Maya Python - Set object pivot to selection center
39,902,493
<p>I'm trying to move the selected object pivot to the center of the objects selected vertices.</p> <p>When I run the code I don't recieve any errors and almost everything works as intended, However the pivot of (obj)my selected object doesn't seem to set itself to the locator xform(piv).</p> <pre><code>import maya.c...
1
2016-10-06T17:44:48Z
39,911,586
<p>I think the main issue was that when you were using <code>obj = cmds.ls(*sel, o=True)</code>, it was only capturing the object's shape node instead of its transform. You can use <code>cmds.listRelatives</code> to get the shape's transform. You also don't need to create the locator as the cluster already gives you th...
2
2016-10-07T07:18:33Z
[ "python", "python-2.7", "maya" ]
Pandas - df.loc assigning NaN when used to replace columns based on a different df
39,902,514
<p>I'm trying to assign values of some columns based on another column mapping them by one single key. The problem is that I don't think the mapping is being used correctly, because it is assigning NaN to the columns.</p> <p>I should be mapping them by 'SampleID'.</p> <p>Here is the DF I want to assign values to</p> ...
0
2016-10-06T17:45:59Z
39,903,100
<p>index does not match,</p> <p>you can use </p> <pre><code>df.ix[df['SampleID'].isin(pooled['SampleID']), cols] = numerical[cols].values </code></pre> <p>only if the size are exactly the same!</p>
1
2016-10-06T18:21:57Z
[ "python", "pandas" ]
Pandas groupby object in legend on plot
39,902,522
<p>I am trying to plot a pandas <code>groupby</code> object using the code <code>fil.groupby('imei').plot(x=['time'],y = ['battery'],ax=ax, title = str(i))</code> </p> <p>The problem is the plot legend lists <code>['battery']</code>as the legend value. Given it's drawing a line for each item in the <code>groupby</code...
1
2016-10-06T17:46:35Z
39,906,127
<p>Slightly tidied data:</p> <pre><code> date time imei battery_raw 0 2016-09-30 07:01:23 862117020146766 42208 1 2016-09-30 07:06:23 862117020146766 42213 2 2016-09-30 07:11:23 862117020146766 42151 3 2016-09-30 07:16:23 862117995146745 42263 4 2016-09-30 07:21...
2
2016-10-06T21:48:27Z
[ "python", "pandas", "matplotlib", "plot" ]
loop in python code to avoid repetition and reduce the code
39,902,529
<p>i would like create a loop and continue the script as long as data is not none. I'm bad with loops. </p> <pre><code>import requests import re import urllib import json url = 'http://bla/bla.html' headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i686; rv:42.0) Gecko/20100101 Firefox/42.0 Iceweasel/42.0', 'Refer...
0
2016-10-06T17:47:00Z
39,907,502
<p>ok i have the solution with an user in a forum, Now it's more clear</p> <pre><code>url = 'http://bla/bla.html' headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i686; rv:42.0) Gecko/20100101 Firefox/42.0 Iceweasel/42.0', 'Referer': ''} r = requests.get(url, headers=headers).text data_a = urllib.unquote_plus(re.find...
0
2016-10-07T00:15:10Z
[ "python", "loops" ]
how to insert a widget to another, if they are from different classes. and how to create a universal function of closing the child widgets?
39,902,546
<p>this is my code. I can't put label2 to self.main, and I don't know, how to write a generic function code, that would close the child widgets, that can be specified in the arguments.</p> <pre><code>import tkinter class mainwin: def __init__(self): self.root = tkinter.Tk() self.main = tkinter.Ca...
-1
2016-10-06T17:48:22Z
39,902,949
<p>You might be able to use: </p> <pre><code>mylist = parent.winfo_children(); </code></pre> <p>Then use a for loop and destroy() to close them off</p> <p>The main reason you can't put the label in is because you are calling mainloop() before addLabel. The program loops through the code and doesn't execute addlabel(...
0
2016-10-06T18:13:15Z
[ "python", "class", "tkinter", "widget" ]
how to insert a widget to another, if they are from different classes. and how to create a universal function of closing the child widgets?
39,902,546
<p>this is my code. I can't put label2 to self.main, and I don't know, how to write a generic function code, that would close the child widgets, that can be specified in the arguments.</p> <pre><code>import tkinter class mainwin: def __init__(self): self.root = tkinter.Tk() self.main = tkinter.Ca...
-1
2016-10-06T17:48:22Z
39,903,723
<pre><code>import tkinter class mainwin: def __init__(self): self.root = tkinter.Tk() self.main = tkinter.Canvas(self.root, width=200, height=400) self.main.place(x=0, y=0, relwidth=1, relheight=1) self.main.config(bg='green') self.root.mainloop() class CustomLabel(tkinter...
-1
2016-10-06T18:59:21Z
[ "python", "class", "tkinter", "widget" ]
How to add wxpython frame style to disable frame resizing
39,902,556
<p>I build a sample program using <code>wxpython</code> and i need to disable frame resizing.</p> <p>I know i should use <strong>wx.Frame style</strong> but i don't know where i can add this in my code.</p> <p><code>style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER</code></p> <p>Code:</p> <pre><code>class Example(wx....
0
2016-10-06T17:48:56Z
39,902,964
<p>I solve my problem by deleting <code>**kwargs</code> from <code>init</code>.</p> <pre><code>class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, style=wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLOSE_BOX | wx.CLIP_CHILDREN) self.AppUI() ...
0
2016-10-06T18:13:59Z
[ "python", "python-2.7", "python-3.x", "wxpython" ]
GridSearch with SVM producing IndexError
39,902,562
<p>I'm building a classifier using an SVM and want to perform a Grid Search to help automate finding the optimal model. Here's the code:</p> <pre><code>from sklearn.svm import SVC from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV from sklearn.multiclass import OneVsR...
1
2016-10-06T17:49:28Z
39,902,864
<p>It seems that there is no error in your implementation.</p> <p>However, as it's mentioned in the <code>sklearn</code>documentation, the "fit time complexity is more than quadratic with the number of samples which makes it hard to scale to dataset with more than a couple of <code>10000</code> samples". <a href="http...
3
2016-10-06T18:07:38Z
[ "python", "pandas", "machine-learning", "scikit-learn", "svm" ]
Right way to set variables at python class
39,902,629
<p>Which is the right way to work with variables inside a class?</p> <p>1- setting them as class attributes where we get them and access them from class itself:</p> <pre><code>class NeuralNetwork(object): def __init__(self, topology): self.topology = topology self.buildLayers() def buildLayers(self): ...
0
2016-10-06T17:53:00Z
39,902,712
<p>In general the first way is the "really object oriented" way, and much preferred over the second and the third.</p> <p>If you want your buildLayers function to be able to change the topology occasionally, give it a param. topology with default value = None.</p> <p>As long as you don't pass that param. at calling b...
2
2016-10-06T17:57:33Z
[ "python", "class", "variables", "standards" ]
Right way to set variables at python class
39,902,629
<p>Which is the right way to work with variables inside a class?</p> <p>1- setting them as class attributes where we get them and access them from class itself:</p> <pre><code>class NeuralNetwork(object): def __init__(self, topology): self.topology = topology self.buildLayers() def buildLayers(self): ...
0
2016-10-06T17:53:00Z
39,902,732
<p>1st one is correct and recommended. As that will be object dependent.</p>
0
2016-10-06T17:58:59Z
[ "python", "class", "variables", "standards" ]
Printing a list of files from a directory
39,902,695
<p>I was wondering how to print a list of files from a directory. I know this should be very easy to do, but I'm blanking out on how to do it. My second method search characteristics(directory) is a method that should return the list of files found in that directory given a key press. The 3rd method take_action(directo...
0
2016-10-06T17:56:46Z
39,902,803
<p>Try <code>os.walk()</code></p> <pre><code>list(os.walk("."))[0] </code></pre> <p>will give you all the sub directories in the current folder.</p> <p>EDIT</p> <p>Maybe this is more suited to your needs </p> <pre><code>filter(lambda x : os.path.isdir(x) , os.listdir(".")) </code></pre>
0
2016-10-06T18:03:29Z
[ "python" ]
Printing a list of files from a directory
39,902,695
<p>I was wondering how to print a list of files from a directory. I know this should be very easy to do, but I'm blanking out on how to do it. My second method search characteristics(directory) is a method that should return the list of files found in that directory given a key press. The 3rd method take_action(directo...
0
2016-10-06T17:56:46Z
39,904,265
<p>First, let me presume to offer a bit of very general advice. Get yourself some software that enables you to try out small snippets of code, if you don't have that already. On Windows the best I know of is PythonWin; you're looking for a REPL program. I mention this because I notice you were very close to an answer w...
0
2016-10-06T19:33:40Z
[ "python" ]
How to produce the following three dimensional array?
39,902,759
<p>I have a cube of size <code>N * N * N</code>, say <code>N=8</code>. Each dimension of the cube is discretised to 1, so that I have labelled points <code>(0,0,0), (0,0,1)..(N,N,N)</code>. At each labelled points, I would like to assign a random value, and thus produce an array which stores value at each vertex. For e...
-1
2016-10-06T18:00:58Z
39,903,131
<p>You could simply generate lists of lists. While not in any way efficient, it would allow you to access your cube like <code>val[0][0][0]</code>.</p> <pre><code>arr = [[[] for _ in range(8)] for _ in range(8)] arr[0][0].append(1) </code></pre>
1
2016-10-06T18:23:37Z
[ "python", "arrays", "python-2.7" ]
How to produce the following three dimensional array?
39,902,759
<p>I have a cube of size <code>N * N * N</code>, say <code>N=8</code>. Each dimension of the cube is discretised to 1, so that I have labelled points <code>(0,0,0), (0,0,1)..(N,N,N)</code>. At each labelled points, I would like to assign a random value, and thus produce an array which stores value at each vertex. For e...
-1
2016-10-06T18:00:58Z
39,903,155
<p>For large matrices, look into using <code>numpy</code>. This is the problem that it's designed to solve</p>
0
2016-10-06T18:25:15Z
[ "python", "arrays", "python-2.7" ]
How to produce the following three dimensional array?
39,902,759
<p>I have a cube of size <code>N * N * N</code>, say <code>N=8</code>. Each dimension of the cube is discretised to 1, so that I have labelled points <code>(0,0,0), (0,0,1)..(N,N,N)</code>. At each labelled points, I would like to assign a random value, and thus produce an array which stores value at each vertex. For e...
-1
2016-10-06T18:00:58Z
39,903,161
<p>Did you mean this:</p> <pre><code>import numpy as np n = 5 val = np.empty((n, n, n)) # Create an 3d array full of 0's val[0,0,0] = 11 val[0,0,1] = 33 print(val[0, 0]) array([ 11., 33., 0., 0., 0.]) </code></pre>
1
2016-10-06T18:25:37Z
[ "python", "arrays", "python-2.7" ]
Python to CSV is splitting string into two columns when I want one
39,902,832
<p>I am scraping a page with BeautifulSoup, and part of the logic is that sometimes part of the contents of a <code>&lt;td&gt;</code> tag can have a <code>&lt;br&gt;</code> in it. </p> <p>So sometimes it looks like this:</p> <pre class="lang-html prettyprint-override"><code>&lt;td class="xyz"&gt; text 1 &lt;...
4
2016-10-06T18:05:02Z
39,903,427
<p>You can handle both cases using <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow"><code>get_text()</code></a> with "strip" and "separator":</p> <pre><code>from bs4 import BeautifulSoup dat=""" &lt;table&gt; &lt;tr&gt; &lt;td class="xyz"&gt; text 1 ...
2
2016-10-06T18:39:56Z
[ "python", "csv", "beautifulsoup" ]
I'm starting out using tkinter
39,902,922
<p>I am just starting out to use tkinter in Python 3.5 and I don't understand it the best yet but hopefully will over time.<br> Anyway, what I was asking was how do I create a text box that a user can type into, I know it is possible but don't yet know how to execute this as, as I said at the beginning, I'm just starti...
-6
2016-10-06T18:11:12Z
39,958,831
<p>Both of the following links contain code relating to text entry.</p> <p><a href="http://effbot.org/tkinterbook/entry.htm" rel="nofollow">http://effbot.org/tkinterbook/entry.htm</a></p> <p><a href="http://effbot.org/tkinterbook/text.htm" rel="nofollow">http://effbot.org/tkinterbook/text.htm</a></p> <p>Entry is a s...
0
2016-10-10T12:56:29Z
[ "python", "tkinter" ]
Python - Cannot join thread - No multiprocessing
39,903,009
<p>I have this piece of code in my program. Where OnDone function is an event in a wxPython GUI. When I click the button DONE, the OnDone event fires up, which then does some functionality and starts the thread self.tstart - with target function StartEnable. This thread I want to join back using self.tStart.join(). How...
0
2016-10-06T18:16:32Z
39,904,295
<p>When the <code>StartEnable</code> method is executing, it is running on the <em>StartEnablingThread</em> you created in the <code>__init__</code> method. You cannot join the current thread. This is clearly stated in the documentation for the <a href="https://docs.python.org/2/library/threading.html#threading.Thread....
1
2016-10-06T19:35:27Z
[ "python", "multithreading", "wxpython" ]
Python - Cannot join thread - No multiprocessing
39,903,009
<p>I have this piece of code in my program. Where OnDone function is an event in a wxPython GUI. When I click the button DONE, the OnDone event fires up, which then does some functionality and starts the thread self.tstart - with target function StartEnable. This thread I want to join back using self.tStart.join(). How...
0
2016-10-06T18:16:32Z
39,904,373
<p>I have some bad news. Threading in Python is pointless and you best bet to look at using only 1 thread or use multi process. If you will need to look at thread then you will need to look at a different language like C# or C. Have look at <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow...
-1
2016-10-06T19:40:06Z
[ "python", "multithreading", "wxpython" ]
Python - Cannot join thread - No multiprocessing
39,903,009
<p>I have this piece of code in my program. Where OnDone function is an event in a wxPython GUI. When I click the button DONE, the OnDone event fires up, which then does some functionality and starts the thread self.tstart - with target function StartEnable. This thread I want to join back using self.tStart.join(). How...
0
2016-10-06T18:16:32Z
39,904,589
<h2>Joining Is Waiting</h2> <p><em>Joining</em> a thread actually means waiting fo another thread to finish.</p> <p>So, in <code>thread1</code>, there can be code which says:</p> <pre><code>thread2.join() </code></pre> <p>That means <em>"stop here and do not execute the next line of code until <code>thread2</code> ...
1
2016-10-06T19:54:11Z
[ "python", "multithreading", "wxpython" ]
SoftLayer_Virtual_Guest_Block_Device_Template_Group.addLocations returns true but no locations added
39,903,063
<p>Trying to copy a private image to another datacenter using Python. Code below returns true but transaction is not initiated and image is not copied.</p> <pre><code>info=client['SoftLayer_Virtual_Guest_Block_Device_Template_Group'].addLocations({'id':449494},id=123456) </code></pre> <p>id is confirmed valid - usin...
0
2016-10-06T18:19:26Z
39,903,561
<p>You should send between <strong>[ ]</strong> the template for locations, please thy the following</p> <pre><code>info=client['SoftLayer_Virtual_Guest_Block_Device_Template_Group'].addLocations([{'id':449494}],id=123456) </code></pre> <p>References:</p> <ul> <li><a href="http://sldn.softlayer.com/reference/service...
0
2016-10-06T18:48:29Z
[ "python", "softlayer" ]
How to switch context in Dragonfly
39,903,075
<p>I have tried the Python module for handling speech recognition Dragonfly and successfully run notepad example with Windows speech recognition. Now I would like to try something more general, but I cannot find how contexts are switched, i.e. grammars loaded. There are always lines like:</p> <pre><code>grammar = Gram...
1
2016-10-06T18:20:20Z
39,927,097
<p>Create a rule which calls a function which does this:</p> <pre><code>grammar.disable() other_grammar.enable() </code></pre> <p>Have a look at <code>grammar_base.py</code> for other relevant functions.</p>
0
2016-10-07T23:30:08Z
[ "python", "python-dragonfly" ]
efficiently replace values from a column to another column Pandas DataFrame
39,903,090
<p>I have a Pandas DataFrame like the following one: </p> <pre><code> col1 col2 col3 1 0.2 0.3 0.3 2 0.2 0.3 0.3 3 0 0.4 0.4 4 0 0 0.3 5 0 0 0 6 0.1 0.4 0.4 </code></pre> <p>I want to replace the <code>col1</code> values with the values in the second column (<code>col2</code>) on...
2
2016-10-06T18:21:33Z
39,903,800
<p>I'm not sure if it's faster, but you're right that you can slice the dataframe to get your desired result.</p> <pre><code>df.col1[df.col1 == 0] = df.col2 df.col1[df.col1 == 0] = df.col3 print(df) </code></pre> <p>Output:</p> <pre><code> col1 col2 col3 0 0.2 0.3 0.3 1 0.2 0.3 0.3 2 0.4 0.4 0....
2
2016-10-06T19:03:41Z
[ "python", "pandas", "replace", "dataframe" ]
efficiently replace values from a column to another column Pandas DataFrame
39,903,090
<p>I have a Pandas DataFrame like the following one: </p> <pre><code> col1 col2 col3 1 0.2 0.3 0.3 2 0.2 0.3 0.3 3 0 0.4 0.4 4 0 0 0.3 5 0 0 0 6 0.1 0.4 0.4 </code></pre> <p>I want to replace the <code>col1</code> values with the values in the second column (<code>col2</code>) on...
2
2016-10-06T18:21:33Z
39,903,944
<p>Using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="nofollow"><code>np.where</code></a> is faster. Using a similar pattern as you used with <code>replace</code>:</p> <pre><code>df['col1'] = np.where(df['col1'] == 0, df['col2'], df['col1']) df['col1'] = np.where(df['col1'] == 0...
4
2016-10-06T19:11:46Z
[ "python", "pandas", "replace", "dataframe" ]
efficiently replace values from a column to another column Pandas DataFrame
39,903,090
<p>I have a Pandas DataFrame like the following one: </p> <pre><code> col1 col2 col3 1 0.2 0.3 0.3 2 0.2 0.3 0.3 3 0 0.4 0.4 4 0 0 0.3 5 0 0 0 6 0.1 0.4 0.4 </code></pre> <p>I want to replace the <code>col1</code> values with the values in the second column (<code>col2</code>) on...
2
2016-10-06T18:21:33Z
39,904,139
<p>approach using <code>pd.DataFrame.where</code> and <code>pd.DataFrame.bfill</code></p> <pre><code>df['col1'] = df.where(df.ne(0), np.nan).bfill(axis=1).col1.fillna(0) df </code></pre> <p><a href="http://i.stack.imgur.com/SeDin.png" rel="nofollow"><img src="http://i.stack.imgur.com/SeDin.png" alt="enter image descr...
2
2016-10-06T19:25:37Z
[ "python", "pandas", "replace", "dataframe" ]
How to assert/verify successful login using Python / Selenium Webdriver
39,903,144
<p>I have done a little research and could not find any answer specific to Selenium WebDriver with Python. I can successfully sign into the page but I cannot find way(s) to verify that the login was successful. Page title does not work for me since it does not change. Python Selenium documentation does not have any g...
0
2016-10-06T18:24:39Z
39,905,433
<p>I am working with the Javascript API instead of the Python version, so the syntax is different, but here is how I would get about it (using mocha as a test framework):</p> <pre><code>facebookLoginButtonElement.click().then(function(_) { driver.findElement(By.xpath('//a[text() = "Tuto"]')).then(function(userLink...
0
2016-10-06T20:53:17Z
[ "python", "selenium", "selenium-webdriver" ]
Checking if a letter is in a character array python
39,903,179
<p>How would I write a small program that takes an array of characters and a search character and prints true if the search character is in the array, and false if it is not?</p>
-2
2016-10-06T18:26:36Z
39,903,227
<p>In Python this kind of thing is very easy.</p> <p><code>search_character in arr</code></p> <p>Evaluates to False when an item is not in an array and True otherwise.</p>
2
2016-10-06T18:28:56Z
[ "python", "arrays", "character" ]
Creating multilabel HDF5 file for caffe
39,903,197
<p>I created HDF5 data using the following python script and placed HDF5 data layer. However, when I tried to train caffe using this data it keeps complaining </p> <blockquote> <pre><code>Check failed: num_spatial_axes_ == 2 (0 vs. 2) kernel_h &amp; kernel_w can only be used for 2D convolution </code></pre> </blockquo...
1
2016-10-06T18:27:32Z
39,940,555
<h3>The problem:</h3> <p>Caffe, by default, expects its data to be 4D: batch_size -by- channel -by- height -by- width.<br> In your <a href="http://stackoverflow.com/q/39888054/1714410">model</a> you assume each sample is of shape 1-by-1-by-3253, that is: your data is 1D with only non-singleton width dimension. This is...
1
2016-10-09T06:06:02Z
[ "python", "machine-learning", "deep-learning", "caffe", "hdf5" ]
How to display data in tabular format on a txt file
39,903,199
<p>I have been stuck on this python problem for hours. I'm trying to figure out how to write the data that can be manually entered above into a txt file in a way that it shows up in a two row eight column table. The contents in name_array are supposed to be headers and the contents in data_array are the actual data pi...
0
2016-10-06T18:27:33Z
39,903,249
<p>Have you tried something like:</p> <pre><code>output_file = 'out.txt' with open(output_file, 'r+') as file: file.write('\t'.join(name_array) + '\n') file.write('\t'.join(data_array) + '\n') </code></pre>
-1
2016-10-06T18:30:12Z
[ "python", "file", "tabular" ]
How to display data in tabular format on a txt file
39,903,199
<p>I have been stuck on this python problem for hours. I'm trying to figure out how to write the data that can be manually entered above into a txt file in a way that it shows up in a two row eight column table. The contents in name_array are supposed to be headers and the contents in data_array are the actual data pi...
0
2016-10-06T18:27:33Z
39,903,667
<p>If you want to simply output a csv-like file you can use the <code>csv</code> package:</p> <pre><code>import csv writer = csv.writer(f, delimiter='\t') writer.writerow(name_array) writer.writerow(data_array) </code></pre> <p>It will output:</p> <pre><code>Student Final Grade Final Exam Exam 1 Exam 2 Assignmen...
1
2016-10-06T18:55:40Z
[ "python", "file", "tabular" ]
Python: Create file from list of dictionaries
39,903,222
<p>I have about 5000 .gz files from which I have to extract the data which is in form of "list of dictionaries". </p> <p>Sample Source Data :</p> <pre><code>{"user" : "J101", "ip" : "192.0.0.0", "usage" : "1000", "Location" : "CA", "time" : "12038098048"} {"user" : "M101", "ip" : "192.0.0.1", "usage" : "5000", "ti...
0
2016-10-06T18:28:37Z
39,903,526
<p>At some point in your code you have row set to a string, say,</p> <pre><code>'{"user" : "J101", "ip" : "192.0.0.0", "usage" : "1000", "Location" : "CA", "time" : "12038098048"}' </code></pre> <p>Then to get what you want calculate,</p> <pre><code>[eval(row)[_] for _ in ['user', 'ip', 'time', 'usage']] </code></pr...
0
2016-10-06T18:46:26Z
[ "python", "json", "csv", "dictionary" ]
Python: Create file from list of dictionaries
39,903,222
<p>I have about 5000 .gz files from which I have to extract the data which is in form of "list of dictionaries". </p> <p>Sample Source Data :</p> <pre><code>{"user" : "J101", "ip" : "192.0.0.0", "usage" : "1000", "Location" : "CA", "time" : "12038098048"} {"user" : "M101", "ip" : "192.0.0.1", "usage" : "5000", "ti...
0
2016-10-06T18:28:37Z
39,905,159
<p>I think the problem might be in your CSV file writer method. You seem to be writing the header of the file and a row with the data <strong>for every key of every row</strong>.</p> <p>You can try something like this:</p> <pre><code>def create_csv(dict_list): with open('dict.csv', 'w') as csv_file: # Cre...
0
2016-10-06T20:33:07Z
[ "python", "json", "csv", "dictionary" ]
Python: Create file from list of dictionaries
39,903,222
<p>I have about 5000 .gz files from which I have to extract the data which is in form of "list of dictionaries". </p> <p>Sample Source Data :</p> <pre><code>{"user" : "J101", "ip" : "192.0.0.0", "usage" : "1000", "Location" : "CA", "time" : "12038098048"} {"user" : "M101", "ip" : "192.0.0.1", "usage" : "5000", "ti...
0
2016-10-06T18:28:37Z
39,905,489
<p>Modify...</p> <p>Two list, one dictionary generation(<strong>cveFieldName</strong>, <strong>eventFieldName</strong>, <strong>inputdict</strong>) </p> <pre><code>inputdict = {} e_list = ('userid', 'user'), ('ipaddr', 'ip'),\ ('event_time', 'time'), ('usage_in_mb', 'usage'),\ ('test_1', 'test1'), (...
0
2016-10-06T20:56:12Z
[ "python", "json", "csv", "dictionary" ]
Is there a more Pythonic way to combine an Else: statement and an Except:?
39,903,242
<p>I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. <code>"overall_weight"</code> in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cas...
32
2016-10-06T18:29:51Z
39,903,338
<p>Use <code>.get()</code> with a default argument of <code>"N/A"</code> which will be used if the key does not exist:</p> <pre><code>nObject.TextString = self.var.jobDetails.get("Overall Weight", "N/A") </code></pre> <h1>Update</h1> <p>If empty strings need to be handled, simply modify as follows:</p> <pre><code>n...
9
2016-10-06T18:34:43Z
[ "python", "python-2.7" ]
Is there a more Pythonic way to combine an Else: statement and an Except:?
39,903,242
<p>I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. <code>"overall_weight"</code> in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cas...
32
2016-10-06T18:29:51Z
39,903,350
<p>Use <code>get()</code> function for dictionaries. It will return <code>None</code> if the key doesn't exist or if you specify a second value, it will set that as the default. Then your syntax will look like:</p> <pre><code>nObject.TextString = self.var.jobDetails.get('Overall Weight', 'N/A') </code></pre>
16
2016-10-06T18:35:11Z
[ "python", "python-2.7" ]
Is there a more Pythonic way to combine an Else: statement and an Except:?
39,903,242
<p>I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. <code>"overall_weight"</code> in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cas...
32
2016-10-06T18:29:51Z
39,903,442
<p>I think this is a good case for setting the default value in advance</p> <pre><code>if nObject.TextString == "overall_weight": nObject.TextString = "N/A" try: if self.var.jobDetails["Overall Weight"]: nObject.TextString = self.var.jobDetails["Overall Weight"] except KeyError: ...
3
2016-10-06T18:40:43Z
[ "python", "python-2.7" ]
Is there a more Pythonic way to combine an Else: statement and an Except:?
39,903,242
<p>I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. <code>"overall_weight"</code> in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cas...
32
2016-10-06T18:29:51Z
39,903,519
<p>Use <code>dict.get()</code> which will return the value associated with the given key if it exists otherwise <code>None</code>. (Note that <code>''</code> and <code>None</code> are both falsey values.) If <code>s</code> is true then assign it to <code>nObject.TextString</code> otherwise give it a value of <code>"N/A...
63
2016-10-06T18:45:36Z
[ "python", "python-2.7" ]
Is there a more Pythonic way to combine an Else: statement and an Except:?
39,903,242
<p>I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. <code>"overall_weight"</code> in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cas...
32
2016-10-06T18:29:51Z
39,904,193
<p>How about <a href="http://effbot.org/zone/python-with-statement.htm" rel="nofollow"><code>with</code></a>:</p> <pre><code>key = 'Overall Weight' with n_object.text_string = self.var.job_details[key]: if self.var.job_details[key] is None \ or if self.var.job_details[key] is '' \ or if KeyError: ...
-2
2016-10-06T19:29:13Z
[ "python", "python-2.7" ]
Is there a more Pythonic way to combine an Else: statement and an Except:?
39,903,242
<p>I have a piece of code that searches AutoCAD for text boxes that contain certain keywords (eg. <code>"overall_weight"</code> in this case) and replaces it with a value from a dictionary. However, sometimes the dictionary key is assigned to an empty string and sometimes, the key doesn't exist altogether. In these cas...
32
2016-10-06T18:29:51Z
39,907,658
<p>The Zen of Python says "Explicit is better than implicit." I have found this to be very true in my own experience. When I write a piece of code I think to my self, "Will I understand what this means a year from now?" If the answer is "no" then it needs to be re-written or documented. The accepted answer relies on re...
2
2016-10-07T00:35:17Z
[ "python", "python-2.7" ]
Breaking down rows in Pyspark DataFrame
39,903,246
<p>I have a PySpark DataFrame in this format:</p> <pre><code> dbn | bus | subway | score ----------|----------------|----------|-------- XYZ12 | B1, B44, B66 | A, C | 59 ZYY3 | B8, B3, B7 | J, Z | 66 </code></pre> <p>What I want to do is be able to attach the score column to e...
0
2016-10-06T18:30:07Z
39,904,913
<p>You can <code>explode</code> function which expects an <code>array</code> or a <code>map</code> column as an input. If <code>bus</code> is a string you can use string processing functions, like <code>split</code>, to break it into pieces first. Let's assume this scenario:</p> <pre><code>df = sc.parallelize([ ("...
0
2016-10-06T20:16:21Z
[ "python", "dataframe", "pyspark", "pyspark-sql" ]
how framing byte packet to time length from android to python server?
39,903,258
<p>I'm trying to develop an application which send to pcm data to python server.</p> <p>I used AudioRecord library to get real-time audio signal.</p> <p>And this is the source code.</p> <pre><code>/*------ setting audio recording ------*/ private static final int SAMPLE_RATE = 44100; private static final int RECORD...
0
2016-10-06T18:30:50Z
39,903,599
<p>You have a problem with your while loop in your python code</p> <pre><code>i = True while(i): print "Listening...\n" packet, client = server.recvfrom(buffer_size) #Convert packet to numpy array signal = np.fromstring(packet, dtype=np.int16) i=False server.close() </code></pre> <p>This wil...
0
2016-10-06T18:51:10Z
[ "android", "python", "sockets", "fft" ]
Scikit-learn fails to import only in Jupyter notebook
39,903,337
<p>I have Anaconda installed on OS X. I am able to import sklearn from a python terminal and an IPython terminal. But when I try to import sklearn from a Jupyter notebook, I get the following error:</p> <pre><code>--------------------------------------------------------------------------- ImportError ...
0
2016-10-06T18:34:42Z
39,906,922
<p>I managed to figure out what was going on, so I'll post my solution here in case anyone else runs into the same problem. As it turns out, I had modified the <code>DYLD_FALLBACK_LIBRARY_PATH</code> environment variable in my <code>.bashrc</code> file when I had installed another piece of software. Restoring this en...
2
2016-10-06T23:03:09Z
[ "python", "scikit-learn", "importerror", "jupyter-notebook" ]
PyCharm can't find module beatifulsoup4
39,903,388
<p>I installed beautifulsoup4 through the Project Interperter in PyCharm, and when I try to import it, it says that the module doesn't exist and I've checked the spelling a billion times I don't get it</p>
-2
2016-10-06T18:38:09Z
39,903,449
<blockquote> <p>can't find module <code>beatifulsoup4</code></p> </blockquote> <p>You should be importing <code>bs4</code>, not <code>beautifulsoup4</code>:</p> <pre><code>from bs4 import BeautifulSoup </code></pre>
3
2016-10-06T18:41:00Z
[ "python", "module", "beautifulsoup", "pycharm" ]
Raspberry Pi python website with plotly graph updates
39,903,438
<p>I am currently working on a project from home where I have a network of Arduino's sending data (temp humidity etc.) to a raspberry pi. I want to make the rasp take the data and using plotly make a variety of graphs and then embed said graphs into a website that automatically updates at a set interval. I already ha...
0
2016-10-06T18:40:30Z
39,915,124
<p>Some time ago I had a very similar problem. A very simple solution was to use Python3's <code>http.server</code> to return a <code>JSON</code> with a time stamp and the temperature.</p> <pre><code># !/usr/bin/env python3 from http.server import HTTPServer, BaseHTTPRequestHandler import random import json import tim...
0
2016-10-07T10:29:00Z
[ "python", "html", "website", "plotly", "raspberry-pi3" ]
antlr4 grammar non greedy
39,903,531
<p>I'm trying to write a grammar the allows me to write any expression in a if statement. </p> <p>My if statement will be something like below: if [ x == 1 ] [Do some stuff]</p> <p>The expression is supposed to be any Python expression. </p> <p>If I use the non-greedy match like below, how can I specify '[' or ']' a...
0
2016-10-06T18:46:43Z
39,908,724
<p>Generalized, use a typical statement formulation:</p> <pre><code>stmt : ifval | .... ; ifval : IF expr body ; expr : LBRACK expr? RBRACK | NOT expr | WORD ( LBRACK WORD? RBRACK )? // value or array[idx] | .... ; body : WORD | LBRACE stmt* RBRACE | ....
1
2016-10-07T03:04:12Z
[ "python", "antlr4" ]
How to get actual line number of where python exception occurred?
39,903,798
<p>I have the following python decorator in my file <code>decorators.py</code></p> <pre><code>def catch_exceptions(function): #Line #1 @wraps(function) #Line #2 def decorator(*args, **kwargs): ...
1
2016-10-06T19:03:37Z
39,903,979
<p>You may want to look into the <code>traceback</code> module</p> <pre><code>import traceback try: function_that_raises_exception() except Exception: traceback.print_exc() </code></pre> <p>It will print the entire stack trace.</p>
3
2016-10-06T19:15:04Z
[ "python", "django", "exception-handling" ]
How to get actual line number of where python exception occurred?
39,903,798
<p>I have the following python decorator in my file <code>decorators.py</code></p> <pre><code>def catch_exceptions(function): #Line #1 @wraps(function) #Line #2 def decorator(*args, **kwargs): ...
1
2016-10-06T19:03:37Z
39,904,221
<p>If you want to do it as you described then</p> <pre><code>from functools import wraps import sys, os, traceback def catch_exceptions(function): @wraps(function) def decorator(*args, **kwargs): ...
2
2016-10-06T19:30:54Z
[ "python", "django", "exception-handling" ]
docker-py getarchive destination folder
39,903,822
<p>I am following the instructions given in this link for get_archive()<a href="https://docker-py.readthedocs.io/en/stable/api/#get_archive" rel="nofollow">link</a> but instead of creating my container i was trying to use already running container in my case "docker-nginx" as an input string and also the destination f...
0
2016-10-06T19:04:55Z
39,937,617
<p>I found out how this function works what it does it returns raw response of a requests made to our container. raw response explaination can be found <a href="http://docs.python-requests.org/en/master/user/quickstart/#raw-response-content" rel="nofollow">in this link</a> in order to extract raw content we can use th...
0
2016-10-08T21:33:59Z
[ "python", "docker", "raw-data", "dockerpy" ]
Print file contents using cat in subprocess
39,903,838
<p>I am using a subprocess call in python where I have to print a file contents using <code>cat</code>. The file name is a variable that I generate in the python code itself. This is my code:</p> <pre><code>pid = str(os.getpid()) tmp_file_path = "/tmp/" + pid + "/data_to_synnet" synnet_output = subprocess.check_output...
0
2016-10-06T19:05:55Z
39,903,866
<p>The command you want is this:</p> <pre><code>"cat '%s'"%tmp_file_path </code></pre> <p>Just get rid of the "echo" word.</p> <p>Alternatively,</p> <pre><code> synnet_output = subprocess.check_output(["cat", tmp_file_path], shell=False) </code></pre>
2
2016-10-06T19:07:36Z
[ "python", "shell", "subprocess" ]
Read in csv file faster
39,903,867
<p>I am currently reading in a large csv file (around 100 million lines), using command along the lines of that described in <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a> e.g. :</p> <pre><code>import csv with open('eggs.csv', 'rb') as csvfile: s...
0
2016-10-06T19:07:37Z
39,903,946
<pre><code>import pandas as pd df =pd.DataFrame.from_csv('filename.csv') </code></pre> <p>This will read it in as a pandas dataframe so you can do all sorts of fun things with it</p>
3
2016-10-06T19:11:49Z
[ "python", "csv" ]
Read in csv file faster
39,903,867
<p>I am currently reading in a large csv file (around 100 million lines), using command along the lines of that described in <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a> e.g. :</p> <pre><code>import csv with open('eggs.csv', 'rb') as csvfile: s...
0
2016-10-06T19:07:37Z
39,903,947
<blockquote> <p>my machine has sufficient ram to hold that in memory.</p> </blockquote> <p>Well then, call <code>list</code> on the <em>iterator</em>:</p> <pre><code>spamreader = list(csv.reader(csvfile, delimiter=' ', quotechar='|')) </code></pre>
1
2016-10-06T19:11:51Z
[ "python", "csv" ]
Read in csv file faster
39,903,867
<p>I am currently reading in a large csv file (around 100 million lines), using command along the lines of that described in <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a> e.g. :</p> <pre><code>import csv with open('eggs.csv', 'rb') as csvfile: s...
0
2016-10-06T19:07:37Z
39,903,955
<p>Yes, there is a way to read the entire file at once:</p> <pre><code>with open('eggs.csv', 'rb', 5000000000) as ...: ... </code></pre> <p>Reference: <a href="https://docs.python.org/2/library/functions.html#open" rel="nofollow">https://docs.python.org/2/library/functions.html#open</a></p>
1
2016-10-06T19:12:17Z
[ "python", "csv" ]
Streaming video using pyzmq
39,903,926
<p>I am using the Python bindings for zmq to send messages both between processes and across a network. So far, no problem. I now have an application where I want to stream data recovered from a small camera on a Raspberry Pi. I have no issues actually recording the data but now I want to be able to stream that data...
0
2016-10-06T19:10:28Z
39,948,569
<h2>RPi side: <code>picamera.PiCamera()</code> API rulez:</h2> <p>Besides the file-based output, RPi has another alternative for the <strong><code>output</code></strong> attribute, worth a try.</p> <blockquote> <p><a href="https://picamera.readthedocs.io/en/release-1.12/api_camera.html" rel="nofollow">If output is ...
0
2016-10-09T21:10:24Z
[ "python", "sockets", "raspberry-pi", "zeromq", "pyzmq" ]
Django: TypeError: int() argument must be a string, a bytes-like object or a number, not
39,903,959
<p>Please help! I tried searching for an answer, but I think this issue is too specific to have a generalized enough solution. </p> <p>It's very difficult for me to pin point when, exactly, it is that this error started. I've Attempted too many changes now to know when the site was last working. I'm very new to this. ...
-1
2016-10-06T19:12:54Z
39,923,313
<p>Problem solved, thanks to @MosesKoledoye. </p> <p>I deleted the migrations folder inside the app that was causing the problem. And recreated it by running '<code>python manage.py makemigrations &lt;appname&gt;</code>' I then migrated to the server, and everything was great. </p> <p>Thank you, @MosesKoledoye</p>
0
2016-10-07T17:59:27Z
[ "python", "django", "typeerror" ]
How can I convert a categorical index to a float?
39,903,986
<p>I have a categorical index of wind directions in a pandas dataframe.</p> <pre><code>print (self.Groups.index) CategoricalIndex([22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5], categories=[22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5], ordered=True, name='Dir', dtype='category') </code></pre> <p>I a...
-1
2016-10-06T19:15:25Z
39,904,114
<p>Use <code>astype</code> to perform the conversion:</p> <pre><code>self.Groups.index = self.Groups.index.astype('float') </code></pre>
1
2016-10-06T19:24:11Z
[ "python", "pandas" ]
How can I convert a categorical index to a float?
39,903,986
<p>I have a categorical index of wind directions in a pandas dataframe.</p> <pre><code>print (self.Groups.index) CategoricalIndex([22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5], categories=[22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5], ordered=True, name='Dir', dtype='category') </code></pre> <p>I a...
-1
2016-10-06T19:15:25Z
39,904,181
<p>You can use the <code>to_numeric</code> function to convert the index. It gives more control of the expected behavior in case of failure.</p> <pre><code># Test data index = pd.CategoricalIndex([22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5], categories=[22.5, 67.5, 112.5, 157.5, 202.5, 247.5, 292.5, 337.5], ...
1
2016-10-06T19:28:21Z
[ "python", "pandas" ]
Python Beautifulsoup access text in tags?
39,904,089
<p>I am having trouble finding and returning the value that appears to be in the <code>&lt;b&gt;</code> tag, I have no luck when reading any of the tags. </p> <p>I don't want to post a hundred lines of the view-source info and am not sure how to properly post the link to it but here is the webpage if you would be able...
1
2016-10-06T19:22:24Z
39,913,353
<p>You can see the page takes a while to load the data, the data is requested through an Ajax request so what requests returns is not what you see in your browser. You can mimic the ajax request with a simple get to <a href="http://yugiohprices.com/get_card_prices/Dark+Magician" rel="nofollow">http://yugiohprices.com/g...
1
2016-10-07T08:58:03Z
[ "python", "beautifulsoup" ]
Pandas/SQL-calculate the pecentage based on different Group
39,904,128
<p>I want to calculate the percentage of each group and a new column For example: data=</p> <pre><code>Group Value A 1 A 2 A 1 B 4 B 4 B 8 </code></pre> <p>and I want to get:</p> <pre><code>Group Value Percentage A 1 0.25 A 2 0.50 A 1 ...
1
2016-10-06T19:24:53Z
39,904,202
<p>Try to use</p> <pre><code>SELECT A.Group, A.Value, ( A.Value / (SELECT Sum(b.Value) FROM yourtable b WHERE b.Group = A.Group) ) Percentage FROM yourtable A </code></pre>
1
2016-10-06T19:29:35Z
[ "python", "sql", "pandas", "dataframe" ]
Pandas/SQL-calculate the pecentage based on different Group
39,904,128
<p>I want to calculate the percentage of each group and a new column For example: data=</p> <pre><code>Group Value A 1 A 2 A 1 B 4 B 4 B 8 </code></pre> <p>and I want to get:</p> <pre><code>Group Value Percentage A 1 0.25 A 2 0.50 A 1 ...
1
2016-10-06T19:24:53Z
39,904,779
<p>Using pandas:</p> <pre><code>df['Percentage'] = df.groupby('Group')['Value'].transform(lambda x: x / x.sum()) </code></pre> <p>output:</p> <pre><code> Group Value Percentage 0 A 1 0.25 1 A 2 0.50 2 A 1 0.25 3 B 4 0.25 4 B 4 0.25 5 ...
2
2016-10-06T20:06:11Z
[ "python", "sql", "pandas", "dataframe" ]
Organizing list of tuples
39,904,161
<p>I have a list of tuples which I create dynamically.</p> <p>The list appears as:</p> <pre><code>List = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)] </code></pre> <p>Each tuple <code>(a, b)</code> of list represents the range of indexes from a certain table.</p> <p>The ranges <code>(a, b) and (b, d)</code> ...
6
2016-10-06T19:27:24Z
39,904,389
<p>If you need to take into account things like skovorodkin's example in the comment, </p> <pre><code>[(1, 4), (4, 8), (8, 10)] </code></pre> <p>(or even more complex examples), then one way to do efficiently would be using graphs. </p> <p>Say you create a digraph (possibly using <a href="https://networkx.github.io/...
6
2016-10-06T19:41:27Z
[ "python", "algorithm", "list", "tuples" ]
Organizing list of tuples
39,904,161
<p>I have a list of tuples which I create dynamically.</p> <p>The list appears as:</p> <pre><code>List = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)] </code></pre> <p>Each tuple <code>(a, b)</code> of list represents the range of indexes from a certain table.</p> <p>The ranges <code>(a, b) and (b, d)</code> ...
6
2016-10-06T19:27:24Z
39,904,486
<p>Here is one optimized recursion approach:</p> <pre><code>In [44]: def find_intersection(m_list): for i, (v1, v2) in enumerate(m_list): for j, (k1, k2) in enumerate(m_list[i + 1:], i + 1): if v2 == k1: m_list[i] = (v1, m_list.pop(j)[1]) ...
2
2016-10-06T19:47:03Z
[ "python", "algorithm", "list", "tuples" ]
Organizing list of tuples
39,904,161
<p>I have a list of tuples which I create dynamically.</p> <p>The list appears as:</p> <pre><code>List = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)] </code></pre> <p>Each tuple <code>(a, b)</code> of list represents the range of indexes from a certain table.</p> <p>The ranges <code>(a, b) and (b, d)</code> ...
6
2016-10-06T19:27:24Z
39,904,568
<p>If they don't overlap, then you can sort them, and then just combine adjacent ones.</p> <p>Here's a generator that yields the new tuples:</p> <pre><code>def combine_ranges(L): L = sorted(L) # Make a copy as we're going to remove items! while L: start, end = L.pop(0) # Get the first item w...
5
2016-10-06T19:52:43Z
[ "python", "algorithm", "list", "tuples" ]
Organizing list of tuples
39,904,161
<p>I have a list of tuples which I create dynamically.</p> <p>The list appears as:</p> <pre><code>List = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)] </code></pre> <p>Each tuple <code>(a, b)</code> of list represents the range of indexes from a certain table.</p> <p>The ranges <code>(a, b) and (b, d)</code> ...
6
2016-10-06T19:27:24Z
39,904,580
<p>non-recursive approach, using sorting (I've added more nodes to handle complex case):</p> <pre><code>l = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30), (30,34), (38,40)] l = sorted(l) r=[] idx=0 while idx&lt;len(l): local=idx+1 previous_value = l[idx][1] # search longest string while local&lt...
2
2016-10-06T19:53:09Z
[ "python", "algorithm", "list", "tuples" ]
Organizing list of tuples
39,904,161
<p>I have a list of tuples which I create dynamically.</p> <p>The list appears as:</p> <pre><code>List = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)] </code></pre> <p>Each tuple <code>(a, b)</code> of list represents the range of indexes from a certain table.</p> <p>The ranges <code>(a, b) and (b, d)</code> ...
6
2016-10-06T19:27:24Z
39,904,588
<p>The list is first sorted and adjacent pairs of (min1, max1), (min2, max2) are merged together if they overlap.</p> <pre><code>MIN=0 MAX=1 def normalize(intervals): isort = sorted(intervals) for i in range(len(isort) - 1): if isort[i][MAX] &gt;= isort[i + 1][MIN]: vmin = isort[i][MIN] ...
1
2016-10-06T19:54:05Z
[ "python", "algorithm", "list", "tuples" ]
Organizing list of tuples
39,904,161
<p>I have a list of tuples which I create dynamically.</p> <p>The list appears as:</p> <pre><code>List = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)] </code></pre> <p>Each tuple <code>(a, b)</code> of list represents the range of indexes from a certain table.</p> <p>The ranges <code>(a, b) and (b, d)</code> ...
6
2016-10-06T19:27:24Z
39,904,621
<p>You can use a dictionary to map the different end indices to the range ending at that index; then just iterate the list sorted by start index and merge the segments accordingly:</p> <pre><code>def join_lists(lst): ending = {} # will map end position to range for start, end in sorted(lst): # iterate in sor...
2
2016-10-06T19:56:07Z
[ "python", "algorithm", "list", "tuples" ]
Organizing list of tuples
39,904,161
<p>I have a list of tuples which I create dynamically.</p> <p>The list appears as:</p> <pre><code>List = [(1,4), (8,10), (19,25), (10,13), (14,16), (25,30)] </code></pre> <p>Each tuple <code>(a, b)</code> of list represents the range of indexes from a certain table.</p> <p>The ranges <code>(a, b) and (b, d)</code> ...
6
2016-10-06T19:27:24Z
39,904,762
<p>The following should work. It breaks tuples into individual numbers, then finds the tuple bound on each cluster. This should work even with difficult overlaps, like <code>[(4, 10), (9, 12)]</code></p> <p>It's a very simple fix.</p> <pre><code># First turn your list of tuples into a list of numbers: my_list = [] ...
1
2016-10-06T20:05:00Z
[ "python", "algorithm", "list", "tuples" ]
Nginx + uwsgi + django + odbc - issues with not finding odbc driver, possibly related to wrong user somewhere
39,904,216
<p>I'm trying to connect to teradata through odbc from django under CentOS. The problem is that odbc cannot find teradata driver when run under django. If I run the script from python directly (or through django's <code>./manage command</code>) it works fine, which makes me to believe that something in the chain above ...
0
2016-10-06T19:30:23Z
39,907,024
<p>After trial and error this made it work for now:</p> <ol> <li><p>Add <code>HOME</code> env variable to uwsgi's app.ini config pointing to home dir of the right user:</p> <pre><code>env=HOME=/home/myuser </code></pre></li> <li><p>Pass <code>odbcLibPath</code> param explicitly when initializing the teradata connecti...
0
2016-10-06T23:13:15Z
[ "python", "django", "nginx", "teradata", "uwsgi" ]
Python - No module named
39,904,239
<p>I have the following code with few modules:</p> <pre><code>import Persistence.Image as img import sys def main(): print(sys.path) original_image = img.Image.open_image() if __name__ == "__main__": main() </code></pre> <p>(I've created my own Image module)</p> <p>And so I'm getting the following err...
0
2016-10-06T19:31:49Z
39,904,345
<p>I don't believe that you are importing with proper syntax. You need to use <code>from Persistance import Image as img</code>. For example:</p> <pre><code>&gt;&gt;&gt; import cmath.sqrt as c_sqrt Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import cmath.sqrt ImportEr...
-1
2016-10-06T19:38:17Z
[ "python", "python-2.7" ]
Python - No module named
39,904,239
<p>I have the following code with few modules:</p> <pre><code>import Persistence.Image as img import sys def main(): print(sys.path) original_image = img.Image.open_image() if __name__ == "__main__": main() </code></pre> <p>(I've created my own Image module)</p> <p>And so I'm getting the following err...
0
2016-10-06T19:31:49Z
39,905,562
<p><code>Persistence</code> package does not exist in that source tree. There is a <em>"Persistence"</em> directory there, but it is not a package, because it does not contain a <code>__init__.py</code> file.</p> <p>From the <a href="https://docs.python.org/2/tutorial/modules.html#packages" rel="nofollow">Python docum...
1
2016-10-06T21:01:35Z
[ "python", "python-2.7" ]
deploying python code to heroku not working
39,904,261
<p>I have added the buildpack for python, it works.</p> <p>But when i do a git push it doesnt work. </p> <p>I get the below error all the time.</p> <pre><code>(venv) D:\Projects\ecommerce\clone\cut_veggies&gt;heroku buildpacks:set heroku/python Buildpack set. Next release on cutveggie will use heroku/python. Run git...
0
2016-10-06T19:33:01Z
39,906,307
<p>I've had this problem with my application too. Adding a <code>requirements.txt</code> file with the dependencies to the root of the project solved it. Check <a href="https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-python" rel="nofollow">here</a> for more details. You can check <a href="https://github....
0
2016-10-06T22:03:05Z
[ "python", "django", "heroku" ]
Python, code works, but openning via bat file get error
39,904,383
<p>Following is a simple working GUI programm. However, when I try to open it from a <code>bat</code> file, it gives an error.</p> <p>Bat file (2 lines):</p> <pre><code>ch10.2.py pause </code></pre> <p>The error I receive is:</p> <p>[error message in text format to be included here]</p> <p>My code:</p> <pre><code...
0
2016-10-06T19:40:45Z
39,905,585
<p>It's giving error on <code>super(Application, self).__init__(master)</code>.<br> If you replace with <code>Frame.__init__(self, master)</code> , its working. See below </p> <pre><code># Lazy Buttons 2 # Demonstrates using a class with Tkinter from tkinter import * class Application(Frame): """ A GUI applicat...
0
2016-10-06T21:03:25Z
[ "python" ]
Locating Lazy Load Elements While Scrolling in PhantomJS in Python
39,904,477
<p>I'm using python and Webdriver to scrape data from a page that dynamically loads content as the user scrolls down the page (lazy load). I have a total of 30 data elements, while only 15 are displayed without first scrolling down.</p> <p>I am locating my elements, and getting their values in the following way, after...
0
2016-10-06T19:46:47Z
39,905,354
<p>I had the exact same issue. The solution I found was to execute javascript code in the virtual browser to force elements to scroll to the bottom. </p> <p>Before putting the Javascript command into selenium, I recommend opening up your page in Firefox and inspecting the elements to find the scrollable content. Th...
0
2016-10-06T20:48:23Z
[ "python", "web-scraping", "webdriver", "phantomjs" ]
Efficient, large-scale competition scoring in Python
39,904,506
<p>Consider a large dataframe of scores <code>S</code> containing entries like the following. Each row represents a contest between a subset of the participants <code>A</code>, <code>B</code>, <code>C</code> and <code>D</code>. </p> <pre><code> A B C D 0.1 0.3 0.8 1 1 0.2 NaN NaN 0.7 NaN 2 0.5 ...
3
2016-10-06T19:48:15Z
39,905,034
<p>Let's look at a NumPy based solution and thus let's assume that the input data is in an array named <code>a</code>. Now, the number of pairwise combinations for 4 such variables would be <code>4*3/2 = 6</code>. We can generate the IDs corresponding to such combinations with <a href="http://docs.scipy.org/doc/numpy/r...
3
2016-10-06T20:23:38Z
[ "python", "pandas", "numpy", "matrix", "numba" ]
How to run multiple functions using thread measuring time?
39,904,525
<p>I want to run two functions concurrently until they both return True up to 60 sec timeout.</p> <p>This is what I have:</p> <pre><code>import time start_time = time.time() timeout = time.time() + 60 a_result = b_result = False a_end_time = b_end_time = None a_duration = b_duration = None while time.time() &lt; ...
0
2016-10-06T19:49:08Z
39,906,255
<p>I think it would be easiest to implement if each function timed itself:</p> <pre><code>import random import time import threading MAX_TIME = 20 a_lock, b_lock = threading.Lock(), threading.Lock() a_result = b_result = False a_duration = b_duration = None def func_a(): global a_result, a_duration start_ti...
1
2016-10-06T21:59:35Z
[ "python", "multithreading" ]
Access JSON data from API
39,904,546
<p>I am trying to write a script to download images from an API, I have a set up a loop that is as follows: </p> <pre><code> response = requests.get(url, params=query) json_data = json.dumps(response.text) pythonVal = json.loads(json.loads(json_data)) print(pythonVal) </code></pre> <p>The print(pythonV...
1
2016-10-06T19:51:17Z
39,904,655
<p>Why doing <code>json.loads()</code> twice? Change:</p> <pre><code>json.loads(json.loads(json_data)) </code></pre> <p>to:</p> <pre><code>json.loads(json_data) </code></pre> <p>and it should work.</p> <p>Now since you are getting error <code>TypeError: string indices must be integers</code> on doing <code>pythonV...
1
2016-10-06T19:57:31Z
[ "python", "json" ]
Access JSON data from API
39,904,546
<p>I am trying to write a script to download images from an API, I have a set up a loop that is as follows: </p> <pre><code> response = requests.get(url, params=query) json_data = json.dumps(response.text) pythonVal = json.loads(json.loads(json_data)) print(pythonVal) </code></pre> <p>The print(pythonV...
1
2016-10-06T19:51:17Z
39,904,697
<p>Put the following on top of your code. This works by overriding the native ascii encoding of Python to UTF-8. </p> <pre><code># -*- coding: utf-8 -*- </code></pre> <p>The second error is because you have already gotten the string, and you need integer indices to get the characters of the string. </p>
0
2016-10-06T20:00:39Z
[ "python", "json" ]
how to loop through certain directories in a directory structure in python?
39,904,559
<p>I have the following directory structure</p> <p><a href="http://i.stack.imgur.com/AR4Sv.png" rel="nofollow"><img src="http://i.stack.imgur.com/AR4Sv.png" alt="enter image description here"></a></p> <p><a href="http://i.stack.imgur.com/vEnMe.png" rel="nofollow"><img src="http://i.stack.imgur.com/vEnMe.png" alt="ent...
0
2016-10-06T19:51:57Z
39,904,640
<p>Since your structure is not recursive I would recommend this:</p> <pre><code>import glob zero_files_list = glob.glob("spinux/generated/Human_C*/*/contours/*.0") for f in zero_files_list: print("do something with "+f) </code></pre> <p>Run it from the parent directory of <code>spinux</code> or you'll have no mat...
3
2016-10-06T19:57:02Z
[ "python", "file", "loops", "operating-system" ]
Setting up 'encoding' in Python's gzip.open() doesn't seem to work
39,904,587
<p>Even tho I tried to specify encoding in python's gzip.open(), it seems to be always using cp1252.py to encode the file's content. My code:</p> <pre><code>with gzip.open('file.gz', 'rt', 'cp1250') as f: content = f.read() </code></pre> <p>Response:</p> <blockquote> <p>File "C:\Python34\lib\encodings\cp1252.p...
0
2016-10-06T19:54:03Z
39,904,877
<h1>Python 3.x</h1> <p><code>gzip.open</code> is <a href="https://docs.python.org/3.4/library/gzip.html#gzip.open" rel="nofollow">defined</a> as:</p> <blockquote> <p>gzip.open(filename, mode='rb', compresslevel=9, encoding=None, errors=None, newline=None)</p> </blockquote> <p>Therefore, <code>gzip.open('file.gz', ...
0
2016-10-06T20:14:11Z
[ "python", "python-3.x", "character-encoding", "gzip" ]
Why can't class variables be used in __init__ keyword arg?
39,904,590
<p>I can't find any documentation on when exactly a class can reference itself. In the following it will fail. This is because the class has been created but not initialized until after <code>__init__</code>'s first line, correct?</p> <pre><code>class A(object): class_var = 'Hi' def __init__(self, var=A.class_...
4
2016-10-06T19:54:13Z
39,904,740
<p>Python scripts are interpreted as you go. So when the interpreter enters <code>__init__()</code> the class variable <code>A</code> isn't defined yet (you are inside it), same with <code>self</code> (that is a different parameter and only available in function body).</p> <p>However anything in that class is interpre...
6
2016-10-06T20:03:32Z
[ "python", "class", "variables", "keyword-argument" ]
IndentationError running python script
39,904,634
<p>Im very new to python and Im trying to run this script but keep getting indentation errors in this part:</p> <pre><code>while (time.time()-self.time) &amp;lt; self.limit </code></pre> <p>I have tried to remove all indentation and then ree-indent in different ways but nothing seems to work. Does anyone have an idea...
-4
2016-10-06T19:56:45Z
39,904,661
<p>The methods of your class must be indented under your <code>class</code> statement and the body of the methods must be indented under the <code>def</code> line. The body of the <code>try</code> and <code>except</code> blocks must be indented under those statements.</p> <pre><code>start_time = time.time() #grabs the...
0
2016-10-06T19:58:13Z
[ "python" ]
IndentationError running python script
39,904,634
<p>Im very new to python and Im trying to run this script but keep getting indentation errors in this part:</p> <pre><code>while (time.time()-self.time) &amp;lt; self.limit </code></pre> <p>I have tried to remove all indentation and then ree-indent in different ways but nothing seems to work. Does anyone have an idea...
-4
2016-10-06T19:56:45Z
39,904,924
<p>you need to fix your syntax for the while condition statement.</p> <p>first, as several others have mentioned <code>&amp;lt</code> is not a python operator. nor do you want a semicolon after it. The proper syntax would be <code>while (time.time()-self.time) &lt; self.limit:</code></p> <p>The semicolon is not speci...
0
2016-10-06T20:17:03Z
[ "python" ]
Clarification on python websockets example
39,904,635
<p>From the example found here: <a href="http://websockets.readthedocs.io/en/stable/intro.html" rel="nofollow">http://websockets.readthedocs.io/en/stable/intro.html</a></p> <p>Can someone explain what the parameter 'path' does here? Is it a tuple for the host and port needed by websocket.serve()?</p> <pre><code>impor...
0
2016-10-06T19:56:45Z
39,904,763
<p>The <a href="http://websockets.readthedocs.io/en/stable/api.html#websockets.server.serve" rel="nofollow">documentation for <code>websockets.serve</code></a> says that its first argument is <code>ws_handler</code>:</p> <blockquote> <p>ws_handler is the WebSocket handler. It must be a coroutine accepting two argume...
0
2016-10-06T20:05:03Z
[ "python", "function", "websocket" ]
treatment of mouse events opencv gui vs pyqt
39,904,646
<p>I was working with OpenCV gui functions for a while, and the possibilities are a little restricting for python users. Today I started with Pyqt and come across the following conclusion: qt is really confusing. </p> <p>Now the question concerning mouse events:</p> <p>In OpenCV I just do the following:</p> <pre><co...
0
2016-10-06T19:57:15Z
39,907,062
<p>You can use an event-filter to avoid having to subclass the <code>QLabel</code>:</p> <pre><code>class QCustomWidget (QtGui.QWidget): def __init__ (self, parent = None): super(QCustomWidget, self).__init__(parent) self.setWindowOpacity(1) # Init QLabel self.positionQLabel = QtGui....
0
2016-10-06T23:17:45Z
[ "python", "opencv", "mouseevent", "pyqt4" ]
How to set proxy settings on MacOS using python
39,904,647
<p>How to change the internet proxy settings using python in MacOS to set <code>Proxy server</code> and <code>Proxy port</code></p> <p>I do that with windows using this code:</p> <pre><code>import _winreg as winreg INTERNET_SETTINGS = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersi...
1
2016-10-06T19:57:17Z
39,934,154
<p>After a long time fo search, i found this way of how to change proxy on MacOs using python.</p> <p>We need to use <code>networksetup</code> via terminal.</p> <p>To set http proxy server on MacOS using python:</p> <pre><code>import os proxy = "proxy.example.com" port = 8080 def Proxy_on(): os.system('network...
0
2016-10-08T15:30:43Z
[ "python", "osx", "python-2.7", "python-3.x", "proxy" ]
WxPython : Button Events
39,904,648
<p>Is there a way, that I could bind two events to a button in a sequential way. What I mean is as following: </p> <p>In this example buttons 1 &amp; 2 are bonded to their events respectively. </p> <pre><code>self.button1 = wx.Button(panel, -1, 'BUTTON1') self.button1.Bind(wx.EVT_BUTTON, self.OnButton1) self.button2...
0
2016-10-06T19:57:17Z
39,921,164
<pre><code> self.button1 = wx.Button(panel, -1, 'BUTTON1') self.button1.Bind(wx.EVT_BUTTON, self.OnButton1) self.button2 = wx.Button(panel, -1, 'Button2') self.button2.Bind(wx.EVT_BUTTON, self.OnButton2) def OnButton1(self,event): #why not call a function directly beforehand? self.D...
0
2016-10-07T15:44:42Z
[ "python", "button", "wxpython" ]
Error "ODBC data type -150 is not supported" when connecting sqlalchemy to mssql
39,904,693
<p>I keep running into an odd error when attempting to connect python sqlalchemy to a msssql server/database. I need to use sqlalchemy as it is (from what I've been told) the only way to connect pandas dataframes to mssql. </p> <p>I have tried connecting sqlalchemy two different ways:</p> <ol> <li><p>using full conne...
2
2016-10-06T20:00:18Z
39,905,565
<p>IIRC, this is because you can't select non-cast functions directory, since they don't return a datatype <em>pyodbc</em> recognizes.</p> <p>Try this:</p> <pre><code>SELECT CAST(GETDATE() AS DATETIME) AS dt </code></pre> <p>Also, your may want to use <code>CURRENT_TIMESTAMP</code>, which is ANSI standard SQL, inste...
0
2016-10-06T21:02:05Z
[ "python", "sql-server", "sqlalchemy", "pyodbc" ]
Error "ODBC data type -150 is not supported" when connecting sqlalchemy to mssql
39,904,693
<p>I keep running into an odd error when attempting to connect python sqlalchemy to a msssql server/database. I need to use sqlalchemy as it is (from what I've been told) the only way to connect pandas dataframes to mssql. </p> <p>I have tried connecting sqlalchemy two different ways:</p> <ol> <li><p>using full conne...
2
2016-10-06T20:00:18Z
39,908,496
<p>I upgraded to sqlalchemy 1.1 today and ran into a similar issue with connections that were working before. Bumped back to 1.0.15 and no problems. Not the best answer, more of a workaround, but it may work if you are on 1.1 and need to get rolling.</p> <p>If you are unsure of your version:</p> <pre><code>&gt;&gt;im...
3
2016-10-07T02:34:04Z
[ "python", "sql-server", "sqlalchemy", "pyodbc" ]
Error "ODBC data type -150 is not supported" when connecting sqlalchemy to mssql
39,904,693
<p>I keep running into an odd error when attempting to connect python sqlalchemy to a msssql server/database. I need to use sqlalchemy as it is (from what I've been told) the only way to connect pandas dataframes to mssql. </p> <p>I have tried connecting sqlalchemy two different ways:</p> <ol> <li><p>using full conne...
2
2016-10-06T20:00:18Z
39,910,381
<p>This is most certainly a bug introduced in <a href="https://bitbucket.org/zzzeek/sqlalchemy/issues/3814">Issue 3814</a>, new in SQLAlchemy 1.1.0, where they introduce <code>SELECT SERVERPROPERTY('ProductVersion')</code> to fetch server version for the pyodbc MSSQL driver. Downgrading to 1.0.15 will make the code wo...
5
2016-10-07T05:58:04Z
[ "python", "sql-server", "sqlalchemy", "pyodbc" ]
Extracting between tokens with NLTK
39,904,719
<p>I'm experimenting with NLTK to help me parse some text. So far , just using the sent_tokenize function has been very helpful in organizing the text. As an example I have:</p> <pre><code>1 Robins Drive owned by Gregg S. Smith was sold to TeStER, LLC of 494 Bridge Avenue, Suite 101-308, Sheltville AZ 02997 for $27,00...
2
2016-10-06T20:01:55Z
39,904,811
<p>This is one solution to select tokens between the words you wrote:</p> <pre><code>import re from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer(r'owned by(.*?)was sold to') string = '1 Robins Drive owned by Gregg S. Smith was sold to TeStER, LLC of 494 Bridge Avenue, Suite 101-308, Sheltville AZ...
2
2016-10-06T20:08:33Z
[ "python", "nltk" ]
Regex: exception to negative character class
39,904,862
<p>Using Python with Matthew Barnett's regex module.</p> <p>I have this string:</p> <pre><code>The well known *H*rry P*tter*. </code></pre> <p>I'm using this regex to process the asterisks to obtain <code>&lt;em&gt;H*rry P*tter&lt;/em&gt;</code>:</p> <pre><code>REG = re.compile(r""" (?&lt;!\p{L}|\p{N}|\\) \* ([^\*]...
2
2016-10-06T20:12:53Z
39,905,163
<p>I suggest a single regex replacement for the cases like you mentioned above:</p> <pre><code>re.sub(r'\B\*\b([^*]*(?:\b\*\b[^*]*)*)\b\*\B', r'&lt;em&gt;\1&lt;/em&gt;', s) </code></pre> <p>See the <a href="https://regex101.com/r/SLEeCB/1" rel="nofollow">regex demo</a></p> <p><strong>Details</strong>:</p> <ul> <li>...
1
2016-10-06T20:33:21Z
[ "python", "regex" ]
What is `$6$rounds=` when running Passlib with Python?
39,904,882
<p>I'm generating SHA-512 encoded password keys with Python's <code>Passlib</code>'s command.</p> <p><code>python -c "from passlib.hash import sha512_crypt; import getpass; print sha512_crypt.encrypt(getpass.getpass())"</code></p> <p>This is per Ansible documentation: <a href="http://docs.ansible.com/ansible/faq.html...
-1
2016-10-06T20:14:38Z
39,904,985
<p>This indicates to the schema for the used algorithm. In the case of <code>sha512_crypt</code> <code>6</code> indicates <code>sha512</code> and <code>rounds=x</code> indicate the number of rounds to compute the hash. </p> <p>Also current <code>NIST</code> standards suggest <code>pbkdf2_sha256</code> for password has...
2
2016-10-06T20:20:15Z
[ "python", "encryption", "passlib" ]
Pandas cast all object columns to category
39,904,889
<p>I want to have ha elegant function to cast all object columns in a pandas data frame to categories</p> <p><code>df[x] = df[x].astype("category")</code> performs the type cast <code>df.select_dtypes(include=['object'])</code> would sub-select all categories columns. However this results in a loss of the other colum...
2
2016-10-06T20:15:05Z
39,906,514
<p>use <code>apply</code> and <code>pd.Series.astype</code> with <code>dtype='category'</code></p> <p>Consider the <code>pd.DataFrame</code> <code>df</code></p> <pre><code>df = pd.DataFrame(dict( A=[1, 2, 3, 4], B=list('abcd'), C=[2, 3, 4, 5], D=list('defg') )) df </code></pre> <p...
2
2016-10-06T22:21:57Z
[ "python", "pandas", "casting", "categorical-data" ]
Why should I rebuild Caffe each time I want to use a new package?
39,905,248
<p>I am very new to Ubuntu and I just started learning Caffe. The question might come stupid as I have no idea about how 'make' command works. </p> <p>Anyway, I installed Caffe following the instruction in this link: <a href="https://gist.github.com/titipata/f0ef48ad2f0ebc07bcb9" rel="nofollow">Caffe Installation</a> ...
0
2016-10-06T20:40:39Z
39,906,633
<p>You have to 'make' caffe for each installation. I don't know of any other way. This is because each version might have different layers. </p> <p>You can have multiple versions of caffe on your system. There is no need to remove one in order to make another. You'll just have to change the $PYTHONPATH$ to whichever ...
1
2016-10-06T22:32:34Z
[ "python", "package", "install", "ubuntu-14.04", "caffe" ]
How do I import a submodule with web2py?
39,905,256
<p>I'm trying to do a dynamic import (using "__import__()") of a submodule in web2py and it doesn't seem to be finding the submodule.</p> <p>Here's an example path: web2py/app/modules/module.py &lt;-- This works web2py/app/modules/module_folder/submodule.py &lt;-- This won't get spotted.</p> <p>Right now as a workaro...
0
2016-10-06T20:41:30Z
39,910,270
<p>The problem here is that <code>__import__</code> does not do the most intuitive thing (neither does <code>import</code> btw).</p> <p>Here's what happens:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; x = __import__('package1.package2.module') &gt;&gt;&gt; x &lt;module 'package1' from 'C:\\Temp\\package1\\__i...
0
2016-10-07T05:49:04Z
[ "python", "web2py" ]
Python: Saving to CSV file, accidentally writing to next column instead of row after manually opening the file
39,905,281
<p>I've noticed a really weird bug and didn't know if anyone else had seen this / knows how to stop it. </p> <p>I'm writing to a CSV file using this:</p> <pre><code>def write_to_csv_file(self, object, string): with open('data_model_1.csv', 'a') as f: writer = csv.writer(f) writer.write...
-1
2016-10-06T20:43:21Z
39,905,521
<p>You're opening the file in <strong>a</strong>ppend <a href="https://docs.python.org/3.6/library/functions.html#open" rel="nofollow">mode</a>, so the data is appended to the end of the file. If the file doesn't end in a newline, rows may get concatenated. Try writing a newline to the file before appending new rows:</...
1
2016-10-06T20:58:43Z
[ "python", "csv" ]
Unexpected behaviour in python multiprocessing
39,905,360
<p>I'm trying to understand the following odd behavior observed using the <code>python mutiprocessing</code>.</p> <p>Sample testClass: import os import multiprocessing </p> <pre><code>class testClass(multiprocessing.Process): def __del__(self): print "__del__ PID: %d" % os.getpid() ...
0
2016-10-06T20:48:41Z
39,905,471
<p>You can wrap your expensive initialization inside a context manager:</p> <pre><code>def run(self): with expensive_initialization() as initialized_object: do_some_logic_here(initialized_object) </code></pre> <p>You will have a chance to properly initialize your object before calling <code>do_some_logic_...
0
2016-10-06T20:55:28Z
[ "python", "python-multiprocessing" ]
Unexpected behaviour in python multiprocessing
39,905,360
<p>I'm trying to understand the following odd behavior observed using the <code>python mutiprocessing</code>.</p> <p>Sample testClass: import os import multiprocessing </p> <pre><code>class testClass(multiprocessing.Process): def __del__(self): print "__del__ PID: %d" % os.getpid() ...
0
2016-10-06T20:48:41Z
39,906,198
<p>When calling <code>start()</code>, the interpreter forks and creates a child process, which gets a copy of the page tables from the parent. These point to pages which are marked as readonly and only copied when written (COW). The interpreter, when executing <code>run</code> in the child process, accesses the child's...
0
2016-10-06T21:54:28Z
[ "python", "python-multiprocessing" ]
How to use multi-level indexing in pyomo with a set and a rangeset?
39,905,366
<p>I have multiple levels of indices in my model in <code>pyomo</code>, and I need to be able to index variables like this:</p> <pre><code>model.b['a',1] </code></pre> <p>But this doesn't seem possible for some reason. I can use multilevel indexing like this:</p> <pre><code>model = ConcreteModel() model.W = RangeSe...
0
2016-10-06T20:48:58Z
39,905,929
<p>The problem is that when you write</p> <pre><code>model.W = Set(['a','b']) </code></pre> <p>you are actually creating an indexed Set object rather than a Set with the values in the provided list. This is because all Pyomo component constructors treat positional arguments as indexing sets.</p> <p>You can fix this ...
1
2016-10-06T21:31:20Z
[ "python", "python-2.7", "pyomo" ]