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
Convert python abbreviated month name to full name
40,076,887
<p>How can I convert an abbreviated month anme e.g. <code>Apr</code> in python to the full name?</p>
3
2016-10-17T00:13:27Z
40,076,933
<p>One quick and dirty way:</p> <pre><code>conversions = {"Apr": "April", "May": "May", "Dec": "December"} date = "Apr" if date in conversions: converted_date = conversions[date] </code></pre>
1
2016-10-17T00:21:45Z
[ "python", "datetime" ]
Convert python abbreviated month name to full name
40,076,887
<p>How can I convert an abbreviated month anme e.g. <code>Apr</code> in python to the full name?</p>
3
2016-10-17T00:13:27Z
40,077,286
<p>Here is a method to use <em>calendar</em> library.</p> <pre><code>&gt;&gt;&gt; import calendar &gt;&gt;&gt; calendar.month_name [list(calendar.month_abbr).index('Apr')] 'April' &gt;&gt;&gt; </code></pre>
2
2016-10-17T01:26:50Z
[ "python", "datetime" ]
Median of three, pivot
40,076,890
<p>I'm looking for the <strong>median of three</strong>, using this for a pivot in a QuickSort. I would not like to import any statistics library because I believe it creates a bit of overhead which I would like to reduce as much as possible.</p> <pre><code>def median(num_list): if (num_list[0] &gt; num_list[len(num_...
0
2016-10-17T00:13:46Z
40,076,989
<p>Let Python do the work for you. Sort the three elements, then return the middle one.</p> <pre><code>def median(num_list): return sorted([num_list[0], num_list[len(num_list) // 2], num_list[-1]])[1] </code></pre>
1
2016-10-17T00:31:02Z
[ "python", "quicksort" ]
Median of three, pivot
40,076,890
<p>I'm looking for the <strong>median of three</strong>, using this for a pivot in a QuickSort. I would not like to import any statistics library because I believe it creates a bit of overhead which I would like to reduce as much as possible.</p> <pre><code>def median(num_list): if (num_list[0] &gt; num_list[len(num_...
0
2016-10-17T00:13:46Z
40,076,999
<p>In Quicksort you do not usually want just to know the median of three, you want to arrange the three values so the smallest is in one spot, the median in another, and the maximum in yet another. But if you really just want the median of three, here are two ways, plus another that rearranges.</p> <p>Here's a short w...
1
2016-10-17T00:32:39Z
[ "python", "quicksort" ]
Median of three, pivot
40,076,890
<p>I'm looking for the <strong>median of three</strong>, using this for a pivot in a QuickSort. I would not like to import any statistics library because I believe it creates a bit of overhead which I would like to reduce as much as possible.</p> <pre><code>def median(num_list): if (num_list[0] &gt; num_list[len(num_...
0
2016-10-17T00:13:46Z
40,078,280
<p>Using <code>min</code> and <code>max</code>:</p> <pre><code>&gt;&gt;&gt; numlist = [21, 12, 16] &gt;&gt;&gt; a, b, c = numlist &gt;&gt;&gt; max(min(a,b), min(b,c), min(a,c)) 16 &gt;&gt;&gt; </code></pre> <hr> <p>Going out on a limb - I have a functional streak so here is the itertools equivalent, even though it ...
1
2016-10-17T03:58:08Z
[ "python", "quicksort" ]
Python regex to replace a double newline delimited paragraph containing a string
40,076,903
<p>Define a paragraph as a multi-line string delimited on both side with double new lines ('\n\n'). if there exist a paragraph which contains a certain string ('BAD'), i want to replace that paragraph (i.e. any text containing BAD up to the closest preceding and following double newlines) with some other token ('GOOD')...
-2
2016-10-17T00:16:51Z
40,076,973
<p>Here you are:</p> <pre><code>/\n\n(?:[^\n]|\n(?!\n))*BAD(?:[^\n]|\n(?!\n))*/g </code></pre> <p>OK, to break it down a little (because it's nasty looking):</p> <ul> <li><code>\n\n</code> matches two literal line breaks.</li> <li><code>(?:[^\n]|\n(?!\n))*</code> is a non-capturing group that matches either a single...
4
2016-10-17T00:28:57Z
[ "python", "regex" ]
Python regex to replace a double newline delimited paragraph containing a string
40,076,903
<p>Define a paragraph as a multi-line string delimited on both side with double new lines ('\n\n'). if there exist a paragraph which contains a certain string ('BAD'), i want to replace that paragraph (i.e. any text containing BAD up to the closest preceding and following double newlines) with some other token ('GOOD')...
-2
2016-10-17T00:16:51Z
40,076,977
<p>Firstly, you're mixing actual newlines and <code>'\n'</code> characters in your example, I assume that you only meant either. Secondly, let me challenge your assumption that you need regex for this:</p> <pre><code>inp = '''dfsdf sdadf blablabla blaBAD bla dsfsdf sdfdf''' replaced = '\n\n'.join(['GOOD' if 'BAD' i...
4
2016-10-17T00:29:30Z
[ "python", "regex" ]
shapely is_valid for polygons in 3D
40,076,962
<p>I'm trying to validate some polygons that are on planes with <code>is_valid</code>, but I get <code>Too few points in geometry component at or near point</code> for polygons where the z is not constant.</p> <p>Is there a way to validate these other polygons?</p> <p>Here's an example:</p> <pre><code>from shapely....
0
2016-10-17T00:27:19Z
40,138,876
<p>The problem is that <code>shapely</code> in fact ignores the z coordinate. So, as far as shapely can tell you are building a polygon with the points <code>[(1,0),(1,1), (1,1)]</code> that aren't enough to build a polygon.</p> <p>See this other SO question for more information: <a href="http://stackoverflow.com/ques...
1
2016-10-19T18:21:42Z
[ "python", "gis", "shapely" ]
Can't pass random variable to tf.image.central_crop() in Tensorflow
40,077,010
<p>In Tensorflow I am training from a set of PNG files and I wish to apply data augmentation. I have successfully used <code>tf.image.random_flip_left_right()</code></p> <p>But I get an error when I try to use <code>tf.image.central_crop()</code>. basically I would like the central_fraction to be drawn from a uniform ...
2
2016-10-17T00:33:51Z
40,143,349
<p>I solved my own problem defining the following function. I adjusted the code provided in tf.image.central_crop(image, central_fraction). The function RandomCrop will crop an image taking a central_fraction drawn from a uniform distribution. You can just specify the min and max fraction you want. You can replace ran...
0
2016-10-19T23:54:02Z
[ "python", "tensorflow" ]
scikit-learn CountVectorizer UnicodeDecodeError
40,077,084
<p>I have the following code snippet where I'm trying to list the term frequencies, where <code>first_text</code> and <code>second_text</code> are <code>.tex</code> documents:</p> <pre><code>from sklearn.feature_extraction.text import CountVectorizer training_documents = (first_text, second_text) vectorizer = CountV...
0
2016-10-17T00:47:55Z
40,077,782
<p>If you can work out what the encoding of your documents is (maybe they are <code>latin-1</code>) you can pass this to <code>CountVectorizer</code> with</p> <pre><code>vectorizer = CountVectorizer(encoding='latin-1') </code></pre> <p>Otherwise you can just skip the tokens containing the problematic bytes with</p> ...
1
2016-10-17T02:45:59Z
[ "python", "scikit-learn" ]
Counting/Print Unique Words in Directory up to x instances
40,077,089
<p>I am attempting to take all unique words in tale4653, count their instances, and then read off the top 100 mentioned unique words. </p> <p>My struggle is sorting the directory so that I can print both the unique word and its' respected instances. </p> <h2>My code thus far:</h2> <pre><code>import string fhand = ...
0
2016-10-17T00:48:28Z
40,077,193
<p>you loose the word (the key in your dictionary) when you do <code>counts.values()</code>)</p> <p>you can do this instead</p> <pre><code>rangedValue = sorted(counts.items(), reverse=True, key=lambda x: x[1]) for word, count in rangedValue: print word + ': ' + str(rangedValue) </code></pre> <p>when you do count...
0
2016-10-17T01:07:54Z
[ "python", "sorting", "while-loop", "directory" ]
Counting/Print Unique Words in Directory up to x instances
40,077,089
<p>I am attempting to take all unique words in tale4653, count their instances, and then read off the top 100 mentioned unique words. </p> <p>My struggle is sorting the directory so that I can print both the unique word and its' respected instances. </p> <h2>My code thus far:</h2> <pre><code>import string fhand = ...
0
2016-10-17T00:48:28Z
40,078,587
<p>DorElias is correct in the initial problem: you need to use <code>count.items()</code> with <code>key=lambda x: x[1]</code> or <code>key=operator.itemgetter(1)</code>, latter of which would be faster.</p> <hr> <p>However, I'd like to show how I'd do it, completely avoiding <code>sorted</code> in your code. <code>c...
0
2016-10-17T04:38:53Z
[ "python", "sorting", "while-loop", "directory" ]
Some help in my moment of stupidness
40,077,119
<p>so I have this project that's due and for one of the questions, after doing all the calculations, you compare two different booleans. So, if both booleans are true the answer will return false, and if both booleans are false it will return false, and it will only return true if one of the booleans are true and the o...
0
2016-10-17T00:52:16Z
40,077,149
<p>You are both right, the result is the same. Just one option is shorter than the other or simpler.</p> <p>There isn't only one way to solve a problem, as long as the result is right. Here I offer yet another solution.</p> <p>You also can use XOR ^ </p> <pre><code>t = False f = False result = t ^ f print result &...
0
2016-10-17T00:58:12Z
[ "python", "boolean", "logic" ]
Some help in my moment of stupidness
40,077,119
<p>so I have this project that's due and for one of the questions, after doing all the calculations, you compare two different booleans. So, if both booleans are true the answer will return false, and if both booleans are false it will return false, and it will only return true if one of the booleans are true and the o...
0
2016-10-17T00:52:16Z
40,077,267
<p><a href="https://i.stack.imgur.com/W405E.png" rel="nofollow">True False Table</a></p> <p>See the above true false table.</p> <p>XOR => ^</p> <p>So, in this case you can use A ^ B. However, A != B also works here.</p> <p>You are both right. But, your code is more concise. </p>
-1
2016-10-17T01:23:19Z
[ "python", "boolean", "logic" ]
Some help in my moment of stupidness
40,077,119
<p>so I have this project that's due and for one of the questions, after doing all the calculations, you compare two different booleans. So, if both booleans are true the answer will return false, and if both booleans are false it will return false, and it will only return true if one of the booleans are true and the o...
0
2016-10-17T00:52:16Z
40,077,271
<p>In my opinion, both of you are right. But I think your answer is more simple. </p> <pre><code>def fun(a,b): result = a ^ b #your code resultA= a!=b #your friend's code resultB= (a and not b) or (b and not a) print result print resultA print resultB print '-'*20 a = False b = Fa...
0
2016-10-17T01:24:02Z
[ "python", "boolean", "logic" ]
File Access in python
40,077,180
<p>Whenever I go to load a text file for my program it displays the info in the text file yet when I input the roster function it does not display the text file and show it is available to be modified. Is it something with how I created the text file in the first place or is my coding for <code>loadData</code> not writ...
2
2016-10-17T01:03:53Z
40,077,241
<p>you didnt load your data into <code>dict_member</code> before displaying the roster </p> <p>when you load your data in the loadData function you redefine <code>dict_member</code> so it will "shadow" the outer <code>dict_member</code> so when the <code>display</code> function is called <code>dict_member</code> will ...
-1
2016-10-17T01:17:32Z
[ "python" ]
File Access in python
40,077,180
<p>Whenever I go to load a text file for my program it displays the info in the text file yet when I input the roster function it does not display the text file and show it is available to be modified. Is it something with how I created the text file in the first place or is my coding for <code>loadData</code> not writ...
2
2016-10-17T01:03:53Z
40,077,242
<p>Try this:</p> <pre><code>def loadData(self): file = open(input("Filename to load: "), "r") text = file.read() file.close() for line in text: name, number, jersey = (line.rstrip()).split(',') dict_member[name] = (name, number, jersey) print("Data Loaded...
-1
2016-10-17T01:17:36Z
[ "python" ]
Pandas - Data Frame - Reshaping Values in Data Frame
40,077,188
<p>I am new to Pandas and have a data frame with a team's score in 2 separate columns. This is what I have.</p> <pre><code>Game_ID Teams Score 1 Team A 95 1 Team B 85 2 Team C 90 2 Team D 72 </code></pre> <p>This is where I would like to get to and then ideally to.</p> <pre><code>1 Team A 95 Te...
4
2016-10-17T01:07:02Z
40,077,293
<p>You can try something as follows: Create a <code>row_id</code> within each group by the <code>Game_ID</code> and then unstack by the <code>row_id</code> which will transform your data to wide format:</p> <pre><code>import pandas as pd df['row_id'] = df.groupby('Game_ID').Game_ID.transform(lambda g: pd.Series(range(...
4
2016-10-17T01:27:35Z
[ "python", "pandas", "dataframe" ]
Pandas - Data Frame - Reshaping Values in Data Frame
40,077,188
<p>I am new to Pandas and have a data frame with a team's score in 2 separate columns. This is what I have.</p> <pre><code>Game_ID Teams Score 1 Team A 95 1 Team B 85 2 Team C 90 2 Team D 72 </code></pre> <p>This is where I would like to get to and then ideally to.</p> <pre><code>1 Team A 95 Te...
4
2016-10-17T01:07:02Z
40,077,933
<p>Knowing that games always involve exactly 2 teams, we can manipulate the underlying numpy array.</p> <pre><code>pd.DataFrame(df.values[:, 1:].reshape(-1, 4), pd.Index(df.values[::2, 0], name='Game_ID'), ['Team', 'Score'] * 2) </code></pre> <p><a href="https://i.stack.imgur.com/YZPPL.png" ...
1
2016-10-17T03:09:13Z
[ "python", "pandas", "dataframe" ]
How to extract and divide values from dictionary with another in Python?
40,077,209
<pre><code>sample = [['CGG','ATT'],['GCGC','TAAA']] #Frequencies of each base in the pair d1 = [[{'G': 0.66, 'C': 0.33}, {'A': 0.33, 'T': 0.66}], [{'G': 0.5, 'C': 0.5}, {'A': 0.75, 'T': 0.25}]] #Frequencies of each pair occurring together d2 = [{('C', 'A'): 0.33, ('G', 'T'): 0.66}, {('G', 'T'): 0.25, ('C', 'A'): 0.5...
4
2016-10-17T01:10:11Z
40,091,556
<p>Usually when there is a tricky problem like this with multiple formulas and intermediate steps, I like to modularize it by splitting the work into several functions. Here is the resulting commented code which handles the cases in the original question and in the comments:</p> <pre><code>from collections import Coun...
1
2016-10-17T16:41:00Z
[ "python", "list", "dictionary", "counter" ]
Luhn's Algorithm Pseudocode to code
40,077,230
<p>Hey guys I'm fairly new to the programming world. For a school practice question I was given the following text and I'm suppose to convert this into code. I've spent hours on it and still can't seem to figure it out but I'm determine to learn this. I'm currently getting the error</p> <pre><code> line 7, in &lt;mod...
2
2016-10-17T01:14:49Z
40,077,285
<p>well, i can see 2 problems:</p> <p>1)when you do:</p> <pre><code>for i in creditCard[-1] </code></pre> <p>you dont iterate on the creditCard you simply take the last digit. you probably meant to do </p> <pre><code>for i in creditCard[::-1] </code></pre> <p>this will iterate the digits from the last one to the f...
1
2016-10-17T01:26:23Z
[ "python" ]
How to display images inside the new tab in Python
40,077,278
<p>Suppose that I have 10 images in a directory, and need them to be displayed inside a newly created tab once the user presses a push-button. The images must be displayed according to a 5x5 grid with a proper image label. </p> <p>I have designed a GUI using Qt Designer containing three different tabs (tab1, tab2 and ...
-1
2016-10-17T01:24:53Z
40,083,504
<p>You can easly display an image inside the tab by creating a label in the tab, here is an example for that : ( the tab in my example is tab_3)</p> <p><code>def setupUi(self, MainWindow): self.label = QtWidgets.QLabel(self.tab_3) self.label.setGeometry(QtCore.QRect(340, 30, 241, 171)) self.lab...
0
2016-10-17T10:03:31Z
[ "python", "image", "user-interface", "tabs", "pyqt" ]
How to display images inside the new tab in Python
40,077,278
<p>Suppose that I have 10 images in a directory, and need them to be displayed inside a newly created tab once the user presses a push-button. The images must be displayed according to a 5x5 grid with a proper image label. </p> <p>I have designed a GUI using Qt Designer containing three different tabs (tab1, tab2 and ...
-1
2016-10-17T01:24:53Z
40,091,238
<p>You need to create a new list-widget for each tab. Here's a demo:</p> <pre><code>import sys, os from PyQt4 import QtCore, QtGui class Window(QtGui.QWidget): def __init__(self): super(Window, self).__init__() self.tabs = QtGui.QTabWidget(self) self.edit = QtGui.QLineEdit(self) se...
0
2016-10-17T16:21:21Z
[ "python", "image", "user-interface", "tabs", "pyqt" ]
Trying to rewrite variables
40,077,284
<pre><code> print("Please enter some integers to average. Enter 0 to indicate you are done.") #part (a) -- what are the initial values for these variables? #incomplete done = 0 mySum = 0 count = 0 while not done: valid = False #don't yet have a valid input while not valid: #this loop keeps attempting to...
-1
2016-10-17T01:25:57Z
40,077,336
<p>Denominator cannot be zero. In this case, count is zero.</p> <p>You may need to use count += 1 instead of count = len(num).</p> <p>You should check whether the denominator is zero before you do the division.</p> <p>Suggestion: study python 3 instead of python 2.7. Python 2 will be finally replaced by python 3.</p...
0
2016-10-17T01:33:58Z
[ "python", "python-2.7" ]
Trying to rewrite variables
40,077,284
<pre><code> print("Please enter some integers to average. Enter 0 to indicate you are done.") #part (a) -- what are the initial values for these variables? #incomplete done = 0 mySum = 0 count = 0 while not done: valid = False #don't yet have a valid input while not valid: #this loop keeps attempting to...
-1
2016-10-17T01:25:57Z
40,077,358
<p>The "divide by zero" is a consequence of other problems in your code (or incompleteness of it). The proximate cause can be understood from the message: you are dividing by <code>0</code>, which means <code>count</code> is <code>0</code> at that point, which means you haven't actually tracked the numbers you put in. ...
0
2016-10-17T01:37:46Z
[ "python", "python-2.7" ]
scikit-learn SVM.SVC() is extremely slow
40,077,432
<p>i try to use the SVM classifier to train the data which is around 100k, but I find it is extremely slow and there is no any response when I run the code after 2 hr. when dataset is around 1k, i can get the result immediately, I also try the SGDClassifier and naïve bayes which is quite fast and get result within cou...
3
2016-10-17T01:49:36Z
40,077,679
<h3>General remarks about SVM-learning</h3> <p>SVM-training (with nonlinear-kernels; default in sklearn's SVC) is complexity-wise approximately (depends on the data and parameters) <strong>using the widely used SMO-algorithm (don't compare it with SGD-based approaches)</strong>: <code>O(n_samples^2 * n_features)</code...
3
2016-10-17T02:31:27Z
[ "python", "scikit-learn", "svm" ]
Generate Sample dataframes with constraints
40,077,508
<p>I have a dataframe of records that looks like:</p> <pre><code> 'Location' 'Rec ID' 'Duration' 'Rec-X' 0 Houston 126 17 [0.2, 0.34, 0.45, ..., 0.28] 1 Chicago 126 19.3 [0.12, 0.3, 0.41, ..., 0.39] 2 Boston 348 17.3 [0.12, 0.3,...
0
2016-10-17T02:01:45Z
40,077,899
<p>you can drop duplicates based on your column from the dataframe and then access the 10 elements</p> <pre><code>df2 = df.drop_duplicates('Rec ID') df2.head(10) </code></pre> <p><strong>EDIT</strong> If you want to select randomly 10 unique elements Then something like this will work</p> <pre><code>def selectRandom...
1
2016-10-17T03:04:41Z
[ "python", "dataframe", "genetic" ]
How to draw onscreen controls in panda 3d?
40,077,546
<p>I want to make a game in panda3d with support for touch because I want it to be playable on my windows tablet also without attaching a keyboard. What I want to do is, find a way to draw 2d shapes that don't change when the camera is rotated. I want to add a dynamic analog pad so I must be able to animate it when the...
1
2016-10-17T02:09:39Z
40,102,063
<p>Make those objects children of <code>base.render2d</code>, <code>base.aspect2d</code> or <code>base.pixel2d</code>. For proper GUI elements take a look at <code>DirectGUI</code>, for "I just want to throw these images up on the screen" at <code>CardMaker</code>.</p>
0
2016-10-18T07:26:26Z
[ "python", "panda3d" ]
Remote command does not return python
40,077,580
<p>I am rebooting a remote machine through Python, as it is a reboot, the current ssh session is killed. The request is not returned. I am not interested in the return though.</p> <p>os.command('sshpass -p password ssh user@host reboot')</p> <p>The code is performing the reboot, however the current session is killed ...
1
2016-10-17T02:15:22Z
40,077,696
<p>I'm surprised that the script doesn't return. The connection should be reset by the remote before it reboots. You can run the process asyc, the one problem is that subprocesses not cleaned up up by their parents become zombies (still take up space in the process table). You can add a Timer to give the script time to...
1
2016-10-17T02:33:51Z
[ "python", "python-2.7", "ssh" ]
Output random number between 30-35 using Random.seed(), 'for' and multiplication in Python
40,077,591
<p>I am new to programming. I had an assignment to write a code that will output a random number between 30 and 35. This code needs to use <code>random.seed()</code>, a FOR statement and a multiplication. I understand the <code>random.seed([x])</code> generates an initial value that could be used in the proceeding sect...
2
2016-10-17T02:16:34Z
40,077,752
<p>I'm not exactly sure how the <code>for</code> loop is relevant here, but you can use the formula that follows (based off Java's random number in range equation, mentioned <a href="http://stackoverflow.com/questions/363681/generating-random-integers-in-a-specific-range">here</a>) and in particular <a href="http://sta...
0
2016-10-17T02:42:09Z
[ "python", "python-3.x", "random" ]
Output random number between 30-35 using Random.seed(), 'for' and multiplication in Python
40,077,591
<p>I am new to programming. I had an assignment to write a code that will output a random number between 30 and 35. This code needs to use <code>random.seed()</code>, a FOR statement and a multiplication. I understand the <code>random.seed([x])</code> generates an initial value that could be used in the proceeding sect...
2
2016-10-17T02:16:34Z
40,077,830
<p>Here is another way to do it:</p> <pre><code>import random #initial random seed based on current system time #https://docs.python.org/2/library/random.html#random.seed random.seed(9) #We set this so random is repeatable in testing random_range = [30, 31, 32, 33, 34, 35] while True: num = int(round(random.ran...
0
2016-10-17T02:55:54Z
[ "python", "python-3.x", "random" ]
How do I import a CSV into an have each line be an object?
40,077,694
<p>I have a csv file with 8-12 values per line, this is spending data with categories, payment method, date, amount etc. Each line is a single purchase with these details. I want to import the file into python into a list that I can then iterate through easily to find for example, how much was spent on a given catego...
0
2016-10-17T02:33:37Z
40,077,760
<p>One tricky/hacky thing you can do with objects is programatically create them with <strong>dict</strong>. Here is an example:</p> <pre><code>In [1]: vals = {"one":1, "two":2} In [2]: class Csv():pass In [3]: c = Csv() In [4]: c.__dict__ = vals In [5]: c.one Out[5]: 1 </code></pre> <p>So, yes, you could create ...
0
2016-10-17T02:42:43Z
[ "python", "csv", "import" ]
How do I import a CSV into an have each line be an object?
40,077,694
<p>I have a csv file with 8-12 values per line, this is spending data with categories, payment method, date, amount etc. Each line is a single purchase with these details. I want to import the file into python into a list that I can then iterate through easily to find for example, how much was spent on a given catego...
0
2016-10-17T02:33:37Z
40,077,835
<p>Python brings its own CSV reader in <a href="https://docs.python.org/3/library/csv.html" rel="nofollow">the csv module</a>. You can use it to read your CSV file and convert the lines to objects like this:</p> <pre><code>import csv # Read values from csv file. values = [] with open('file.csv', 'r') as csv_file: ...
0
2016-10-17T02:56:52Z
[ "python", "csv", "import" ]
how to remove host from ip address?
40,077,854
<p>Currently, I created a method to generate random ip(IPv4) address as below:</p> <pre><code>def rand_ip(mask=False): """This uses the TEST-NET-3 range of reserved IP addresses. """ test_net_3 = '203.0.113.' address = test_net_3 + six.text_type(random.randint(0, 255)) if mask: address = '/...
0
2016-10-17T02:58:49Z
40,078,492
<p>Is this something that you were looking for?</p> <pre><code>&gt;&gt;&gt; from netaddr import * &gt;&gt;&gt; ip = IPNetwork('1.1.2.23/16') &gt;&gt;&gt; ip.ip IPAddress('1.1.2.23') &gt;&gt;&gt; ip.network (IPAddress('1.1.0.0') &gt;&gt;&gt; ip.netmask (IPAddress('255.255.0.0') </code></pre> <p>To randomly generate an...
1
2016-10-17T04:27:16Z
[ "python", "ip", "openstack" ]
Framing an indefinite horizon MDP, cost minimization with must-visit states
40,077,864
<p>Looking for some help in framing a problem of the indefinite horizon, cost minimization, with some must visit states.</p> <p>We are given a budget b and a cost matrix M which represents the deduction for travel between states ( Mij represents the cost for traveling from i to j ), similar to a classic traveling sale...
0
2016-10-17T03:00:57Z
40,078,636
<p>In case your cost matrix contains negative cycles then all the states can be eventually visited. You can use <a href="https://en.wikipedia.org/wiki/Bellman%E2%80%93Ford_algorithm" rel="nofollow">Bellman-Ford</a> to detect the cycles so rest of the answer assumes that no such cycle exists.</p> <p>The algorithm consi...
1
2016-10-17T04:45:10Z
[ "java", "python", "algorithm" ]
Bootstrap accordion with Django: How to only load the data for the open accordion section?
40,077,880
<p>I'm trying to make a webpage that will display recipes in the format of a bootstrap accordion like so (<a href="https://i.stack.imgur.com/1QEbG.png" rel="nofollow">see here</a>). This is how I'm doing it as of now:</p> <pre><code>&lt;div class="panel-group" id="accordion"&gt; {% for recipe in recipes %} &lt...
2
2016-10-17T03:02:22Z
40,077,981
<p>Always better to do that logic before it gets to the template. What if you set the ordering on ingredients so then you won't have to order them in the template? Does that work and improve the performance?</p> <pre><code>class Ingredient(models.Model): ... class Meta: ordering = ['ingredient_name'] &lt;di...
1
2016-10-17T03:15:35Z
[ "python", "django", "twitter-bootstrap", "django-templates", "templatetags" ]
Guessinggame (replace variable issue)
40,077,881
<p>so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to</p> <p>1) prompt the user to enter a guess and store the value in the "guess" variable,<br> 2) if guess is greater than goal print...<br> 3) if guess ...
0
2016-10-17T03:02:35Z
40,077,928
<p>The code is only asking for a guess once before the while loop. You need to update the guess variable inside the while loop by asking for input again.</p>
1
2016-10-17T03:08:43Z
[ "python", "python-3.x" ]
Guessinggame (replace variable issue)
40,077,881
<p>so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to</p> <p>1) prompt the user to enter a guess and store the value in the "guess" variable,<br> 2) if guess is greater than goal print...<br> 3) if guess ...
0
2016-10-17T03:02:35Z
40,078,067
<p>Put this line : </p> <pre><code>inputguess = int(input("Please guess the number: ") </code></pre> <p>inside the while loop. The code is only asking the user input once, user input must be in the loop.</p>
0
2016-10-17T03:26:59Z
[ "python", "python-3.x" ]
Guessinggame (replace variable issue)
40,077,881
<p>so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to</p> <p>1) prompt the user to enter a guess and store the value in the "guess" variable,<br> 2) if guess is greater than goal print...<br> 3) if guess ...
0
2016-10-17T03:02:35Z
40,078,151
<p>Have you read your stack trace in detail? It's very easy to just skim over them, but stack traces can actually provide a lot of very useful information. For instance, the message is probably complaining that it was expecting a closing parenthesis. The line:</p> <pre><code>inputguess = int(input("Please guess the nu...
0
2016-10-17T03:37:51Z
[ "python", "python-3.x" ]
Guessinggame (replace variable issue)
40,077,881
<p>so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to</p> <p>1) prompt the user to enter a guess and store the value in the "guess" variable,<br> 2) if guess is greater than goal print...<br> 3) if guess ...
0
2016-10-17T03:02:35Z
40,078,450
<p>I think you are looking for this. hope this will work. </p> <pre><code>import random goal = random.randint(1,100) guess = 0 print ("The object of this game is to") print ("guess a number between 1 and 100") inputguess = int(input("Please guess the number: ")) while True: if inputguess &gt; goal: ...
1
2016-10-17T04:21:47Z
[ "python", "python-3.x" ]
Guessinggame (replace variable issue)
40,077,881
<p>so doing this for my stage 1 computer science paper. following code is what i've written atm. Line 16 (while statement) is giving a syntax error. The book asks us to</p> <p>1) prompt the user to enter a guess and store the value in the "guess" variable,<br> 2) if guess is greater than goal print...<br> 3) if guess ...
0
2016-10-17T03:02:35Z
40,081,285
<p>So I had someone help me irl and this works perfectly for anyone interested. Thanks everyone for help. :) Appreciate it.</p> <pre><code>goal = random.randint(1,100) guess = 0 print ("The object of this game is to") print ("guess a number between 1 and 100") print() while guess != goal: guess =...
0
2016-10-17T08:03:36Z
[ "python", "python-3.x" ]
Can I use PyQt for both C++ and Python?
40,077,940
<p>I'd like to learn Qt both on Python and C++. I am on Windows.</p> <p>Is instaling PyQT5 with <code>pip3 install pyqt5</code> enough for C++ development or do I still have to install both Qt and PyQt?</p> <p>How do I do the second option?</p>
0
2016-10-17T03:09:59Z
40,078,130
<p>For C++ development you're going to need a C++ compiler. On Windows Qt supports both the Mingw and Visual Studio toolchains. From there, I don't believe pyqt includes the header files you're going to need for C++ development and I cannot say for certain what toolchain it was compiled with. </p> <p>Your best bet is ...
0
2016-10-17T03:35:33Z
[ "python", "c++", "pyqt" ]
Can I use PyQt for both C++ and Python?
40,077,940
<p>I'd like to learn Qt both on Python and C++. I am on Windows.</p> <p>Is instaling PyQT5 with <code>pip3 install pyqt5</code> enough for C++ development or do I still have to install both Qt and PyQt?</p> <p>How do I do the second option?</p>
0
2016-10-17T03:09:59Z
40,140,451
<p>PyQt5 is for developing with Python.</p> <p>If you want to code in C++ the best you do is to download Qt5 and code inside QtCreator.</p> <p>Here is a link for <a href="https://www.qt.io/download-open-source/" rel="nofollow">Qt5 Opensource</a></p>
0
2016-10-19T19:58:59Z
[ "python", "c++", "pyqt" ]
Cropping Python lists by value instead of by index
40,077,966
<p>Good evening, StackOverflow. Lately, I've been wrestling with a Python program which I'll try to outline as briefly as possible. </p> <p>In essence, my program plots (and then fits a function to) graphs. Consider <a href="https://i.stack.imgur.com/axth1.png" rel="nofollow">this graph.</a> The graph plots just fine...
2
2016-10-17T03:13:38Z
40,080,720
<p>If you are working with <code>numpy</code>, you can use it inside the brackets</p> <pre><code>m = x M = x + OrbitalPeriod croppedList = List[m &lt;= List] croppedList = croppedList[croppedList &lt; M] </code></pre>
0
2016-10-17T07:30:33Z
[ "python", "list", "plot", "crop", "slice" ]
TypeErrpr is raised when using `abort(404)`
40,077,971
<p>When I use <code>abort(status_code=404, detail='No such user', passthrough='json')</code> This exception is raised:</p> <p><code>TypeError: 'NoneType' object is not iterable</code> This is the traceback:</p> <pre><code>File "/home/jugger/.virtualenvs/ave/lib/python3.5/site-packages/tg/appwrappers/identity.py", lin...
1
2016-10-17T03:13:56Z
40,094,197
<p>That's something the authentication layer does, whenever is signaled back to the user that authentication is needed the challenger will intervene and force the user to login ( <a href="http://turbogears.readthedocs.io/en/latest/turbogears/authentication.html?highlight=challenger#how-it-works-in-turbogears" rel="nofo...
3
2016-10-17T19:29:06Z
[ "python", "testing", "nose", "turbogears2" ]
python receive image over socket
40,077,980
<p>I'm trying to send an image over a socket - I'm capturing an image on my raspberry pi using pycam, sending to a remote machine for processing, and sending a response back.</p> <p>On the server (the pi), I'm capturing the image, transforming to an array, rearranging to a 1D array and using the tostring() method.</p>...
0
2016-10-17T03:15:25Z
40,078,395
<h1>Decoding to the Proper Type</h1> <p>When you call <code>tostring()</code>, datatype (and shape) information is lost. You must supply numpy with the datatype you expect.</p> <p>Ex:</p> <pre><code>import numpy as np image = np.random.random((50, 50)).astype(np.uint8) image_str = image.tostring() # Works image_de...
1
2016-10-17T04:13:43Z
[ "python", "sockets", "opencv", "raspberry-pi" ]
Global Variable Python
40,077,992
<pre><code>A=[] def main(): global A A=[1,2,3,4,5] b() def b(): if(len(A)&gt;0): A=[7,8,9] else: if(A[3]==4): A.remove(2) main() </code></pre> <p>This code gives error in line A.remove(2) giving reason:"UnboundLocalError: local variable 'A' referenced before assignm...
0
2016-10-17T03:17:12Z
40,078,083
<p>You must declare a variable <code>global</code> in any function that assigns to it.</p> <pre><code>def b(): global A if some_condition: A.append(6) else: A.remove(2) </code></pre> <p>Without declaring <code>A</code> <code>global</code> within the scope of <code>b()</code>, Python assume...
0
2016-10-17T03:28:54Z
[ "python", "list", "python-2.7", "python-3.x", "global-variables" ]
Global Variable Python
40,077,992
<pre><code>A=[] def main(): global A A=[1,2,3,4,5] b() def b(): if(len(A)&gt;0): A=[7,8,9] else: if(A[3]==4): A.remove(2) main() </code></pre> <p>This code gives error in line A.remove(2) giving reason:"UnboundLocalError: local variable 'A' referenced before assignm...
0
2016-10-17T03:17:12Z
40,078,154
<p>The reason you are getting this is because when you performed this assignment in your function: </p> <pre><code>A = [7, 8, 9] </code></pre> <p>The interpreter will now see <code>A</code> as a locally bound variable. So, what will happen now, looking at this condition:</p> <pre><code>if(len(A)&gt;0): </code></pre>...
2
2016-10-17T03:38:17Z
[ "python", "list", "python-2.7", "python-3.x", "global-variables" ]
Flask restful - Exception handling traceback?
40,078,015
<p>I am using Flask Restful to build an API. I have a number of model classes with methods that may raise custom exceptions (for example: AuthFailed exception on my User model class). I am using the custom error handling, documented <a href="http://flask-restful-cn.readthedocs.io/en/0.3.4/extending.html#custom-error-ha...
2
2016-10-17T03:19:43Z
40,078,263
<p>Unfortunately for you, it is handled this way "by design" of the Flask-RESTful APIs <code>errors</code> functionality. The exceptions which are thrown are logged and the corresponding response defined in the <code>errors</code> dict is returned.</p> <p>However, you can change the level of log output by modifying th...
1
2016-10-17T03:55:14Z
[ "python", "flask", "flask-restful" ]
python pandas dataframe - can't figure out how to lookup an index given a value from a df
40,078,107
<p>I have 2 dataframes of numerical data. Given a value from one of the columns in the second df, I would like to look up the index for the value in the first df. More specifically, I would like to create a third df, which contains only index labels - using values from the second to look up its coordinates from the fir...
0
2016-10-17T03:31:45Z
40,078,203
<p>You can build a Series with the indexing the other way around:</p> <pre><code>mapA = pd.Series(data.index, index=data.A) </code></pre> <p>Then <code>mapA[rollmax.ix['j','A']]</code> gives <code>'g'</code>.</p>
1
2016-10-17T03:46:29Z
[ "python", "pandas", "indexing", "dataframe", "lookup" ]
How can I ensure a write has completed in PostgreSQL before releasing a lock?
40,078,164
<p>I have a function on a Django model that calculates a value from a PostgreSQL 9.5 database and, based on the result, determines whether to add data in another row. The function must know the value before adding the row, and future values of the calculation will be dependent on the new row.</p> <p>To enforce these r...
2
2016-10-17T03:39:47Z
40,084,268
<p>I assume it's because of Django's (or middleware's) transaction management , I'm not completely sure, it's better to test it on your code, but it looks for me like: when you try to acquire a lock, Django might start a new transaction, so when you're actually getting lock at <code>cursor.execute(LOCK_SQL, [self._meta...
1
2016-10-17T10:40:33Z
[ "python", "django", "postgresql", "transactions", "locking" ]
Subtracting two cloumns in pandas with lists to create a cummalative column
40,078,181
<p>dataframe conists of set x which is a universal set and subset columm contains of some subsets. I want to choose the subsets with the highest ratios until I covered the full set x. uncovered = setx - subset This is how my dataframe look like in pandas :</p> <pre><code> ratio set x subset ...
0
2016-10-17T03:42:28Z
40,079,246
<p>This should work for you:</p> <pre><code>import pandas as pd # ratio set x subset uncovered # 2 2.00 [1, 3, 6, 8, 9, 0, 7] [8, 3, 6, 1] [0, 9, 7] # 0 1.50 [1, 3, 6, 8, 9, 0, 7] [1, 3, 6] [0, 8, 9, 7] # 1 1.00 [1, 3, 6, 8, 9, 0, 7] [9, 0] [8, 1, 3, ...
0
2016-10-17T05:45:10Z
[ "python", "pandas" ]
Not sure how to fix this error Luhn Algorithm PYTHON
40,078,265
<p>Alright, So I think i'm almost there, my first/second part work perfect when they are on their own, but i'm having trouble combining the two this is what I have so far I'm thinking the error is in the last bit, sorry, im new with python, so i'm hoping to get the hang of it soon</p> <p>Edit3: i've gotten it to work...
2
2016-10-17T03:55:42Z
40,078,374
<p>in the control statements under the comment <code>#Figure out what credit card the user has</code>, the variable <code>cardType</code> is defined in every branch except <code>else</code>. Since the name was never defined outside the scope of the control statement, the interpreter gives you a NameError when you try ...
1
2016-10-17T04:10:18Z
[ "python", "luhn" ]
Pandas dataframe output formatting
40,078,447
<p>I'm importing a trade list and trying to consolidate it into a position file with summed quantities and average prices. I'm grouping based on (ticker, type, expiration and strike). Two questions:</p> <ol> <li>Output has the index group (ticker, type, expiration and strike) in the first column. How can I change t...
0
2016-10-17T04:21:30Z
40,078,574
<p>For the first question, you should use groupby(df.index_col) instead of groupby(df.index)</p> <p>For the second, I am not sure why you couldn't preserve "", is that numeric?</p> <p>I mock some data like below:</p> <pre><code>import pandas as pd ...
0
2016-10-17T04:37:06Z
[ "python", "pandas", "format", "export-to-csv" ]
Combine String in a Dictionary with Similar Key
40,078,508
<p>I am trying to create a new Dictionary based on 3 others dictionary in my python data processing.</p> <p>I have 3 Dictionaries, each with similar ID representing different section in the document.</p> <p>For example</p> <pre><code>dict1 = {'001': 'Dog', '002': 'Cat', '003': 'Mouse'} dict2 = {'001': 'Dog2', '002':...
0
2016-10-17T04:29:21Z
40,078,684
<p>To keep in line with your current approach, and specifically binding the following solution to the fact that you always have three equally length dictionaries, the approach is as such: </p> <p>Iterate using one of the dictionaries, and create a new dictionary that will hold the values as a space separated string. T...
1
2016-10-17T04:51:37Z
[ "python" ]
docopt fails with docopt.DocoptLanguageError: unmatched '['
40,078,516
<p>Why does this code fail with the following exception?</p> <pre><code>"""my_program - for doing awesome stuff Usage: my_program [--foo] Options: --foo - this will do foo """ import docopt args = docopt.docopt(doc=__doc__) </code></pre> <p>Exception:</p> <pre><code>Traceback (most recent call last): File "...
1
2016-10-17T04:30:22Z
40,078,517
<p>It fails because of only a single space after <code>--foo</code> on this line:</p> <pre><code> --foo - this will do foo </code></pre> <p>Fix it by adding another space after <code>--foo</code>:</p> <pre><code> --foo - this will do foo </code></pre> <p><br/> <br/> Per <a href="https://docopt.readthedocs.io...
2
2016-10-17T04:30:22Z
[ "python", "docopt" ]
How to get the key value output from RDD in pyspark
40,078,530
<p>Following is the RDD:</p> <pre><code>[(8, [u'darkness']), (2, [u'in', u'of', u'of', u'of']), (4, [u'book', u'form', u'void', u'upon', u'face', u'deep', u'upon', u'face'])] </code></pre> <p>How do i print the keys and the value length for the above.</p> <p>The output for above should be: (key, no of words in the l...
-1
2016-10-17T04:31:53Z
40,083,820
<p>You can use a <code>map</code> function to create a tuple of the key and number of words in the list:</p> <pre><code>data = sc.parallelize([(8, [u'darkness']), (2, [u'in', u'of', u'of', u'of']), (4, [u'book', u'form', u'void', u'upon', u'face', u'deep', u'upon', u'face'])]) data.map(lambda x:tuple([x[0],len(x[1])]...
0
2016-10-17T10:19:44Z
[ "python", "pyspark", "rdd" ]
Python - Why are some test cases failing?
40,078,532
<p>So I'm working through problems on hackerrank, I am a beginner in python.</p> <p>The information about what I'm trying to dois found here: <a href="https://www.hackerrank.com/challenges/compare-the-triplets?h_r=next-challenge&amp;h_v=zen" rel="nofollow">https://www.hackerrank.com/challenges/compare-the-triplets?h_r...
4
2016-10-17T04:32:08Z
40,078,682
<p>Maybe you need to change varibale name of a1,b1 in your code to some other names.</p> <pre><code>.... a1 = 0 b1 = 0 ... </code></pre> <p>They will remove input a1/b1 as the same name, I don't see why that needed :)</p> <pre><code>a0,a1,a2 = [int(a0),int(a1),int(a2)] b0,b1,b2 = [int(b0),int(b1),int(b2)] </code></p...
3
2016-10-17T04:51:15Z
[ "python" ]
Python - Why are some test cases failing?
40,078,532
<p>So I'm working through problems on hackerrank, I am a beginner in python.</p> <p>The information about what I'm trying to dois found here: <a href="https://www.hackerrank.com/challenges/compare-the-triplets?h_r=next-challenge&amp;h_v=zen" rel="nofollow">https://www.hackerrank.com/challenges/compare-the-triplets?h_r...
4
2016-10-17T04:32:08Z
40,078,722
<p>I find 2 issues in this. 1. variable names are same. Notice a1 in list and and a1 as a separate Variable. 2. Instead of print you can use '{0} {1}'.format(a1,b1) Also I would suggest using raw_input() instead of input(), that will help your input treated as a string.</p>
4
2016-10-17T04:56:31Z
[ "python" ]
Webscraping with Python ( beginner)
40,078,536
<p>I'm doing the first example of the webscrapping tutorial from the book "Automate the Boring Tasks with Python". The project consists of typing a search term on the command line and have my computer automatically open a browser with all the top search results in new tabs</p> <p>It mentions that I need to locate the ...
2
2016-10-17T04:32:19Z
40,078,640
<p>This will work for you : </p> <pre><code>&gt;&gt;&gt; import requests &gt;&gt;&gt; from lxml import html &gt;&gt;&gt; r = requests.get("https://www.google.co.uk/search?q=how+to+do+web+scraping&amp;num=10") &gt;&gt;&gt; source = html.fromstring((r.text).encode('utf-8')) &gt;&gt;&gt; links = source.xpath('//h3[@class...
1
2016-10-17T04:45:49Z
[ "python", "web-scraping" ]
Print string without a certain word?
40,078,569
<p>So, if I have code like this:</p> <pre><code>a = ["a", "b", "c", "null"] print a </code></pre> <p>The number of <code>"null"</code>s varies in the output quite a lot for some reason. How could I print <code>a</code> without the <code>"null"</code>?</p>
0
2016-10-17T04:36:22Z
40,078,597
<p>A simple way to filter your list is using list comprehension:</p> <pre><code>print([x for x in a if x != "null"]) </code></pre>
2
2016-10-17T04:39:56Z
[ "python", "python-2.7", "printing" ]
Print string without a certain word?
40,078,569
<p>So, if I have code like this:</p> <pre><code>a = ["a", "b", "c", "null"] print a </code></pre> <p>The number of <code>"null"</code>s varies in the output quite a lot for some reason. How could I print <code>a</code> without the <code>"null"</code>?</p>
0
2016-10-17T04:36:22Z
40,078,600
<p>Just iterate through your list to print out everything that does not equal to "null"</p> <pre><code>a = ["a", "b", "c", "null"] for data in a: if data != "null": print(data) </code></pre> <p>If you were looking to filter out data you don't want in your data structure, however, then, the easiest way t...
2
2016-10-17T04:40:22Z
[ "python", "python-2.7", "printing" ]
Print string without a certain word?
40,078,569
<p>So, if I have code like this:</p> <pre><code>a = ["a", "b", "c", "null"] print a </code></pre> <p>The number of <code>"null"</code>s varies in the output quite a lot for some reason. How could I print <code>a</code> without the <code>"null"</code>?</p>
0
2016-10-17T04:36:22Z
40,078,802
<p>@m1ksu , I just saw above you asking for a function : see below</p> <pre><code>a = ["a", "b", "c", "null"] def remove_null(self): return [x for x in self if x != "null"] asd = remove_null(a) print asd </code></pre> <p>output </p> <pre><code>['a', 'b', 'c'] </code></pre>
0
2016-10-17T05:04:55Z
[ "python", "python-2.7", "printing" ]
Print string without a certain word?
40,078,569
<p>So, if I have code like this:</p> <pre><code>a = ["a", "b", "c", "null"] print a </code></pre> <p>The number of <code>"null"</code>s varies in the output quite a lot for some reason. How could I print <code>a</code> without the <code>"null"</code>?</p>
0
2016-10-17T04:36:22Z
40,081,791
<p>I get the impression that you wish to convert the list to a string with a function and display each data element on a separate line without null being included. So, here's what I suggest:</p> <pre><code># remove null and convert list to string with function # and display results on separate lines a = ["a", "b",...
0
2016-10-17T08:35:16Z
[ "python", "python-2.7", "printing" ]
Grouping by almost similar strings
40,078,596
<p>I have a dataset with city names and counts of crimes. The data is dirty such that a name of a city for example 'new york', is written as 'newyork', 'new york us', 'new york city', 'manhattan new york' etc. How can I group all these cities together and sum their crimes?</p> <p>I tried the 'difflib' package in pytho...
1
2016-10-17T04:39:28Z
40,078,773
<p>Maybe this might help:</p> <p><a href="http://chairnerd.seatgeek.com/fuzzywuzzy-fuzzy-string-matching-in-python/" rel="nofollow">http://chairnerd.seatgeek.com/fuzzywuzzy-fuzzy-string-matching-in-python/</a></p> <p>Another way: if a string contains 'new' and 'york', then label it 'new york city'. </p> <p>Another w...
1
2016-10-17T05:01:46Z
[ "python", "pandas" ]
Grouping by almost similar strings
40,078,596
<p>I have a dataset with city names and counts of crimes. The data is dirty such that a name of a city for example 'new york', is written as 'newyork', 'new york us', 'new york city', 'manhattan new york' etc. How can I group all these cities together and sum their crimes?</p> <p>I tried the 'difflib' package in pytho...
1
2016-10-17T04:39:28Z
40,080,818
<p>Another approach is to go through each entry and strip the white space and see if they contain a base city name. For example 'newyork', 'new york us', 'new york city', 'manhattan new york' when stripped of white space would be 'newyork', 'newyorkus', 'newyorkcity', 'manhattannewyork', which all contain the word 'new...
0
2016-10-17T07:36:22Z
[ "python", "pandas" ]
Finding and extracting multiple substrings in a string?
40,078,607
<p>After looking <a href="http://stackoverflow.com/questions/11886815/pull-a-specific-substring-out-of-a-line-in-python">a</a> <a href="http://gis.stackexchange.com/questions/4748/python-question-how-do-i-extract-a-part-of-a-string">few</a> <a href="http://stackoverflow.com/questions/6633678/finding-words-after-keyword...
1
2016-10-17T04:41:15Z
40,078,659
<p>Leverage (zero width) lookarounds:</p> <pre><code>(?&lt;!\w)PG|SG|SF|PF|C(?!\w) </code></pre> <ul> <li><p><code>(?&lt;!\w)</code> is zero width negative lookbehind pattern, making sure the desired match is not preceded by any alphanumerics</p></li> <li><p><code>PG|SG|SF|PF|C</code> matches any of the desired patte...
2
2016-10-17T04:48:29Z
[ "python", "regex", "string", "substring" ]
Finding and extracting multiple substrings in a string?
40,078,607
<p>After looking <a href="http://stackoverflow.com/questions/11886815/pull-a-specific-substring-out-of-a-line-in-python">a</a> <a href="http://gis.stackexchange.com/questions/4748/python-question-how-do-i-extract-a-part-of-a-string">few</a> <a href="http://stackoverflow.com/questions/6633678/finding-words-after-keyword...
1
2016-10-17T04:41:15Z
40,078,687
<p>heemayl's response is the most correct, but you could probably get away with splitting on commas and keeping only the last two (or in the case of 'C', the last) characters in each substring.</p> <pre><code>s = 'Chi\xa0SG, SF\xa0\xa0DTD' fin = list(map(lambda x: x[-2:] if x != 'C' else x[-1:],s.split(','))) </code><...
0
2016-10-17T04:52:03Z
[ "python", "regex", "string", "substring" ]
Playing video in Gtk in a window with a menubar
40,078,718
<p>I have created a video player in Gtk3 using Gstreamer in Python3. It works except when I add a GtkMenuBar (place 2). It will then either show a black screen, or fail with an exception. The exception references the <code>XInitThreads</code>, which I am calling (Place 1) (I took this from the pitivi project) but this ...
2
2016-10-17T04:56:23Z
40,099,230
<p>When searching through documentation on a separate issue, I came across a reference to the <code>gtksink</code> widget. This seems to be the correct way to put video in a gtk window, but unfortunately none of the tutorials on this use it.</p> <p>Using the <code>gtksink</code> widget fixes all the problems and great...
0
2016-10-18T03:55:21Z
[ "python", "gstreamer", "gtk3", "xlib" ]
Tkinter - Grid elements next to each other
40,078,748
<p>I'm trying to make some UI in python with tkinter.</p> <p>This is a sample of the code I'm using:</p> <pre><code>root = Tk() root.geometry("1000x700x0x0") canvas = Canvas(root, width = 700, height = 700, bg ='white').grid(row = 0, column = 0) button1 = Button(root, text = "w/e", command = w/e).grid(row = 0, colum...
1
2016-10-17T04:59:29Z
40,089,035
<p>Since your GUI seems to have two logical groups of widgets, I would organize it as such. Start by placing the canvas on the left and a frame on the right. You can use <code>pack</code>, <code>place</code>, <code>grid</code>, or a paned window to manage them. For a left-to-right orientation, <code>pack</code> is a go...
2
2016-10-17T14:27:27Z
[ "python", "tkinter" ]
How to display equation and R2 of a best fit 3D plane?
40,078,921
<p>I have created a 3D plane as the best fit on 3D plot using python. Can someone help me to display the equation of the plane and the R2 of the plane?</p>
-1
2016-10-17T05:16:31Z
40,092,705
<p>r2 is 1.0 - [(absolute error variance] / [dependent data variance])</p> <p>With numpy this is simple, like so:</p> <p>err = numpy.array(absolute error)</p> <p>Z = numpy.array(Z of "XYZ" data)</p> <p>r2 = 1.0 - (err.var() / Z.var())</p> <p>To draw the surface you have to calculate a grid to display. Matplotlib...
0
2016-10-17T17:52:57Z
[ "python", "curve-fitting" ]
Regex for capital letters followed be a space folllowed by numbers 'ABC 123' or 'BLZ 420'
40,079,232
<p>So I have this script that identifies <code>ABC-123</code></p> <pre><code>e = r'[A-Z]+-\d+' </code></pre> <p>shouldn't this identify <code>ABC 123</code></p> <pre><code>e = r'[A-Z]+/s\d+' </code></pre> <p>Or am I missing something blindingly obvious. Thanks. This is in Python as well. </p>
0
2016-10-17T05:44:05Z
40,079,249
<p>You have the wrong slash, you need a backslash:</p> <pre><code>e = r'[A-Z]+\s\d+' </code></pre> <p><code>/s</code> will match <code>/</code> followed by a <code>s</code> literally, whereas <code>\s</code> is a Regex token that indicates a whitespace.</p>
5
2016-10-17T05:45:21Z
[ "python", "regex" ]
How do I pass in an argument to a list of lambdas?
40,079,240
<p>Intent: I'm trying to return each dictionary that contains the passed in matching keywords and values within a list of dictionaries. For example, <code>a='woot', e='1', c='duh'</code> would return only</p> <pre><code>{'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'} </code></pre> <p>This is what I hav...
0
2016-10-17T05:44:27Z
40,079,423
<pre><code>def get_matched_lines(input_dict, array): output=[] keys=[] values=[] for a in array: keyvalue = a.split("=") keys.append(keyvalue[0]) values.append(keyvalue[1]) for dict in input_dict: bool=1 for i in range(0,len(keys)): if keys[i] ...
0
2016-10-17T06:00:48Z
[ "python", "lambda", "filtering", "list-comprehension" ]
How do I pass in an argument to a list of lambdas?
40,079,240
<p>Intent: I'm trying to return each dictionary that contains the passed in matching keywords and values within a list of dictionaries. For example, <code>a='woot', e='1', c='duh'</code> would return only</p> <pre><code>{'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'} </code></pre> <p>This is what I hav...
0
2016-10-17T05:44:27Z
40,079,502
<p>You can do this (in Python 2.7):</p> <pre><code>def get_matched_lines(input_dict, **param): return [dic for dic in input_dict if all([key in dic and dic[key] == val for key, val in param.iteritems()])] </code></pre> <p>The same code in Python 3 is</p> <pre><code>def get_matched_lines(input_dict, **param): ...
3
2016-10-17T06:08:09Z
[ "python", "lambda", "filtering", "list-comprehension" ]
How do I pass in an argument to a list of lambdas?
40,079,240
<p>Intent: I'm trying to return each dictionary that contains the passed in matching keywords and values within a list of dictionaries. For example, <code>a='woot', e='1', c='duh'</code> would return only</p> <pre><code>{'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'} </code></pre> <p>This is what I hav...
0
2016-10-17T05:44:27Z
40,079,924
<p>I think you don't have to use lambda here... basic for loop is enough...</p> <p>Concept is simple as the following: If all the keys and values in param belongs and equals to the input_dict, it returns the whole dictionary row which you want to return. If at least a key can't be found or a value isn't the same, retu...
0
2016-10-17T06:38:18Z
[ "python", "lambda", "filtering", "list-comprehension" ]
How to add an unspecified amount of variables together?
40,079,400
<p>I'm trying to add in python 3.5.2 but I have an unspecified amount of variables. I have to use very basic functions; I can't use <code>list</code>. I can't figure out how I'm supposed to add each new variable together without a <code>list</code>. When I run the code it adds the last entered <code>price1</code> which...
0
2016-10-17T05:59:41Z
40,079,477
<p>Keep another variable around and sum than up, also, <code>count</code> isn't used for anything so no real reason to keep it around. </p> <p>For example, initialize a <code>price</code> name to <code>0</code>:</p> <pre><code>price = 0 </code></pre> <p>then, check if the value is <code>-1</code> and, if not, simply...
3
2016-10-17T06:05:09Z
[ "python", "python-2.7", "python-3.x" ]
How to add an unspecified amount of variables together?
40,079,400
<p>I'm trying to add in python 3.5.2 but I have an unspecified amount of variables. I have to use very basic functions; I can't use <code>list</code>. I can't figure out how I'm supposed to add each new variable together without a <code>list</code>. When I run the code it adds the last entered <code>price1</code> which...
0
2016-10-17T05:59:41Z
40,079,515
<p>You almost had it. Looking at your code, what I would suggest you do is create a <code>subtotal</code> variable just outside of your loop and initialize it to <code>0</code>. Furthermore, you are not using <code>count</code> for anything, so get rid of that.</p> <p>When you get your <code>price</code> input, check ...
2
2016-10-17T06:09:27Z
[ "python", "python-2.7", "python-3.x" ]
No JSON object could be decoded - Django request.body
40,079,504
<p>I am making web service for posting comments from smart phone, Below is my code </p> <pre><code>@api_view(['POST']) def comment_post(request,newsId=None): data = json.loads(request.body) responseData= dict({ "result": list() }) if(newsId): commentNews = models.Comments.objects.cre...
0
2016-10-17T06:08:15Z
40,079,738
<p>I guess, You are using <code>django-rest-framework</code>. So, You don't have to do <code>json.loads()</code>, becasue <code>django-rest-framework</code> provides <code>request.data</code> for <code>POST</code> requests and <code>request.query_params</code> for <code>GET</code> requests, <strong>already parsed in js...
2
2016-10-17T06:24:46Z
[ "python", "json", "django", "python-2.7" ]
Process data from several text files
40,079,612
<p>Any recommendation on how I can grab data from several text files and process them (compute totals for example). I have been trying to do it in Python but keep on encountering dead ends.</p> <p>A machine generates a summary file in text format each time you do an operation, for this example, screening good apples f...
-2
2016-10-17T06:16:45Z
40,082,963
<p>The following should help get you started. As your text files are fixed format, it is relatively simple to read them in and parse them. This script searches for all text files in the current folder, reads each file in and stores the batches in a dictionary based on the batch name so that all batches of the same name...
1
2016-10-17T09:36:35Z
[ "python", "scripting" ]
Get models ordered by an attribute that belongs to its OneToOne model
40,079,728
<p>Let's say there is one model named <code>User</code> and the other named <code>Pet</code> which has a <code>OneToOne</code> relationship with <code>User</code>, the <code>Pet</code> model has an attribute <code>age</code>, how to get the ten <code>User</code> that owns the top ten <code>oldest</code> dog?</p> <pre>...
3
2016-10-17T06:24:09Z
40,079,772
<p>Use the double-underscore syntax.</p> <pre><code>User.objects.order_by('-pet__age')[:10] </code></pre> <p><strong>Edit</strong></p> <p>To get the ten friends of Tom, you can get the instance and filter:</p> <pre><code>User.objects.get(name='Tom').friends.order_by('-pet__age')[:10] </code></pre> <p>or if you alr...
6
2016-10-17T06:27:14Z
[ "python", "django", "python-3.x" ]
Get models ordered by an attribute that belongs to its OneToOne model
40,079,728
<p>Let's say there is one model named <code>User</code> and the other named <code>Pet</code> which has a <code>OneToOne</code> relationship with <code>User</code>, the <code>Pet</code> model has an attribute <code>age</code>, how to get the ten <code>User</code> that owns the top ten <code>oldest</code> dog?</p> <pre>...
3
2016-10-17T06:24:09Z
40,080,190
<p>Try this : First define <strong>unicode</strong> in model User like this: By this,User model objects will always return name field of the user records.</p> <pre><code> class User(models.Model): name = models.CharField(max_length=50, null=False, blank=False) friends = models.ManyToManyField(self, ...) d...
0
2016-10-17T06:56:41Z
[ "python", "django", "python-3.x" ]
Get models ordered by an attribute that belongs to its OneToOne model
40,079,728
<p>Let's say there is one model named <code>User</code> and the other named <code>Pet</code> which has a <code>OneToOne</code> relationship with <code>User</code>, the <code>Pet</code> model has an attribute <code>age</code>, how to get the ten <code>User</code> that owns the top ten <code>oldest</code> dog?</p> <pre>...
3
2016-10-17T06:24:09Z
40,082,910
<p>Another solution (alternative to <code>order_by</code>) is using <code>nlargest</code> function of <code>heapq</code> module, this might be better if you already have <code>friends</code> list (tom's friends in this case) with a large number of items (I mean from performance perspective).</p> <pre><code>import heap...
0
2016-10-17T09:33:38Z
[ "python", "django", "python-3.x" ]
Adding multiple key,value pair using dictionary comprehension
40,079,792
<p>for a list of dictionaries</p> <pre><code>sample_dict = [ {'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'}, {'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'}, {'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'}, {'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'}, {'...
1
2016-10-17T06:28:48Z
40,079,875
<p>You are generating multiple key-value pairs with the same key, and a dictionary will only ever store <em>unique</em> keys.</p> <p>If you wanted just <em>one</em> key, you'd use a dictionary with a list comprehension:</p> <pre><code>container = {'a': [s['a'] for s in sample_dict if 'a' in s]} </code></pre> <p>Note...
4
2016-10-17T06:35:13Z
[ "python" ]
Adding multiple key,value pair using dictionary comprehension
40,079,792
<p>for a list of dictionaries</p> <pre><code>sample_dict = [ {'a': 'woot', 'b': 'nope', 'c': 'duh', 'd': 'rough', 'e': '1'}, {'a': 'coot', 'b': 'nope', 'c': 'ruh', 'd': 'rough', 'e': '2'}, {'a': 'doot', 'b': 'nope', 'c': 'suh', 'd': 'rough', 'e': '3'}, {'a': 'soot', 'b': 'nope', 'c': 'fuh', 'd': 'rough', 'e': '4'}, {'...
1
2016-10-17T06:28:48Z
40,080,007
<p>Another option:</p> <pre><code>filter = lambda arr, x: { x: [ e.get(x) for e in arr] } </code></pre> <p>So, from here, you can construct the dict based on the original array and the key </p> <pre><code> filter(sample_dict, 'a') # {'a': ['woot', 'coot', 'doot', 'soot', 'toot']} </code></pre>
-1
2016-10-17T06:44:08Z
[ "python" ]
django 3.5 makemessages refers to previous virtual env
40,079,837
<p>I am running django 1.10 with python 3.5 on windows 7 and I am trying to translate my test files.</p> <p>I have created the es language directory in the locale directory.</p> <p>In the virtual environment, at the command prompt I enter: <code>python manage.py makemessages --locale=es</code></p> <p>I get the follo...
0
2016-10-17T06:32:03Z
40,083,793
<p>Maybe there is a character even if you don't see it. Try pasteing in notepad++ the text (sometimes it helps to detect wrong chars) or try to delete/rewrite close newlines, tabs, or similar symbols just in case they came from a copy/paste from a file with different coding.</p>
0
2016-10-17T10:18:16Z
[ "python", "django", "translation" ]
django 3.5 makemessages refers to previous virtual env
40,079,837
<p>I am running django 1.10 with python 3.5 on windows 7 and I am trying to translate my test files.</p> <p>I have created the es language directory in the locale directory.</p> <p>In the virtual environment, at the command prompt I enter: <code>python manage.py makemessages --locale=es</code></p> <p>I get the follo...
0
2016-10-17T06:32:03Z
40,095,167
<p>This error was due to an old virtual environment folder that was on my system. I have deleted this folder, and a new error now displays. I have posted a different thread for the new error.</p>
0
2016-10-17T20:33:07Z
[ "python", "django", "translation" ]
inheritance using parent class method without calling parent class
40,079,985
<p>Is there any way to access parent class method, without actually calling the class?</p> <p>e.g.:</p> <p>1)</p> <pre><code>class A(): def __init__(self): print('A class') def name(): print('name from A class') </code></pre> <p>2)</p> <pre><code>class B(A): # I want to make use of nam...
1
2016-10-17T06:42:29Z
40,080,038
<p>Yeah, you can just call it directly. This works fine:</p> <pre><code>class A(): def __init__(self): print('A class') def name(self): print('name from A class') class B(A): pass B().name() &gt; A class &gt; name from A class </code></pre> <p>You can also use it inside of the class, l...
2
2016-10-17T06:46:12Z
[ "python", "inheritance" ]
I have two text files which contains same data but in different columns and different rows
40,080,102
<p>Example: First file.txt:</p> <pre><code>a | b | c | d 0 | 1 | 2 | 3 4 | 5 | 6 | 7 </code></pre> <p>Second file.txt</p> <pre><code>c | b | d | a 6 | 5 | 7 | 4 2 | 1 | 3 | 0 </code></pre> <p>Suggest me some easy way to populate and compare the values.</p>
-2
2016-10-17T06:50:51Z
40,081,494
<p>I would suggest saving them as <code>csv</code> files but text will work as well as long as you specify the correct separator. </p> <pre><code>import pandas as pd df1 = pd.read_csv('text1.csv', sep=',') df2 = pd.read_csv('text2.csv', sep=',') </code></pre> <p>you can then sort the columns</p> <pre><code>df1 = df1...
0
2016-10-17T08:16:37Z
[ "python" ]
Adding a seed to my program (Word Letter Scramble)
40,080,156
<p>I am having trouble figuring out how to add a seed to my program. It is supposed to be able take a given seed value and return a scrambled sentence. The first and last letters in a words should stay the same as well as ending punctuation. Any punctuation within a word is allowed to be scrambled. </p> <pre><code>imp...
0
2016-10-17T06:54:05Z
40,080,275
<p>To add a seed to the program, with 0 being a random seed, you would need to call <code>random.seed()</code> to your program as so:</p> <pre><code>seed = int(input("Enter a seed (0 for random): ")) if seed is not 0: random.seed(seed) </code></pre> <p>Pretty simple.</p> <p>See the Python docs for more info: <...
2
2016-10-17T07:02:31Z
[ "python", "python-3.x" ]
Change RGB color in matplotlib animation
40,080,248
<p>I seems that it is not possible to change colors of a Matplotlib scatter plot through a RGB definition. Am I wrong?</p> <p>Here is a code (already given in stack overflow) which work with colors indexed in float:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import matplotlib.animation as anima...
0
2016-10-17T07:00:59Z
40,083,831
<p>Not sure what you are trying to achieve. But if you are trying to change the color, why not use the <code>set_color()</code> function of <code>Collection</code>?</p> <pre><code>def update_plot2(i,data,scat): data[ i%10 ] = np.random.random((3)) scat.set_color(data) # &lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;...
0
2016-10-17T10:20:14Z
[ "python", "matplotlib", "colors" ]
Find combinations with arrays and a combination pattern
40,080,263
<p>I have arrays such as these, and each pattern designates a combination shape with each number representing the size of the combination.</p> <ul> <li>pattern 0: <code>[1, 1, 1, 1]</code></li> <li>pattern 1: <code>[2, 1, 1]</code></li> <li>pattern 2: <code>[3, 1]</code></li> <li>pattern 3: <code>[4]</code></li> <li>....
2
2016-10-17T07:01:50Z
40,083,720
<p>You can use recursive function that takes the first number in pattern and generates all the combinations of that length from remaining items. Then recurse with remaining pattern &amp; items and generated prefix. Once you have consumed all the numbers in pattern just <code>yield</code> the prefix all the way to calle...
1
2016-10-17T10:14:25Z
[ "python", "combinations", "permutation" ]
Get column names (title) from a Vertica data base?
40,080,375
<p>I'm trying to extract the column names when pulling data from a vertica data base in python via an sql query. I am using vertica-python 0.6.8. So far I am creating a dictionary of the first line, but I was wondering if there is an easier way of doing it. This is how I am doing it right now:</p> <pre><code>import ve...
1
2016-10-17T07:08:41Z
40,084,238
<p>If I am not wrong you are asking about the title of each column. You can do that by using data descriptors of "class hp_vertica_client.cursor". It can be found here : <a href="https://my.vertica.com/docs/7.2.x/HTML/Content/python_client/cursor.html" rel="nofollow">https://my.vertica.com/docs/7.2.x/HTML/Content/pytho...
0
2016-10-17T10:39:11Z
[ "python", "vertica" ]
Get column names (title) from a Vertica data base?
40,080,375
<p>I'm trying to extract the column names when pulling data from a vertica data base in python via an sql query. I am using vertica-python 0.6.8. So far I am creating a dictionary of the first line, but I was wondering if there is an easier way of doing it. This is how I am doing it right now:</p> <pre><code>import ve...
1
2016-10-17T07:08:41Z
40,091,918
<p>Two ways: </p> <p>First, you can just access the dict's keys if you want the column list, this is basically like what you have, but shorter:</p> <pre><code>ColumnList = temp[0].keys() </code></pre> <p>Second, you can access the cursor's field list, which I think is what you are really looking for: </p> <pre><cod...
1
2016-10-17T17:02:04Z
[ "python", "vertica" ]
How can I select the "Sort By" element through Selenium Webdriver Python
40,080,506
<p>I was trying to automate one task using Selenium Webdriver with Python 2.7.The task goes as follows: 1. Open "<a href="https://www.flipkart.com" rel="nofollow">https://www.flipkart.com</a>". 2. Search for 'laptop'. 3. Hit search button. 4. Whatever is the answer of the search query, sort them "By Popularity" using t...
0
2016-10-17T07:17:46Z
40,080,695
<p>As far as syntax error goes replace <code>////</code> with <code>//</code> in your xpath</p> <p><code>driver.find_element_by_xpath("//*@id='container']/div/div[2]/div[2]/div/div[2]/div[2]/div/section/ul/li[2]").click() </code></p> <p>This will resolve your syntax error and will do the required job Though In my opi...
1
2016-10-17T07:29:05Z
[ "python", "selenium", "xpath" ]
How can I select the "Sort By" element through Selenium Webdriver Python
40,080,506
<p>I was trying to automate one task using Selenium Webdriver with Python 2.7.The task goes as follows: 1. Open "<a href="https://www.flipkart.com" rel="nofollow">https://www.flipkart.com</a>". 2. Search for 'laptop'. 3. Hit search button. 4. Whatever is the answer of the search query, sort them "By Popularity" using t...
0
2016-10-17T07:17:46Z
40,080,716
<p>you can use following code.</p> <pre><code>from selenium import webdriver import time url="https://www.flipkart.com" xpaths={'submitButton' : "//button[@type='submit']", 'searchBox' : "//input[@type='text']"} driver=webdriver.Chrome() # driver.maxmimize_window() driver.get(url) #to search for laptops dri...
0
2016-10-17T07:30:21Z
[ "python", "selenium", "xpath" ]
How can I select the "Sort By" element through Selenium Webdriver Python
40,080,506
<p>I was trying to automate one task using Selenium Webdriver with Python 2.7.The task goes as follows: 1. Open "<a href="https://www.flipkart.com" rel="nofollow">https://www.flipkart.com</a>". 2. Search for 'laptop'. 3. Hit search button. 4. Whatever is the answer of the search query, sort them "By Popularity" using t...
0
2016-10-17T07:17:46Z
40,080,774
<p>You may try with this css selector too:</p> <pre><code>#container &gt; div &gt; div:nth-child(2) &gt; div:nth-child(2) &gt; div &gt; div:nth-child(2) &gt; div:nth-child(2) &gt; div &gt; section &gt; ul &gt; li:nth-child(2) </code></pre> <p>To me, cssSelector is better than xpath for browser compatibility too.</...
0
2016-10-17T07:33:49Z
[ "python", "selenium", "xpath" ]
For-loop with range is only taking the last element
40,080,593
<p>I have a 2D array of strings from which I delete certain elements (those containing the '#' char). When I print <code>lista</code> from inside the loop, it prints this: </p> <pre><code>['call', '_imprimirArray'] ['movl', '24', '%2', '%3'] ['movl', '%1', '%2'] ['call', '_buscarMayor'] ['movl', '%1', '4', '%3'] ['mov...
1
2016-10-17T07:22:56Z
40,080,736
<p>You're appending the same row many times to <code>temp</code> while just removing items from it on each iteration. Instead of <code>del lista[:]</code> just assign a new list to the variable: <code>lista = []</code> so that content in previously added rows doesn't get overwritten.</p> <p>Effectively you're doing fo...
4
2016-10-17T07:31:16Z
[ "python", "arrays", "list", "python-3.x", "multidimensional-array" ]
For-loop with range is only taking the last element
40,080,593
<p>I have a 2D array of strings from which I delete certain elements (those containing the '#' char). When I print <code>lista</code> from inside the loop, it prints this: </p> <pre><code>['call', '_imprimirArray'] ['movl', '24', '%2', '%3'] ['movl', '%1', '%2'] ['call', '_buscarMayor'] ['movl', '%1', '4', '%3'] ['mov...
1
2016-10-17T07:22:56Z
40,080,839
<p>Adding to niemmi's answer, what you need to do is:</p> <pre><code> for i in range(0, len(programa)): lista = [] # creates a new empty list object alltogether ... </code></pre> <p>instead of</p> <pre><code> for i in range(0, len(programa)): del lista[:]; # only clears the content, the...
1
2016-10-17T07:37:35Z
[ "python", "arrays", "list", "python-3.x", "multidimensional-array" ]
How can I transfer a compiled tuple(rawly taken from Sql) in to a array, series, or a dataframe?
40,080,636
<ol> <li><p>What I have is like this:</p> <pre><code>(('3177000000000053', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 36, 42)), ('3177000000000035', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 37, 6 ))) </code></pre></li> </ol> <p>It is exactly the way it looks in mysql database.</p> <ol sta...
1
2016-10-17T07:25:48Z
40,081,054
<p>In case you have tuple of tuples you may try the following list comprehension</p> <pre><code>import datetime input_tuple = (('3177000000000053', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 36, 42)), ('3177000000000035', '8018000000000498', datetime.datetime(2016, 9, 29, 21, 37, 6 ))) output_list = [[i...
0
2016-10-17T07:51:04Z
[ "python", "mysql" ]
Understanding Inheritance in python
40,080,783
<p>I am learning OOP in python.</p> <p>I am struggling why this is not working as I intended?</p> <pre><code>class Patent(object): """An object to hold patent information in Specific format""" def __init__(self, CC, PN, KC=""): self.cc = CC self.pn = PN self.kc = KC class USPatent(Pat...
2
2016-10-17T07:34:11Z
40,080,877
<pre><code>class USPatent(Patent): """"Class for holding information of uspto patents in Specific format""" def __init__(self, CC, PN, KC=""): Patent.__init__(self, CC, PN, KC="") </code></pre> <p>Here you pass <code>KC</code>as <code>""</code> by coding <code>KC=""</code>, instead of <code>KC=KC</code...
1
2016-10-17T07:39:42Z
[ "python", "inheritance" ]