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 |
|---|---|---|---|---|---|---|---|---|---|
Django userena check if mugshot is set | 39,751,901 | <p>Ok so this is the models.py of userena. Can i check using template tags in html if mugshot is set? The first if statement checks if the mugshot is uploaded.</p>
<pre><code>def get_mugshot_url(self):
"""
Returns the image containing the mugshot for the user.
The mugshot can be a uploaded image or a Grav... | 0 | 2016-09-28T15:33:48Z | 39,752,090 | <p>You could simply replicate the first <code>if</code> statement in the template on the user profile's instance. Something like</p>
<pre><code>{% if profile.mugshot %}
profile.mugshot.url
{% endif %}
</code></pre>
| 1 | 2016-09-28T15:43:06Z | [
"python",
"django"
] |
how to align text in python turtle with drawn polygon with n sides | 39,751,935 | <p>I am a beginner at python and am writing a simple program with python turtle, prompting the user to enter a side length of a polygon, and the program is supposed to draw the polygon and print the name of the person (me) under the polygon.</p>
<p>I have gotten the program to work, however I cannot seem to figure out... | 0 | 2016-09-28T15:35:13Z | 39,785,257 | <p>Let's try to go the simplest route to a solution. First, let's get your polygon centered on the window. We can do that by adding:</p>
<pre><code>turtle.backward(polygonSideLength / 2)
</code></pre>
<p>before the filled polygon drawing begins. Next, let's get it into the upper half of the window instead of the l... | 0 | 2016-09-30T06:43:56Z | [
"python",
"turtle-graphics"
] |
what is most pythonic way to find a element in a list that is different with other elements? | 39,751,945 | <p>Suppose we have a list with unknown size and there is an element in the list that is different with other elements but we don't know the index of the element. the list only contains numerics and is fetched from a remote server and the length of the list and the index of the different element is changed every time. w... | 2 | 2016-09-28T15:35:36Z | 39,752,124 | <p>Would this work for you?</p>
<pre><code>In [6]: my_list = [1,1,1,2,1,1,1]
In [7]: different = [ii for ii in set(my_list) if my_list.count(ii) == 1]
In [8]: different
Out[8]: [2]
</code></pre>
| 2 | 2016-09-28T15:44:38Z | [
"python"
] |
what is most pythonic way to find a element in a list that is different with other elements? | 39,751,945 | <p>Suppose we have a list with unknown size and there is an element in the list that is different with other elements but we don't know the index of the element. the list only contains numerics and is fetched from a remote server and the length of the list and the index of the different element is changed every time. w... | 2 | 2016-09-28T15:35:36Z | 39,752,197 | <p>You can use <code>Counter</code> from <code>collections</code> package</p>
<pre><code>from collections import Counter
a = [1,2,3,4,3,4,1]
b = Counter(a) # Counter({1: 2, 2: 1, 3: 2, 4: 2})
elem = list(b.keys())[list(b.values()).index(1)] # getting elem which is key with value that equals 1
print(a.index(elem))
<... | 2 | 2016-09-28T15:48:26Z | [
"python"
] |
what is most pythonic way to find a element in a list that is different with other elements? | 39,751,945 | <p>Suppose we have a list with unknown size and there is an element in the list that is different with other elements but we don't know the index of the element. the list only contains numerics and is fetched from a remote server and the length of the list and the index of the different element is changed every time. w... | 2 | 2016-09-28T15:35:36Z | 39,752,296 | <p>I would try maybe something like this:</p>
<pre><code>newList = list(set(my_list))
print newList.pop()
</code></pre>
<p>Assuming there's only 1 different value and the rest are all the same.
There's a little bit of ambiguity in your question which makes it difficult to answer but that's all I could think of optima... | 1 | 2016-09-28T15:53:31Z | [
"python"
] |
what is most pythonic way to find a element in a list that is different with other elements? | 39,751,945 | <p>Suppose we have a list with unknown size and there is an element in the list that is different with other elements but we don't know the index of the element. the list only contains numerics and is fetched from a remote server and the length of the list and the index of the different element is changed every time. w... | 2 | 2016-09-28T15:35:36Z | 39,754,208 | <p>This is a great use for <a href="http://www.numpy.org" rel="nofollow">numpy</a></p>
<p>Given some random uniform list with a single uniquely different number in it:</p>
<pre><code>>>> li=[1]*100+[200]+[1]*250
</code></pre>
<p>If the uniform value is known (in this case 1 and the unknown value is 200) you... | 1 | 2016-09-28T17:36:03Z | [
"python"
] |
Variable length arguments | 39,752,005 | <p>I am creating a python program using the <a href="https://docs.python.org/3/library/argparse.html"><code>argparse</code> module</a> and I want to allow the program to take either one argument or 2 arguments.</p>
<p>What do I mean? Well, I am creating a program to download/decode MMS messages and I want the user to... | 6 | 2016-09-28T15:38:30Z | 39,752,370 | <p>This is a little beyond the scope of what <code>argparse</code> can do, as the "type" of the first argument isn't known ahead of time. I would do something like</p>
<pre><code>import argparse
p = argparse.ArgumentParser()
p.add_argument("file_or_phone", help="MMS File or phone number")
p.add_argument ("mmsid", nar... | 4 | 2016-09-28T15:56:41Z | [
"python",
"python-3.x",
"argparse"
] |
Python How to detect vertical and horizontal lines in an image with HoughLines with OpenCV? | 39,752,235 | <p>I m trying to obtain a threshold of the calibration chessboard. I cant detect directly the chessboard corners as there is some dust as i observe a micro chessboard.
I try several methods and HoughLinesP seems to be the easiest approach. But the results are not good, how to improve my results?</p>
<pre><code>import ... | 2 | 2016-09-28T15:51:07Z | 39,916,236 | <p>I would rather write this as a comment but unfortunately I can't. You should change the minLineLength and minLineGap. Or what if its just sqaures that you have to find, I would get all the lines and check the angles between them to get lines only along squares. I have worked with HoughLineP before and it is pretty m... | 0 | 2016-10-07T11:33:47Z | [
"python",
"opencv",
"camera-calibration",
"hough-transform"
] |
Python How to detect vertical and horizontal lines in an image with HoughLines with OpenCV? | 39,752,235 | <p>I m trying to obtain a threshold of the calibration chessboard. I cant detect directly the chessboard corners as there is some dust as i observe a micro chessboard.
I try several methods and HoughLinesP seems to be the easiest approach. But the results are not good, how to improve my results?</p>
<pre><code>import ... | 2 | 2016-09-28T15:51:07Z | 39,925,027 | <p>in images processing they are some roles you have to go through such as filters before you go for edges detection, in your condition the dust is just a noise that you have to remove by filter, use gausse or blure after that use thresholding and then use canny for edges and in opencv they are cornere detection you ca... | 0 | 2016-10-07T20:08:12Z | [
"python",
"opencv",
"camera-calibration",
"hough-transform"
] |
Python How to detect vertical and horizontal lines in an image with HoughLines with OpenCV? | 39,752,235 | <p>I m trying to obtain a threshold of the calibration chessboard. I cant detect directly the chessboard corners as there is some dust as i observe a micro chessboard.
I try several methods and HoughLinesP seems to be the easiest approach. But the results are not good, how to improve my results?</p>
<pre><code>import ... | 2 | 2016-09-28T15:51:07Z | 39,925,278 | <p>You are using too small value for rho.</p>
<p><strong>Try the below code:-</strong></p>
<pre><code>import numpy as np
import cv2
gray = cv2.imread('lines.jpg')
edges = cv2.Canny(gray,50,150,apertureSize = 3)
cv2.imwrite('edges-50-150.jpg',edges)
minLineLength=100
lines = cv2.HoughLinesP(image=edges,rho=1,theta=np... | 3 | 2016-10-07T20:25:58Z | [
"python",
"opencv",
"camera-calibration",
"hough-transform"
] |
Using BeautifulSoup, how to get text only from the specific selector without the text in the children? | 39,752,403 | <p>I don't know how to code BeautifulSoup so that it gives me only the text from the selected tag. I get more such as the text of its child(ren)!</p>
<p>For example:</p>
<pre><code>from bs4 import BeautifulSoup
soup = BeautifulSoup('<div id="left"><ul><li>"I want this text"<a href="someurl.com"&g... | 1 | 2016-09-28T15:58:33Z | 39,752,453 | <p>One option would be to get the first element of the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#contents-and-children" rel="nofollow"><code>contents</code> list</a>:</p>
<pre><code>for i in x:
print(i.contents[0])
</code></pre>
<p>Another - find the first <em>text node</em>:</p>
<pre><code... | 3 | 2016-09-28T16:01:04Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Using BeautifulSoup, how to get text only from the specific selector without the text in the children? | 39,752,403 | <p>I don't know how to code BeautifulSoup so that it gives me only the text from the selected tag. I get more such as the text of its child(ren)!</p>
<p>For example:</p>
<pre><code>from bs4 import BeautifulSoup
soup = BeautifulSoup('<div id="left"><ul><li>"I want this text"<a href="someurl.com"&g... | 1 | 2016-09-28T15:58:33Z | 39,753,003 | <pre><code>from bs4 import BeautifulSoup
from bs4 import NavigableString
soup = BeautifulSoup('<div id="left"><ul><li>"I want this text"<a href="someurl.com"> I don\'t want this text</a><p>I don\'t want this either</li><li>"Good"<a href="someurl.com"> Not Good</a... | -1 | 2016-09-28T16:29:59Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Reading 3 columns of data from .txt into list | 39,752,428 | <p>Hello I have a question here. I have the following text file (3 columns and space between). I want to insert each column(tt,ff,ll) into it's own list(time,l,f).</p>
<p>Text file:</p>
<pre><code> 0.0000000000000000 656.5342434532456082 0.9992059165961109
1.0001828508431749 656.5342334512754405 ... | 0 | 2016-09-28T15:59:46Z | 39,752,603 | <p>use the <code>loadtxt</code> function of numpy</p>
<pre><code>text_array = np.loadtxt('my_file.txt')
time = text_array[:, 0]
l = text_array[:, 1]
f = text_array[:, 2]
</code></pre>
| 0 | 2016-09-28T16:08:03Z | [
"python",
"list",
"text-files",
"multiple-columns"
] |
Reading 3 columns of data from .txt into list | 39,752,428 | <p>Hello I have a question here. I have the following text file (3 columns and space between). I want to insert each column(tt,ff,ll) into it's own list(time,l,f).</p>
<p>Text file:</p>
<pre><code> 0.0000000000000000 656.5342434532456082 0.9992059165961109
1.0001828508431749 656.5342334512754405 ... | 0 | 2016-09-28T15:59:46Z | 39,752,608 | <p>I just tried your code and it works, returning a tuple of lists. If your question is how to turn this tuple of lists into your requested format (which will be very clunky, because of the amount of data), you can just add this to the end, using your <code>txt1</code> variable:</p>
<p>(edited to include line breaks)<... | 1 | 2016-09-28T16:08:18Z | [
"python",
"list",
"text-files",
"multiple-columns"
] |
Reading 3 columns of data from .txt into list | 39,752,428 | <p>Hello I have a question here. I have the following text file (3 columns and space between). I want to insert each column(tt,ff,ll) into it's own list(time,l,f).</p>
<p>Text file:</p>
<pre><code> 0.0000000000000000 656.5342434532456082 0.9992059165961109
1.0001828508431749 656.5342334512754405 ... | 0 | 2016-09-28T15:59:46Z | 39,752,635 | <p>Your <code>return</code> statement is currently incorrectly indented. When I corrected that it appears to work.</p>
<p>A simpler way might be</p>
<pre><code>def read_file(filename):
infile = open(filename, "r") # reads file
rows = [line.split() for line in infile]
return [r[i] for r in rows for i in ra... | 0 | 2016-09-28T16:09:49Z | [
"python",
"list",
"text-files",
"multiple-columns"
] |
Merge two CSV files Keeping duplicates | 39,752,434 | <p>I am trying to merge two csv files and keep duplicate records. Each file may have a matching record, one file may have duplicate records (same student ID with different test scores), and one file may not have a matching student record in the other file. The code below works as expected however if a duplicate recor... | -2 | 2016-09-28T16:00:03Z | 39,752,562 | <p>You're using an <code>OrderedDict</code> to store student IDs (keys) and their record (values) from both files. </p>
<p>This has a subtle implication: new <em>student ID</em> entries will replace the old duplicate <em>student ID</em> dict entries from the previous file, because dict keys are unique.</p>
<p>You ma... | 0 | 2016-09-28T16:06:09Z | [
"python",
"python-3.x",
"csv",
"merge"
] |
Merge two CSV files Keeping duplicates | 39,752,434 | <p>I am trying to merge two csv files and keep duplicate records. Each file may have a matching record, one file may have duplicate records (same student ID with different test scores), and one file may not have a matching student record in the other file. The code below works as expected however if a duplicate recor... | -2 | 2016-09-28T16:00:03Z | 39,752,987 | <p>For your inner loop you can do the following:</p>
<pre><code>for row in reader:
new_record = dict(row)
records = data.setdefault(row['Student_Number'], [])
for record in records:
new_record.update(record) # preserve old values
record = copy.copy(new_record)
new_record.update(dict(ro... | 0 | 2016-09-28T16:29:07Z | [
"python",
"python-3.x",
"csv",
"merge"
] |
Merge two CSV files Keeping duplicates | 39,752,434 | <p>I am trying to merge two csv files and keep duplicate records. Each file may have a matching record, one file may have duplicate records (same student ID with different test scores), and one file may not have a matching student record in the other file. The code below works as expected however if a duplicate recor... | -2 | 2016-09-28T16:00:03Z | 39,753,180 | <p>I would personally use <a href="http://pandas.pydata.org/" rel="nofollow">Pandas</a> for something like this, specifically <a href="http://pandas.pydata.org/pandas-docs/stable/merging.html#concatenating-using-append" rel="nofollow">DataFrame.append</a></p>
<p>First you would create a DataFrame for both CSVs using <... | 0 | 2016-09-28T16:39:40Z | [
"python",
"python-3.x",
"csv",
"merge"
] |
matplotlib - multiple markers for a plot based on additional data | 39,752,488 | <p>Lets say I have the following data say</p>
<pre><code>x=[0,1,2,3,4,5,6,7,8,9]
y=[1.0,1.5,2.3,2.2,1.1,1.4,2.0,2.8,1.9,2.0]
z=['A','A','A','B','B','A','B','B','B','B']
plt.plot(x,y, marker='S')
</code></pre>
<p>will give me a x-y plot with square markers. Is there a way to change the marker type based on the data z,... | 1 | 2016-09-28T16:03:17Z | 39,753,209 | <pre><code>import matplotlib.pyplot as plt
fig = plt.figure(0)
x=[0,1,2,3,4,5,6,7,8,9]
y=[1.0,1.5,2.3,2.2,1.1,1.4,2.0,2.8,1.9,2.0]
z=['A','A','A','B','B','A','B','B','B','B']
plt.plot(x,y)
if 'A' in z and 'B' in z:
xs = [a for a,b in zip(x, z) if b == 'A']
ys = [a for a,b in zip(y, z) if b == 'A']
plt.sca... | 1 | 2016-09-28T16:41:15Z | [
"python",
"matplotlib"
] |
error to execute djangocms -f -p . mysite | 39,752,641 | <p>I have a problem when I execute <code>djangocms -f -p . mysite</code>
the process started but fail when it have to create an admin user.</p>
<pre><code>Creating admin user
/Users/ccsguest/Site/djangoProject/django1101/bin/python2.7: can't open file 'create_user.py': [Errno 2] No such file or directory
The install... | 0 | 2016-09-28T16:10:18Z | 39,766,057 | <p>I had the same issue.<br>
Adding '-w' did the trick for me:</p>
<p><code>source venv/bin/activate</code><br>
<code>mkdir project_name</code><br>
<code>cd project_name</code><br>
<code>djangocms -w -f -p . project_name</code> </p>
| 1 | 2016-09-29T09:09:03Z | [
"python",
"django",
"django-cms"
] |
Graphene/Django (GraphQL): How to use a query argument in order to exclude nodes matching a specific filter? | 39,752,667 | <p>I have some video items in a Django/Graphene backend setup. Each video item is linked to one owner.
In a React app, I would like to query via GraphQL all the videos owned by the current user on the one hand and all the videos NOT owned by the current user on the other hand.</p>
<p>I could run the following GraphQl ... | 0 | 2016-09-28T16:11:37Z | 39,774,434 | <p>Switching to graphene-django 1.0, I have been able to do what I wanted with the following query definition:</p>
<pre><code>class Query(AbstractType):
selected_scenes = DjangoFilterConnectionField(SceneNode, exclude=Boolean())
def resolve_selected_scenes(self, args, context, info):
owner__name = ar... | 0 | 2016-09-29T15:30:37Z | [
"python",
"django",
"graphql",
"graphene-python"
] |
imaplib: what factors decide maintype is "text" or "multipart" | 39,752,682 | <p>I have been writing python code for small tool, wherein i am trying to fetch mails using python libraries imaplib and email.
code statement is something like below.</p>
<pre><code>import imaplib
import email
mail = imaplib.IMAP4_SSL('imap.server')
mail.login('userid@mail.com', 'password')
result, data = mail.uid('... | 1 | 2016-09-28T16:12:15Z | 39,784,652 | <p>From comments:</p>
<blockquote>
<p>raw_email for both cases has raw html code with multiple values. all most all html code is same except few differences. For maintype=multipart, Content-Type="multipart/alternative", boundary tag is present. For maintype=text, Content-Type="text/html", boundary field is not prese... | 0 | 2016-09-30T05:57:41Z | [
"python",
"email",
"imaplib"
] |
How to get spcific child page in django cms with {% show_menu_below_id %}? | 39,752,716 | <p>My DjangoCMS has the structure:</p>
<p>--Page a<br>
----Page a.1<br>
----Page a.2<br>
----Page a.3<br>
----Page a.4<br></p>
<p>Using {% show_menu_below_id "Page a"%} shows this:</p>
<pre><code><ul>
<li> Page a.1</li>
<li> Page a.2</li>
<li> Page a.3</li>
<l... | 0 | 2016-09-28T16:14:36Z | 39,753,134 | <p>You can do a lot when you specify a custom HTML for the menu. The template tag would be following:</p>
<pre><code>{% show_menu 0 100 100 100 "menu_top.html" %}
</code></pre>
<p>And in the menu_top.html, you have a variable called <code>children</code> available for your convenience. You can use the for loop counte... | 1 | 2016-09-28T16:37:20Z | [
"python",
"django",
"django-cms"
] |
convenient way to reindex one level of a multiindex | 39,752,729 | <p>consider the <code>pd.Series</code> <code>s</code> and <code>pd.MultiIndex</code> <code>idx</code></p>
<pre><code>idx = pd.MultiIndex.from_product([list('AB'), [1, 3], list('XY')],
names=['one', 'two', 'three'])
s = pd.Series(np.arange(8), idx)
s
one two three
A 1 X ... | 3 | 2016-09-28T16:15:36Z | 39,752,802 | <p>Unfortunately if need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> with <code>MultiIndex</code>, need all levels:</p>
<pre><code>mux = pd.MultiIndex.from_product([list('AB'), np.arange(4), list('XY')],
... | 2 | 2016-09-28T16:19:54Z | [
"python",
"pandas"
] |
Insert my chatbot in a website | 39,752,749 | <p>i have a question for you,</p>
<p>i have built a bot in python and i need to know if there is a way (or a service with REST API) to embed it in a website. I dont want to use slack/telegram/facebook messanger and others as comunication channels. I want to use a chat environment in a website but i dont really want to... | 1 | 2016-09-28T16:16:43Z | 39,763,581 | <h3>Use a chatbot generator</h3>
<p><strong><a href="https://codename.co/botgen/designer/" rel="nofollow">bot<em>gen</em></a></strong> is a service for designing and publishing a chatbot in minutes. I'm pretty sure it can suit your basic needs.</p>
<p>It can help you:</p>
<ul>
<li>define your bot behaviors (its logi... | 0 | 2016-09-29T07:04:20Z | [
"python",
"chatbot",
"web-chat"
] |
Insert my chatbot in a website | 39,752,749 | <p>i have a question for you,</p>
<p>i have built a bot in python and i need to know if there is a way (or a service with REST API) to embed it in a website. I dont want to use slack/telegram/facebook messanger and others as comunication channels. I want to use a chat environment in a website but i dont really want to... | 1 | 2016-09-28T16:16:43Z | 39,826,616 | <p>You can use <a href="http://talkus.io" rel="nofollow" title="Talkus">Talkus</a> and write a slack bot.
Talkus provide a hook that will be called when a visitor start a conversation.
So when the hook is called, make your bot join the channel and it will be able to discuss with your website visitors.</p>
<p>For the ... | 0 | 2016-10-03T07:40:23Z | [
"python",
"chatbot",
"web-chat"
] |
Interpretation of "too many resources for launch" | 39,752,819 | <p>Consider the following Python code:</p>
<pre><code>from numpy import float64
from pycuda import compiler, gpuarray
import pycuda.autoinit
# N > 960 is crucial!
N = 961
code = """
__global__ void kern(double *v)
{
double a = v[0]*v[2];
double lmax = fmax(0.0, a), lmin = fmax(0.0, -a);
double smax = s... | 1 | 2016-09-28T16:20:59Z | 39,753,783 | <p>It is almost certain that you are hitting a registers-per-block limit. </p>
<p>Reading the <a href="http://docs.nvidia.com/cuda/cuda-c-programming-guide/index.html#features-and-technical-specifications" rel="nofollow">relevant documentation</a>, your device has a limit of 32k 32 bit registers per block. When the bl... | 2 | 2016-09-28T17:12:45Z | [
"python",
"numpy",
"cuda",
"pycuda"
] |
Change axis in mapltolib figure | 39,752,943 | <p>Usually matplotlib uses this axis:</p>
<pre><code>Y
|
|
|_______X
</code></pre>
<p>But I need to plot my data using:</p>
<pre><code> _________Y
|
|
|
X
</code></pre>
<p>How can I do it? I will prefer not modify my data (i.e. transposing). I need to be able of use the coordinates always and matplotlib change... | 1 | 2016-09-28T16:27:08Z | 39,757,481 | <p>One of the variations:</p>
<pre><code>import matplotlib.pyplot as plt
def Scatter(x, y):
ax.scatter(y, x)
#Data preparation part:
x=[1, 2, 3, 4, 5]
y=[2, 3, 4, 5, 6]
#Plotting and axis inverting part
fig, ax = plt.subplots(figsize=(10,8))
plt.ylabel('X', fontsize=15)
plt.xlabel('Y', fontsize=15)
... | 2 | 2016-09-28T20:55:02Z | [
"python",
"numpy",
"matplotlib",
"axis"
] |
unable to runserver in django 1.10.1 due to database connection | 39,753,066 | <p>I am using PostGRE sql in my localhost in Django 1.10.1 and have installed all dependencies, psycopg2, postgresql, pgadmin3 and have set the password of postgresql via command line. I've used exactly the same password in settings.py of the django project. Still I am being shown the authentication error. I am using p... | 1 | 2016-09-28T16:33:44Z | 39,755,812 | <p>Looks like psycopg2 also had its own dependencies that were not properly installed for me.</p>
<p>Also the default username of is not postgresql but its just postgres</p>
<p>Both of the above checks gave me the solution required and django 1.10 server is up and running now.</p>
| 0 | 2016-09-28T19:10:46Z | [
"python",
"django",
"postgresql",
"psycopg2"
] |
Is there a more pythonic way to write this? | 39,753,082 | <p>I'm looking to make this a little more pythonic.</p>
<pre><code>user_df[-1:]['status_id'].values[0] in {3,5}
</code></pre>
<p>I ititially tried <code>user_id.ix[-1:, 'status_id'].isin([3,5])</code>, but didn't work.</p>
<p>Any suggestions? The top version works, but looks a little weird.</p>
| 1 | 2016-09-28T16:34:29Z | 39,753,131 | <p>You can try:</p>
<pre><code>user_id['status_id'].iloc[-1:].isin([3,5])
</code></pre>
<p>Sample:</p>
<pre><code>user_id = pd.DataFrame({'status_id':[1,2,3]})
print (user_id)
status_id
0 1
1 2
2 3
#iloc without : [-1] return scalar
print (user_id['status_id'].iloc[-1] in set({3,5}))
T... | 4 | 2016-09-28T16:37:08Z | [
"python",
"pandas"
] |
Is there a more pythonic way to write this? | 39,753,082 | <p>I'm looking to make this a little more pythonic.</p>
<pre><code>user_df[-1:]['status_id'].values[0] in {3,5}
</code></pre>
<p>I ititially tried <code>user_id.ix[-1:, 'status_id'].isin([3,5])</code>, but didn't work.</p>
<p>Any suggestions? The top version works, but looks a little weird.</p>
| 1 | 2016-09-28T16:34:29Z | 39,753,152 | <p><code>isin</code> might be marginally faster (the more values that you have to check the more speed up you would notice ... but even for large sets its not going to be a huge difference ...(I doubt its any faster in this example... its probably a little slower) ... but <code>val in set()</code> <strong>is pretty dan... | 2 | 2016-09-28T16:38:11Z | [
"python",
"pandas"
] |
Python: Replace df1.col values with df2.col2 values | 39,753,085 | <p>I have two data frames df1 and df2.
In df1 I have 50 columns and in df2 I have 50+ columns. What I want to achieve is that
In df1 I have 13000 rows and a column name subject where names of all subjects are given.
In df2 I have 250 rows and along 50+ I have two columns named subject code and subject_name. </p>
<pr... | 0 | 2016-09-28T16:34:40Z | 39,754,407 | <p>One of the issues you have is the incorrect spellings. You can try to harmonise the spelling of the subject across both <code>dataframes</code> using the <code>difflib</code> module and its <code>get_close_matches</code> method. </p>
<p>Using this code will return the closest matching subject for each match in <cod... | 0 | 2016-09-28T17:48:03Z | [
"python",
"pandas"
] |
Python: Replace df1.col values with df2.col2 values | 39,753,085 | <p>I have two data frames df1 and df2.
In df1 I have 50 columns and in df2 I have 50+ columns. What I want to achieve is that
In df1 I have 13000 rows and a column name subject where names of all subjects are given.
In df2 I have 250 rows and along 50+ I have two columns named subject code and subject_name. </p>
<pr... | 0 | 2016-09-28T16:34:40Z | 39,929,085 | <p>Correct the spelling then merge...</p>
<pre><code>import pandas as pd
import operator, collections
df1 = pd.DataFrame.from_items([("subjects",
["Biology","Physicss","Phsicss","Chemistry",
"Biology","Physics","Physics","Biolgy","navelgazing"])])
df2 =... | 0 | 2016-10-08T05:38:53Z | [
"python",
"pandas"
] |
VLOOKUP/ETL with Python | 39,753,103 | <p>I have a data that comes from MS SQL Server. The data from the query returns a list of names straight from a public database. For instance, If i wanted records with the name of "Microwave" something like this would happen:</p>
<pre><code>Microwave
Microwvae
Mycrowwave
Microwavee
</code></pre>
<p>Microwave would be... | 0 | 2016-09-28T16:35:37Z | 39,770,931 | <p>If you had have data like this:</p>
<pre><code>+-------------+-----------+
| typo | word |
+-------------+-----------+
| microweeve | microwave |
| microweevil | microwave |
| macroworv | microwave |
| murkeywater | microwave |
+-------------+-----------+
</code></pre>
<p>Save it as typo_map.csv</p>... | 1 | 2016-09-29T12:54:13Z | [
"python",
"sql-server",
"excel",
"python-3.x",
"vlookup"
] |
Write string to file with different byte size? | 39,753,119 | <p>I am doing a Python scripting.</p>
<p>I have a string, the <code>len()</code> of the string is <code>1048576</code> and the <code>sys.getsizeof()</code> of the string is <code>1048597</code>.</p>
<p>However, when I write this string to a file, the byte size of the file is <code>1051027</code>. My code is below, an... | 0 | 2016-09-28T16:36:33Z | 39,753,212 | <p>Your <code>allInOne = numpy.uint8(dataset.pixel_array).tostring()</code> doesn't look like text. When writing anything but text to a file in Python, you need to <a href="https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files">open the file in binary mode</a> (<code>"wb"</code> instead of <code... | 5 | 2016-09-28T16:41:39Z | [
"python",
"file"
] |
A generator for refactoring a combination of for loops and nested if statements | 39,753,217 | <p>The next code scans some log file and selects the lines with some particular characters.</p>
<pre><code>with open(file) as input:
for line in input:
if 'REW' in line or 'LOSE' in line:
<some optional code>
if 'REW VAL' in line or 'LOSE INV' in line:
<some... | 1 | 2016-09-28T16:42:03Z | 39,753,622 | <p>For arbitrary code, the best you can do is write a function like</p>
<pre><code>def foo(file, f1, f2):
with open(file) as input:
for line in input:
if 'REW' in line or 'LOSE' in line:
f1(line)
if 'REW VAL' in line or 'LOSE INV' in line:
f2(... | 1 | 2016-09-28T17:03:18Z | [
"python",
"refactoring",
"generator"
] |
A generator for refactoring a combination of for loops and nested if statements | 39,753,217 | <p>The next code scans some log file and selects the lines with some particular characters.</p>
<pre><code>with open(file) as input:
for line in input:
if 'REW' in line or 'LOSE' in line:
<some optional code>
if 'REW VAL' in line or 'LOSE INV' in line:
<some... | 1 | 2016-09-28T16:42:03Z | 39,753,677 | <p>Sometimes repetition is not that bad!</p>
<p>But anyway you can try something like this:</p>
<pre><code>#!/usr/bin/env python
# script.py
def process_file(filename, func1, func2):
with open(filename) as f:
for line in f:
if '1' in line:
func1(line)
if '2' in... | 1 | 2016-09-28T17:06:29Z | [
"python",
"refactoring",
"generator"
] |
scatter plot with single pixel marker in matplotlib | 39,753,282 | <p>I am trying to plot a large dataset with a scatter plot.
I want to use matplotlib to plot it with single pixel marker.
It seems to have been solved.</p>
<p><a href="https://github.com/matplotlib/matplotlib/pull/695" rel="nofollow">https://github.com/matplotlib/matplotlib/pull/695</a></p>
<p>But I cannot find a m... | 0 | 2016-09-28T16:45:15Z | 39,778,483 | <p>I fear that the bugfix discussed at matplotlib git repository that you're citing is only valid for <code>plt.plot()</code> and not for <code>plt.scatter()</code></p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4,2))
ax = fig.add_subplot(121)
ax2 = fig.add_subplot(122, sharex=ax, sharey=ax)... | 0 | 2016-09-29T19:27:19Z | [
"python",
"matplotlib",
"scatter-plot"
] |
Automatically running app .py in in Heroku | 39,753,285 | <p>I have created a bot for my website and I currently host in on heroku.com.
I run it by executing the command </p>
<p><code>heroku run --app cghelper python bot.py</code></p>
<p>This executes the command perfectly through CMD and runs that specific .py file in my github repo. </p>
<p>The issue is when I close the... | 0 | 2016-09-28T16:45:22Z | 39,754,555 | <p>Not sure but try: </p>
<p>heroku run --app cghelper python bot.py &</p>
| 0 | 2016-09-28T17:58:30Z | [
"python",
"django",
"git",
"heroku"
] |
How can an average equation be added to this? | 39,753,350 | <p>I am taking GCSE programming and have be set a task to create a program which takes "n" amount of numbers and works out the average.</p>
<pre><code>#presets for varibles
nCount = 0
total = 0
average = 0.0
Numbers = []
ValidInt = False
#start of string
nCount = (input("How many numbers? "))
print(nCount)
while not... | -1 | 2016-09-28T16:48:01Z | 39,753,742 | <p>You're <em>really</em> close to the answer. Looks like you've got everything setup and ready to calculate the average, so very good job.<br>
Python's got two built-in functions <code>sum</code> and <code>len</code> which can be used to calculate the sum of all the numbers, then divide that sum by how many numbers ha... | 0 | 2016-09-28T17:10:08Z | [
"python",
"average"
] |
'int' object is not callable when using groupby | 39,753,383 | <p>I am trying to find the longest sequence of numbers in a list using the following code</p>
<pre><code>from itertools import groupby
ggg = groupby([1,2,3,3,3,5,88,9,9,9,9,9,9,9,1,1,1,2,2,3,3,3,3,3])
max(ggg, key=lambda k: len(list(k[1])))
</code></pre>
<p>However, I get the error 'int' object is not callable. Addi... | 1 | 2016-09-28T16:49:58Z | 39,753,584 | <p>The code works fine for me:</p>
<pre><code>>>> from itertools import groupby
>>> ggg = groupby([1,2,3,3,3,5,88,9,9,9,9,9,9,9,1,1,1,2,2,3,3,3,3,3])
>>> max(ggg, key=lambda k: len(list(k[1])))
(9, <itertools._grouper object at 0x019973F0>)
</code></pre>
<p>As @FamousJameous mentioned... | 0 | 2016-09-28T17:01:08Z | [
"python"
] |
'int' object is not callable when using groupby | 39,753,383 | <p>I am trying to find the longest sequence of numbers in a list using the following code</p>
<pre><code>from itertools import groupby
ggg = groupby([1,2,3,3,3,5,88,9,9,9,9,9,9,9,1,1,1,2,2,3,3,3,3,3])
max(ggg, key=lambda k: len(list(k[1])))
</code></pre>
<p>However, I get the error 'int' object is not callable. Addi... | 1 | 2016-09-28T16:49:58Z | 39,753,626 | <p>Your code works for me in Python 3. My best guess is that your problem is coming from assigning <code>len</code>, <code>list</code>, or <code>max</code> to be an <code>int</code>. For example:</p>
<pre><code>>>> list_a = [1, 2]
>>> len(list_a)
2
>>> len = 4
>>> len(list_a)
Trac... | 0 | 2016-09-28T17:03:22Z | [
"python"
] |
Using replace instead of find | 39,753,605 | <p>I have written the following piece but not able to figure the next part:</p>
<pre><code>if request.guess in game.target:
position = game.target.find(request.guess)
game.correct[position] = request.guess.upper()
</code></pre>
<p>The point here is <code>request.guess</code> is a character input like ... | 2 | 2016-09-28T17:02:28Z | 39,753,758 | <p>just use a set of guessed letters and do something like the below.</p>
<pre><code>In [164]: word = 'Australia'
In [165]: guessed = set()
In [166]: guessed.add('a')
In [167]: print(''.join(c if c.lower() in guessed else '*' for c in word))
A****a**a
</code></pre>
| 2 | 2016-09-28T17:11:24Z | [
"python",
"python-3.x"
] |
Using replace instead of find | 39,753,605 | <p>I have written the following piece but not able to figure the next part:</p>
<pre><code>if request.guess in game.target:
position = game.target.find(request.guess)
game.correct[position] = request.guess.upper()
</code></pre>
<p>The point here is <code>request.guess</code> is a character input like ... | 2 | 2016-09-28T17:02:28Z | 39,753,779 | <p>With regular expressions:</p>
<pre><code>import re
correct = re.sub(r'[^a]',"*","australia") # returns "a****a**a"
</code></pre>
<p>This the regular expression <code>[^a]</code> matches all characters except "a". The <code>re.sub</code> function replaces each "not a" with a "*"</p>
<p><em>edit</em></p>
<p>Your ... | 1 | 2016-09-28T17:12:33Z | [
"python",
"python-3.x"
] |
Using replace instead of find | 39,753,605 | <p>I have written the following piece but not able to figure the next part:</p>
<pre><code>if request.guess in game.target:
position = game.target.find(request.guess)
game.correct[position] = request.guess.upper()
</code></pre>
<p>The point here is <code>request.guess</code> is a character input like ... | 2 | 2016-09-28T17:02:28Z | 39,753,802 | <p><code>replace</code> will not help here, since you are not changing the string you are searching.</p>
<p>There are two options here:</p>
<ol>
<li><p>Use <code>str.find</code> repeatedly:</p>
<pre><code>pos = 0
while True:
pos = game.target.find(request.guess, start=pos)
if pos == -1: break
game.correc... | 0 | 2016-09-28T17:13:29Z | [
"python",
"python-3.x"
] |
Using replace instead of find | 39,753,605 | <p>I have written the following piece but not able to figure the next part:</p>
<pre><code>if request.guess in game.target:
position = game.target.find(request.guess)
game.correct[position] = request.guess.upper()
</code></pre>
<p>The point here is <code>request.guess</code> is a character input like ... | 2 | 2016-09-28T17:02:28Z | 39,753,850 | <p>I'd suggest you invest some time in learning <a href="https://docs.python.org/2/library/re.html" rel="nofollow">regular expressions</a>, they come in handy in many similar situations and are often more expressive (and efficient) than ad-hoc implementations. Plus you can reuse (with some quirks) your understanding of... | 0 | 2016-09-28T17:16:33Z | [
"python",
"python-3.x"
] |
Django Rest Framework: How to include linked resources in serializer response? | 39,753,706 | <p>If write my own implementation of a <code>ViewSet</code>, and I want to return some objects, it's pretty simple:</p>
<pre><code>class MyViewSet(ViewSet):
def my_method(self, request):
objects = MyModel.objects.all()
return Response( MyModelSerializer(objects, many=True).data )
</code></pre>
<p>But let's ... | 0 | 2016-09-28T17:08:09Z | 39,753,761 | <p>You can use the <a href="http://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization" rel="nofollow">depth</a> meta attribute on your serializer.</p>
<pre><code>class AccountSerializer(serializers.ModelSerializer):
class Meta:
model = Account
fields = ('id', 'acco... | 1 | 2016-09-28T17:11:36Z | [
"python",
"django",
"django-rest-framework"
] |
Django Rest Framework: How to include linked resources in serializer response? | 39,753,706 | <p>If write my own implementation of a <code>ViewSet</code>, and I want to return some objects, it's pretty simple:</p>
<pre><code>class MyViewSet(ViewSet):
def my_method(self, request):
objects = MyModel.objects.all()
return Response( MyModelSerializer(objects, many=True).data )
</code></pre>
<p>But let's ... | 0 | 2016-09-28T17:08:09Z | 39,753,765 | <p>What you're looking for is <a href="http://www.django-rest-framework.org/api-guide/relations/" rel="nofollow">nested relations</a>. This is built into Django REST Framework. By explicitly defining your relation fields in your serializer you can specify <code>many=True</code> which will expand the related object. </p... | 1 | 2016-09-28T17:11:47Z | [
"python",
"django",
"django-rest-framework"
] |
How do I apply QScintilla syntax highlighting to a QTextEdit in PyQt4? | 39,753,717 | <p>I have a simple PyQt text editor, and would like to apply QScintilla formatting to it. I need to use a QTextEdit for the text, as it provides other functionality that I am using (cursor position, raw text output, etc), and would like to apply QScintilla formatting. </p>
<p>Just for refrence, the initialisation of t... | 2 | 2016-09-28T17:08:47Z | 39,772,188 | <p>I believe you cannot use <code>QScintilla</code> directly with <code>QTextEdit</code>. </p>
<p>But have a look at this question: stackoverflow.com/questions/20951660/⦠and if you want to see the usage <code>QTextEdit</code> (or <code>QPlainTextEdit</code>) with <code>QSyntaxHiglighter</code>, see for example this... | 1 | 2016-09-29T13:49:58Z | [
"python",
"qt",
"pyqt",
"scintilla",
"qscintilla"
] |
When using ElasticSearch scroll api, can I skip to page n? | 39,753,731 | <p>I'm using the elasticsearch scroll api. In some cases I'd like to return the hits on page n without returning the previous pages' hits. I believe this should be like an iterator. So I'd like to just pass the iterator through the first few pages, but then actually return the hits of the n-th page. </p>
<p>My current... | 1 | 2016-09-28T17:09:30Z | 39,755,123 | <p>Elasticsearch python client <code>search</code> method allows you to specify the <code>size</code> and <code>from_</code> argument to start searching for elements for a <code>query</code> skipping a few records.</p>
<pre><code>client.search(index=ES_INDEX, body=QUERY, doc_type=ES_TYPE, size=SIZE,from_=FROM)
</code>... | -1 | 2016-09-28T18:31:06Z | [
"python",
"elasticsearch",
"pagination",
"iterator"
] |
Managing django urls | 39,753,808 | <p>I am making a personal site. I have a blog page(site.com/blog), where I have a list of my blog posts. If I want to check a blog post simple enough I can click it and the code:</p>
<pre><code> <a href="/blog/{{ obj.id }}"><h1>{{ obj.topic_title }}</h1></a>
</code></pre>
<p>will get me... | 0 | 2016-09-28T17:13:55Z | 39,753,932 | <p>Use the built-in Django <a href="https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url" rel="nofollow"><code>url</code></a> template tag, which takes the view name and returns an absolute path to it.</p>
<blockquote>
<p>Returns an absolute path reference (a URL without the domain name) matching a giv... | 2 | 2016-09-28T17:20:44Z | [
"python",
"html",
"django",
"url"
] |
How to use regular experession inside function? | 39,753,842 | <p>I am using following python script to copy files between windows machines.</p>
<pre><code>from subprocess import call
def copy_logs():
file= '.\pscp.exe -pw test123 C:\Users\Administrator\Desktop\interact.* Administrator@1.1.1.1:/'
call(file)
copy_logs()
</code></pre>
<p>If I run the above script, I'm g... | 0 | 2016-09-28T17:16:05Z | 39,754,390 | <p>I tried "import os" module as shown below. Its working perfectly.</p>
<pre><code>import os
def copy_logs():
os.system(".\pscp.exe -pw test123 C:\Users\Administrator\Desktop\interact_pyth* Administrator@1.1.1.1:/")
copy_logs()
</code></pre>
| 0 | 2016-09-28T17:47:18Z | [
"python",
"python-2.7"
] |
Second level looping over dictionaries | 39,753,861 | <p>In building a class with an out line like below I would like the behaviour of the for loops to, if done once: just give the keys as normal an then move on to the next line of code. But if a second loop is set up inside the first loop it would give the keys on the first loop and then ea value in the sequences in the... | 0 | 2016-09-28T17:17:40Z | 39,754,173 | <p>How would you feel about this:</p>
<pre><code>class MyClass():
def __init__(self):
self.cont1 = [1,2,3,4]
self.cont2 = ('a','b','c')
self.conts = {'container1':self.cont1, 'container2':self.cont2}
def __iter__(self):
return self.conts.iteritems()
dct = MyClass()
print('One ... | 0 | 2016-09-28T17:34:52Z | [
"python",
"class",
"for-loop"
] |
Second level looping over dictionaries | 39,753,861 | <p>In building a class with an out line like below I would like the behaviour of the for loops to, if done once: just give the keys as normal an then move on to the next line of code. But if a second loop is set up inside the first loop it would give the keys on the first loop and then ea value in the sequences in the... | 0 | 2016-09-28T17:17:40Z | 39,754,234 | <p>To answer your immediate question, you could just copy how dictionaries implement <code>dict.get</code> and <code>dict.__iter__</code>:</p>
<pre><code>class MyClass():
def __init__(self):
self.cont1 = [1,2,3,4]
self.cont2 = ('a','b','c')
def __iter__(self):
for attr in dir(self):
... | 1 | 2016-09-28T17:37:22Z | [
"python",
"class",
"for-loop"
] |
Second level looping over dictionaries | 39,753,861 | <p>In building a class with an out line like below I would like the behaviour of the for loops to, if done once: just give the keys as normal an then move on to the next line of code. But if a second loop is set up inside the first loop it would give the keys on the first loop and then ea value in the sequences in the... | 0 | 2016-09-28T17:17:40Z | 39,754,576 | <p>You can do this with a second class like this</p>
<pre><code>class MyClass():
def __init__(self):
self.data = [MyClass2({'cont1' : [1,2,3,4]}),MyClass2({'cont2' : ('a','b','c')})]
def __iter__(self):
for item in self.data:
yield item
class MyClass2():
def __init__(se... | 0 | 2016-09-28T17:59:42Z | [
"python",
"class",
"for-loop"
] |
Second level looping over dictionaries | 39,753,861 | <p>In building a class with an out line like below I would like the behaviour of the for loops to, if done once: just give the keys as normal an then move on to the next line of code. But if a second loop is set up inside the first loop it would give the keys on the first loop and then ea value in the sequences in the... | 0 | 2016-09-28T17:17:40Z | 39,755,716 | <p>You cannot do that simply by implementing <code>__iter__</code>. <code>__iter__</code> should return an <em>iterator</em>, that is, an object that keeps the state of an iteration (the current position in a sequence of items) and has a method <code>next</code> that returns with each invocation the next item in the se... | 0 | 2016-09-28T19:05:28Z | [
"python",
"class",
"for-loop"
] |
How to get the width of a matplotlib text, including the padded bounding box? | 39,753,972 | <p>I know how to get the width of the text:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.patches import BoxStyle
xpos, ypos = 0, 0
text = 'blah blah'
boxstyle = BoxStyle("Round", pad=1)
props = {'boxstyle': boxstyle,
'facecolor': 'white',
'linestyle': 'solid',
'linewidth'... | 2 | 2016-09-28T17:23:00Z | 39,754,917 | <blockquote>
<p><a href="http://matplotlib.org/api/patches_api.html#matplotlib.patches.FancyBboxPatch" rel="nofollow"><code>matplotlib.patches.FancyBboxPatch</code></a> class is similar to <a href="http://matplotlib.org/api/patches_api.html#matplotlib.patches.Rectangle" rel="nofollow"><code>matplotlib.patches.Rectang... | 2 | 2016-09-28T18:19:53Z | [
"python",
"matplotlib"
] |
python 27 - Boolean check fails while multiprocessing | 39,753,995 | <p>I have a script that retrieves a list of active 'jobs' from a MySQL table and then instantiates my main script once per active job using the multiprocessing library. My multiprocessing script has a function that checks if a given job has been claimed by another thread. It does this by checking if a particular column... | 0 | 2016-09-28T17:24:54Z | 39,754,968 | <p>Any non-empty tuple (or list, string, iterable, etc.) will evaluate to <code>True</code>. It doesn't matter if the contents of the iterable are non-True. To test that, you can use either <code>any(iterable)</code> or <code>all(iterable)</code> to test whether any or all of the items in the iterable evaluate to Tru... | 1 | 2016-09-28T18:22:32Z | [
"python",
"mysql",
"boolean",
"multiprocessing"
] |
file writing not working as expected | 39,754,030 | <p>I have a python code where it will take the first column of a sample.csv file and copy it to temp1.csv file. Now I would like to compare this csv file with another serialNumber.txt file for any common rows. If any common rows found, It should write to a result file. My temp1.csv is being created properly but the pro... | 0 | 2016-09-28T17:26:41Z | 39,754,108 | <pre><code>with open('temp1.csv', 'r') as file1:
list1 = file1.readlines()
set1 = set(list1)
with open('temp2.csv', 'r') as file2:
list2 = file2.readlines()
set2 = set(list2)
</code></pre>
<p>now you can process the contents as sets</p>
<p>I want to note that your original code does not insert line breaks ... | 0 | 2016-09-28T17:31:19Z | [
"python",
"file-writing"
] |
file writing not working as expected | 39,754,030 | <p>I have a python code where it will take the first column of a sample.csv file and copy it to temp1.csv file. Now I would like to compare this csv file with another serialNumber.txt file for any common rows. If any common rows found, It should write to a result file. My temp1.csv is being created properly but the pro... | 0 | 2016-09-28T17:26:41Z | 39,754,121 | <p>You probably want this instead</p>
<pre><code>same = set(list(file1)).intersection(list(file2))
</code></pre>
| 0 | 2016-09-28T17:31:58Z | [
"python",
"file-writing"
] |
Python:Minumim Function | 39,754,115 | <p>I'm new to Python and I have a problem which needs to be solved with the min function in Python.</p>
<p>I have three ingredients which are:</p>
<pre><code>chicken = 20
lettuce = 30
tomato = 50
max_burgers = "Code Goes Here"
</code></pre>
<p>You need to make burgers with these. Each burger contains 1 piece of chic... | -4 | 2016-09-28T17:31:41Z | 39,754,232 | <p>The <code>min</code> function takes an arbitrary amount of arguments and takes the lowest value:</p>
<pre><code>>>> min(1, 2, 3,)
1
</code></pre>
<p>To solve this, simply calculate the max amount of burgers that could be made with each ingredient using floor division, and then pick the lowest amount:</p>
... | 1 | 2016-09-28T17:37:22Z | [
"python",
"min"
] |
Extract a specific section of a string depending on an input | 39,754,196 | <p>I have a very large <code>.json</code> converted into a <code>string</code>, containing numerous cities/countries.</p>
<p>I'd like to extract the information of the city depending on the user's choice of country (<em>London is just an example</em>). </p>
<p>For example, if the <code>Country</code> the user <em>inp... | 0 | 2016-09-28T17:35:34Z | 39,754,519 | <pre><code>import json
country = raw_input('Country: ')
jsondata = "the large json string mentioned in your post"
info = json.loads(jsondata)
for item in info:
if item['country'] == country:
print item
</code></pre>
| 0 | 2016-09-28T17:56:46Z | [
"python",
"json",
"string",
"python-2.7",
"wunderground"
] |
Extract a specific section of a string depending on an input | 39,754,196 | <p>I have a very large <code>.json</code> converted into a <code>string</code>, containing numerous cities/countries.</p>
<p>I'd like to extract the information of the city depending on the user's choice of country (<em>London is just an example</em>). </p>
<p>For example, if the <code>Country</code> the user <em>inp... | 0 | 2016-09-28T17:35:34Z | 39,754,639 | <p>You can try this. Might still want to consider some user input errors in your code. For example, str.strip() and capital sensitive.</p>
<pre><code>import json
input_country = raw_input('Please enter country:')
with open('London.json') as fp:
london_json = fp.read()
london = json.loads(london_json)
for i... | 0 | 2016-09-28T18:02:59Z | [
"python",
"json",
"string",
"python-2.7",
"wunderground"
] |
Extract a specific section of a string depending on an input | 39,754,196 | <p>I have a very large <code>.json</code> converted into a <code>string</code>, containing numerous cities/countries.</p>
<p>I'd like to extract the information of the city depending on the user's choice of country (<em>London is just an example</em>). </p>
<p>For example, if the <code>Country</code> the user <em>inp... | 0 | 2016-09-28T17:35:34Z | 39,755,340 | <p>The initial response wasn't great because a few of us overlooked the raw JSON. However, you <em>did</em> provide it so in future it would be better to make it more obvious that the snippet you showed had a more complete (and valid) counterpart.</p>
<p>That said, I would load the data into a dictionary and do someth... | 1 | 2016-09-28T18:43:06Z | [
"python",
"json",
"string",
"python-2.7",
"wunderground"
] |
Python - Convert string-numeric to float | 39,754,222 | <p>I have the following string numeric values, and need to keep only the digit and decimals. I just can't find a right regular expression for this. </p>
<pre><code>s = [
"12.45-280", # need to convert to 12.45280
"A10.4B2", # need to convert to 10.42
]
</code></pre>
| 2 | 2016-09-28T17:36:43Z | 39,754,382 | <p>Convert each alphabetical character in the string to empty char ""</p>
<pre><code>import re
num_string = []* len(s)
for i, string in enumerate(s):
num_string[i] = re.sub('[a-zA-Z]+', '', string)
</code></pre>
| 0 | 2016-09-28T17:46:46Z | [
"python",
"regex",
"typeconverter"
] |
Python - Convert string-numeric to float | 39,754,222 | <p>I have the following string numeric values, and need to keep only the digit and decimals. I just can't find a right regular expression for this. </p>
<pre><code>s = [
"12.45-280", # need to convert to 12.45280
"A10.4B2", # need to convert to 10.42
]
</code></pre>
| 2 | 2016-09-28T17:36:43Z | 39,754,472 | <p>You could go for a combination of <code>locale</code> and regular expressions:</p>
<pre><code>import re, locale
from locale import atof
# or whatever else
locale.setlocale(locale.LC_NUMERIC, 'en_GB.UTF-8')
s = [
"12.45-280", # need to convert to 12.45280
"A10.4B2", # need to convert to 10.42
]
rx = r... | 0 | 2016-09-28T17:53:11Z | [
"python",
"regex",
"typeconverter"
] |
Python - Convert string-numeric to float | 39,754,222 | <p>I have the following string numeric values, and need to keep only the digit and decimals. I just can't find a right regular expression for this. </p>
<pre><code>s = [
"12.45-280", # need to convert to 12.45280
"A10.4B2", # need to convert to 10.42
]
</code></pre>
| 2 | 2016-09-28T17:36:43Z | 39,754,501 | <p>You can also remove all non-digits and non-dot characters, then convert the result to float:</p>
<pre><code>In [1]: import re
In [2]: s = [
...: "12.45-280", # need to convert to 12.45280
...: "A10.4B2", # need to convert to 10.42
...: ]
In [3]: for item in s:
...: print(float(re.sub(r"... | 1 | 2016-09-28T17:55:26Z | [
"python",
"regex",
"typeconverter"
] |
Django: Request timeout for long-running script | 39,754,283 | <p>I have a webpage made in Django that feeds data from a form to a script that takes quite a long time to run (1-5 minutes) and then returns a detailview with the results of that scripts.
I have problem with getting a request timeout. Is there a way to increase time length before a timeout so that the script can finis... | 0 | 2016-09-28T17:41:00Z | 39,754,475 | <p>Yes, the timeout value can be adjusted in the web server configuration.</p>
<p>Does anyone else but you use this page? If so, you'll have to educate them to be patient and not click the Stop or Reload buttons on their browser.</p>
| 0 | 2016-09-28T17:53:36Z | [
"python",
"django",
"python-3.x",
"pythonanywhere",
"django-1.9"
] |
Django: Request timeout for long-running script | 39,754,283 | <p>I have a webpage made in Django that feeds data from a form to a script that takes quite a long time to run (1-5 minutes) and then returns a detailview with the results of that scripts.
I have problem with getting a request timeout. Is there a way to increase time length before a timeout so that the script can finis... | 0 | 2016-09-28T17:41:00Z | 39,775,664 | <p>We don't change the request timeout for individual users on PythonAnywhere. In the vast majority of cases, a request that takes 5 min (or even, really, 1 min) indicates that something is very wrong with the app.</p>
| 0 | 2016-09-29T16:35:44Z | [
"python",
"django",
"python-3.x",
"pythonanywhere",
"django-1.9"
] |
regex both numberic and numeric with one decimal place | 39,754,352 | <p>Using
<a href="https://regex101.com/r/ukjM5F/1" rel="nofollow">https://regex101.com/r/ukjM5F/1</a></p>
<p>My regex is:</p>
<pre><code>(?:'\d+[A-Za-z ]*)(\d+|\d+\.)
</code></pre>
<p>It uses the <code>g</code> (global) modifier.</p>
<p>How do I grab all the<br>
10<br>
12 </p>
<p>As well as<br>
2.5<br>
3.5?</p>
... | -3 | 2016-09-28T17:45:14Z | 39,754,481 | <p>You can use a non-capturing group: it is then simple to match a number with two decimal places:</p>
<pre><code>(?:\d[\s\w]+?)(\d+\.\d\d)
</code></pre>
<p><a href="https://regex101.com/r/ukjM5F/3" rel="nofollow">https://regex101.com/r/ukjM5F/3</a></p>
| 0 | 2016-09-28T17:53:57Z | [
"python",
"regex"
] |
regex both numberic and numeric with one decimal place | 39,754,352 | <p>Using
<a href="https://regex101.com/r/ukjM5F/1" rel="nofollow">https://regex101.com/r/ukjM5F/1</a></p>
<p>My regex is:</p>
<pre><code>(?:'\d+[A-Za-z ]*)(\d+|\d+\.)
</code></pre>
<p>It uses the <code>g</code> (global) modifier.</p>
<p>How do I grab all the<br>
10<br>
12 </p>
<p>As well as<br>
2.5<br>
3.5?</p>
... | -3 | 2016-09-28T17:45:14Z | 39,754,487 | <p>Try this: <code>\d+[.]?\d*</code></p>
<p>That matches all numbers with or without a decimal point</p>
<p><a href="https://regex101.com/r/9UHCt4/1" rel="nofollow">https://regex101.com/r/9UHCt4/1</a></p>
<p>But, probably even better would be not to try to use regexes for the bulk of your text processing. Because th... | 1 | 2016-09-28T17:54:27Z | [
"python",
"regex"
] |
regex both numberic and numeric with one decimal place | 39,754,352 | <p>Using
<a href="https://regex101.com/r/ukjM5F/1" rel="nofollow">https://regex101.com/r/ukjM5F/1</a></p>
<p>My regex is:</p>
<pre><code>(?:'\d+[A-Za-z ]*)(\d+|\d+\.)
</code></pre>
<p>It uses the <code>g</code> (global) modifier.</p>
<p>How do I grab all the<br>
10<br>
12 </p>
<p>As well as<br>
2.5<br>
3.5?</p>
... | -3 | 2016-09-28T17:45:14Z | 39,754,538 | <p>To get only the price of a menu item use:</p>
<pre><code>(?:[a-zA-Z]+\s[a-zA-Z]+\s+)(\d+\.\d\d)(?:')
</code></pre>
<p><a href="https://regex101.com/r/ukjM5F/5" rel="nofollow">https://regex101.com/r/ukjM5F/5</a></p>
| 0 | 2016-09-28T17:57:53Z | [
"python",
"regex"
] |
python: Threading classes from main_window class | 39,754,459 | <p>I'm trying to create a game using Tkinter that can run functions from multiple class objects simultaneously using threads. In the MainWindow class, I have "player" and "player2" assigned to the "Player" class. </p>
<p>In the "Player" class, have a function called "move" that simply moves the canvas object.</p>
<p... | 0 | 2016-09-28T17:52:30Z | 39,754,884 | <p>1) your need to fix your model and have a separation between the model/data and the representation/visualization :</p>
<p><code>players</code> need only to hold their data, and not be responsible for drawing anything. You should have a main rendering loop in charge of reading the components on the display, and posi... | 0 | 2016-09-28T18:17:36Z | [
"python",
"class",
"python-3.x",
"tkinter",
"python-multithreading"
] |
concatenate arrays with mixed types | 39,754,658 | <p>consider the <code>np.array</code> <code>a</code></p>
<pre><code>a = np.concatenate(
[np.arange(2).reshape(-1, 1),
np.array([['a'], ['b']])],
axis=1)
a
array([['0', 'a'],
['1', 'b']],
dtype='|S11')
</code></pre>
<p>How can I execute this concatenation such that the first column of <code... | 0 | 2016-09-28T18:04:26Z | 39,755,454 | <p>You can mix types in a numpy array by using a <code>numpy.object</code> as the <code>dtype</code>:</p>
<pre><code>>>> import numpy as np
>>> a = np.empty((2, 0), dtype=np.object)
>>> a = np.append(a, np.arange(2).reshape(-1,1), axis=1)
>>> a = np.append(a, np.array([['a'],['b']])... | 2 | 2016-09-28T18:49:07Z | [
"python",
"numpy"
] |
concatenate arrays with mixed types | 39,754,658 | <p>consider the <code>np.array</code> <code>a</code></p>
<pre><code>a = np.concatenate(
[np.arange(2).reshape(-1, 1),
np.array([['a'], ['b']])],
axis=1)
a
array([['0', 'a'],
['1', 'b']],
dtype='|S11')
</code></pre>
<p>How can I execute this concatenation such that the first column of <code... | 0 | 2016-09-28T18:04:26Z | 39,755,795 | <p>A suggested duplicate recommends making a recarray or structured array.</p>
<p><a href="http://stackoverflow.com/questions/11309739/store-different-datatypes-in-one-numpy-array">Store different datatypes in one NumPy array?</a></p>
<p>In this case:</p>
<pre><code>In [324]: a = np.rec.fromarrays((np.arange(2).resh... | 2 | 2016-09-28T19:10:03Z | [
"python",
"numpy"
] |
overriding not operator in Python | 39,754,808 | <p>I cannot find the method corresponding to <code>not x</code> operator. There is one for <code>and,or,xor</code> tho. Where is it?
<a href="https://docs.python.org/3/reference/datamodel.html" rel="nofollow">https://docs.python.org/3/reference/datamodel.html</a></p>
| -1 | 2016-09-28T18:13:45Z | 39,754,858 | <blockquote>
<p>There is one for <code>and,or,xor</code> tho</p>
</blockquote>
<p>The methods you're looking at are for <em>bitwise</em> <code>&</code>, <code>|</code>, and <code>^</code>, not <code>and</code>, <code>or</code>, or <code>xor</code> (which isn't even a Python operator).</p>
<p><code>not</code> ca... | 3 | 2016-09-28T18:16:23Z | [
"python",
"operator-overloading",
"operators"
] |
overriding not operator in Python | 39,754,808 | <p>I cannot find the method corresponding to <code>not x</code> operator. There is one for <code>and,or,xor</code> tho. Where is it?
<a href="https://docs.python.org/3/reference/datamodel.html" rel="nofollow">https://docs.python.org/3/reference/datamodel.html</a></p>
| -1 | 2016-09-28T18:13:45Z | 39,754,868 | <p>There are no hooks for <code>and</code> or <code>or</code> operators, no (as they short-circuit), and there is no <code>xor</code> operator in Python. The <code>__and__</code> and <code>__or__</code> are for the <a href="https://docs.python.org/3/reference/expressions.html#unary-arithmetic-and-bitwise-operations" re... | 1 | 2016-09-28T18:16:59Z | [
"python",
"operator-overloading",
"operators"
] |
scrapy run spider from path | 39,754,822 | <p>A number of suggestions on running scrapy suggest doing this in order to start scrapy via script, or to debug in an IDE, etc:</p>
<pre><code>from scrapy import cmdline
cmdline.execute(("scrapy runspider spider-file-name.py").split())
</code></pre>
<p>This works, so long as the script is placed in the project dire... | 2 | 2016-09-28T18:14:15Z | 39,756,350 | <p>It's highly advised to use a distributed crawling software but if you really want to do it like this just for some dirty testing here it is</p>
<pre><code>import subprocess
project_path="/Users/name/intellij-workspace/crawling/scrape"
subprocess.Popen(["scrapy","runspider","scrape/spiders/some-spider.py"],cwd=proj... | 2 | 2016-09-28T19:42:55Z | [
"python",
"scrapy"
] |
Syntax error in if...elif...else | 39,755,012 | <p>tax calculator</p>
<pre><code>def computeTax(maritalStatus,userIncome):
if maritalStatus == "Single":
print("User is single")
if userIncome <= 9075:
tax = (.10) * (userIncome)
elif userIncome <= 36900:
tax = 907.50 + ((.15) * (userIncome - 9075))
elif userIncome <= 89350:
... | 0 | 2016-09-28T18:25:26Z | 39,755,916 | <p>A quick glance at the lines around it, shows a missing parenthesis</p>
<pre><code>...
tax = 45353.75 + ((.33) * (userIncome - 186350)) # <- two ending parens
elif userIncome <= 406750:
tax = 117541.25 + ((.35) * (userIncome - (405100) # <- one ending paren, plus extra paren around 405100
else:
...... | 1 | 2016-09-28T19:17:24Z | [
"python",
"syntax-error"
] |
How to do LOAD DATA command from within python | 39,755,033 | <p>How would I do the following?</p>
<pre><code>import MySQLdb
conn = MySQLdb.connect (
host = settings.DATABASES['default']['HOST'],
port = 3306,
user = settings.DATABASES['default']['USER'],
passwd = settings.DATABASES['default']['PA... | 1 | 2016-09-28T18:26:32Z | 39,755,190 | <p>In order for <code>load file</code> to work your database user account needs MySQL's <code>file_priv</code>. The database also needs to have read permissions on the file in question.</p>
<p>In this query the database is instructed to look for <code>a_short.csv</code> on the database's filsystem, which will probabl... | 2 | 2016-09-28T18:34:45Z | [
"python",
"mysql"
] |
How to do LOAD DATA command from within python | 39,755,033 | <p>How would I do the following?</p>
<pre><code>import MySQLdb
conn = MySQLdb.connect (
host = settings.DATABASES['default']['HOST'],
port = 3306,
user = settings.DATABASES['default']['USER'],
passwd = settings.DATABASES['default']['PA... | 1 | 2016-09-28T18:26:32Z | 39,755,325 | <p>This doesn't seem to be a cursor issue, but yet it seems that the user you are using does not having the required permissions to execute said command.</p>
<p>Make sure you give the user the needed permissions.</p>
| 1 | 2016-09-28T18:42:03Z | [
"python",
"mysql"
] |
Putting a list in the same order as another list | 39,755,045 | <p>There's a bunch of questions that are phrased similarly, but I was unable to find one that actually mapped to my intended semantics.</p>
<p>There are two lists, <code>A</code> and <code>B</code>, and I want to rearrange <code>B</code> so that it is in the same relative order as <code>A</code> - the maximum element ... | 4 | 2016-09-28T18:27:12Z | 39,755,202 | <p>You can easily do this with <code>numpy</code> by sorting both lists (to get a mapping between the two lists) and by inverting one of the sorting permutations:</p>
<pre><code>import numpy as np
a = [7, 14, 0, 9, 19, 9]
b = [45, 42, 0, 1, -1, 0]
a = np.array(a)
b = np.array(b)
ai = np.argsort(a)
bi = np.argsort(b... | 3 | 2016-09-28T18:35:43Z | [
"python",
"list",
"sorting"
] |
Putting a list in the same order as another list | 39,755,045 | <p>There's a bunch of questions that are phrased similarly, but I was unable to find one that actually mapped to my intended semantics.</p>
<p>There are two lists, <code>A</code> and <code>B</code>, and I want to rearrange <code>B</code> so that it is in the same relative order as <code>A</code> - the maximum element ... | 4 | 2016-09-28T18:27:12Z | 39,755,265 | <pre><code>a = [7, 14, 0, 9, 19, 9]
b = [45, 42, 0, 1, -1, 0]
print zip(*sorted(zip(sorted(b), sorted(enumerate(a), key=lambda x:x[1])), key=lambda x: x[1][0]))[0]
#or, for 3.x:
print(list(zip(*sorted(zip(sorted(b), sorted(enumerate(a), key=lambda x:x[1])), key=lambda x: x[1][0])))[0])
</code></pre>
<p>result:</p>
<p... | 5 | 2016-09-28T18:38:58Z | [
"python",
"list",
"sorting"
] |
How do I add a multiline variable in a honcho .env file? | 39,755,063 | <p>I am trying to add a multiline value for an env var in .env so that my process, run by honcho, will have access to it.</p>
<p>Bash uses a '\' to permit multilines. But this gives errors in honcho/python code. How to do this?</p>
| 0 | 2016-09-28T18:28:13Z | 39,755,064 | <p>I put '\\' at the end of the line to permit multiline values.</p>
| 0 | 2016-09-28T18:28:13Z | [
"python",
"environment-variables"
] |
How to divide the sum with the size in a pandas groupby | 39,755,075 | <p>I have a dataframe like</p>
<pre><code> ID_0 ID_1 ID_2
0 a b 1
1 a c 1
2 a b 0
3 d c 0
4 a c 0
5 a c 1
</code></pre>
<p>I would like to groupby ['ID_0','ID_1'] and produce a new dataframe which has the sum of the ID_2 values for each group divided by th... | 1 | 2016-09-28T18:28:39Z | 39,755,183 | <p>Use <code>groupby.apply</code> instead:</p>
<pre><code>df.groupby(['ID_0', 'ID_1']).apply(lambda x: x['ID_2'].sum()/len(x))
ID_0 ID_1
a b 0.500000
c 0.666667
d c 0.000000
dtype: float64
</code></pre>
| 1 | 2016-09-28T18:34:16Z | [
"python",
"pandas"
] |
List in column Python + Pandas | 39,755,131 | <p>I'm new to pandas and would like to analyse some data arranged like this:</p>
<pre><code>label aa bb
index
0 [2, 5, 1, 4] [x1, x2, y1, z1]
1 [3, 3, 19] [x3, x4, y2]
2 [6, 4, 2, 8, 9, 10] [y1, y2, z3, z4, x1, w]
<... | 1 | 2016-09-28T18:31:32Z | 39,755,863 | <p>Pandas works best when your data are in a table format and individual cells contain values, not collections. To use pandas effectively for your problem, you need to change the way you create your data table. </p>
<p>Ultimately, it looks like you want to generate a table with columns representing object "id", "amoun... | 1 | 2016-09-28T19:14:09Z | [
"python",
"pandas"
] |
How to insert string to each token of a list of strings? | 39,755,171 | <p>Lets assume I have the following list:</p>
<pre><code>l = ['the quick fox', 'the', 'the quick']
</code></pre>
<p>I would like to transform each element of the list into a url as follows:</p>
<pre><code>['<a href="http://url.com/the">the</a>', '<a href="http://url.com/quick">quick</a>','<... | 4 | 2016-09-28T18:33:46Z | 39,755,220 | <p>You were close, you limited your comprehension to the contents of <code>x[0].split</code>, i.e you were missing one <code>for</code> loop through the elements of <code>l</code>:</p>
<pre><code>list_words = ['<a href="http://url.com/{}">{}</a>'.format(a,a) for x in l for a in x.split()]
</code></pre>
<p... | 5 | 2016-09-28T18:36:25Z | [
"python",
"string",
"python-3.x",
"list-comprehension"
] |
How to insert string to each token of a list of strings? | 39,755,171 | <p>Lets assume I have the following list:</p>
<pre><code>l = ['the quick fox', 'the', 'the quick']
</code></pre>
<p>I would like to transform each element of the list into a url as follows:</p>
<pre><code>['<a href="http://url.com/the">the</a>', '<a href="http://url.com/quick">quick</a>','<... | 4 | 2016-09-28T18:33:46Z | 39,755,230 | <pre><code>list_words = ['<a href="http://url.com/{}">{}</a>'.format(a,a) for item in l for a in item.split(' ')]
</code></pre>
| 2 | 2016-09-28T18:36:55Z | [
"python",
"string",
"python-3.x",
"list-comprehension"
] |
How to insert string to each token of a list of strings? | 39,755,171 | <p>Lets assume I have the following list:</p>
<pre><code>l = ['the quick fox', 'the', 'the quick']
</code></pre>
<p>I would like to transform each element of the list into a url as follows:</p>
<pre><code>['<a href="http://url.com/the">the</a>', '<a href="http://url.com/quick">quick</a>','<... | 4 | 2016-09-28T18:33:46Z | 39,755,246 | <p>In <strong>one-liner</strong>:</p>
<pre><code>list_words = ['<a href="http://url.com/{}">{}</a>'.format(a,a) for a in [i for sub in [i.split() for i in l] for i in sub]]
</code></pre>
<p><strong>In steps</strong></p>
<p>You can split the list:</p>
<pre><code>l = [i.split() for i in l]
</code></pre>
... | 2 | 2016-09-28T18:37:51Z | [
"python",
"string",
"python-3.x",
"list-comprehension"
] |
How to remove window frame from program using Tkinter and Matplotlib | 39,755,216 | <p>I am writing a graphical program in Python for my Raspberry Pi project. I have started writing it using Tkinter and wish to use the Matplotlib tools. </p>
<p>Due to limited screen space and the purpose of the project, I want it to be fullscreen without a window frame and menubar showing. Normally I use the follo... | 0 | 2016-09-28T18:36:17Z | 39,777,743 | <p>I found the problem. The example code I followed involved using the command canvas.show() along with canvas.get_tk_widget().grid(...). The canvas.show() was not needed and caused it to override the app.overrideredirect(1) command.</p>
| 0 | 2016-09-29T18:41:28Z | [
"python",
"matplotlib",
"tkinter",
"fullscreen"
] |
Python append column header & append column values from list to csv | 39,755,232 | <p>I am trying to append column header (hard-coded) and append column values from list to an existing csv. I am not getting the desired result. </p>
<p>Method 1 is appending results on an existing csv file. Method 2 clones a copy of existing csv into temp.csv. Both methods don't get me the desired output I am looking ... | 2 | 2016-09-28T18:37:03Z | 39,755,404 | <p>First method is bound to fail: you don't want to add new lines but new columns. So back to second method:</p>
<p>You insert the title OK, but then you're looping through the results on each row, whereas you need to iterate on them.</p>
<p>For this, i create an iterator from the <code>final_results</code> list (wit... | 1 | 2016-09-28T18:46:40Z | [
"python",
"list",
"loops",
"csv",
"parsing"
] |
Python append column header & append column values from list to csv | 39,755,232 | <p>I am trying to append column header (hard-coded) and append column values from list to an existing csv. I am not getting the desired result. </p>
<p>Method 1 is appending results on an existing csv file. Method 2 clones a copy of existing csv into temp.csv. Both methods don't get me the desired output I am looking ... | 2 | 2016-09-28T18:37:03Z | 39,755,652 | <pre><code>import csv
HEADER = "Type,Id,TypeId,CalcValues,ID"
final_results = ['0.1065599566767107', '20.061623176440904', '0.0038113334533441123']
with open("test.csv") as inputs, open("tmp.csv", "wb") as outputs:
reader = csv.reader(inputs, delimiter=",")
writer = csv.writer(outputs, delimiter=",")
rea... | 1 | 2016-09-28T19:01:00Z | [
"python",
"list",
"loops",
"csv",
"parsing"
] |
Can Pywinauto Track or Log Error with an Application? | 39,755,271 | <p>Is there any way to track or log error in Pywinauto (eg a pop-up window does not appear, etc.) ? I am trying to track if a window opens correctly or not. I am also trying to verify values in an Excel Worksheet. Is this possible ? Oh! Yes, I am a newbie to Python and Pywinauto. Thanks for your assistance !!</p>
| 0 | 2016-09-28T18:39:18Z | 39,756,392 | <p>For working with MS Excel I would recommend using standard <code>win32com.client</code> module (it's included into ActivePython, or pyWin32 extensions can be installed by <code>pip install pypiwin32</code> for example). Almost every Microsoft application has nice <code>IDispatch</code> COM interface. By the way stan... | 1 | 2016-09-28T19:45:08Z | [
"python",
"pywinauto"
] |
Python code for ABAQUS to create helix | 39,755,275 | <p>I have this code I have found online that creates a helix when run in ABAQUS. I am trying to understand the logic behind it to perhaps customize it to the size of my helix.</p>
<p>I have added comments above the line of codes I understand.</p>
<pre><code>#######################
# Imports controls from abaqus
fr... | 0 | 2016-09-28T18:39:29Z | 39,852,890 | <p>This code creates a Construction(!!) line from point1 to point2, around this line your helix will construct:</p>
<p><code>cl = s.ConstructionLine(point1=(0.0, -100.0), point2=(0.0, 100.0))</code></p>
<p>This code revolves your sketch(rectange) around your construction line with defined pitch and number of turns:</... | 0 | 2016-10-04T12:53:40Z | [
"python",
"abaqus"
] |
Understanding Django Q - Dynamic | 39,755,289 | <p>I'm reading <a href="http://www.michelepasin.org/blog/2010/07/20/the-power-of-djangos-q-objects/" rel="nofollow">this article</a> on dynamically generating Q objects. I understand (for the most part) Q objects but I'm not understanding how the author specifically is doing this example:</p>
<pre><code># string repre... | 2 | 2016-09-28T18:40:16Z | 39,755,862 | <p>The article relies on the undocumented feature that <code>Q()</code> accepts args as well as kwargs.</p>
<p>If you look at <a href="https://github.com/django/django/blob/9c522d2ed8e752932bfff62d6e2940e56dee700b/django/db/models/query_utils.py#L53" rel="nofollow">source code for the <code>Q</code> class</a>, you can... | 4 | 2016-09-28T19:14:09Z | [
"python",
"django",
"list-comprehension"
] |
Find and replace texts in all files from the text file input using Python in Notepad++ | 39,755,291 | <p>I'm using Notepad ++ to do a find and replacement function. Currently I have a a huge numbers of text files. I need to do a replacement for different string in different file. I want do it in batch. For example.</p>
<p>I have a folder that has the huge number of text file. I have another text file that has the stri... | 0 | 2016-09-28T18:40:20Z | 39,756,091 | <pre><code>with open('replace.txt') as f:
replacements = [tuple(line.split()) for line in f]
for filename in filenames:
with open(filename, 'w') as f:
contents = f.read()
for old, new in replacements:
contents = contents.replace(old, new)
f.write(contents)
</code></pre>
<p>R... | 0 | 2016-09-28T19:28:43Z | [
"python",
"replace",
"find",
"notepad++"
] |
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 55: character maps to <undefined> | 39,755,301 | <p>I am new to Python and am hoping that someone could please explain to me what the error message means. </p>
<p>To be specific, I have some code of Python and SPSS combined together saved in Atom, which was created by a former colleague. Now since the former colleague is not here anymore, I need to run the code now.... | 0 | 2016-09-28T18:40:53Z | 39,771,447 | <p>It's hard to be sure about what is going on here as there is a lot of code off stage, but the error message is telling you that there is an invalid character in the input stream. Code x81 is undefined in code page 1252, which is the code page in effect. That's the western Europe/US default code page. The program ... | 0 | 2016-09-29T13:18:37Z | [
"python",
"syntax-error",
"decode",
"spss"
] |
Beautiful Soup: extracting tagged and untagged HTML text | 39,755,346 | <p>As a novice with bs4 I'm looking for some help in working out how to extract the text from a series of webpage tables, one of which is like this:</p>
<pre><code><table style="padding:0px; margin:1px" width="715px">
<tr>
<td height="22" width="33%" >
<span class="darkGreenText"><strong>... | 0 | 2016-09-28T18:43:29Z | 39,755,726 | <p>It seems like what you want is to call <code>get_text(strip=True)</code>(<a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#get-text" rel="nofollow">docs</a>) on the BeautifulSoup Tag. Assuming <code>raw_html</code> is the html you pasted above:</p>
<p><code>htmlSoup = BeautifulSoup(raw_html)
for tag i... | 1 | 2016-09-28T19:05:59Z | [
"python",
"beautifulsoup"
] |
How to modify my code to scrape these links? | 39,755,365 | <p>I am new to use python scrapy, and my scrapy version is 1.1.3. I want to get a link list in <a href="http://i.stack.imgur.com/ZrLsf.png" rel="nofollow">this part</a> on <a href="https://www.wikipedia.org/" rel="nofollow">https://www.wikipedia.org/</a>. How should I modify my code? </p>
<pre><code>import scrapy
... | -2 | 2016-09-28T18:44:41Z | 39,757,101 | <p>You need to modify the xpath query to get the value of the attribute not the tag</p>
<pre><code>import scrapy
class LinkSpider(scrapy.Spider):
name = "links"
start_urls = [
'https://www.wikipedia.org/',
]
def parse(self, response):
for link in response.xpath('//div/ul/li/a/@href'):... | 0 | 2016-09-28T20:30:33Z | [
"python",
"scrapy"
] |
How to modify my code to scrape these links? | 39,755,365 | <p>I am new to use python scrapy, and my scrapy version is 1.1.3. I want to get a link list in <a href="http://i.stack.imgur.com/ZrLsf.png" rel="nofollow">this part</a> on <a href="https://www.wikipedia.org/" rel="nofollow">https://www.wikipedia.org/</a>. How should I modify my code? </p>
<pre><code>import scrapy
... | -2 | 2016-09-28T18:44:41Z | 39,772,293 | <p>You are missing couple of things,</p>
<ul>
<li>You need to add attribute @href to get the value</li>
<li><p>Your href value on first index, you need to add index number.</p>
<pre><code>import scrapy
class LinkSpider(scrapy.Spider):
name = "links"
start_urls = ['https://www.wikipedia.org/', ]
def parse... | 0 | 2016-09-29T13:53:57Z | [
"python",
"scrapy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.