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 |
|---|---|---|---|---|---|---|---|---|---|
Removing List from List of Lists with condition | 39,381,769 | <p>I have this list of projects, and I want to remove it one by one start from last item to item-n until it reach some total value of budget = 325.000</p>
<pre><code>from collections import namedtuple
Item = namedtuple('Item', 'region sector name budget target performance'.split())
sorted_KP = [Item(region='H', sect... | 3 | 2016-09-08T02:39:17Z | 39,383,320 | <p>I couldn't easily sort through your code. <code>if counter_R_el >= 1 or counter_S_el >= 1:</code> just can't work, you can't compare a Counter() to an int(). It also looks like you continually remake/reset <em>things</em> in your loop suite and it became confusing.</p>
<p>You seem to be on the right track.<... | 0 | 2016-09-08T05:41:33Z | [
"python",
"list",
"condition"
] |
Removing List from List of Lists with condition | 39,381,769 | <p>I have this list of projects, and I want to remove it one by one start from last item to item-n until it reach some total value of budget = 325.000</p>
<pre><code>from collections import namedtuple
Item = namedtuple('Item', 'region sector name budget target performance'.split())
sorted_KP = [Item(region='H', sect... | 3 | 2016-09-08T02:39:17Z | 39,386,444 | <p>Assume that you are using Python 2 as you use <code>print</code> without <code>()</code>.</p>
<p>See the comments in the modified code:</p>
<pre><code>unpack = []
for item in sorted_KP[::-1]: # loop the items in reverse order
#item_budget = item[3] # variable not used
sum_unpack = sum(item[3] for item in u... | 1 | 2016-09-08T08:47:01Z | [
"python",
"list",
"condition"
] |
Python How to use global verables and DRY | 39,381,845 | <p>So I have finally got my base class set up nicely and ready to build a class to test. However when I started buildign this I noticed that I had to repeat myself Lot with setting everything to global</p>
<p>the start() event is called to set up everything
Update() is called every tick (20 ticks a sec)</p>
<p>Is the... | 1 | 2016-09-08T02:49:11Z | 39,381,886 | <p><strong>Replace global variables</strong></p>
<p>example:</p>
<pre><code> global obj1;
obj1 = ChildClassA('Obj1'); => self.obj1 = ChildClassA('Obj1');
</code></pre>
| 1 | 2016-09-08T02:55:00Z | [
"python",
"global-variables",
"dry"
] |
Python How to use global verables and DRY | 39,381,845 | <p>So I have finally got my base class set up nicely and ready to build a class to test. However when I started buildign this I noticed that I had to repeat myself Lot with setting everything to global</p>
<p>the start() event is called to set up everything
Update() is called every tick (20 ticks a sec)</p>
<p>Is the... | 1 | 2016-09-08T02:49:11Z | 39,381,889 | <p>Don't use global variables. You're literally not using self at all. Move all your shared state to <code>self</code>. That's what it's for. Don't use global variables.</p>
| 0 | 2016-09-08T02:55:08Z | [
"python",
"global-variables",
"dry"
] |
float object has no attribute __getitem__ [Looked elsewhere but haven't been able to find anything applicable] | 39,381,895 | <p>Here is the data frame i'm working with:</p>
<pre><code> patient_id marker_1 marker_2 subtype patient_age patient_gender
0 619681 21.640523 144.001572 0.0 3 female
1 619711 13.787380 162.408932 0.0 15 female
2 619595 22.675580 130.2272... | 3 | 2016-09-08T02:55:45Z | 39,382,171 | <p>With children being your dataframe, I think if you use:</p>
<pre><code>children.describe()
</code></pre>
<p>or</p>
<pre><code>children.describe().transpose()
</code></pre>
<p>You will save yourself some time.</p>
| 1 | 2016-09-08T03:31:24Z | [
"python",
"pandas",
"dataframe"
] |
float object has no attribute __getitem__ [Looked elsewhere but haven't been able to find anything applicable] | 39,381,895 | <p>Here is the data frame i'm working with:</p>
<pre><code> patient_id marker_1 marker_2 subtype patient_age patient_gender
0 619681 21.640523 144.001572 0.0 3 female
1 619711 13.787380 162.408932 0.0 15 female
2 619595 22.675580 130.2272... | 3 | 2016-09-08T02:55:45Z | 39,382,175 | <pre><code>np.mean
</code></pre>
<p>Sums entire dataframe and returns float</p>
<p>Use</p>
<pre><code>children.mean()
</code></pre>
| 2 | 2016-09-08T03:31:57Z | [
"python",
"pandas",
"dataframe"
] |
Printing multiple objects without spaces | 39,381,936 | <p>I'm writing a basic program to convert any 4 digit number in reverse.</p>
<p>I know I'm taking a very complex approach, but that's what my professor requires. So far I've got:</p>
<pre><code>print("This program will display any 4-digit integer in reverse order")
userNum = eval(input("Enter any 4-digit integer: ")... | 1 | 2016-09-08T03:00:43Z | 39,381,971 | <p>If you read the description of the <a href="https://docs.python.org/3.5/library/functions.html#print"><code>print()</code></a>, you can see that you can change your last line for:</p>
<pre><code>print(num1,num2,num3,num4, sep='')
</code></pre>
| 5 | 2016-09-08T03:04:59Z | [
"python",
"printing",
"reverse",
"spaces"
] |
Printing multiple objects without spaces | 39,381,936 | <p>I'm writing a basic program to convert any 4 digit number in reverse.</p>
<p>I know I'm taking a very complex approach, but that's what my professor requires. So far I've got:</p>
<pre><code>print("This program will display any 4-digit integer in reverse order")
userNum = eval(input("Enter any 4-digit integer: ")... | 1 | 2016-09-08T03:00:43Z | 39,382,375 | <p>Since you just want to convert the input in reverse order. You can take the following approach.</p>
<pre><code>print("This program will display any 4-digit integer in reverse order")
userNum = input("Enter any 4-digit integer: ")
reverse_input = userNum[::-1]
reverse_input = int(reverse_input) # If you want to keep... | 1 | 2016-09-08T03:59:28Z | [
"python",
"printing",
"reverse",
"spaces"
] |
Printing multiple objects without spaces | 39,381,936 | <p>I'm writing a basic program to convert any 4 digit number in reverse.</p>
<p>I know I'm taking a very complex approach, but that's what my professor requires. So far I've got:</p>
<pre><code>print("This program will display any 4-digit integer in reverse order")
userNum = eval(input("Enter any 4-digit integer: ")... | 1 | 2016-09-08T03:00:43Z | 39,383,276 | <p>I used this as a sort of exercise for myself to nail down loops. There are a few loops you can use.</p>
<pre><code>#if using python <3
from __future__ import print_function
x = 3456
z = x
print('While:')
while z > 0:
print(z % 10, end="")
z = z / 10;
print()
print('For:')
for y in xrange(4):
... | 0 | 2016-09-08T05:37:50Z | [
"python",
"printing",
"reverse",
"spaces"
] |
How to set the max thread a python script could use when calling from shell | 39,381,974 | <p>Have script a.py, it will run some task with multiple-thread, please noticed that I have no control over the a.py.</p>
<p>I'm looking for a way to limit the number of thread it could use, as I found that using more threads than my CPU core will slow down the script.</p>
<p>It could be something like:</p>
<p>pytho... | 2 | 2016-09-08T03:05:12Z | 39,382,195 | <p>Read the <a href="https://docs.python.org/2/library/threading.html" rel="nofollow">threading</a> doc, it said:</p>
<blockquote>
<p>CPython implementation detail: In CPython, due to the Global Interpreter Lock, only one thread can execute Python code at once (even though certain performance-oriented libraries migh... | 0 | 2016-09-08T03:34:53Z | [
"python",
"multithreading",
"scikit-learn"
] |
How to set the max thread a python script could use when calling from shell | 39,381,974 | <p>Have script a.py, it will run some task with multiple-thread, please noticed that I have no control over the a.py.</p>
<p>I'm looking for a way to limit the number of thread it could use, as I found that using more threads than my CPU core will slow down the script.</p>
<p>It could be something like:</p>
<p>pytho... | 2 | 2016-09-08T03:05:12Z | 39,384,723 | <p>A more general way, not specific to python: </p>
<pre><code>taskset -c 1-3 python yourProgram.py
</code></pre>
<p>In this case the threads 1-3 (3 in total) will be used. Any parallelization invoked by your program will share those resources. </p>
<p>For a solution that fits your exact problem you should better id... | 1 | 2016-09-08T07:16:15Z | [
"python",
"multithreading",
"scikit-learn"
] |
Getting an IndexError: string index out of range | 39,382,010 | <p>I'm not sure why I'm getting an </p>
<blockquote>
<p>IndexError: string index out of range </p>
</blockquote>
<p>with this code. </p>
<pre><code>s = 'oobbobobo'
a = 0
for b in range(len(s)-1):
if (s[b] == 'b') and (s[b+1] == 'o') and (s[b+2] == s[b]):
a += 1
elif (s[b] == 'b') and (s[b+1] == 'o'... | 1 | 2016-09-08T03:11:09Z | 39,382,039 | <p>In this case, the length of <code>s</code> is 9 which means that you're looping over <code>range(8)</code> and therefore the highest value that <code>b</code> will have is <code>7</code> (Stay with me, I'm going somewhere with this ...)</p>
<p>When <code>b = 7</code> (on the last iteration of the loop), the conditi... | 1 | 2016-09-08T03:15:55Z | [
"python"
] |
AWS API Gateway's querystring is not json format | 39,382,068 | <p>In aws api gateway, I wanna pass the entire query string into the kinesis through api gateway,</p>
<pre><code>#set($querystring = $input.params().querystring)
"Data": "$util.base64Encode($querystring)"
</code></pre>
<p>but the data fetching from kinesis record looks like '{tracker_name=xxxx, tracker=yyyy}', which ... | 0 | 2016-09-08T03:19:17Z | 39,385,078 | <p>I'm not familiar with the AWS API Gateway, but focusing on the string formatting issue, it is not that hard to write a simple parser to convert it to any other format you want.</p>
<p>As for your description, I write a simple Python parser, hope it can give you some ideas.</p>
<pre><code>class MyParser:
def __ini... | 1 | 2016-09-08T07:34:53Z | [
"python",
"amazon-lambda",
"amazon-api-gateway"
] |
Got stuck with pxssh. It doesn't login again after the first successful login? | 39,382,077 | <p>I'm working on simple ssh login using pxssh. Following T.J. Connor scripts from Cookbook.</p>
<p>I was able to successfully get into the remote machine using pxssh and pass commands when trying from the python interpreter.
Below is the view.</p>
<pre><code>>>> from pexpect import pxssh
>>> s = px... | 3 | 2016-09-08T03:20:21Z | 39,502,625 | <p>After going through a lot of examples/articles, finally figured what was stopping pxssh from a successful SSH login. </p>
<p>The connect() method from pxssh takes in "login_timeout=10" by default. In here the SSH login to the remote machine was taking more than 10 secs and thus login() was raising a ExceptionPxssh ... | 1 | 2016-09-15T03:20:25Z | [
"python",
"python-2.7",
"ssh",
"pexpect",
"pxssh"
] |
How to check if a list already contains an element in Python? | 39,382,078 | <p>i have been working on this for quite a time and my if statement does not seem to have any effect on the code. what I am trying to do is that I want to enter words in a list without repetition.</p>
<pre><code>fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line.rstrip()
... | 2 | 2016-09-08T03:20:24Z | 39,382,102 | <p>Use a <a href="https://docs.python.org/2/library/sets.html" rel="nofollow"><code>set()</code></a>, it ensures unique elements. Alternatively, you can use the <a href="https://docs.python.org/3/reference/expressions.html#membership-test-operations" rel="nofollow"><code>in</code></a> operator to check for membership i... | 5 | 2016-09-08T03:23:09Z | [
"python",
"python-2.7",
"python-3.x"
] |
How to check if a list already contains an element in Python? | 39,382,078 | <p>i have been working on this for quite a time and my if statement does not seem to have any effect on the code. what I am trying to do is that I want to enter words in a list without repetition.</p>
<pre><code>fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line.rstrip()
... | 2 | 2016-09-08T03:20:24Z | 39,382,158 | <pre><code>>>> instuff = """one two three
... two three four
... three four five
... """
>>> lst = set()
>>> for line in instuff.split("\n"):
... lst |= set(line.split())
...
>>> lst
set(['four', 'five', 'two', 'three', 'one'])
>>>
</code></pre>
| 2 | 2016-09-08T03:29:53Z | [
"python",
"python-2.7",
"python-3.x"
] |
Why is math.sqrt(r**2 - (x-h)**2) + k returning a ValueError: math domain error | 39,382,197 | <pre><code>def drawCircle(h, k, r):
#(x-h)^2 + (y-k)^2 = r^2
for x in range(screen.Width):
y = (math.sqrt(r**2 - (x-h)**2) + k)
if y % 1 == 0:
screen.Set(x, int(y), "X")
drawCircle(0, 0, 5)
</code></pre>
<p>screen is a simple console renderer library that I wrote that positions ite... | 0 | 2016-09-08T03:35:27Z | 39,382,234 | <p>It is my guess that the result in parens that you are <code>sqrt</code>ing ends up being negative at some point. If and when it does, the error you are seeing will be raised when you try to take the square root of that number. </p>
<p>To confirm this, try saving <code>r**2 - (x-h)**2</code> to a variable and printi... | 3 | 2016-09-08T03:40:15Z | [
"python",
"math"
] |
Using BetaBinomial in PyMC3 | 39,382,396 | <p>I have a table of counts of binary outcomes and I would like to fit a beta binomial distribution to estimate $\alpha$ and $\beta$ parameters, but I am getting errors when I try to fit/sample the model distribution the way I do for other cases:</p>
<pre><code>import pymc3 as pm
import pandas as pd
df = pd.read_csv(... | 0 | 2016-09-08T04:02:05Z | 39,384,350 | <p>Your model should run, and you can write this </p>
<pre><code>with pm.Model() as model:
alpha = pm.Exponential('alpha', 1/(C0.sum()+1))
beta = pm.Exponential('beta', 1/(I0.sum()+1))
obs = pm.BetaBinomial('obs', alpha, beta, N0, observed=C0)
</code></pre>
<p>That is, (C, I C1, I1) were defined in you mo... | 2 | 2016-09-08T06:52:16Z | [
"python",
"bayesian",
"pymc",
"data-science",
"pymc3"
] |
crop center portion of a numpy image | 39,382,412 | <p>Let's say I have a numpy image of some width x and height y.
I have to crop the center portion of the image to width cropx and height cropy. Let's assume that cropx and cropy are positive non zero integers and less than the respective image size. What's the best way to apply the slicing for the output image?</p>
<p... | 1 | 2016-09-08T04:04:33Z | 39,382,475 | <p>Something along these lines -</p>
<pre><code>def crop_center(img,cropx,cropy):
y,x = img.shape
startx = x//2-(cropx//2)
starty = y//2-(cropy//2)
return img[starty:starty+cropy,startx:startx+cropx]
</code></pre>
<p>Sample run -</p>
<pre><code>In [45]: img
Out[45]:
array([[88, 93, 42, 25, 36, 1... | 1 | 2016-09-08T04:12:43Z | [
"python",
"image",
"numpy",
"crop"
] |
crop center portion of a numpy image | 39,382,412 | <p>Let's say I have a numpy image of some width x and height y.
I have to crop the center portion of the image to width cropx and height cropy. Let's assume that cropx and cropy are positive non zero integers and less than the respective image size. What's the best way to apply the slicing for the output image?</p>
<p... | 1 | 2016-09-08T04:04:33Z | 39,383,139 | <p>Thanks, Divakar.</p>
<p>Your answer got me going the right direction. I came up with this using negative slice offsets to count 'from the end':</p>
<pre><code>def cropimread(crop, xcrop, ycrop, fn):
"Function to crop center of an image file"
img_pre= msc.imread(fn)
if crop:
ysize, xsize, chan =... | 1 | 2016-09-08T05:24:53Z | [
"python",
"image",
"numpy",
"crop"
] |
Pandas timeseries with superimposed lines | 39,382,481 | <p>I have two data frames in pandas one with four timesseries with second by second data like the following</p>
<pre><code>timestamp ID value1 value2 value3 value4
2016/01/01T01:01:01 1234 100 50 50 60
2016/01/01T01:01:02 1234 101 48 48 52
2016/01/01T01:01:02 1234 1... | 0 | 2016-09-08T04:13:12Z | 39,382,982 | <p>The easiest way is to put all the data into a single DataFrame and use the built-in <code>.plot()</code> method.</p>
<p>Assuming your original DataFrame is called <code>df</code> the the code below should solve your issue (you might need to strip out the "ID" column):</p>
<pre><code>means = df.groupby(pd.TimeGroup... | 0 | 2016-09-08T05:09:25Z | [
"python",
"pandas"
] |
Find the last element (digit) on each line and sum all that are even python 3 | 39,382,509 | <p>Hi there Stack Overflow!</p>
<p>I'm trying to solve an assignment we got in my Python class today. I'm not super familiar with python yet so I could really need some tips.</p>
<p>The task is to:
Find the last element (digit) on each line, if there are any, and sum all
that are even.</p>
<p>I have started to do so... | 1 | 2016-09-08T04:17:12Z | 39,382,591 | <p><code>isdigit()</code> return <code>True</code> or <code>False</code>, which is assigned to <code>digitFirst</code> (try print it!).<br>
<code>True</code> and <code>False</code> are evaluated as 0 and 1 (respectively) in math operations.<br>
So, it always pass the <code>if digitFirst % 2 == 0</code> when <code>digit... | 1 | 2016-09-08T04:25:27Z | [
"python",
"python-3.x"
] |
Find the last element (digit) on each line and sum all that are even python 3 | 39,382,509 | <p>Hi there Stack Overflow!</p>
<p>I'm trying to solve an assignment we got in my Python class today. I'm not super familiar with python yet so I could really need some tips.</p>
<p>The task is to:
Find the last element (digit) on each line, if there are any, and sum all
that are even.</p>
<p>I have started to do so... | 1 | 2016-09-08T04:17:12Z | 39,382,718 | <pre><code>result = []
with open('https-access.txt') as fin:
for line in fin:
l = line.strip()
if l[-1].isdigit():
if int(l[-1]) % 2 == 0:
result.append(int(l[-1]))
ANSWER = sum(result)
</code></pre>
<p>How does your file look? You want to calculate the last digit on eac... | 1 | 2016-09-08T04:41:16Z | [
"python",
"python-3.x"
] |
Find the last element (digit) on each line and sum all that are even python 3 | 39,382,509 | <p>Hi there Stack Overflow!</p>
<p>I'm trying to solve an assignment we got in my Python class today. I'm not super familiar with python yet so I could really need some tips.</p>
<p>The task is to:
Find the last element (digit) on each line, if there are any, and sum all
that are even.</p>
<p>I have started to do so... | 1 | 2016-09-08T04:17:12Z | 39,382,913 | <p>Don't even bother with the <code>isdigit</code>. Go ahead and try the conversion to <code>int</code> and catch the exception if it fails.</p>
<pre><code>result = 0
with open('httpd-access.txt') as f:
for line in f:
try:
i = int(line.strip()[-1:])
if(i % 2 == 0):
... | 3 | 2016-09-08T05:02:22Z | [
"python",
"python-3.x"
] |
ipython notebook clear all code | 39,382,531 | <p>All I want to do is try some new codes in ipython notebook and I don't want to save it every time as its done automatically. Instead what I want is clear all the codes of ipython notebook along with reset of variables.</p>
<p>I want to do some coding and clear everything and start coding another set of codes withou... | 0 | 2016-09-08T04:19:22Z | 39,382,560 | <p>Ok youngster, I will break this down for ya in simple steps:</p>
<ol>
<li>go to the intended textbox and put your mouse cursor there</li>
<li>on keyboard press crtl-a and delete</li>
<li>Ta-dah all done </li>
</ol>
<p>Glad to help </p>
| 0 | 2016-09-08T04:22:54Z | [
"python",
"jupyter-notebook"
] |
ipython notebook clear all code | 39,382,531 | <p>All I want to do is try some new codes in ipython notebook and I don't want to save it every time as its done automatically. Instead what I want is clear all the codes of ipython notebook along with reset of variables.</p>
<p>I want to do some coding and clear everything and start coding another set of codes withou... | 0 | 2016-09-08T04:19:22Z | 39,472,132 | <p>Well, you could use Shift-M to merge the cells (from top) - at least there's only one left to delete manually. </p>
| 0 | 2016-09-13T14:08:19Z | [
"python",
"jupyter-notebook"
] |
Python: Assigning # values in a list to bins, by rounding up | 39,382,594 | <p>I want a function that can take a series and a set of bins, and basically round up to the nearest bin. For example:</p>
<pre><code>my_series = [ 1, 1.5, 2, 2.3, 2.6, 3]
def my_function(my_series, bins):
...
my_function(my_series, bins=[1,2,3])
> [1,2,2,3,3,3]
</code></pre>
<p>This seems to be very close ... | 4 | 2016-09-08T04:25:42Z | 39,382,732 | <p>I believe <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.searchsorted.html" rel="nofollow"><code>np.searchsorted</code></a> will do what you want:</p>
<blockquote>
<p>Find the indices into a sorted array <code>a</code> such that, if the corresponding
elements in <code>v</code> were inserted... | 1 | 2016-09-08T04:42:45Z | [
"python",
"numpy",
"grouping",
"rounding",
"bins"
] |
Python: Assigning # values in a list to bins, by rounding up | 39,382,594 | <p>I want a function that can take a series and a set of bins, and basically round up to the nearest bin. For example:</p>
<pre><code>my_series = [ 1, 1.5, 2, 2.3, 2.6, 3]
def my_function(my_series, bins):
...
my_function(my_series, bins=[1,2,3])
> [1,2,2,3,3,3]
</code></pre>
<p>This seems to be very close ... | 4 | 2016-09-08T04:25:42Z | 39,382,758 | <p>Another way would be:</p>
<pre><code>In [25]: def find_nearest(array,value):
...: idx = (np.abs(array-np.ceil(value))).argmin()
...: return array[idx]
...:
In [26]: my_series = np.array([ 1, 1.5, 2, 2.3, 2.6, 3])
In [27]: bins = [1, 2, 3]
In [28]: [find_nearest(bins, x) for x in my_series]... | 1 | 2016-09-08T04:44:52Z | [
"python",
"numpy",
"grouping",
"rounding",
"bins"
] |
Python: Assigning # values in a list to bins, by rounding up | 39,382,594 | <p>I want a function that can take a series and a set of bins, and basically round up to the nearest bin. For example:</p>
<pre><code>my_series = [ 1, 1.5, 2, 2.3, 2.6, 3]
def my_function(my_series, bins):
...
my_function(my_series, bins=[1,2,3])
> [1,2,2,3,3,3]
</code></pre>
<p>This seems to be very close ... | 4 | 2016-09-08T04:25:42Z | 39,397,822 | <p>We can simply use <code>np.digitize</code> with its <code>right</code> option set as <code>True</code> to get the indices and then to extract the corresponding elements off <code>bins</code>, bring in <code>np.take</code>, like so -</p>
<pre><code>np.take(bins,np.digitize(a,bins,right=True))
</code></pre>
| 1 | 2016-09-08T18:25:46Z | [
"python",
"numpy",
"grouping",
"rounding",
"bins"
] |
Saving Python list containing Tensorflow Sparsetensors to file for later access? | 39,382,725 | <p>I'm creating a list of Sparsetensors in Tensorflow. I want to access them in later sessions of my program. I've read online that you can store Python lists as json files but how do I save a list of Sparsetensors to a json file and then use that later on?</p>
<p>Thanks in advance</p>
| 0 | 2016-09-08T04:42:15Z | 39,395,872 | <p>A Tensor in TensorFlow is a node in the graph which, when run, will produce a tensor. So you can't save the SparseTensor directly because it's not a value (you can serialize the graph). If you do evaluate the sparsetensor, you get a SparseTensorValue object back which can be serialized as it's just a tuple.</p>
| 1 | 2016-09-08T16:17:35Z | [
"python",
"json",
"tensorflow"
] |
<urlopen error (-1, 'SSL exception: Differences between the SSL socket behaviour of cpython vs. jython are explained on the wiki | 39,382,800 | <p>I'm using the following code.</p>
<pre><code>import urllib2
#Setting proxy
myProxy = {'https':'https://proxy.example.com:8080'}
proxy = urllib2.ProxyHandler(myProxy)
opener = urllib2.build_opener(proxy)
urllib2.install_opener(opener)
#Access URL
auth_token = "realLy_loNg_AuTheNicaTion_toKen"
headers={"Content-Typ... | 6 | 2016-09-08T04:51:17Z | 39,558,507 | <p>It seems issue of certificate trust.
<a href="http://bugs.jython.org/issue1688" rel="nofollow">http://bugs.jython.org/issue1688</a></p>
<p>There are these two options that will solve your problem.</p>
<blockquote>
<p>Jython is not like cpython. Cpython does not verify the chain of trust
for server certificates... | 0 | 2016-09-18T14:07:48Z | [
"python",
"ssl",
"jython"
] |
Two subplots of gridspec, one line plot and the other bar plot, with a time-series on x, are not displaying | 39,382,801 | <p>I can't figure out what I'm doing wrong in my plotting.
Plotting some data vs datetime on two subplots, one is a line plot, the other one should be a bar plot. I have tried several different ways of plotting it but without much success. </p>
<p><strong>UPDATE</strong>
Minor progress - the first plot is displayed, ... | 0 | 2016-09-08T04:51:20Z | 39,385,614 | <p>I found out what the problem was!!! I don't understand why it worked fine with the line plot and not with the bar plot, but all that needed to be changed in the code is the actual one line for the bar plot. It should go like this:</p>
<pre><code>ax2 = plt.bar(Test["A"].values,Test["C"],width=1)
</code></pre>
<p>So... | 0 | 2016-09-08T08:02:08Z | [
"python",
"python-2.7",
"pandas",
"matplotlib",
"bar-chart"
] |
Ubuntu 14.04 LTS: `apt-get install rake` -> âImportError: No module named rakeâ | 39,382,898 | <pre><code>I used 'sudo apt-get install rake'.
>>> import rake
but Fails with error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named rake
</code></pre>
<p>Why this happened?I'm missing something.</p>
| 0 | 2016-09-08T05:00:37Z | 39,383,795 | <p>Ok, I got answer.</p>
<pre><code>$ git clone https://github.com/zelandiya/RAKE-tutorial
$ cd RAKE-tutorial/
:~/RAKE-tutorial$ python
>>> import rake
</code></pre>
| 0 | 2016-09-08T06:20:03Z | [
"python",
"ubuntu",
"rake"
] |
mypy spurious error: "module" has no attribute "XPath" with etree | 39,382,937 | <p>I'm trying to use <code>mypy</code> to do type checking in some code that uses the <a href="http://lxml.de/" rel="nofollow">LXML</a> library to parse XML.</p>
<p>On each line where I use <code>etree.XPath</code>, I get a spurious error from <code>mypy</code>. For example, the following trivial script</p>
<pre><co... | 2 | 2016-09-08T05:04:31Z | 39,393,394 | <p>It looks like this is a bug in <a href="https://github.com/python/typeshed" rel="nofollow">typeshed</a>, the community-contributed collection of type annotations for the stdlib and various third party libraries.</p>
<p>In particular, it looks as if the <a href="https://github.com/python/typeshed/tree/master/third_p... | 1 | 2016-09-08T14:18:54Z | [
"python",
"lxml",
"mypy"
] |
Install OpenStack: ImportError: Could not import settings 'openstack_dashboard.settings' (***?): No module named angular_fileupload | 39,383,334 | <p>I was trying to build openstack (stack.sh), tried many times, still can't figure out the reason, below is the logs:</p>
<pre><code>2016-09-08 05:36:48.424 | Warning: Could not import Horizon dependencies. This is normal during installation.
2016-09-08 05:36:48.425 | WARNING:root:No local_settings file found.
2016-0... | 0 | 2016-09-08T05:42:18Z | 39,571,998 | <p>First of all you need to make sure you have <code>pip</code> installed, if you've bootstrapped using Ubuntu <code>sudo apt-get install python-pip -y</code> where the -y flag is simply to accept any packages and prepare them for installation.</p>
<p>If you are using CentOS or any other Redhat based system <code>yum ... | 0 | 2016-09-19T11:22:49Z | [
"python",
"openstack"
] |
Python Import Error - specific case | 39,383,412 | <p>I know there has been a ton of questions about this, but mine is pretty specific and i don't really know why the import is not working.
I've got the following Folder Structure:</p>
<pre><code>importmodule
-classes
-pluginhelper
-- __init__.py
-plugins
-- plugin_a
-- plugin b
-- ..
-__init__.py
-<other py file... | 0 | 2016-09-08T05:50:33Z | 39,505,134 | <p>I want to share my solution with you, since anybody reading the question seems to have similar problems. </p>
<p>The problem occured because the package werent included in pythonpath / syspath. I am calling the plugins in a new thread with a script called execute.py. This is called via cmd from the main.py because ... | 0 | 2016-09-15T07:18:57Z | [
"python",
"importerror"
] |
Why won't my Angular front-end pass correct $http.get parameters to Django back-end? | 39,383,507 | <p>I have a Web Application made up of front-end client written in Angular/Javascript and a back-end server written in Python/Django. </p>
<p>I'm trying to do a simple http GET request from the client to the server and it is not working. The reason it is failing is because for some unknown reason, the parameters are n... | 1 | 2016-09-08T06:00:19Z | 39,383,735 | <p>A HTTP GET request can't contain data to be posted to the server. However you can add a query string to the request.</p>
<pre><code> $http.get(API + '/api/getProfile', {params:{'profileId':5}})
.then(function (response) { /* */ })...
</code></pre>
<p>OR</p>
<pre><code>$http({
url: API + '/api/getProfi... | 2 | 2016-09-08T06:16:18Z | [
"javascript",
"python",
"angularjs",
"django",
"http-get"
] |
SQLAlchemy InvalidRequestError when inserting to automap generated ORM | 39,383,528 | <p>I'm trying to use the SQLAlchemy automap extension to generate an ORM for an existing database, and am getting an InvalidRequestError exception ("Instance cannot be refreshed - it's not persistent and does not contain a full primary key.") whenever I try to insert into a table that uses a composite primary key con... | 1 | 2016-09-08T06:01:49Z | 39,384,996 | <p>The problem is not actually the composite primary key with the foreign key, but the <code>func.now()</code> passed as <code>timestamp</code>, which is part of the primary key. As the value is not known to SQLAlchemy, since it is generated during insert in the database, it cannot perform the post-fetch; it has no ide... | 1 | 2016-09-08T07:30:05Z | [
"python",
"sqlalchemy"
] |
Is this python pattern for a singleton safe? | 39,383,554 | <p>I have a module R that handles gets and sets to a redis cluster. It is imported all over a flask api's endpoints. My first thought was to use a Singleton class in R so that we maintain one single connection to the redis cluster, but I'm not entirely I should putting a singleton class pattern into a code base that is... | 0 | 2016-09-08T06:03:39Z | 39,384,656 | <p>It is safe but there are two things I don't think are good practices.</p>
<ol>
<li>Initializations or class definitions etc should not be there in
init.py Init file is use to hide internal structure of the package.
A simple <strong>init</strong>.py is a good <strong>init</strong>.py </li>
<li>Creating objects in gl... | 1 | 2016-09-08T07:13:04Z | [
"python",
"singleton",
"python-module"
] |
Multiple python virtual env | 39,383,776 | <p>Suppose i have normal system python 2.7 packages in system locations</p>
<p>Then i do</p>
<pre><code>virtualenv env1
</code></pre>
<p>I install all requirements there</p>
<p>Then i deactivate that and do</p>
<pre><code>export PYTHONPATH=$PYTHONPATH:/path/to/env1
</code></pre>
<p>Then i do <code>virtualenv env2... | -1 | 2016-09-08T06:18:56Z | 39,383,877 | <p>Have you activated env2 before installing module ?</p>
<blockquote>
<p>source bin/activate</p>
</blockquote>
<p>If you want to uninstall any module from virtualenv, then use</p>
<blockquote>
<p>pip uninstall module_name</p>
</blockquote>
| 1 | 2016-09-08T06:25:04Z | [
"python",
"linux",
"virtualenv"
] |
Multiple python virtual env | 39,383,776 | <p>Suppose i have normal system python 2.7 packages in system locations</p>
<p>Then i do</p>
<pre><code>virtualenv env1
</code></pre>
<p>I install all requirements there</p>
<p>Then i deactivate that and do</p>
<pre><code>export PYTHONPATH=$PYTHONPATH:/path/to/env1
</code></pre>
<p>Then i do <code>virtualenv env2... | -1 | 2016-09-08T06:18:56Z | 39,384,106 | <p>Probably you have not activated the virtual environment (lets call it as <code>venv</code>) and installed the package system wide.</p>
<p>I suggest you to try activating the venv first and then proceed with installations in either of the venv.</p>
<p>You can activate venv using following code : </p>
<pre><code> ... | 0 | 2016-09-08T06:37:58Z | [
"python",
"linux",
"virtualenv"
] |
Multiple python virtual env | 39,383,776 | <p>Suppose i have normal system python 2.7 packages in system locations</p>
<p>Then i do</p>
<pre><code>virtualenv env1
</code></pre>
<p>I install all requirements there</p>
<p>Then i deactivate that and do</p>
<pre><code>export PYTHONPATH=$PYTHONPATH:/path/to/env1
</code></pre>
<p>Then i do <code>virtualenv env2... | -1 | 2016-09-08T06:18:56Z | 39,384,152 | <p>Firstly, do not change PYTHONPATH manually.
Steps should look something like this:</p>
<pre><code>[root@demo src]$ source /usr/local/env1/bin/activate
(env1)[root@demo src]$ # pip install blah
(env1)[root@demo src]$ source /usr/local/env2/bin/activate
(env2)[root@demo src]$ #pip install blah
(env2)[root@demo src]$... | 1 | 2016-09-08T06:40:11Z | [
"python",
"linux",
"virtualenv"
] |
Python - speed up pathfinding | 39,383,914 | <p>This is my pathfinding function:</p>
<pre><code>def get_distance(x1,y1,x2,y2):
neighbors = [(-1,0),(1,0),(0,-1),(0,1)]
old_nodes = [(square_pos[x1,y1],0)]
new_nodes = []
for i in range(50):
for node in old_nodes:
if node[0].x == x2 and node[0].y == y2:
return node... | 1 | 2016-09-08T06:27:17Z | 39,384,012 | <p>You should replace your algorithm with <a href="https://en.wikipedia.org/wiki/A*_search_algorithm" rel="nofollow">A*-search</a> with the Manhattan distance as a heuristic.</p>
| 3 | 2016-09-08T06:32:55Z | [
"python",
"path-finding"
] |
Python - speed up pathfinding | 39,383,914 | <p>This is my pathfinding function:</p>
<pre><code>def get_distance(x1,y1,x2,y2):
neighbors = [(-1,0),(1,0),(0,-1),(0,1)]
old_nodes = [(square_pos[x1,y1],0)]
new_nodes = []
for i in range(50):
for node in old_nodes:
if node[0].x == x2 and node[0].y == y2:
return node... | 1 | 2016-09-08T06:27:17Z | 39,385,685 | <p>One reasonably fast solution is to implement the Dijkstra algorithm (that I have already implemented in <a href="http://stackoverflow.com/q/39244636/1679629">that question</a>):</p>
<p>Build the original map. It's a masked array where the walker cannot walk on masked element:</p>
<pre><code>%pylab inline
map_size ... | 1 | 2016-09-08T08:06:35Z | [
"python",
"path-finding"
] |
Python - speed up pathfinding | 39,383,914 | <p>This is my pathfinding function:</p>
<pre><code>def get_distance(x1,y1,x2,y2):
neighbors = [(-1,0),(1,0),(0,-1),(0,1)]
old_nodes = [(square_pos[x1,y1],0)]
new_nodes = []
for i in range(50):
for node in old_nodes:
if node[0].x == x2 and node[0].y == y2:
return node... | 1 | 2016-09-08T06:27:17Z | 39,387,039 | <p>The biggest issue with your code is that you don't do anything to avoid the same coordinates being visited multiple times. This means that the number of nodes you visit is <em>guaranteed</em> to grow exponentially, since it can keep going back and forth over the first few nodes many times.</p>
<p>The best way to av... | 0 | 2016-09-08T09:17:01Z | [
"python",
"path-finding"
] |
Django DRF: Default URL always gets trigered first instead of route.url | 39,383,926 | <p>I have a very simple Django Rest Framework application, my <code>urls.py</code> looks like the following</p>
<pre><code>router = routers.DefaultRouter()
router.register(r'activity-list', activities.views.ArticleViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include(router.urls, ... | 0 | 2016-09-08T06:27:56Z | 39,384,007 | <p>You will have to learn <code>url dispatcher</code> in django. Your default url's and DRF route's url's <code>pattern</code> is same, and default url is on top of the <code>urlpatterns</code> thus that url is getting triggered.</p>
<p><a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#how-django-proce... | 0 | 2016-09-08T06:32:37Z | [
"python",
"django",
"routes",
"django-rest-framework"
] |
Django DRF: Default URL always gets trigered first instead of route.url | 39,383,926 | <p>I have a very simple Django Rest Framework application, my <code>urls.py</code> looks like the following</p>
<pre><code>router = routers.DefaultRouter()
router.register(r'activity-list', activities.views.ArticleViewSet)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^api/', include(router.urls, ... | 0 | 2016-09-08T06:27:56Z | 39,402,663 | <p>Finally figured it out. According to the DRF docs:</p>
<blockquote>
<p>By default the URLs created by <code>SimpleRouter</code> are appended with a
trailing slash. This behavior can be modified by setting the
<code>trailing_slash</code> argument to <code>False</code> when instantiating the router. For
examp... | 1 | 2016-09-09T01:55:15Z | [
"python",
"django",
"routes",
"django-rest-framework"
] |
Bokeh - Link dataframe time series data to Select interaction | 39,384,066 | <p>I'm trying create a single line chart in Bokeh and linking different charts in one dataframe to a Select interaction. The dataframe structure looks something like this:</p>
<p>Date, KPI1, KPI2, KPI3, KPI4 ... ...</p>
<p>Date is always x axis, whereas KPI's should be changeable on the y axis.</p>
<p>I can't get i... | 0 | 2016-09-08T06:36:03Z | 39,385,405 | <p>I found an answer to my question here:</p>
<p><a href="https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/2rCCRIyXtk8" rel="nofollow">https://groups.google.com/a/continuum.io/forum/#!topic/bokeh/2rCCRIyXtk8</a></p>
| 1 | 2016-09-08T07:51:59Z | [
"python",
"pandas",
"bokeh"
] |
Replacing part of a string in a list in python | 39,384,235 | <p>For example i have list of a name written diffently </p>
<pre><code>list1 = ["jai.kumar","jaikumar","j_kumar","jk","kumar-jai","ja.ku"]
for str in l1:
if str == âjaiâ
str.replace (âjaiâ,âfirstnameâ)
if str == âjaâ
str.replace (âjaâ,âfirst 2 character of firstnameâ)
if str == ... | -1 | 2016-09-08T06:44:51Z | 39,385,061 | <p>first of all, you're defining a list "list1" then operating on a list "l1" which is not defined, I'll assume this is a typo. Also you're indentation is fucked up and you're missing tons of colons after your ifs, I'll correct all that, if I shouldn't have and missed the purpose, please tell me.</p>
<p>second, you're... | 0 | 2016-09-08T07:33:53Z | [
"python"
] |
Replacing part of a string in a list in python | 39,384,235 | <p>For example i have list of a name written diffently </p>
<pre><code>list1 = ["jai.kumar","jaikumar","j_kumar","jk","kumar-jai","ja.ku"]
for str in l1:
if str == âjaiâ
str.replace (âjaiâ,âfirstnameâ)
if str == âjaâ
str.replace (âjaâ,âfirst 2 character of firstnameâ)
if str == ... | -1 | 2016-09-08T06:44:51Z | 39,385,364 | <p>I assume you meant sth like this?:</p>
<pre><code>if str == âjaiâ:
str.replace (âjaiâ,âfirstnameâ)
if str == âjaâ:
str.replace (âjaâ,âfirst 2 character of firstnameâ)
if str == âjâ:
str.replace (âjâ,âfirst character of firstnameâ)
</code></pre>... | 0 | 2016-09-08T07:49:38Z | [
"python"
] |
Xlsx Writer: Writing stings with multiple format in a single cell | 39,384,236 | <p>I have a string with multiple semicolons.</p>
<pre><code>'firstline: abc \n secondline: bcd \n thirdline: efg'
</code></pre>
<p>I want to write this strings in excel cell using Xlsx Writer like below.</p>
<p><b>firstline</b>: abc <br>
<b>secondline</b>: bcd <br>
<b>thirdline</b>: efg <br></p>
<p>This is what I d... | 2 | 2016-09-08T06:44:53Z | 39,385,849 | <p>The jmcnamara's solution works well. I posted a similar possible solution, but dynamic. </p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook("<your path>")
worksheet = workbook.add_worksheet()
# add style for first column
cell_format = workbook.add_format({'bold': True})
text_wrap = workbook.add_f... | 2 | 2016-09-08T08:15:43Z | [
"python",
"excel",
"python-2.7",
"xlsx",
"xlsxwriter"
] |
Xlsx Writer: Writing stings with multiple format in a single cell | 39,384,236 | <p>I have a string with multiple semicolons.</p>
<pre><code>'firstline: abc \n secondline: bcd \n thirdline: efg'
</code></pre>
<p>I want to write this strings in excel cell using Xlsx Writer like below.</p>
<p><b>firstline</b>: abc <br>
<b>secondline</b>: bcd <br>
<b>thirdline</b>: efg <br></p>
<p>This is what I d... | 2 | 2016-09-08T06:44:53Z | 39,389,532 | <p>The <a href="http://xlsxwriter.readthedocs.io/worksheet.html#worksheet-write-rich-string" rel="nofollow"><code>write_string()</code></a> method takes a list as an argument but you are passing a string.</p>
<p>You should use something like this to pass your list of strings and formats:</p>
<pre><code>result = [bold... | 2 | 2016-09-08T11:18:07Z | [
"python",
"excel",
"python-2.7",
"xlsx",
"xlsxwriter"
] |
Copy all files from one FTP directory to another | 39,384,246 | <p>I have to copy all existing files inside one ftp directory to another ftp directory on another server. I have not had any experience writing scripts - so any help with this would be great.</p>
<p>I'm wondering if its possible to write this script so that it happens every day at a specific time?</p>
<p>What softwar... | 1 | 2016-09-08T06:45:28Z | 39,384,635 | <p>In the end you will probably end up downloading the whole directory to a local machine and re-uploading it to the other, as there's generally no way to copy files between directories in FTP.<br>
See <a href="http://stackoverflow.com/q/3808799/850848">FTP copy a file to another place in same FTP</a>.</p>
<p>You will... | 0 | 2016-09-08T07:11:44Z | [
"python",
"shell",
"ftp"
] |
It is possible for Django to upload file without FORMS? | 39,384,417 | <p>Im currently working with a custom html template not using forms on my django app to upload an img in a specific path.</p>
<p><strong>app structure</strong></p>
<pre><code>src/
media/
app/
img/
app_name/
templates/
app_name/
app_template.html
... | 0 | 2016-09-08T06:57:44Z | 39,385,452 | <p>Your backend code is fine. The problem is with a frontend. You can't submit file input with jQuery.ajax like other fields. Use <a href="https://developer.mozilla.org/en/docs/Web/API/FormData" rel="nofollow">FormData</a>:</p>
<pre><code>$('#myform').submit(function(event) {
if(window.FormData !== undefined) {
... | 1 | 2016-09-08T07:54:17Z | [
"python",
"django",
"file",
"django-models"
] |
It is possible for Django to upload file without FORMS? | 39,384,417 | <p>Im currently working with a custom html template not using forms on my django app to upload an img in a specific path.</p>
<p><strong>app structure</strong></p>
<pre><code>src/
media/
app/
img/
app_name/
templates/
app_name/
app_template.html
... | 0 | 2016-09-08T06:57:44Z | 39,385,793 | <p>I don't understand why you don't want to use a modelform; it'll make things a lot easier.</p>
<p>However, if you really do want to do it without one, you'll need to take care of the actual uploading yourself. The <a href="https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/#basic-file-uploads" rel="nofo... | 1 | 2016-09-08T08:12:49Z | [
"python",
"django",
"file",
"django-models"
] |
How to read data in chunks in Python dataframe? | 39,384,539 | <p>I want to read the file f in chunks to a dataframe. Here is part of a code that I used.</p>
<pre><code>for i in range(0, maxline, chunksize):
df = pandas.read_csv(f,sep=',', nrows=chunksize, skiprows=i)
df.to_sql(member, engine, if_exists='append',index= False, index_label=None, chunksize=chunksize)
</code></pre>
... | 1 | 2016-09-08T07:06:10Z | 39,384,706 | <p>I think it is better to use the parameter <code>chunksize</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow"><code>read_csv</code></a>. Also, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html" rel="nofollow"><code>concat</... | 2 | 2016-09-08T07:15:36Z | [
"python",
"csv",
"pandas",
"dataframe",
"chunks"
] |
Can't set an arbitrary attribute in an instance of an object | 39,384,634 | <p>I'm using the pygame library, it has an object pygame.Surface() that has a bunch of methods. This is what I'm trying to do:</p>
<pre><code>my_surface = pygame.Surface((5,5)) #the object requires a size to instantiate
my_surface.coords = (10,10)
</code></pre>
<p>But it throws me this error:</p>
<pre><code>Tracebac... | 0 | 2016-09-08T07:11:42Z | 39,385,787 | <p>I don't think there's a better way than subclassing <code>Surface</code> if you <em>really</em> need to be able to assign arbitrary attributes to an instance. The subclass can be empty if you don't need to add any other features (the instance <code>__dict__</code> will be created automatically).</p>
<pre><code>clas... | 1 | 2016-09-08T08:12:32Z | [
"python",
"python-3.x"
] |
groupby pandas : incompatible index of inserted column with frame index | 39,384,749 | <p>I have performed a groupby on pandas and I want to apply a complex function which needs several inputs and gives as output a pandas Series that I want to burn in my original dataframe. this is a known procedure to me and has worked very well - that is excpet in this last case (of which I forward my apologies for not... | 0 | 2016-09-08T07:17:25Z | 39,385,558 | <p>ok, for reasons beyond my understanding, when I performed a merge inside the code, although their numpy representation was equivalent, they differed for something else before pandas' eyes. I tried a work-around of the merge (longer and more inefficient) and now with more traditional means it works.</p>
<p>today I w... | 0 | 2016-09-08T07:59:12Z | [
"python",
"pandas",
"indexing",
"group-by"
] |
Unable to extract unique words from a CSV | 39,384,762 | <p>I have a <code>csv</code> which looks like below:</p>
<pre><code> Description
0 ['boy']
1 ['boy', 'jumped', 'roof']
2 ['paris']
3 ['paris', 'beautiful', 'new', 'york']
4 ['lets', 'go', 'party']
5 ['refused', 'come', 'party']
</code></pre>
<p>I need to find out unique words from this data. So output ... | 1 | 2016-09-08T07:18:07Z | 39,384,964 | <p>You can first need convert <code>string</code> column to <code>list</code>, I use <code>ast.literal_eval</code>. Then make flat list of lists by list comprehension, use <code>set</code> and last create new <code>DataFrame</code> by constructor:</p>
<pre><code>import ast
print (type(df.ix[0, 'Description']))
<cl... | 3 | 2016-09-08T07:28:07Z | [
"python",
"list",
"csv",
"pandas",
"unique"
] |
Unable to extract unique words from a CSV | 39,384,762 | <p>I have a <code>csv</code> which looks like below:</p>
<pre><code> Description
0 ['boy']
1 ['boy', 'jumped', 'roof']
2 ['paris']
3 ['paris', 'beautiful', 'new', 'york']
4 ['lets', 'go', 'party']
5 ['refused', 'come', 'party']
</code></pre>
<p>I need to find out unique words from this data. So output ... | 1 | 2016-09-08T07:18:07Z | 39,385,257 | <p>This approach works:</p>
<pre><code>import pandas as pd
import ast
test = {'Description':["['boy']","['boy', 'jumped', 'roof']","['paris']",\
"['paris', 'beautiful', 'new', 'york']","['lets', 'go', 'party']",\
"['refused', 'come', 'party']"]}
tt = pd.DataFrame(test)
listOfWords = []
for i,row in tt.iterrows():... | 1 | 2016-09-08T07:43:51Z | [
"python",
"list",
"csv",
"pandas",
"unique"
] |
Is it OK to replace a method by a plain function? | 39,384,922 | <p>This works as expected, but I am somehow unsure about this approach. Is it safe? Is it pythonic?</p>
<pre><code>class Example:
def __init__(self, parameter):
if parameter == 0:
# trivial case, the result is always zero
self.calc = lambda x: 0.0 # <== replacing a method
... | 1 | 2016-09-08T07:26:19Z | 39,384,999 | <p>You'll have a problem should <code>parameter</code> ever changes, so I don't consider it good practice.
Instead, I think you should do this:</p>
<pre><code>class Example:
def __init__(self, parameter):
self._parameter = parameter
def calc(self, x):
if not self._parameter:
return... | 3 | 2016-09-08T07:30:17Z | [
"python"
] |
Is it OK to replace a method by a plain function? | 39,384,922 | <p>This works as expected, but I am somehow unsure about this approach. Is it safe? Is it pythonic?</p>
<pre><code>class Example:
def __init__(self, parameter):
if parameter == 0:
# trivial case, the result is always zero
self.calc = lambda x: 0.0 # <== replacing a method
... | 1 | 2016-09-08T07:26:19Z | 39,385,018 | <p>This is very confusing. If someone else reads it, they won't understand what is going on. Just put a <code>if</code> statement at the beginning of your method.</p>
<pre><code>def calc(self, x):
if self.parameter == 0:
return 0
# ... long calculation of result ...
return result
</code></pre>
<p... | 4 | 2016-09-08T07:31:47Z | [
"python"
] |
Is it OK to replace a method by a plain function? | 39,384,922 | <p>This works as expected, but I am somehow unsure about this approach. Is it safe? Is it pythonic?</p>
<pre><code>class Example:
def __init__(self, parameter):
if parameter == 0:
# trivial case, the result is always zero
self.calc = lambda x: 0.0 # <== replacing a method
... | 1 | 2016-09-08T07:26:19Z | 39,385,875 | <p><em>I decided to post a summary of several comments and answers. Please do not vote for this summary, but give +1 to the original authors instead</em>.</p>
<ul>
<li>the approach is safe except for special <code>__methods__</code></li>
<li>the approach is deemed unpythonic, undesirable, or unnecessary etc.</li>
<li>... | 0 | 2016-09-08T08:16:48Z | [
"python"
] |
Change dtype data_type fields of numpy array | 39,384,998 | <p>I have a <code>.mat</code> file which I load using <code>scipy</code>:</p>
<pre><code>from oct2py import octave
import scipy.io as spio
matPath = "path/to/file.mat"
matFile = spio.loadmat(matPath)
</code></pre>
<p>I get a numpy array which I want to pass to octave function using <code>oct2py</code>, like that:</p>... | 0 | 2016-09-08T07:30:12Z | 39,386,846 | <p>Found a workaround!</p>
<p>I used the <a href="http://stackoverflow.com/questions/7008608/scipy-io-loadmat-nested-structures-i-e-dictionaries">following script</a>, which reconstructs python dictionaries from the loaded struct, which <code>oct2py2</code> in turn interpret as matlab structs.</p>
| 0 | 2016-09-08T09:06:20Z | [
"python",
"numpy",
"scipy",
"octave"
] |
Change dtype data_type fields of numpy array | 39,384,998 | <p>I have a <code>.mat</code> file which I load using <code>scipy</code>:</p>
<pre><code>from oct2py import octave
import scipy.io as spio
matPath = "path/to/file.mat"
matFile = spio.loadmat(matPath)
</code></pre>
<p>I get a numpy array which I want to pass to octave function using <code>oct2py</code>, like that:</p>... | 0 | 2016-09-08T07:30:12Z | 39,387,123 | <p>I was going to suggest converting the resulting array to a valid dictionary but you beat me to it so I won't code it :p</p>
<p>However, the other, simpler solution I was going to suggest is that, since you're only using the struct within octave, you <em>could</em> just load it into its workspace and evaluate direct... | 0 | 2016-09-08T09:21:16Z | [
"python",
"numpy",
"scipy",
"octave"
] |
How remove duplicates of tuples in a list, where the tuple elements are in reverse order? | 39,385,019 | <p>I am working on a assignment where my program shall ask the user about a positive integer <em>n</em> which the prgogram will found the positive integers a and b, satsifying <em>a</em>^3 + <em>b</em>^3 = <em>n</em>.</p>
<p>My work and progress thus far is shown below</p>
<pre><code>def ramunajan(n):
list=[]
... | 0 | 2016-09-08T07:31:47Z | 39,385,207 | <p>replace <code>u = int(n**(1/3)+1)</code> with <code>u = int((n**(1/3))/2) + 1</code></p>
<p>so it checks only the first half of the pool, since the second half are duplicates</p>
| 2 | 2016-09-08T07:41:07Z | [
"python",
"duplicates",
"tuples"
] |
How to do List flattening inside the loop with list comprehension? | 39,385,026 | <p>here i am having list of dictionaries, my goal is to iterate over list and whenever there is 2 or more list available, i want to merge them and append in a output list, and whenever there is only one list it needs to be stored as it as.</p>
<pre><code>data = [
[[{'font-weight': '1'},{'font-weight': '1'}... | 2 | 2016-09-08T07:31:54Z | 39,385,155 | <p>Try this,</p>
<pre><code>result = []
for item in data:
result.append([i for j in item for i in j])
</code></pre>
<p>Single line code with list comprehension,</p>
<pre><code>[[i for j in item for i in j] for item in data]
</code></pre>
<p>Alternative method,</p>
<pre><code>import numpy as np
[list(np.array(i... | 3 | 2016-09-08T07:38:31Z | [
"python",
"list",
"dictionary"
] |
How to do List flattening inside the loop with list comprehension? | 39,385,026 | <p>here i am having list of dictionaries, my goal is to iterate over list and whenever there is 2 or more list available, i want to merge them and append in a output list, and whenever there is only one list it needs to be stored as it as.</p>
<pre><code>data = [
[[{'font-weight': '1'},{'font-weight': '1'}... | 2 | 2016-09-08T07:31:54Z | 39,385,181 | <p>You could use <a href="http://stackoverflow.com/questions/4406389/if-else-in-a-list-comprehension">conditional list comprehension</a> with <a href="http://docs.python.org/2/library/itertools.html#itertools.chain"><code>itertools.chain</code></a> for those elements which need flattening:</p>
<pre><code>In [54]: impo... | 5 | 2016-09-08T07:40:04Z | [
"python",
"list",
"dictionary"
] |
How to do List flattening inside the loop with list comprehension? | 39,385,026 | <p>here i am having list of dictionaries, my goal is to iterate over list and whenever there is 2 or more list available, i want to merge them and append in a output list, and whenever there is only one list it needs to be stored as it as.</p>
<pre><code>data = [
[[{'font-weight': '1'},{'font-weight': '1'}... | 2 | 2016-09-08T07:31:54Z | 39,385,352 | <p>iterate through list and check if each item is lists of list. If so flatten it.</p>
<hr>
<pre><code>data = [
[[{'font-weight': '1'},{'font-weight': '1'}],[{'font-weight': '2'},{'font-weight': '2'}]],
[{'font-weight': '3'},{'font-weight': '3'},{'font-weight': '3'}],
[[{'font-weight': '1'}... | 0 | 2016-09-08T07:48:56Z | [
"python",
"list",
"dictionary"
] |
Debug slow ANTLR generating and parsing | 39,385,282 | <p>I'm using ANTLR4 + Python2 target, </p>
<pre><code>time java -jar lib/antlr-4.5-complete.jar -visitor -o build -Dlanguage=Python2 xxx.g4
time ./main.py
</code></pre>
<p>It takes 10s to generate the visitor/lexer/parser file, and another 4s to execute the visitor.</p>
<p>How should I debug its slowness?</p>
| 0 | 2016-09-08T07:45:17Z | 39,427,608 | <p>I write a lot of antlr4 parsers, and I face speed issues all the time. I have a feeling Python target is usually pretty slow. When a parser is really slow, it usually have reduce/reduce issue meaning there are multiple sub rules having the same terminal rule so the parser get confused.</p>
<p>When a parser is slow,... | 0 | 2016-09-10T15:31:30Z | [
"python",
"antlr4"
] |
Selenium Python Webdriver chrome print src's of all imgs | 39,385,460 | <p>I want to print all src of imgs in the page, i want to see if it recognize it,
cuz when i do </p>
<pre><code>driver.find_element_by_xpath("//img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png'").click()
</code></pre>
<p>its says:</p>
<pre><code> C:\Users\Bar\App... | 0 | 2016-09-08T07:54:52Z | 39,386,070 | <blockquote>
<p>selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //img[@src='<a href="http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png" rel="nofollow">http://images.yad2.co.il/Pic/site_images/... | 0 | 2016-09-08T08:27:25Z | [
"python",
"selenium",
"selenium-webdriver"
] |
Selenium Python Webdriver chrome print src's of all imgs | 39,385,460 | <p>I want to print all src of imgs in the page, i want to see if it recognize it,
cuz when i do </p>
<pre><code>driver.find_element_by_xpath("//img[@src='http://images.yad2.co.il/Pic/site_images/yad2/MyYad2/images/myorderbottom/new/jump_ad.png'").click()
</code></pre>
<p>its says:</p>
<pre><code> C:\Users\Bar\App... | 0 | 2016-09-08T07:54:52Z | 39,442,082 | <p>Ok propably @Saurabh Gaur were right there is Iframe in the site ,
Simple solution ,</p>
<pre><code>driver.switch_to.frame(driver.find_element_by_id("FrameID"))
</code></pre>
<p>Thats it from there i could find the button , then i comeback</p>
<pre><code>driver.switch_to.default_content()
</code></pre>
<p>and f... | 0 | 2016-09-12T00:53:44Z | [
"python",
"selenium",
"selenium-webdriver"
] |
Plot data without interpolation from former x value | 39,385,461 | <p>I am doing some particle tracking at the moment. Therefore I want to plot the distribution and the cumulative function of the passing particles. </p>
<p>When I plot the distribution, my plot always starts one time step to early.
Is there a way to just plot the event as a kind of peak, without any interpolation on t... | 1 | 2016-09-08T07:54:54Z | 39,385,649 | <p>There is no interpolation; with <code>plot(.., '-')</code>, matplotlib simply <em>"connects the dots"</em> (data coordinates that you provide). Either don't draw the line and use markers, e.g.:</p>
<pre><code>ax1.plot(time, counts, "o", label="Density")
</code></pre>
<p>Or use e.g. <code>bar()</code> to draw "peak... | 1 | 2016-09-08T08:04:25Z | [
"python",
"matplotlib",
"plot"
] |
what is wrong with this AngularJs code- in browser code editor- Nodejs | 39,385,571 | <p>Hi am trying to create in browser code editor for free knowledge sharing for high school students from basic level. after long struggle with search i got <a href="https://github.com/scriptnull/compilex" rel="nofollow">this</a> link. i just did some setup and changes as per guidance available in that link.</p>
<p><d... | -3 | 2016-09-08T08:00:00Z | 39,393,973 | <p>Move <code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</code>
into the <code><head></code>. Not certain that this is your problem, but that'd be the first step in my book in the debugging process. </p>
| 0 | 2016-09-08T14:45:42Z | [
"javascript",
"python",
"angularjs",
"node.js",
"code-editor"
] |
what is wrong with this AngularJs code- in browser code editor- Nodejs | 39,385,571 | <p>Hi am trying to create in browser code editor for free knowledge sharing for high school students from basic level. after long struggle with search i got <a href="https://github.com/scriptnull/compilex" rel="nofollow">this</a> link. i just did some setup and changes as per guidance available in that link.</p>
<p><d... | -3 | 2016-09-08T08:00:00Z | 39,403,126 | <p>Actually, you have just plain HTML and there is nothing in there that uses angular.</p>
<p>Adding a script tag alone does not make something "angular code".
BTW, the tag is indeed in the wrong place, and it holds an ancient angular version. By now you should be using version 1.5.8. If you want to learn how to use ... | 2 | 2016-09-09T02:55:06Z | [
"javascript",
"python",
"angularjs",
"node.js",
"code-editor"
] |
Python - download file using GET form | 39,385,655 | <p>I am trying to write a script that downloads a xlsx file and saves it to the computer. This file doesn't have a specific path and it gets generated after filling a <code>GET</code> form. There are two submit buttons. </p>
<p>The first one makes a list of results under the form (I can do it).
The second one create... | 0 | 2016-09-08T08:04:47Z | 39,385,739 | <p>if I get you right you're trying to write a script that interacts with an existing website, fills a form, downloads a file and saves it, right?
you're not the one writing the website.</p>
<p>is so - I highly recommend using <a href="http://selenium-python.readthedocs.io/" rel="nofollow">selenium</a> to automate the... | 0 | 2016-09-08T08:09:57Z | [
"python",
"downloadfile"
] |
Concatenate Pandas Dataframe | 39,385,711 | <p>I am trying to concatenate few dataframes which depends on if they are created in the process. So for example I have following master list of many data frame</p>
<pre><code> List=['df_facebook','df_LinkedIn','df_Insta','tweet_final','df_Google','df_Slide','df_Youtube']
</code></pre>
<p>Now In my process, assume df... | 0 | 2016-09-08T08:08:34Z | 39,385,872 | <p>it is not a good idea to look variables in locals.
however, you can try:</p>
<pre><code>list_a=[locals()[col] for col in List if col in locals()]
# for example
List = ['df_google', 'df_facebook', 'df_linkedin']
# the frames should have the same column name if you want to concat vertically
df_google = pd.DataFrame(n... | 1 | 2016-09-08T08:16:45Z | [
"python",
"pandas",
"for-loop",
"dataframe"
] |
Regex in django models | 39,385,914 | <p>I've got a problem with regex in django models, the file name must start with letter or numer and the rest of work can caontains letters, numbers and two special signs: - and _. My code looks like:</p>
<pre><code>file_validator = validators.RegexValidator(
regex='^[a-zA-Z0-9]*[a-zA-Z0-9\_\-]*$',
message=(u'Name mus... | 0 | 2016-09-08T08:18:51Z | 39,386,681 | <p>I believe you do not need the <code>+</code> as <a href="http://stackoverflow.com/questions/39385914/regex-in-django-models#comment66098698_39385914">Avinash suggests</a>, you just need to drop the first <code>*</code> quantifier that means <em>zero or more occurrences</em>. Since it allows 0 occurrences the <em>mus... | 0 | 2016-09-08T08:58:59Z | [
"python",
"regex",
"django",
"django-models"
] |
How to replace a pattern start with {| to end of string (multi line), if there is no |} inside | 39,385,967 | <p>What I need is to manipulate bad-formated wiki code.
I have:</p>
<pre><code>s = '''
whatever...
{|
line1
|}
whatever...
{|
lineXXX
'''
</code></pre>
<p>Now I want to delete from {| to end, if no |} inside.</p>
<p>The result I want is:</p>
<pre><code>'''
whatever...
{|
line1
|}
whatever...
'''
</code></pre>
... | 1 | 2016-09-08T08:22:17Z | 39,386,160 | <p>First of all, your pattern contains an unescaped <code>|</code> that becomes an alternation operator. Then, <code>[^(\|\})]*</code> does not negate a <em>sequence</em> of <code>|}</code>, it just matches 0+ chars other than <code>(</code>, <code>|</code>, <code>}</code> and <code>)</code>.</p>
<p>You may use a <a h... | 2 | 2016-09-08T08:31:30Z | [
"python",
"regex"
] |
Python copy, cut and paste detection | 39,385,996 | <p>I am new to python, I am currently designing a program that runs in the background and i want it to detect if any copy, cut or paste operation is performed on a PC.
Or is there a way i can detect when control c, control v or control x is pressed by a user
Thanks</p>
| -1 | 2016-09-08T08:23:41Z | 39,386,065 | <p>You can try a key logger to detect key stroke like <a href="https://github.com/ajinabraham/Xenotix-Python-Keylogger/blob/master/xenotix_python_logger.py" rel="nofollow">this</a> one. Other than that you can use key hooking using system calls.</p>
| 0 | 2016-09-08T08:27:06Z | [
"python",
"copy",
"paste",
"cut"
] |
Python copy, cut and paste detection | 39,385,996 | <p>I am new to python, I am currently designing a program that runs in the background and i want it to detect if any copy, cut or paste operation is performed on a PC.
Or is there a way i can detect when control c, control v or control x is pressed by a user
Thanks</p>
| -1 | 2016-09-08T08:23:41Z | 39,386,820 | <p>You could try to register changes to clipboard to trigger your event.</p>
<p>Take a look at this stack overflow question: <a href="http://stackoverflow.com/questions/14685999/trigger-an-event-when-clipboard-content-changes">link</a></p>
| 0 | 2016-09-08T09:04:58Z | [
"python",
"copy",
"paste",
"cut"
] |
Python Indentation Error Issue | 39,386,080 | <p>I'm getting this problem on a simple test on a Python file,</p>
<pre><code>class Prueba(object):
def __init__(self):
self.position = 0
def build_message(self, signal):
message = self.position
message = message | (0b1<<signal)
s = bin(message)
s = s[2:len(s)]
... | 0 | 2016-09-08T08:28:02Z | 39,386,166 | <p>This must be an issue of tabs mixed with spaces.</p>
<p>You can convert all the tabs into spaces by changing some settings in editor you are using.</p>
<p>In case of sublime text :
Preferences -> settings-User</p>
<p>Try saving this as Packages/User/Preferences.sublime-settings</p>
<pre><code>{
"tab_size": 4... | 0 | 2016-09-08T08:31:49Z | [
"python"
] |
How to save results for each while loop in python? | 39,386,134 | <p>as you can see from my code there will be 150 dx value like dx(1) for j=50, dx(2) for j=51---dx(150) for j=149. I want to write all dx (upto 149) value in one column of "foobar.xls" file. Presently, I found in xls file, only the value of dx(150). so that is my problem. Sorry for improper questioning. (I`m new here).... | -3 | 2016-09-08T08:29:57Z | 39,407,180 | <pre><code>Its working like this way. Thanks for our nice comments and helpful mind.
j=50
i=1
while j<300:
x=np.array([sh1.cell_value(j,1)])
condition = [(x1<=(sh1.cell_value(j,1)+100)) & (x1>= (sh1.cell_value(j,1)-200)) ]
dx=x-x1[condition]
j+=1
for n in dx:
sheet.write... | 0 | 2016-09-09T08:30:59Z | [
"python",
"excel",
"while-loop",
"saving-data"
] |
How to open a mat file in python | 39,386,264 | <p>I was trying to open a mat file in python but my attempts did fail.
Here is my code</p>
<pre><code>from scipy import *
from pylab import *
save('rfdata.mat')
import scipy.io as sio
mat = scipy.io.loadmat('rfdata.mat');
</code></pre>
<p>python says that : </p>
<pre><code>Traceback (most recent call last):
Fi... | 0 | 2016-09-08T08:37:38Z | 39,386,312 | <p>As you did:</p>
<pre><code>import scipy.io as sio
</code></pre>
<p>You loaded <code>scipy.io</code> into <code>sio</code>. So, when you call:</p>
<pre><code>mat = scipy.io.loadmat('rfdata.mat');
</code></pre>
<p><code>scipy</code> is not defined, but <code>sio</code> is:</p>
<pre><code>mat = sio.loadmat('rfdata... | 0 | 2016-09-08T08:39:58Z | [
"python"
] |
Python/Django unittest, how to handle outside calls? | 39,386,340 | <p>I read multiple times that one should use <code>mock</code> to mimic outside calls and there should be no calls made to any outside service because your tests need to run regardless of outside services. </p>
<p>This totally makes sense....BUT</p>
<p>What about outside services changing? What good is a test, testin... | 1 | 2016-09-08T08:41:30Z | 39,386,569 | <p>There are different levels of testing.</p>
<p><strong>Unit tests</strong> are testing, as you might guess from the name, a unit. Which is for example a function or a method, maybe a class. If you interpret it wider it might include a view to be tested with Djangos test client. Unittests never test external stuff li... | 3 | 2016-09-08T08:53:41Z | [
"python",
"django",
"unit-testing",
"testing",
"call"
] |
Search and replace specific line which starts with specific string in a file | 39,386,384 | <p>My requirement is to open a properties file and update the file, for update purpose i need to search for a specific string which stores the url information. For this purpose i have written the below code in python:</p>
<pre><code>import os
owsURL="https://XXXXXXXXXXXXXX/"
reowsURL = "gStrOwsEnv = " + owsURL + "/" +... | 0 | 2016-09-08T08:44:08Z | 39,386,679 | <p>I'm pretty sure that this is not the best way of doing that, but this is still one way:</p>
<pre><code>with open(input_file_name, 'r') as f_in, open(output_file_name, 'w') as f_out:
for line in f_in:
if line.startswith("gStrOwsEnv"):
f_out.write(reowsURL)
else:
f_out.writ... | 1 | 2016-09-08T08:58:56Z | [
"python",
"file",
"search",
"replace"
] |
Why doesn't the numpy-C api warn me about failed allocations? | 39,386,450 | <p>I've been writing a python extension that writes into a numpy array from C. During testing, I noticed that certain very large arrays would generate a segfault when I tried to access some of their elements. Specifically, the last line of the following code segment fails with a SEGFAULT:</p>
<pre><code> // Size of... | 3 | 2016-09-08T08:47:19Z | 39,392,253 | <p>The issue (diagnosed in the comments) was actually with the array lookup rather than the allocation of the array. Your code contained the line</p>
<pre><code>output_buffer[((int) buffer_len_alt) - 1] = 'x'
</code></pre>
<p>When <code>buffer_len_alt</code> (approx value 3000000000) was cast to an (32 bit) int (max... | 2 | 2016-09-08T13:27:03Z | [
"python",
"c",
"numpy",
"python-c-api"
] |
How to read data in Python dataframe without concatenating? | 39,386,458 | <p>I want to read the file f (file size:85GB) in chunks to a dataframe. Following code is suggested.</p>
<pre><code>chunksize = 5
TextFileReader = pd.read_csv(f, chunksize=chunksize)
</code></pre>
<p>However, this code gives me TextFileReader, not dataframe. Also, I don't want to concatenate these chunks to convert T... | 0 | 2016-09-08T08:47:44Z | 39,386,767 | <p>As you are trying to process 85GB CSV file, if you will try to read all the data by breaking it into chunks and converting it into dataframe then it will hit memory limit for sure. You can try to solve this problem by using different approach. In this case, you can use filtering operations on your data. For example,... | 0 | 2016-09-08T09:02:30Z | [
"python",
"csv",
"pandas",
"dataframe",
"chunks"
] |
How to print the query of .get queryset in django | 39,386,513 | <p>How can I know the query when doing a .get queryset in django</p>
<p>I have this model:</p>
<pre><code>class Artist(EsIndexable, models.Model):
name = models.CharField(max_length=50)
birth_date = models.DateField()
</code></pre>
<p>And I did this in the shell:</p>
<pre><code>x = Artist.objects.get(name="... | 1 | 2016-09-08T08:50:47Z | 39,386,591 | <pre><code>from django.db import connection
x = Artist.objects.get(name="Eminem")
print connection.queries[-1]
</code></pre>
| 3 | 2016-09-08T08:55:21Z | [
"python",
"django"
] |
How to print the query of .get queryset in django | 39,386,513 | <p>How can I know the query when doing a .get queryset in django</p>
<p>I have this model:</p>
<pre><code>class Artist(EsIndexable, models.Model):
name = models.CharField(max_length=50)
birth_date = models.DateField()
</code></pre>
<p>And I did this in the shell:</p>
<pre><code>x = Artist.objects.get(name="... | 1 | 2016-09-08T08:50:47Z | 39,386,611 | <p><code>.get</code> returns an instance, not a queryset.</p>
<p>To see the query that is done, do the same thing but with <code>.filter</code>, which does return a queryset:</p>
<pre><code>queryset = Artist.objects.filter(name="Eminem")
print queryset.query
x = queryset.get()
</code></pre>
| 2 | 2016-09-08T08:56:10Z | [
"python",
"django"
] |
Python 'except' clauses not working | 39,386,618 | <p>Hello Stack Overflow community.</p>
<p>I'm currently trying to learn how to program in Python (3.5) and I've had a problem with a conversion program. Summarised, it seems like Python is ignoring the except clauses in the source code.</p>
<pre><code>try:
print("Welcome to CONVERSION. Choose an option.")
pri... | 0 | 2016-09-08T08:56:29Z | 39,386,699 | <p>The exception is thrown after you caught an exception. This basically puts it outside the try catch scenario.</p>
<p>If you add <code>Option = None</code> before <code>try</code> the code should execute properly.</p>
<p>The reason for this is because <code>int(input(...))</code> raises an exception before Option i... | 4 | 2016-09-08T08:59:41Z | [
"python",
"nameerror",
"except"
] |
Python 'except' clauses not working | 39,386,618 | <p>Hello Stack Overflow community.</p>
<p>I'm currently trying to learn how to program in Python (3.5) and I've had a problem with a conversion program. Summarised, it seems like Python is ignoring the except clauses in the source code.</p>
<pre><code>try:
print("Welcome to CONVERSION. Choose an option.")
pri... | 0 | 2016-09-08T08:56:29Z | 39,386,724 | <p>You are trying to use variable <code>Option</code> in your string with error, but that variable doesn't exist, as it's the reason of the error. Try initiating <code>Option = input()</code> before the <code>try</code> and convert it to int in <code>try</code></p>
| 2 | 2016-09-08T09:00:52Z | [
"python",
"nameerror",
"except"
] |
Python 'except' clauses not working | 39,386,618 | <p>Hello Stack Overflow community.</p>
<p>I'm currently trying to learn how to program in Python (3.5) and I've had a problem with a conversion program. Summarised, it seems like Python is ignoring the except clauses in the source code.</p>
<pre><code>try:
print("Welcome to CONVERSION. Choose an option.")
pri... | 0 | 2016-09-08T08:56:29Z | 39,386,735 | <p>It works as it should. When you're handling the <code>ValueError</code> exception, you try to read <code>Option</code>, which is not set yet. This results in another exception. which you don't catch anymore.</p>
| 0 | 2016-09-08T09:01:29Z | [
"python",
"nameerror",
"except"
] |
How do you set a default value for a variable in Python3? | 39,386,729 | <p>For an assignment I have to write a program that can create directories and files, we have to write a DirectoryEntry class to help do this, and for part of it we have to create a name for the file or directory. If a name is entered then we just use the name but if no name is entered we just use 9 spaces. </p>
<p>I ... | 0 | 2016-09-08T09:01:09Z | 39,386,805 | <p>You can use:</p>
<pre><code>def __init__(self, name='your_default_name'):
</code></pre>
<p>Then you can either create an object of that class with <code>my_object()</code> and it will use the default value, or use <code>my_object('its_name')</code> and it will use the input value.</p>
| 3 | 2016-09-08T09:04:11Z | [
"python",
"default-value",
"default-constructor"
] |
How do you set a default value for a variable in Python3? | 39,386,729 | <p>For an assignment I have to write a program that can create directories and files, we have to write a DirectoryEntry class to help do this, and for part of it we have to create a name for the file or directory. If a name is entered then we just use the name but if no name is entered we just use 9 spaces. </p>
<p>I ... | 0 | 2016-09-08T09:01:09Z | 39,386,807 | <p>You can use default arguments:</p>
<pre><code>def __init__(self, name=' '):
</code></pre>
| 0 | 2016-09-08T09:04:18Z | [
"python",
"default-value",
"default-constructor"
] |
How do you set a default value for a variable in Python3? | 39,386,729 | <p>For an assignment I have to write a program that can create directories and files, we have to write a DirectoryEntry class to help do this, and for part of it we have to create a name for the file or directory. If a name is entered then we just use the name but if no name is entered we just use 9 spaces. </p>
<p>I ... | 0 | 2016-09-08T09:01:09Z | 39,386,809 | <p>Just set it like this, so for default will use 9 spaces</p>
<pre><code>def __init__(self, name=' '):
self.type = "f:"
self.name = name
self.length = "0000"
self.colon = ":"
self.blocks = ["000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000", "000... | 1 | 2016-09-08T09:04:27Z | [
"python",
"default-value",
"default-constructor"
] |
How do you set a default value for a variable in Python3? | 39,386,729 | <p>For an assignment I have to write a program that can create directories and files, we have to write a DirectoryEntry class to help do this, and for part of it we have to create a name for the file or directory. If a name is entered then we just use the name but if no name is entered we just use 9 spaces. </p>
<p>I ... | 0 | 2016-09-08T09:01:09Z | 39,386,848 | <p>Specify it as a default variable as shown below</p>
<pre><code>def __init__(self, name=' '*9):
self.type = "f:"
self.name = name
self.length = "0000"
self.colon = ":"
self.blocks = ["000", "000", "000", "000", "000", "000", "000","000","000","000", "000", "000"]
</code></pre>
| 1 | 2016-09-08T09:06:28Z | [
"python",
"default-value",
"default-constructor"
] |
Opening file from a Fileshare-system with python | 39,386,825 | <p>im trying to open a file from a Filesharing-System of our company. Here is the Code of the script:</p>
<pre><code>import sys
import xlrd
from tkinter import *
import pandas as pd
import time
from os import *
#hvl_file_path = filedialog.askopenfilename()
save_path = filedialog.asksaveasfilename(initialdir="C:/", de... | 0 | 2016-09-08T09:05:11Z | 39,390,146 | <p>When dealing with UNC strings or Windows strings in general it is better to declare constant strings with the <code>r</code> (raw) prefix:</p>
<pre><code>pd.read_csv(r'\\Q4DEE1SYVFS.ffm ...')
</code></pre>
<p>not doing that result in some chars to be interpreted:</p>
<pre><code>print("foo\test")
</code></pre>
<p... | 1 | 2016-09-08T11:49:58Z | [
"python",
"pandas"
] |
PySpark - How to output JSON with specific fields? | 39,386,832 | <p>The JSON format looks like:</p>
<pre><code>{
"name": "aaa",
"address": {
"street": "blv abc",
"street_num": "122"
}
}
</code></pre>
<p>I would read the data from parquet files and execute a sql query on them, like finding all those living at street <code>blv abc</code>. But I just want to output the ... | 1 | 2016-09-08T09:05:37Z | 39,406,696 | <p>My last resort for this kind of unusual data transformation is</p>
<pre><code>from pyspark.sql.types import Row
def transform(row):
d = row.asDict() # now in python data types
del d['address']['street_num']
return Row(**d)
new = dataframe.rdd.map(transform)
</code></pre>
<p>I suppose you want to r... | 1 | 2016-09-09T08:02:25Z | [
"python",
"json",
"apache-spark",
"pyspark"
] |
How to define a temporary variable in python? | 39,386,837 | <p>Does python have a "temporary" or "very local" variable facility? I am looking for a one-liner and I want to keep my variable space tidy.</p>
<p>I would like to do something like this:</p>
<pre><code>...a, b, and c populated as lists earlier in code...
using ix=getindex(): print(a[ix],b[ix],c[ix])
...now ix is no... | 1 | 2016-09-08T09:05:47Z | 39,386,999 | <p>Comprehensions and generator expressions have their own scope, so you can put it in one of those:</p>
<pre><code>>>> def getindex():
... return 1
...
>>> a,b,c = range(2), range(3,5), 'abc'
>>> next(print(a[x], b[x], c[x]) for x in [getindex()])
1 4 b
>>> x
Traceback (most re... | 1 | 2016-09-08T09:14:19Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.