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 |
|---|---|---|---|---|---|---|---|---|---|
In sympy, how do I get the coefficients of a rational expression? | 39,348,937 | <p>I have a rational (here: bilinear) expression and want I sympy to collect the
coefficients. But how?</p>
<pre><code>from sympy import symbols, Wild, pretty_print
a, b, c, d, x, s = symbols("a b c d x s")
def coeffs(expr):
n0 = Wild("n0", exclude=[x])
n1 = Wild("n1", exclude=[x])
d0 = Wild("d0", exclud... | 3 | 2016-09-06T12:21:09Z | 39,352,751 | <p>If you know that the expressions you will consider are rational, you could extract their numerator and denominator and find their coefficients independently.</p>
<p>Here's one approach to do so:</p>
<pre><code>import sympy as sp
def get_rational_coeffs(expr):
num, denom = expr.as_numer_denom()
return [sp... | 3 | 2016-09-06T15:28:43Z | [
"python",
"numpy",
"sympy"
] |
I'm not sure what a certain code line does | 39,348,980 | <p>I was trying to have a program using Python to create a "pyramid" based on a number, n, out of o's and came up with this: ( I would print nn, that would be the lines.)</p>
<pre><code>import time
n = 0
while True:
n += 2 #just another way to show n=n+2
nn = n, "o" #nn would be an amount of o's, based on wha... | 0 | 2016-09-06T12:23:51Z | 39,349,087 | <pre><code>import time
n = 0
while True:
n += 2 #just another way to show n=n+2
nn = "o" * n #nn would be an amount of o's, based on what #n was
time.sleep(1)
print (nn.center(40," "))
</code></pre>
<p>As someone has mentioned in the comments "o" * n will give a a string containing n "o"s.
I've fixed ... | 1 | 2016-09-06T12:30:18Z | [
"python"
] |
I'm not sure what a certain code line does | 39,348,980 | <p>I was trying to have a program using Python to create a "pyramid" based on a number, n, out of o's and came up with this: ( I would print nn, that would be the lines.)</p>
<pre><code>import time
n = 0
while True:
n += 2 #just another way to show n=n+2
nn = n, "o" #nn would be an amount of o's, based on wha... | 0 | 2016-09-06T12:23:51Z | 39,349,116 | <p>You can try this:</p>
<pre><code>from __future__ import print_function
import time
for n in range(0, 40, 2):
nn = n * "o" #nn would be an amount of o's, based on what #n was
time.sleep(1)
print(nn.center(40, " "))
</code></pre>
| 1 | 2016-09-06T12:32:28Z | [
"python"
] |
I'm not sure what a certain code line does | 39,348,980 | <p>I was trying to have a program using Python to create a "pyramid" based on a number, n, out of o's and came up with this: ( I would print nn, that would be the lines.)</p>
<pre><code>import time
n = 0
while True:
n += 2 #just another way to show n=n+2
nn = n, "o" #nn would be an amount of o's, based on wha... | 0 | 2016-09-06T12:23:51Z | 39,349,150 | <p>This will be the answer to your question</p>
<pre><code>import time
n = 0
while True:
n += 2
nn = n * "o"
time.sleep(1)
print (nn.center(40, " "))
if n > 30:
break
</code></pre>
<p>The reason why they have put <code>time.sleep(1)</code> is to make it look like an animation. <code>pr... | 1 | 2016-09-06T12:34:05Z | [
"python"
] |
I'm not sure what a certain code line does | 39,348,980 | <p>I was trying to have a program using Python to create a "pyramid" based on a number, n, out of o's and came up with this: ( I would print nn, that would be the lines.)</p>
<pre><code>import time
n = 0
while True:
n += 2 #just another way to show n=n+2
nn = n, "o" #nn would be an amount of o's, based on wha... | 0 | 2016-09-06T12:23:51Z | 39,349,187 | <p>You can also use the <a href="https://docs.python.org/3/library/string.html#format-string-syntax" rel="nofollow">built-in formatting options</a> offered by python. Take a look at this:</p>
<pre><code>def pyramid_builder(height, symbol='o', padding=' '):
for n in range(0, height, 2): # wonkiness-correction by @... | 1 | 2016-09-06T12:36:26Z | [
"python"
] |
Getting signature from Outlook using python with Redemption RDO | 39,349,096 | <p>I wrote a program that creates a mail in outlook and saves it as .msg format. I want to add the signature of the user that is sending the mail (so the current account user) at the end of the HTMLBody. So far I haven't been able to find anything.</p>
<p>Any help would be appreacited. Here is an easy example of my co... | 0 | 2016-09-06T12:31:10Z | 39,351,360 | <p>By defualt, you can find user's signatures stored in the following folder on the disk:</p>
<pre><code> C:\Users\%username%\AppData\Roaming\Microsoft\Signatures
</code></pre>
<p>It may contain the following files:</p>
<ul>
<li>.htm - This file is used when creating HTML messages.</li>
<li>.rtf - This file is used ... | 0 | 2016-09-06T14:20:06Z | [
"python",
"email",
"outlook",
"outlook-redemption",
"rdo"
] |
Getting signature from Outlook using python with Redemption RDO | 39,349,096 | <p>I wrote a program that creates a mail in outlook and saves it as .msg format. I want to add the signature of the user that is sending the mail (so the current account user) at the end of the HTMLBody. So far I haven't been able to find anything.</p>
<p>Any help would be appreacited. Here is an easy example of my co... | 0 | 2016-09-06T12:31:10Z | 39,352,373 | <p>You can use RDOSignature.ApplyTo - please see <a href="http://www.dimastr.com/redemption/rdosignature.htm" rel="nofollow">http://www.dimastr.com/redemption/rdosignature.htm</a> </p>
| 0 | 2016-09-06T15:09:24Z | [
"python",
"email",
"outlook",
"outlook-redemption",
"rdo"
] |
Conditional in Django Tables | 39,349,152 | <p>I am trying to include a conditional in my Django table, but I am having some issues finding the correct syntax to do so.</p>
<p>I have a boolean field in one of my models, and based on that value - I would like to render a different <code>label_link</code> and callback url for that specific db record.</p>
<p>Here... | 0 | 2016-09-06T12:34:27Z | 39,349,293 | <p>You can't put the if statement in the <code>Feature</code> class - it is processed when the class is loaded, so you don't have access to the table data yet.</p>
<p>Inside the <code>TemplateColumn</code>, you can access the current row of the table with <code>record</code>, so you could move the logic there.</p>
<p... | 2 | 2016-09-06T12:42:45Z | [
"python",
"django",
"postgresql",
"django-tables2"
] |
How to generate a 2d grid from a set of randomly generated coordinates? | 39,349,158 | <p>The plan for the use of this is in a text based Space RPG game. I want to generate random points (x,y coordinates) - which I have already done - followed by plotting them with connections shown on a 2d grid. As a side, how would I label these coordinates?</p>
<p><strong>The code for the random generation is include... | 0 | 2016-09-06T12:34:55Z | 39,350,839 | <p>Instead of providing you with a direct answer I will point you in a general direction as the scope of this question seems rather big.</p>
<p>Consider using pygame; it provides you with drawing functions, has an event system that you can use to detect user input and has many other helpful features for creating games... | 0 | 2016-09-06T13:55:07Z | [
"python",
"random",
"grid",
"2d"
] |
Merging CSV Using pandas dataframe | 39,349,216 | <p>I am using the below code. All my CSV files have uniform structure. When a dataframe is formed, it contains two columns for date in my CSV.</p>
<p>In the resulting dataframe, for few rows date value is in first date column, while for rest of the data, it goes to second date column.</p>
<p>Any idea, why two columns... | 1 | 2016-09-06T12:38:02Z | 39,349,237 | <p>because you have a space in the second column:</p>
<pre><code>'Date', 'Date '
^
</code></pre>
<p>so you need to normalise the columns prior to appending</p>
<pre><code>all_data = pd.DataFrame()
for f in glob.glob("/Users/tcssig/Desktop/Files/*.csv"):
df = pd.read_csv(f)
df.columns = df.column... | 5 | 2016-09-06T12:39:34Z | [
"python",
"csv",
"pandas"
] |
how I fix unicode error in Python Dexterity Type? | 39,349,257 | <p>I created one Dexterity Type using python, and the code is:</p>
<pre><code># -*- coding: utf-8 -*-
from plone.app.textfield import RichText
from plone.autoform import directives
from plone.namedfile import field as namedfile
from plone.supermodel.directives import fieldset
from plone.supermodel import model
from z3... | 0 | 2016-09-06T12:40:56Z | 39,350,812 | <p>The solutions is change the line 13:</p>
<p><code>from projetime.ged import MessageFactory as _</code></p>
<p>to:</p>
<p><code>from projetime.ged import _</code></p>
<p>Like see here <a href="https://github.com/plone/Products.CMFPlone/issues/386" rel="nofollow">https://github.com/plone/Products.CMFPlone/issues/3... | 0 | 2016-09-06T13:53:57Z | [
"python",
"zope",
"dexterity",
"plone-4.x"
] |
How to remove outer list? | 39,349,281 | <p>I have a simple example,
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p>
<p>And i am solving it like this:</p>
<pre><code>n = 4
list_range = list(range(1,n+1))
divisor_list = []
divisor_list.append([i for i in list_range if n%i==0])
print divisor_... | -1 | 2016-09-06T12:42:10Z | 39,349,353 | <p>Use <code>extend</code>:
<code>divisor_list.extend([i for i in list_range if n%i==0])</code></p>
| 1 | 2016-09-06T12:45:24Z | [
"python",
"list",
"python-2.7"
] |
How to remove outer list? | 39,349,281 | <p>I have a simple example,
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p>
<p>And i am solving it like this:</p>
<pre><code>n = 4
list_range = list(range(1,n+1))
divisor_list = []
divisor_list.append([i for i in list_range if n%i==0])
print divisor_... | -1 | 2016-09-06T12:42:10Z | 39,349,370 | <p>You don't need append, just use:</p>
<pre><code>divisor_list = [i for i in list_range if n% i == 0]
</code></pre>
<p>This way you just assign the result of list comprehension, giving you one clean list. No need to append a list, that will nest a list in a list, and no need to initialize as an empty list. That's re... | 1 | 2016-09-06T12:46:22Z | [
"python",
"list",
"python-2.7"
] |
How to remove outer list? | 39,349,281 | <p>I have a simple example,
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p>
<p>And i am solving it like this:</p>
<pre><code>n = 4
list_range = list(range(1,n+1))
divisor_list = []
divisor_list.append([i for i in list_range if n%i==0])
print divisor_... | -1 | 2016-09-06T12:42:10Z | 39,349,372 | <p>You can use assign the result of the list comprehension to the variable.</p>
| 1 | 2016-09-06T12:46:26Z | [
"python",
"list",
"python-2.7"
] |
How to remove outer list? | 39,349,281 | <p>I have a simple example,
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p>
<p>And i am solving it like this:</p>
<pre><code>n = 4
list_range = list(range(1,n+1))
divisor_list = []
divisor_list.append([i for i in list_range if n%i==0])
print divisor_... | -1 | 2016-09-06T12:42:10Z | 39,349,390 | <p>You don't need to initialize <code>divisor_list</code> as an empty sequence at all. The comprehension you're appending is the actual answer you're looking for.</p>
<pre><code>divisor_list = [i for i in list_range if n%i==0]
</code></pre>
| 1 | 2016-09-06T12:47:08Z | [
"python",
"list",
"python-2.7"
] |
How to remove outer list? | 39,349,281 | <p>I have a simple example,
Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p>
<p>And i am solving it like this:</p>
<pre><code>n = 4
list_range = list(range(1,n+1))
divisor_list = []
divisor_list.append([i for i in list_range if n%i==0])
print divisor_... | -1 | 2016-09-06T12:42:10Z | 39,349,758 | <p>It makes no sense to loop through all range of numbers, it's a waste! Just try to prove there are no more divisors after n/2, here's another benchmarked version comparing an alternative method <code>f2</code>:</p>
<pre><code>import math
import timeit
def f1(num):
return [i for i in range(1, num + 1) if num % ... | 1 | 2016-09-06T13:05:20Z | [
"python",
"list",
"python-2.7"
] |
How to remove square brackets in result pos_tag | 39,349,400 | <p>I want to extract nouns from dataframe. I do as below</p>
<pre><code>import pandas as pd
import nltk
from nltk.tag import pos_tag
df = pd.DataFrame({'pos': ['noun', 'Alice', 'good', 'well', 'city']})
noun=[]
for index, row in df.iterrows():
noun.append([word for word,pos in pos_tag(row) if pos == 'NN'])
df['nou... | 0 | 2016-09-06T12:47:36Z | 39,349,493 | <p>The bracket means you have lists in each cell of the data frame. If you are sure there is only one element at most in each list, you can use <code>str</code> on the noun column and extract the first element:</p>
<pre><code>df['noun'] = df.noun.str[0]
df
# pos noun
#0 noun noun
#1 Alice Alice
#2 good ... | 2 | 2016-09-06T12:52:30Z | [
"python",
"nltk",
"pos-tagger"
] |
install qgis on debian jessie | 39,349,492 | <p>I need to install qgis, qgis server, and lizmap on Debian jessie, and I can not install them. Currently my sources.list is as follows</p>
<p><a href="http://i.stack.imgur.com/48W3h.jpg" rel="nofollow">enter image description here</a></p>
<p>debian version installed:</p>
<pre><code>root@SIG:~# cat /etc/debian_vers... | -1 | 2016-09-06T12:52:28Z | 39,349,847 | <p>It seems that you're missing some dependencies. Try the following using root mode, or sudo if you wish. </p>
<pre><code>apt-get install -f
</code></pre>
<p>then,</p>
<pre><code>apt-get install qgis python-qgis qgis-plugin-grass
</code></pre>
| 1 | 2016-09-06T13:09:33Z | [
"python",
"qgis"
] |
App Engine throws 404 Not Found for any path but root | 39,349,590 | <p>I want to split my App Engine implementation into several files. So I wrote in my app.yaml file:</p>
<pre><code>runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /imageuploader
script: imageuploader.app
- url: /search
script: main.app
- url: /
static_files: index.html
upload: index.html... | 0 | 2016-09-06T12:56:55Z | 39,352,009 | <p>Each <code>app.yaml</code> route script config (like <code>script: imageuploader.app</code>) requires a python file with a matching name (<code>imageuploader.py</code> in this case) which is defining an app called <code>app</code> (just like the <code>main.py</code> does) with app routes being, of course, a subset o... | 2 | 2016-09-06T14:51:19Z | [
"python",
"google-app-engine",
"app.yaml"
] |
Arg parse: parse file name as string (python) | 39,349,653 | <p>I would like to parse the name of a file into my script as a string, rather than directly converting the file into an object.</p>
<p>Here is a sample code, <code>test.py</code>:</p>
<pre><code>import argparse
import os.path
def is_valid_file(parser, arg):
if not os.path.exists(arg):
parser.error("... | -1 | 2016-09-06T13:00:21Z | 39,352,415 | <p>you can modify your function as follows to return the string after having checked it exists:</p>
<pre><code>def is_valid_file(parser, arg):
if not os.path.exists(arg):
parser.error("The file %s does not exist! Use the --help flag for input options." % arg)
else:
return arg
</code><... | 0 | 2016-09-06T15:10:53Z | [
"python",
"string",
"filenames",
"argparse"
] |
Arg parse: parse file name as string (python) | 39,349,653 | <p>I would like to parse the name of a file into my script as a string, rather than directly converting the file into an object.</p>
<p>Here is a sample code, <code>test.py</code>:</p>
<pre><code>import argparse
import os.path
def is_valid_file(parser, arg):
if not os.path.exists(arg):
parser.error("... | -1 | 2016-09-06T13:00:21Z | 39,354,560 | <p>The <code>FileType</code> type factory does most of what your code does, with a slightly different message mechanism:</p>
<pre><code>In [16]: parser=argparse.ArgumentParser()
In [17]: parser.add_argument('-f',type=argparse.FileType('r'))
In [18]: args=parser.parse_args(['-f','test.txt'])
In [19]: args
Out[19]: Nam... | 0 | 2016-09-06T17:19:24Z | [
"python",
"string",
"filenames",
"argparse"
] |
'import sitecustomize' fails when opening spyder with non-empty file | 39,349,701 | <p>I get the error message
<code>'import sitecustomize' failed; use -v for traceback</code> in the internal python console in Spyder. </p>
<p>The interesting thing is, this only happens inside Spyder, running python in a shell doesn't show the same behaviour.</p>
<p>Furthermore, when I do </p>
<pre><code>spyder --... | 0 | 2016-09-06T13:02:37Z | 39,350,377 | <p>I found the problem to be special characters in the path name of the current working-directory. Changing working-directories to a path without special characters before exiting spyder resolved the problem.</p>
| 0 | 2016-09-06T13:34:51Z | [
"python",
"spyder"
] |
multiple columns from a file into a single column of lists in pandas | 39,349,711 | <p>I'm new to pandas , and need to prepare a table using pandas , imitating exact function performed by following code snippet:</p>
<pre><code>with open(r'D:/DataScience/ml-100k/u.item') as f:
temp=''
for line in f:
fields = line.rstrip('\n').split('|')
movieId = int(fields[0])
name = f... | 0 | 2016-09-06T13:03:00Z | 40,125,850 | <p>It's not clear to me what you intend to accomplish -- a single genres column containing fields 5-25 concatenated? Or separate genre columns for fields 5-25?</p>
<p>For the latter, you can use <code>[pandas.read_csv](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html)</code>:</p>
<pre class=... | 0 | 2016-10-19T08:21:12Z | [
"python",
"pandas",
"data-science"
] |
Bash script equivalent in windows to run pip and python commands? | 39,349,884 | <p>I have a python code which I need to send it to a client who will run it windows.
The python code works on a few imported modules mentioned in <code>requirements.txt</code>:</p>
<pre><code>requests==2.11.1
xlwt==1.1.2
beautifulsoup4==4.5.1
</code></pre>
<p>If I have to execute the code in windows, Iâll have man... | 0 | 2016-09-06T13:11:23Z | 39,350,054 | <p>I has similar task in the past. So I just used a tool py2exe which builds a standalone executable and it resolves dependencies at build time. A valid python interpreter will be included to the build. So your client can just execute this standalone exe file by double-click or from cmd shell.</p>
| 0 | 2016-09-06T13:19:33Z | [
"python",
"windows",
"cmd",
"exe"
] |
Simple but require bit manipulation Python Hex and INT | 39,349,977 | <p>I have an integer - say for example </p>
<pre><code>a = 12345
b = hex(a)
</code></pre>
<p>I have to send this to an MCU in a specific format. First I have to convert it into hex. which I did and it gives me --- 0x3039; </p>
<p>I need an array something like this - [0x39, 0x30]</p>
<p>Currently I am converting th... | 0 | 2016-09-06T13:15:46Z | 39,350,047 | <p>If you need a list of hex strings with number as little endian bytes:</p>
<pre><code>a=12345
l = [hex(a&0xff),hex(a>>8)] # little endian format, as hex string
print(l)
</code></pre>
<p>gives:</p>
<pre><code>['0x39', '0x30']
</code></pre>
<p>note the quotes, it is not possible to print <code>[0x39, 0x3... | 2 | 2016-09-06T13:19:06Z | [
"python",
"arrays",
"string",
"int"
] |
When should token be generated using oAuth | 39,350,002 | <p>I am striving to understand oAuth2 to implement in my REST API. I am using DRF in my backend and react native for building mobile app. I can create user registration and login in DRF but when and where should i actually create a token. Do i have to create token when user registers or when user logins ? I might get n... | 0 | 2016-09-06T13:16:45Z | 39,350,548 | <p>Probably, The question you should be asking is will a simple encrypted cookie not suffice which you pass to the server when you try to access the protected URLs/Resources. Now, If you want to still produce the token then after login hook the code to respond back with token in either header or in response payload. On... | 0 | 2016-09-06T13:42:44Z | [
"python",
"django",
"python-3.x",
"oauth",
"django-rest-framework"
] |
How to write better way to python inheritance? | 39,350,017 | <p>I have written this,</p>
<pre><code>class Sp():
def __init__(self):
self.price = 1
class A(Sp):
def __init__(self):
super(A, self).__init__()
self.test = True
class B(A):
pass
class C(A):
pass
class D(A):
"""In this class I don't want to inherit Sp class, but need A class"""
def __init__(sel... | -2 | 2016-09-06T13:17:20Z | 39,350,347 | <p>You can't inherit from <code>A</code> without inheriting from <code>Sp</code> if <code>A</code> itself inherits from <code>Sp</code>. You could try to work around it though, by making <code>A</code> inherit from two classes, one of which implements the non-<code>Sp</code> behaviors (say, call it <code>Abits</code>),... | 0 | 2016-09-06T13:33:08Z | [
"python",
"inheritance"
] |
Selenium Webdriver Python: I can't seem to locate all the text in a label tag | 39,350,070 | <pre><code><label class="control-label">
Rental Charge:
<span class="required" ng-show="vm.rentalInfo.reason">* (Min of $30.00)</span>
</label>
</code></pre>
<p>I used </p>
<pre><code>driver.find_element_by_xpath("//label[@ class = 'control-label']/span[@class = 'required']").text
</cod... | 0 | 2016-09-06T13:20:15Z | 39,351,429 | <p>I am guessing this is a timing issue. <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow">Wait</a> for "$" to be present in element explicitly with <code>text_to_be_present_in_element</code> expected condition:</p>
<pre><code>from selenium.webdriver.common.by import By
from sele... | 0 | 2016-09-06T14:23:02Z | [
"python",
"angularjs",
"selenium",
"selenium-webdriver",
"automated-tests"
] |
Selenium Webdriver Python: I can't seem to locate all the text in a label tag | 39,350,070 | <pre><code><label class="control-label">
Rental Charge:
<span class="required" ng-show="vm.rentalInfo.reason">* (Min of $30.00)</span>
</label>
</code></pre>
<p>I used </p>
<pre><code>driver.find_element_by_xpath("//label[@ class = 'control-label']/span[@class = 'required']").text
</cod... | 0 | 2016-09-06T13:20:15Z | 39,352,336 | <p>It's hard to say what is the issue in your case, it it is not timing issue. You should try using <code>get_attââribute()</code> as below may be it helps :-</p>
<pre><code> driver.find_element_by_css_selector("span.required[ng-show*='rentalInââfo.reason']").get_attââribute("textContent"ââ)
</code></... | 0 | 2016-09-06T15:07:09Z | [
"python",
"angularjs",
"selenium",
"selenium-webdriver",
"automated-tests"
] |
Selenium Webdriver Python: I can't seem to locate all the text in a label tag | 39,350,070 | <pre><code><label class="control-label">
Rental Charge:
<span class="required" ng-show="vm.rentalInfo.reason">* (Min of $30.00)</span>
</label>
</code></pre>
<p>I used </p>
<pre><code>driver.find_element_by_xpath("//label[@ class = 'control-label']/span[@class = 'required']").text
</cod... | 0 | 2016-09-06T13:20:15Z | 39,353,378 | <p>I tried to be a little specific like @alecxe suggested. So i used xpath <em>driver.find_element_by_xpath("//span[@ng-show = 'vm.rentalInfo.reason']").text</em> and it gave me the whole text "* (Min of $30.00)". Thanks to Saurabh Gaur and alecxe for your responses.</p>
| 0 | 2016-09-06T16:06:08Z | [
"python",
"angularjs",
"selenium",
"selenium-webdriver",
"automated-tests"
] |
Doubts about a Python Webserver | 39,350,075 | <p>I've a project which I developed a code to capture a temperature in some sensors and displaying a temperature to people, in fact I've a database (txt archive) whose was readed in a webserver to people in same network, now I've to improve this webpage (with some graphics, analitycs and etc) .
Someone has a tip to imp... | -1 | 2016-09-06T13:20:23Z | 39,350,197 | <p>For sure, if you are beginner in python then you should try do it as simple as it can be for example using Flask, all information you can find here: <a href="http://flask.pocoo.org/" rel="nofollow">http://flask.pocoo.org/</a><br><br>
Also if you want to write serious web page which contain advanced backend then you ... | 0 | 2016-09-06T13:25:56Z | [
"python",
"webserver"
] |
Having error null value in column "publicatithon_date" violates not-null constraint in django | 39,350,113 | <p>Hello I'm new to django and I'm learning django with this book:
djangobook.com
and I stuck in chapter 5 & 6 because when I try to check my work(in <a href="http://127.0.0.1:8000/admin/books/book/add/" rel="nofollow">http://127.0.0.1:8000/admin/books/book/add/</a>) I get some errors and I was trying to fix those ... | 0 | 2016-09-06T13:22:00Z | 39,350,406 | <p>As the error states, the publication_date is a not-null field and you're trying to add a Book with publication_date not set.<br>
One option to fix that is to make publication_date accept null values in your models.py thus: </p>
<pre><code>publication_date = models.DateField(null=true,)
</code></pre>
<p>However, I... | 0 | 2016-09-06T13:36:12Z | [
"python",
"django"
] |
How to return a comparison operator based on provided two values? | 39,350,132 | <p>I would like to create a python function that once provided with two <code>int</code> values will return a comparison string. There are the obvious ways, of using <code>if</code> blocks or <code>for</code> and <code>while</code> loops. I am just curious to find out the best possible solution.</p>
<pre><code>def get... | 0 | 2016-09-06T13:22:35Z | 39,350,287 | <p>You may use <code>operator</code> module to reduce line count, but in the end of the day you need to keep list of operations to check.</p>
<pre><code>import operator
operators = [operator.eq, operator.lt, operator.gt, operator.ne]
labels = ["==", "<", ">", "!="]
def get_comparison_operator(a, b):
for op... | 4 | 2016-09-06T13:30:06Z | [
"python"
] |
Tensorflow: parallel for loop results in out-of-memory | 39,350,164 | <p>My tensorflow code is like these:</p>
<pre><code>for i in range(100):
Zk = Zk + function_call(...)
</code></pre>
<p>It seems that tensorflow runs these 100 iterations in parallel, and keeps many temp vectors which have same size with Zk. However, since Zk is a very long vector, this leads to out-of-memory erro... | 0 | 2016-09-06T13:23:52Z | 39,353,834 | <p>The simplest way to solve this problem is to use a <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#control_dependencies" rel="nofollow"><code>with tf.control_dependencies():</code></a> block:</p>
<pre><code>Zk = ...
for i in range(100):
with tf.control_dependencies([Zk.op]):
... | 0 | 2016-09-06T16:32:03Z | [
"python",
"parallel-processing",
"tensorflow"
] |
Software or python package to draw and plot simple objects in 3D? | 39,350,176 | <p>I am looking for a software package, or even better, a python package that allows me to draw objects by inputing parameters, for example: I want a circle at position x,y, radius r, thickness t, color c and then look at it at different angles.</p>
<p>I know that I could use stuff like blender, but I feel that this i... | 1 | 2016-09-06T13:24:46Z | 39,350,368 | <p>I would recommend <a href="http://www.openscad.org" rel="nofollow">OpenSCad</a>. It is a software to create 3D objects by writing code. Although it isn't a python package, it is quite lightweight, has a nice view and the commands are really easy to learn - take a look at their <a href="http://www.openscad.org/docume... | 3 | 2016-09-06T13:34:33Z | [
"python",
"graphics"
] |
Software or python package to draw and plot simple objects in 3D? | 39,350,176 | <p>I am looking for a software package, or even better, a python package that allows me to draw objects by inputing parameters, for example: I want a circle at position x,y, radius r, thickness t, color c and then look at it at different angles.</p>
<p>I know that I could use stuff like blender, but I feel that this i... | 1 | 2016-09-06T13:24:46Z | 39,849,559 | <p>And I you want to do the same but stick with Python you can combine OpenSCAD with <a href="https://github.com/SolidCode/SolidPython" rel="nofollow">SolidPython</a>.</p>
| 1 | 2016-10-04T10:08:07Z | [
"python",
"graphics"
] |
Dealing with text file containing list and None values | 39,350,184 | <p>I have a text file similar to this one:</p>
<pre><code>a, 1, 2.5, 3
b, 1, 1, 1 1 2 3 4, 1 2, 3
c 1, 2, 2, 2, 2, None, 2
</code></pre>
<p>To put it in a nutshell each row starts with its name and is followed by a variable number of floats or list of floats delimited by commas and some float can be None values.
and ... | 0 | 2016-09-06T13:25:13Z | 39,350,350 | <p>Try this, D is a dictionary, then each row will use its 1st letter as the key and the rest of the list as the value.</p>
<pre><code>import csv
with open('items.csv', 'rB') as f:
csv_reader = csv.reader(f)
for row in csv_reader:
try:
D[row[0]] = [float(x) for x in row[1:]]
except ValueError as ... | 2 | 2016-09-06T13:33:19Z | [
"python",
"csv",
"numpy"
] |
Basemap m.fillcontinents() suppresses points on plot | 39,350,279 | <p>I'd like to change the colour of the land on a map, but doing so overrides any markers I may have on land. The m.fillcontinents() command suppresses any points of interest plotted. How do I get around this?</p>
| 0 | 2016-09-06T13:29:40Z | 39,385,588 | <p>I figured out that the problem was related to the zorder settings, so somethng like:</p>
<pre><code>m.scatter(x, y, zorder=2)
m.fillcontinents(color='#997766', lake_color='#99ffff', zorder=1)
</code></pre>
<p>where setting the symbols to a higher priority (zorder=2) than the fillcontinents (zorder=1) seemed to res... | 0 | 2016-09-08T08:01:04Z | [
"python",
"matplotlib",
"colors",
"matplotlib-basemap"
] |
Run multiple servers in python at same time (Threading) | 39,350,300 | <p>I have <strong>2 servers</strong> in python, <strong>I want to mix them up in one single .py and run together</strong>: </p>
<p>Server.py: </p>
<pre><code>import logging, time, os, sys
from yowsup.layers import YowLayerEvent, YowParallelLayer
from yowsup.layers.auth import AuthError
from yowsup.layers.network impo... | 1 | 2016-09-06T13:30:36Z | 39,350,834 | <pre><code>import thread
def run_app1():
#something goes here
def run_app2():
#something goes here
if __name__=='__main__':
thread.start_new_thread(run_app1)
thread.start_new_thread(run_app2)
</code></pre>
<p>if you need to pass args to the functions you can do:</p>
<pre><code>thread.start_new_thr... | 1 | 2016-09-06T13:54:52Z | [
"python",
"python-2.7",
"web.py",
"yowsup"
] |
How to manipulate list of list of dictionaries | 39,350,364 | <p>Hi there i have a wired situation here that i want to manipulate a dictionary key value which is list of lists include dictionaries here is the formation of the data i have </p>
<pre><code>my_list=[{'data': [[{'name': [0.0, 0.0]}], [{'name': [False, False]}], [{'name': [u'xm', u'xc']}]],'name': u'new',}]
</code></... | -1 | 2016-09-06T13:34:10Z | 39,350,821 | <p>Here we go, a version independant from keys value :</p>
<pre><code>my_list=[{'data': [[{'foo': [0.0, 0.0]}], [{'bar': [False, False]}], [{'pop': [u'xm', u'xc']}]]}]
buff = []
for elt in my_list[0]['data']:
a = []
k = elt[0].keys()[0]
val = elt[0][k]
for i in val:
a.append({k: i})
buff... | 0 | 2016-09-06T13:54:18Z | [
"python",
"list",
"dictionary"
] |
Impregnate string with list entries - alternating | 39,350,419 | <p>So SO, i am trying to "merge" a string (<code>a</code>) and a list of strings (<code>b</code>):</p>
<pre><code>a = '1234'
b = ['+', '-', '']
</code></pre>
<p>to get the desired output (<code>c</code>):</p>
<pre><code>c = '1+2-34'
</code></pre>
<p>The characters in the desired output string alternate in terms of ... | 3 | 2016-09-06T13:36:36Z | 39,350,520 | <p>You can use <a href="https://docs.python.org/3.4/library/itertools.html#itertools.zip_longest" rel="nofollow"><code>itertools.zip_longest</code></a> to <code>zip</code> the two sequences, then keep iterating even after the shorter sequence ran out of characters. If you run out of characters, you'll start getting <co... | 7 | 2016-09-06T13:41:27Z | [
"python"
] |
Could not able to make selection in second drop down list using python and selemium | 39,350,473 | <p>I am trying to make selection on the second drop down list after making a selection on first drop down list</p>
<p>The html code used for the first is :</p>
<p><a href="http://i.stack.imgur.com/Su6qC.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Su6qC.jpg" alt="First Drop down and its option values"></a><... | 0 | 2016-09-06T13:39:20Z | 39,350,742 | <p>You can use <code>indexing</code> here to locate desire <code>dropdown</code>, if there is no possibility to locate using any <code>attribute</code> value of these <code>dropdown</code> as below :-</p>
<pre><code>dropdown = driver.find_elements_by_class_name("StyledDropDown")
#now check first if length is equal to... | 0 | 2016-09-06T13:51:16Z | [
"python",
"selenium"
] |
Split tuple if key is empty and add correspondence value to its previous tuple value | 39,350,496 | <p>Here i have a list of tuples,whenever key is empty i want to add correspondence value to its previous tuple value.</p>
<p>I am able to achieve this in traditional way, but it looks ugly,
Is there any pythonic way to achieve the same ?</p>
<p>input : </p>
<pre><code>data= [('A', 12), ('', 1), ('B', 12), ('', 1), (... | 1 | 2016-09-06T13:40:37Z | 39,350,658 | <pre><code>reduce(
lambda lst,item: (((item[0] != '') and lst) or lst[:-1]) + [lst[-1] + item[1]],
colLabelGrouped[1:],
[colLabelGrouped[0][1]] )
</code></pre>
<p>This reduction...</p>
<ul>
<li>starts with an initial list consisting of the value of the first item in <code>colLabelGrouped</code... | 1 | 2016-09-06T13:47:26Z | [
"python",
"list",
"tuples"
] |
Split tuple if key is empty and add correspondence value to its previous tuple value | 39,350,496 | <p>Here i have a list of tuples,whenever key is empty i want to add correspondence value to its previous tuple value.</p>
<p>I am able to achieve this in traditional way, but it looks ugly,
Is there any pythonic way to achieve the same ?</p>
<p>input : </p>
<pre><code>data= [('A', 12), ('', 1), ('B', 12), ('', 1), (... | 1 | 2016-09-06T13:40:37Z | 39,350,952 | <p>Here's a slightly shorter way of doing it using the accumulate function and list-comprehensions (it might be more readable too):</p>
<pre><code>colLabelGrouped = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)]
from itertools import accumulate
cumsum = list(accumulate([x[1] for x in colLabel... | 1 | 2016-09-06T14:00:27Z | [
"python",
"list",
"tuples"
] |
Split tuple if key is empty and add correspondence value to its previous tuple value | 39,350,496 | <p>Here i have a list of tuples,whenever key is empty i want to add correspondence value to its previous tuple value.</p>
<p>I am able to achieve this in traditional way, but it looks ugly,
Is there any pythonic way to achieve the same ?</p>
<p>input : </p>
<pre><code>data= [('A', 12), ('', 1), ('B', 12), ('', 1), (... | 1 | 2016-09-06T13:40:37Z | 39,351,017 | <p>Using reduce you can do something like this:</p>
<pre><code>from functools import reduce
data = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)]
splitdata = reduce(
lambda res, i: res[:-1] + [res[-1] + i[1]] * (2 if i[0] == '' else 1),
data,
[0]
)
print(splitdata)
</code></pre>
| 1 | 2016-09-06T14:03:23Z | [
"python",
"list",
"tuples"
] |
Pycharm won't connect tfs | 39,350,517 | <p>I'm trying to connect TFS plugin to Pycharm 2016.1.2.
I went to settings - plugins - Intellij task interation for microsoft team found
then select HTTP Proxy setting. Then select Manua proxy configuration and entered Host name, port as 80 and gave the proxy authentication and select check connection.</p>
<p>It is... | 0 | 2016-09-06T13:41:18Z | 39,362,248 | <ol>
<li><p>I don't think this task still works. I have tested by following <a href="https://plugins.jetbrains.com/plugin/7336?pr=dbe" rel="nofollow">article</a> and download the SDK from <a href="http://www.microsoft.com/en-us/download/details.aspx?id=22616" rel="nofollow">http://www.microsoft.com/en-us/download/deta... | 1 | 2016-09-07T06:03:52Z | [
"python",
"tfs",
"pycharm"
] |
Python how to delete a specific value from a dictionary key with multiple values? | 39,350,527 | <p>I have a dictionary with multiple values per key and each value has two elements (possibly more). I would like to iterate over each value-pair for each key and delete those values-pairs that meet some criteria. Here for instance I would like to delete the second value pair for the key A; that is: ('Ok!', '0'):</p>
... | 0 | 2016-09-06T13:41:51Z | 39,350,689 | <p>The code like this:</p>
<pre><code>myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]}
for v in myDict.values():
if ('Ok!', '0') in v:
v.remove(('Ok!', '0'))
print(myDict)
</code></pre>
| 2 | 2016-09-06T13:48:53Z | [
"python",
"dictionary"
] |
Celery kills processes | 39,350,551 | <p>I use celery 3.1.23. </p>
<p>Task code is very simple:</p>
<pre><code>@app.task(bind=True, max_retries=None, default_retry_delay=settings.CELERY_RECONNECT_TIME)
def analize_text(self, **kwargs):
print 'test'
return 1
</code></pre>
<p>I launch celery this command:</p>
<blockquote>
<p>celery -A tasks wor... | 3 | 2016-09-06T13:42:50Z | 39,364,407 | <p>It depends on CELERY_MAX_TASKS_PER_CHILD i.e. number of tasks a worker shall complete before being recycled, default is no limit.</p>
<p><a href="http://docs.celeryproject.org/en/latest/configuration.html#std:setting-CELERYD_MAX_TASKS_PER_CHILD" rel="nofollow">http://docs.celeryproject.org/en/latest/configuration.h... | 1 | 2016-09-07T08:03:01Z | [
"python",
"multiprocessing",
"celery"
] |
Running scipy.integrate.ode in multiprocessing Pool results in huge performance hit | 39,350,557 | <p>I'm using python's <code>scipy.integrate</code> to simulate a 29-dimensional linear system of differential equations. Since I need to solve several problem instances, I thought I could speed it up by doing computations in parallel using <code>multiprocessing.Pool</code>. Since there is no shared data or synchronizat... | 10 | 2016-09-06T13:43:04Z | 39,488,979 | <p>This is intended as a formatted comment regarding the mathematical background raised in <a href="http://stackoverflow.com/questions/39350557/running-scipy-integrate-ode-in-multiprocessing-pool-results-in-huge-performance#comment66277221_39350557">a comment by @Dietrich</a>. As it doesn't address the programming ques... | 2 | 2016-09-14T11:11:35Z | [
"python",
"numpy",
"scipy",
"python-multiprocessing"
] |
Running scipy.integrate.ode in multiprocessing Pool results in huge performance hit | 39,350,557 | <p>I'm using python's <code>scipy.integrate</code> to simulate a 29-dimensional linear system of differential equations. Since I need to solve several problem instances, I thought I could speed it up by doing computations in parallel using <code>multiprocessing.Pool</code>. Since there is no shared data or synchronizat... | 10 | 2016-09-06T13:43:04Z | 39,514,895 | <p>Based on the variability of the execution times you posted for the machine showing the problem, I wonder what else that computer is doing at the time you are running your test. Here are times I saw when I ran your code on an AWS r3.large server (2 cores, 15 GB of RAM) that normally runs interactive R sessions but i... | 2 | 2016-09-15T15:26:18Z | [
"python",
"numpy",
"scipy",
"python-multiprocessing"
] |
Running scipy.integrate.ode in multiprocessing Pool results in huge performance hit | 39,350,557 | <p>I'm using python's <code>scipy.integrate</code> to simulate a 29-dimensional linear system of differential equations. Since I need to solve several problem instances, I thought I could speed it up by doing computations in parallel using <code>multiprocessing.Pool</code>. Since there is no shared data or synchronizat... | 10 | 2016-09-06T13:43:04Z | 39,534,779 | <p>on my compiled linux kernel :</p>
<ol>
<li>times: 8ms, 7ms</li>
<li>times: 5ms, 4ms</li>
<li>times: 4ms, 4ms</li>
<li>times: 8ms, 8ms</li>
<li>times: 4ms, 4ms</li>
<li>times: 5ms, 4ms</li>
<li>times: 4ms, 8ms</li>
<li>times: 8ms, 8ms</li>
<li>times: 8ms, 8ms</li>
<li>times: 4ms, 5ms</li>
</ol>
<p>Intel(R) Core(TM)... | 0 | 2016-09-16T15:08:25Z | [
"python",
"numpy",
"scipy",
"python-multiprocessing"
] |
Python 2.7: Why does string format not work on double __ fields | 39,350,589 | <p>I have the following class:</p>
<pre><code>class Members(object):
def __init__(self, variable=50):
self.__myvariable = variable
def getVariable(self):
return self.__myvariable
# attempt 1
def __repr__(self):
return """{self.__class__.__name__}({self.getVariable()})""".forma... | 0 | 2016-09-06T13:45:00Z | 39,350,827 | <p>When an attribute is <a href="https://docs.python.org/3/tutorial/classes.html#tut-private" rel="nofollow">private</a> (starting with two underscores <code>__</code>), its real name when running is <code>_ClassName__attribute</code>. So, to get <code>__myvariable</code>, you should ask for <code>_Members__myvariable<... | 3 | 2016-09-06T13:54:37Z | [
"python",
"python-2.7"
] |
Python 2.7: Why does string format not work on double __ fields | 39,350,589 | <p>I have the following class:</p>
<pre><code>class Members(object):
def __init__(self, variable=50):
self.__myvariable = variable
def getVariable(self):
return self.__myvariable
# attempt 1
def __repr__(self):
return """{self.__class__.__name__}({self.getVariable()})""".forma... | 0 | 2016-09-06T13:45:00Z | 39,350,884 | <p>You could format it like this instead:</p>
<pre><code> def __repr__(self):
return "{}({})".format(self.__class__.__name__,self.getVariable())
</code></pre>
<p>or like this:</p>
<pre><code> def __repr__(self):
return "{}({})".format(self.__class__.__name__,self.__myvariable)
</code></pre>
| 0 | 2016-09-06T13:57:12Z | [
"python",
"python-2.7"
] |
Python 2.7: Why does string format not work on double __ fields | 39,350,589 | <p>I have the following class:</p>
<pre><code>class Members(object):
def __init__(self, variable=50):
self.__myvariable = variable
def getVariable(self):
return self.__myvariable
# attempt 1
def __repr__(self):
return """{self.__class__.__name__}({self.getVariable()})""".forma... | 0 | 2016-09-06T13:45:00Z | 39,350,895 | <p>You can't access <code>__myvariable</code> because names with two leading __ get mangled (see <a href="http://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes">Does Python have âprivateâ variables in classes?</a>)</p>
<p>And python doesn't do variable interpolation so the other ... | 0 | 2016-09-06T13:57:32Z | [
"python",
"python-2.7"
] |
Python 2.7: Why does string format not work on double __ fields | 39,350,589 | <p>I have the following class:</p>
<pre><code>class Members(object):
def __init__(self, variable=50):
self.__myvariable = variable
def getVariable(self):
return self.__myvariable
# attempt 1
def __repr__(self):
return """{self.__class__.__name__}({self.getVariable()})""".forma... | 0 | 2016-09-06T13:45:00Z | 39,351,038 | <p>Attempt 1 fails because <a href="https://docs.python.org/2/library/string.html#format-examples" rel="nofollow">format function</a> does not call method at all </p>
<p>Attempt 2 fails because of name mangling behavior, see <a href="https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles" rel="nofollow">P... | 1 | 2016-09-06T14:04:37Z | [
"python",
"python-2.7"
] |
Error accessing my webpage from network | 39,350,666 | <p>I've just started learning network developing using <strong>Flask</strong>. According to its official tutorial:</p>
<blockquote>
<p><strong>Externally Visible Server</strong></p>
<p>If you run the server you will notice that the server is only
accessible from your own computer, not from any other in the ne... | 0 | 2016-09-06T13:47:54Z | 39,350,815 | <p>You don't access the Flask server on another computer by going to <code>0.0.0.0:5000</code>. Instead, you need to put in the IP address of the computer that it is running on.</p>
<p>For example, if you are developing on a computer that has IP address <code>10.10.0.1</code>, you can run the server like so:</p>
<pre... | 2 | 2016-09-06T13:54:05Z | [
"python",
"flask",
"hosting",
"web-hosting",
"host"
] |
Python tweet multiple images Twitter API | 39,350,671 | <p>I'm trying to write a script that will post two images to Twitter using the API, any idea why this doesn't work? It only posts the first image. New to this, thanks! </p>
<pre><code>from TwitterAPI import TwitterAPI
import urllib
api = TwitterAPI('','','','')
x = []
file = open('im1.png', 'rb')
data = file.read... | 3 | 2016-09-06T13:48:12Z | 39,351,279 | <p>Use tweepy (much easier);</p>
<pre><code>auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
Im1 = urllib.urlretrieve('http://www.meteociel.fr/cartes_obs/temp_uk.png','im1.png')
images = ('im1.png', 'im1.png')
media_ids = [api.... | 0 | 2016-09-06T14:17:16Z | [
"python",
"twitter"
] |
Python tweet multiple images Twitter API | 39,350,671 | <p>I'm trying to write a script that will post two images to Twitter using the API, any idea why this doesn't work? It only posts the first image. New to this, thanks! </p>
<pre><code>from TwitterAPI import TwitterAPI
import urllib
api = TwitterAPI('','','','')
x = []
file = open('im1.png', 'rb')
data = file.read... | 3 | 2016-09-06T13:48:12Z | 39,351,564 | <p>You are almost there. You just forgot to use your array of ids <code>x</code>. Make the following change to the last part of your code.</p>
<pre><code>if r.status_code == 200:
media_id = ','.join(x)
r = api.request('statuses/update', {'status':'Test', 'media_ids':media_id})
print('UPDATE STATUS SUCCESS'... | 0 | 2016-09-06T14:29:18Z | [
"python",
"twitter"
] |
Need quiz scoring function | 39,350,754 | <p>I have to create a basic 3 question quiz on farming. It needs to ask the 3 questions, output whether you got it correct or incorrect and if you got it incorrect you can try again. It also needs to have a score function. I have completed the questions and the incorrect/correct part of the specification but no matter... | -2 | 2016-09-06T13:51:36Z | 39,350,941 | <p>A n00b (and working) way would be to do something like</p>
<pre><code>score = 0
def quiz():
global score
</code></pre>
<p>The <code>global</code> keyword makes use of the global variable (which you declared <em>outside</em> your function <code>quiz</code>). Since you've not indented your code properly it's un... | 1 | 2016-09-06T13:59:58Z | [
"python"
] |
Need quiz scoring function | 39,350,754 | <p>I have to create a basic 3 question quiz on farming. It needs to ask the 3 questions, output whether you got it correct or incorrect and if you got it incorrect you can try again. It also needs to have a score function. I have completed the questions and the incorrect/correct part of the specification but no matter... | -2 | 2016-09-06T13:51:36Z | 39,350,968 | <p>So python scope is defined by indents (as mentioned by the comment above). So any statement that creates a layer of scope is seperated by an indent. Examples include classes, functions, loops, and boolean statements. Here is an example of this.</p>
<pre><code>Class A:
def __init__(self, msg):
self.messa... | 0 | 2016-09-06T14:01:26Z | [
"python"
] |
Need quiz scoring function | 39,350,754 | <p>I have to create a basic 3 question quiz on farming. It needs to ask the 3 questions, output whether you got it correct or incorrect and if you got it incorrect you can try again. It also needs to have a score function. I have completed the questions and the incorrect/correct part of the specification but no matter... | -2 | 2016-09-06T13:51:36Z | 39,352,021 | <pre><code>import sys
def quiz():
score = 0
print("Here is a quiz to test your knowledge of farming...")
print()
print()
print("Question 1")
print("What percentage of the land is used for farming?")
print()
print("a. 25%")
print("b. 50%")
print("c. 75%")
answer = input("Make ... | 0 | 2016-09-06T14:51:44Z | [
"python"
] |
How can I terminate a python program from an embedded IPython shell? | 39,350,823 | <p>I have the problem that for debugging purposes I drop into an IPython shell in a loop:</p>
<pre><code>for x in large_list:
if x.looks_bad():
import IPython
IPython.embed()
</code></pre>
<p>From there I may want to terminate the <em>parent</em> program, because after debugging the problem cause, <code>emb... | 0 | 2016-09-06T13:54:26Z | 39,350,824 | <p><code>sys.exit</code> just raises the <code>SystemExit</code> exception. The following works by hard-killing the program:</p>
<pre><code>import os
os._exit(1)
</code></pre>
| 0 | 2016-09-06T13:54:26Z | [
"python",
"ipython"
] |
Inserting formatted string with single quotes with Pypyodbc | 39,350,833 | <p>I'm trying to insert a network path as a string value using Pypyodbc:</p>
<pre><code> def insert_new_result(self, low, medium, high, reportpath):
reportpath = "'" + reportpath + "'"
self.insertsql = (
"""INSERT INTO [dbo].[Results] ([low],[medium], [high], [date]) VALUES
({low},{medium},{... | 0 | 2016-09-06T13:54:48Z | 39,378,205 | <p>If you are using <code>string.format()</code> then you are creating <em>dynamic SQL</em> which leaves you open to all the indignities of <em>SQL injection</em>, like messing with string delimiting and escaping. You should simply use a <em>parameterized query</em>, something like this:</p>
<pre class="lang-python pr... | 0 | 2016-09-07T20:08:15Z | [
"python",
"sql-server",
"pypyodbc"
] |
how to make the space between column 1 and 2 the same | 39,350,840 | <p>I am at the moment trying to filter a lexicon/dictionary such that it only contains the word i need. The dictionary has two column first being the word, and the second being the phonetic pronunciation (see the image below).</p>
<p><img src="http://i.stack.imgur.com/VXJMZ.png" alt="Snippet of lexicon"></p>
<p>The l... | 1 | 2016-09-06T13:55:07Z | 39,351,987 | <p>you mean something like the following?
<a href="http://pastebin.com/qvyEmbUr" rel="nofollow">here</a></p>
<p>In this case, this is the code (without using any particular characters):</p>
<pre><code>#!/usr/bin/env python2
import sys
path_to_the_file = sys.argv[1]
word = []
pron = []
maxword = 0
with open(path_to... | 0 | 2016-09-06T14:50:16Z | [
"python",
"unix",
"text",
"file-handling"
] |
Python: os.listdir files are not found | 39,350,844 | <p>I recently moved my config files to another folder in my Project. I try to load the like this:</p>
<pre><code>CONFIG_PATH = os.path.abspath(os.path.dirname(os.path.abspath(__file__))+"/../config/")
def load_config():
configs = {}
for config in os.listdir(CONFIG_PATH):
configs[str(config)[0:-12]... | 1 | 2016-09-06T13:55:17Z | 39,351,019 | <p><code>os.listdir</code> only return the name of the file, not the complete path.</p>
<p>If you're on 3.5 you can use <code>os.scandir</code> where the returned item has a path attribute. If you're not that lucky, you'll have to construct the full path yourself.</p>
<p>It would be: <code>json.load(open(os.path.join... | 0 | 2016-09-06T14:03:35Z | [
"python",
"json",
"file"
] |
Python library for working with 3D kinematics | 39,350,861 | <p>I am new at the field of kinematics and I am looking for some Python library that will make my start with 3D kinematics easier. The only library that I found so far is <strong>thLib</strong>, but nothing else. I am not sure if I am using wrong keywords or is python so pour.</p>
<p>My goal is to use data from accele... | 0 | 2016-09-06T13:56:08Z | 39,351,015 | <p>you can use <a href="http://matplotlib.org/" rel="nofollow">matplotlib</a> in that <a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html" rel="nofollow">mplot3d</a> and you can also use <a href="https://code.google.com/archive/p/robotics-toolbox-python/" rel="nofollow">robotics-toolbox-python</a></p>
| 1 | 2016-09-06T14:03:18Z | [
"python",
"analysis",
"motion",
"kinematics"
] |
Python ImportError: No module named | 39,350,909 | <p>I try to run django project, which has this kind of structure: 2 apps in one project:</p>
<p>projectx</p>
<pre><code>âââapps
â âââ app1
| | âââ __init__.py
| | âââ ...
â âââ app2
| âââ __init__.py
| âââ ...
âââproject
â âââ settings... | 0 | 2016-09-06T13:58:03Z | 39,350,935 | <p>You should add <code>__init__.py</code> inside your <code>apps</code> directory</p>
<pre><code> âââapps
âââ__init__.py
â âââ app1
| | âââ __init__.py
| | âââ ...
â âââ app2
| âââ __init__.py
| âââ ...
</code></p... | 5 | 2016-09-06T13:59:38Z | [
"python",
"django"
] |
Adding Characters to beginning and end of line that matches expression (Python) | 39,350,944 | <p>Background: I am tasked with taking content from one website (mostly HTML tables), and inserting it into a wiki type site. I am able to poll the content (it is dynamic) using a REST API and get HTML formatted output. I must take this output, and convert it into Wiki Markup in order to then insert it into the new sit... | 0 | 2016-09-06T14:00:05Z | 39,352,033 | <p>A first try:</p>
<pre><code>html = html2text.HTML2Text()
input_file = raw_input('File to convert: ')
with open(input_file, 'r') as input_, open('finalconvert', 'w') as output_:
data = input_.read()
data_converted = html.handle(data)
for line in data_converted.split('\n'):
if '|' in line:
... | 0 | 2016-09-06T14:52:22Z | [
"python"
] |
Adding Characters to beginning and end of line that matches expression (Python) | 39,350,944 | <p>Background: I am tasked with taking content from one website (mostly HTML tables), and inserting it into a wiki type site. I am able to poll the content (it is dynamic) using a REST API and get HTML formatted output. I must take this output, and convert it into Wiki Markup in order to then insert it into the new sit... | 0 | 2016-09-06T14:00:05Z | 39,353,623 | <p>1: You can eliminate the temporary files by using <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>split</code></a> to convert from a single string to a list of strings. This has the side effect of removing the <code>\n</code> from each line, which you will have to add back or... | 1 | 2016-09-06T16:20:32Z | [
"python"
] |
Applying Conditions on Pandas DataFrame Columns before reading csv or tsv files | 39,351,036 | <p>Is it possible to set conditions (filters) for the DataFrame columns before reading a csv or tsv files, If I am already aware of the column names and types? If yes, how?</p>
<p>For Example: Consider there are two numerical columns (col1 and col2) in a very big file. I do not want to load whole file in the memory an... | 0 | 2016-09-06T14:04:26Z | 39,351,962 | <p>You can use <a href="https://blaze.readthedocs.io/en/latest/" rel="nofollow">blaze</a> for this which is a handy tool to have alongside <code>pandas</code>.</p>
<p>Let's assume an input file of:</p>
<pre><code>a,b
1,2
3,4
5,3
3,6
6,1
</code></pre>
<p>We then open the file and query the data - note that the query ... | 1 | 2016-09-06T14:49:27Z | [
"python",
"pandas",
"dataframe",
"condition"
] |
Run Sqoop with python 3 using subprocess | 39,351,139 | <p>I am trying to run Sqoop command with python</p>
<pre><code>subprocess.call(["sqoop","import","--connect", "jdbc:oracle:thin:@hostname:1521/ARSMTREP","--username", "username" ,"--password", "password","--table","ARADMIN."+line,"--as-textfile","--target-dir","/data/"+line])
</code></pre>
<p>able to execute this cod... | 0 | 2016-09-06T14:10:29Z | 39,351,986 | <p>Try:</p>
<p><code>process=subprocess.call(["sqoop","import","--connect", "jdbc:oracle:thin:@hostname:1521/ARSMTREP","--username", "hadoop_user" ,"--password", "password","--table","ARADMIN."+line,"--fields-terminated-by","'~'","--as-textfile","--target-dir","/data/"+line])</code></p>
| 0 | 2016-09-06T14:50:16Z | [
"python",
"python-3.x",
"sqoop",
"apache-sqoop"
] |
Run Sqoop with python 3 using subprocess | 39,351,139 | <p>I am trying to run Sqoop command with python</p>
<pre><code>subprocess.call(["sqoop","import","--connect", "jdbc:oracle:thin:@hostname:1521/ARSMTREP","--username", "username" ,"--password", "password","--table","ARADMIN."+line,"--as-textfile","--target-dir","/data/"+line])
</code></pre>
<p>able to execute this cod... | 0 | 2016-09-06T14:10:29Z | 39,361,835 | <pre><code>process=subprocess.call(["sqoop","import","--connect", "jdbc:oracle:thin:@hostname:1521/ARSMTREP","--username", "hadoop_user" ,"--password", "password","--table","ARADMIN."+line,"--fields-terminated-by","~","--as-textfile","--target-dir","/data/"+line])
</code></pre>
<p>This code call the sqoop command and ... | 0 | 2016-09-07T05:30:58Z | [
"python",
"python-3.x",
"sqoop",
"apache-sqoop"
] |
basemap returns blank when plotting points | 39,351,185 | <p>I'm new to basemap and map plots in general. After looking through documentation online, I was able to install basemap and GEOS no problem. I was able to setup my basemap map with the following code:</p>
<pre><code>themap = Basemap(projection='gall',
resolution='i',
llcrnrlon = -135,... | 0 | 2016-09-06T14:12:18Z | 39,351,789 | <p>The order of the points should be (lon, lat). This is working for me:</p>
<p><a href="http://i.stack.imgur.com/sQNXX.png" rel="nofollow"><img src="http://i.stack.imgur.com/sQNXX.png" alt="enter image description here"></a></p>
| 1 | 2016-09-06T14:41:00Z | [
"python",
"matplotlib",
"matplotlib-basemap"
] |
Python write to csv ignore commas | 39,351,222 | <p>I am writing to a csv and it works good, except some of the rows have commas in there names and when I write to the csv those commas throw the fields off...how do I write to a csv and ignore the commas in the rows</p>
<pre><code>header = "Id, FACID, County, \n"
row = "{},{},{}\n".format(label2,facidcsv,County)
with... | 1 | 2016-09-06T14:13:58Z | 39,351,270 | <p>Strip any comma from each field that you write to the row, eg:</p>
<pre><code>label2 = ''.join(label2.split(','))
facidcsv = ''.join(facidcsv.split(','))
County = ''.join(County.split(','))
row = "{},{},{}\n".format(label2,facidcsv,County)
</code></pre>
<hr>
<p>Generalized to format a row with any number of field... | 2 | 2016-09-06T14:16:40Z | [
"python",
"csv"
] |
recvfrom function in C on Windows skips UDP data when using MinGW | 39,351,233 | <p>I have problem with recvfrom function on Windows I cannot resolve.<br>
See the following part of code I wrote.
I run this code on Linux and Windows and I get different results in udp bitrate value. </p>
<p>When compiling it on Windows using Cygwin, I get the same results as on Ubuntu, what is okay. I compared this... | 0 | 2016-09-06T14:14:53Z | 39,352,264 | <p>UDP is an unreliable transport. Dropping packets is an allowed behavior, and it is to be expected where the data transmission rate exceeds the rate at which data are handled by the receiver.</p>
<p>Cygwin and MinGW are separate projects. They each provide their own <code>recvfrom()</code> wrapper built on top of ... | 0 | 2016-09-06T15:03:48Z | [
"python",
"c",
"windows",
"udp",
"recvfrom"
] |
Is it good practice to exit a thread manually in python? | 39,351,271 | <p>Is it good practice to exit a thread manually? The below code has commented #sys.exit() because I assume the thread ends there. But is it good practice to end it anyway? If not, is there any overhead created if that thread is called hundres of times without manually exiting with sys.exit()?</p>
<pre><code>import ti... | 0 | 2016-09-06T14:16:47Z | 39,351,312 | <p><code>sys.exit()</code> has nothing to do with threads. As <a href="https://docs.python.org/3/library/sys.html#sys.exit" rel="nofollow">the docs</a> explain, it only has an effect when called from the main thread. In all other cases, all it does is raise an exception. There's absolutely no reason to call it in a thr... | 4 | 2016-09-06T14:18:49Z | [
"python",
"multithreading"
] |
Python argaprse optional arguments handling | 39,351,272 | <p>So, I have a python script for parsing and plotting data from text files. Argument handling is done with argparse module. The problem is, that some arguments are optional, e.g. one of the is used to add text annotations on the plot. This argument is sent to plotting function via **kwargs. My question is - what is th... | 0 | 2016-09-06T14:16:48Z | 39,351,322 | <p>You can just provide an explicit empty list as the default.</p>
<pre><code>parser.add_argument("-o", "--options", nargs="+", default=[])
</code></pre>
| 3 | 2016-09-06T14:19:04Z | [
"python",
"command-line-arguments",
"argparse",
"kwargs"
] |
Python argaprse optional arguments handling | 39,351,272 | <p>So, I have a python script for parsing and plotting data from text files. Argument handling is done with argparse module. The problem is, that some arguments are optional, e.g. one of the is used to add text annotations on the plot. This argument is sent to plotting function via **kwargs. My question is - what is th... | 0 | 2016-09-06T14:16:48Z | 39,351,403 | <p>use <code>get</code> and set a default value if the key is not found in the dict</p>
<pre><code>def some_function(arguments, **kwargs):
something = kwargs.get('options', 'Not found')
return something
</code></pre>
<p>or an if statement</p>
<pre><code>if 'option' in kwargs:
pass # do something
</code></p... | 1 | 2016-09-06T14:21:39Z | [
"python",
"command-line-arguments",
"argparse",
"kwargs"
] |
Control the mouse click event with a subplot rather than a figure in matplotlib | 39,351,388 | <p>I have a figure with 5 subplots. I am using a mouse click event to create a shaded area in the 4th and 5th subplot only (see attached pic below).</p>
<p><a href="http://i.stack.imgur.com/3G3UO.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/3G3UO.jpg" alt="enter image description here"></a></p>
<p>The mouse... | 1 | 2016-09-06T14:21:05Z | 39,351,847 | <p>You can use the <code>inaxes</code> property of <code>event</code> to find which axes you are in. See the <a href="http://matplotlib.org/users/event_handling.html#event-attributes" rel="nofollow">docs here</a>. If you iterate through your subplot <code>Axes</code>, you can then compare the result of <code>inaxes</co... | 1 | 2016-09-06T14:43:56Z | [
"python",
"matplotlib",
"mouseclick-event"
] |
How to get popup content with splash | 39,351,458 | <p>i'm starting to use scrapy with splash, and i was wondering if splash can handle multiple windows and popups. As an example i would like to use that lua script and try to obtain the google window's content</p>
<pre><code>function main(splash)
assert(splash:go("http://stackoverflow.com/"))
assert(splash:runjs("w... | 0 | 2016-09-06T14:24:23Z | 39,352,609 | <p>I've found a tiny hack, i do a</p>
<pre><code>assert(splash:runjs("window.open = function(url) {window.location.replace(url)};")
</code></pre>
<p>So instead of opening new windows, you are redirected towards the link, however it's a hack and it might not work if window.open is not used to open the popup</p>
<p>I ... | 0 | 2016-09-06T15:20:01Z | [
"python",
"web-scraping",
"popup",
"scrapy",
"scrapy-splash"
] |
Easy way to continue a failed reindex? | 39,351,521 | <p>I'm currently trying to reindex a large set of data (around 96 million documents) using the <a href="http://elasticsearch-py.readthedocs.io/en/master/api.html" rel="nofollow">Python API</a>, specifically the <a href="http://elasticsearch-py.readthedocs.io/en/master/helpers.html#reindex" rel="nofollow"><code>reindex<... | 1 | 2016-09-06T14:27:44Z | 39,351,566 | <p>If you're saying that you're deleting the existing ones and start over, then just delete index and create new one and feed it. Will be faster.</p>
<p><strong>OR</strong></p>
<p>If you cannot have empty index, then one by one or using some batch delete items identified by some <code>id</code> and insert updated acc... | 1 | 2016-09-06T14:29:19Z | [
"python",
"elasticsearch"
] |
Load file into Database | 39,351,687 | <p>I am trying to load a csv file into the database but no success. The issue is that it works when I load the query directly in the mysql shell but it doesn't work when I tried doing from the python code. The code I am using is shown below:</p>
<pre><code>db = connect_to_database()
cursor = db.cursor()
q = "LOAD DAT... | 0 | 2016-09-06T14:35:42Z | 39,418,386 | <p>So I managed to solve the problem. All it was missing was the local_infile parameter in the MySQLDB connect:</p>
<p>db=MySQLdb.connect(host=raw_host,user=raw_user,passwd=raw_passwd,db=raw_db, local_infile = 1)</p>
<p>When I added this parameter, it worked as expected. Thank you all for your efforts in resolving th... | 0 | 2016-09-09T19:19:26Z | [
"python",
"mysql"
] |
Edit a web page with Python | 39,351,699 | <p>I asked a <a href="http://stackoverflow.com/questions/39283333/python-to-view-and-manipulate-web-page?noredirect=1#comment65902596_39283333">similar question</a> about how to edit a web page with Python before using selenium, but since that didn't get anywhere (I want to be able to do it in a browser that still has ... | 0 | 2016-09-06T14:36:26Z | 39,351,778 | <p>You can still do that via <code>selenium</code>, locate the element and edit the <code>style</code> via "execute script":</p>
<pre><code>elm = driver.find_element_by_id("myid")
driver.execute_script("arguments[0].style.display = 'none';", elm)
</code></pre>
| 0 | 2016-09-06T14:40:26Z | [
"python",
"python-2.7",
"google-chrome"
] |
Django - TinyMCE - admin - How to change editor size? | 39,351,709 | <p>I can't seem to find any way to hange editor size in TinyMCE.
I edit posts on my site in Django administration and to make it easier I looked for a better editor than just a textfield. I succesfully installed TinyMCE, but the editor is tiny, which makes editing very annoying.</p>
<p><a href="http://i.imgur.com/eaW5... | 0 | 2016-09-06T14:37:01Z | 39,364,134 | <p>As said in the docs (<a href="http://django-tinymce.readthedocs.io/en/latest/installation.html#configuration" rel="nofollow">http://django-tinymce.readthedocs.io/en/latest/installation.html#configuration</a>), there is the <code>TINYMCE_DEFAULT_CONFIG</code> setting which can be used to configure the editor. Just lo... | 0 | 2016-09-07T07:49:15Z | [
"python",
"django",
"tinymce",
"django-tinymce"
] |
Error: django.core.exceptions.AppRegistryNotReady: The translation infrastructure... in python | 39,351,908 | <p><strong>What I want to do:</strong> I'm trying to run tests with unittest for functions in my views. </p>
<p><strong>Outcome</strong>: I'm getting the following error:</p>
<p><em>....env/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 189, in _fetch
"The translation infrastructure can... | 1 | 2016-09-06T14:46:44Z | 39,352,450 | <p>Finally I solved it changing:</p>
<pre><code>from django.utils.translation import gettext as _
</code></pre>
<p>to:</p>
<pre><code>from django.utils.translation import ugettext_lazy as _
</code></pre>
| 1 | 2016-09-06T15:12:25Z | [
"python",
"django"
] |
Error: django.core.exceptions.AppRegistryNotReady: The translation infrastructure... in python | 39,351,908 | <p><strong>What I want to do:</strong> I'm trying to run tests with unittest for functions in my views. </p>
<p><strong>Outcome</strong>: I'm getting the following error:</p>
<p><em>....env/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 189, in _fetch
"The translation infrastructure can... | 1 | 2016-09-06T14:46:44Z | 39,352,461 | <p>Initialize the WSGI application before you import from views and settings.</p>
<pre><code>application = get_wsgi_application()
from mysite.settings import *
from views import *
</code></pre>
| 0 | 2016-09-06T15:12:54Z | [
"python",
"django"
] |
How to change number of bins in matplotlib? | 39,351,960 | <p>I have the following code:</p>
<pre><code>ax1.hist(true_time, bins=500, edgecolor="none")
ax2.hist(true_time_2, bins=500, edgecolor="none")
</code></pre>
<p>I expected that it would give me two hists with the same number of bins, but it wouldn't:
<a href="http://i.stack.imgur.com/Nkx3k.png" rel="nofollow"><img src... | 0 | 2016-09-06T14:49:12Z | 39,352,129 | <p>If you have some distant outlier in true_time, it may be that the bins were made just really really big to include it.</p>
| 2 | 2016-09-06T14:57:05Z | [
"python",
"matplotlib",
"bins"
] |
Python asyncio program won't exit | 39,351,988 | <p>I have an asyncio/Python program with two asyncio tasks: </p>
<ul>
<li>one that crashes</li>
<li>one that goes on for ever. </li>
</ul>
<p>I want my entire program to exit after the first crash. I cannot get it to happen.</p>
<pre><code>import asyncio
import time
def infinite_while():
while True:
tim... | 4 | 2016-09-06T14:50:28Z | 39,474,956 | <p>When an exception is risen in a task, it never propagates to the scope where the task was launched via eventloop, i.e. the <code>loop.run_until_complete(tasks)</code> call. Think of it, as if the exception is thrown only in the context of your task, and that is the top level scope where you have the chance to handle... | 1 | 2016-09-13T16:34:38Z | [
"python",
"python-asyncio"
] |
Uniquely identifying ManyToMany relationships in Django | 39,352,019 | <p>I'm trying to figure out how best to uniquely identify a ManyToMany relationship in my Django application. I have models similar to the following:</p>
<pre><code>class City(models.Model):
name = models.CharField(max_length=255)
countries = models.ManyToManyField('Country', blank=True)
class Country(models.... | 2 | 2016-09-06T14:51:39Z | 39,352,156 | <p>I think your idea of a <code>through</code> table is the right approach. Then, I would add a <code>unique_together('city', 'country')</code> into the <code>Meta</code>.</p>
<p>I don't think there is a need for an <code>AutoField</code></p>
| 2 | 2016-09-06T14:58:48Z | [
"python",
"django",
"orm"
] |
Unable to locate element because of a dynamic xpath | 39,352,085 | <p>So here is the current XPath i'm trying to use.</p>
<pre><code>//*[@id="highcharts-33"]/svg/g[3]/g[1]/text
</code></pre>
<p>The problem is that this is a Dynamic Xpath, so it goes like "highcharts-33", "highcharts-34" etc... I'm making screenshots of theses graphs by clicking on a checkbox. Each time the checkbox ... | 0 | 2016-09-06T14:55:00Z | 39,353,886 | <p>I'm assuming that there's only one <code><text></code> element inside your <code><div id="highcharts-*></code> element so you could try CSS selector <code>div[id^="highcharts"] text</code></p>
<pre><code>textvote = self.driver.find_element_by_css("div[id^='highcharts-'] text").text
</code></pre>
<p>Thi... | 0 | 2016-09-06T16:35:41Z | [
"python",
"xpath",
"selenium-webdriver"
] |
SQLALCHEMY or_ list comprehension | 39,352,202 | <p>I'm trying to use list comprehension with or_. I already found a post that showed how to do it with only checking one column, but I'm unsure how to check two columns simultaneously with a list. I tried something like this:</p>
<p><code>q = q.filter(or_((model.column.contains(word), model.column2.contains(word))for ... | 0 | 2016-09-06T15:01:26Z | 39,352,294 | <p>From what I understand you need to <em>unpack</em> the conditions into positional arguments of <a href="http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.or_" rel="nofollow"><code>or_()</code></a>:</p>
<pre><code>columns = [model.column, model.column2]
conditions = [column.contains... | 1 | 2016-09-06T15:04:47Z | [
"python",
"sqlalchemy",
"flask-sqlalchemy"
] |
Encoding/Encrypting from stdin in Python | 39,352,278 | <p>I'm trying to encrypt data from stdin to send across a socket, so for testing I'm trying to decrypt what I just encrypted and it's not producing the original message as is.</p>
<pre><code>BS = 16
client_cipher = AES.new(client_conf_key, AES.MODE_CBC, randIV)
message = sys.stdin.readline()
padded_message = message ... | 0 | 2016-09-06T15:04:16Z | 39,353,325 | <p>Here is some code I once wrote to a similar effect;</p>
<pre><code>BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s : s[0:-ord(s[-1])]
def encrypt(plaintext, key, iv):
cipher = AES.new(key, AES.MODE_CBC,iv)
plaintext = pad(plaintext)
return cipher.encrypt(plai... | 0 | 2016-09-06T16:02:51Z | [
"python",
"encoding",
"aes"
] |
How to pull div attributes with BeautifulSoup in Python | 39,352,371 | <p>I'm trying to pull this data (lat and lng):</p>
<pre><code><div class="location"
lat="1234"
lng="5678"
>
</code></pre>
<p>This is giving me nothing:</p>
<pre><code>print (soup.find_all("div", { "class" : "location"}))
</code></pre>
<p>My eventual goal is to store these values in a dictionary. Thank... | 0 | 2016-09-06T15:08:58Z | 39,352,483 | <p>You can use the <em>dictionary like-access to element attribute</em> in BeautifulSoup:</p>
<pre><code>locations = [{'lat': location['lat'], 'lng': location['lng']}
for location in soup.find_all("div", {"class": "location"})]
</code></pre>
<p>If there is a single location, use <code>find()</code> inste... | 2 | 2016-09-06T15:14:28Z | [
"python",
"beautifulsoup"
] |
How to pull div attributes with BeautifulSoup in Python | 39,352,371 | <p>I'm trying to pull this data (lat and lng):</p>
<pre><code><div class="location"
lat="1234"
lng="5678"
>
</code></pre>
<p>This is giving me nothing:</p>
<pre><code>print (soup.find_all("div", { "class" : "location"}))
</code></pre>
<p>My eventual goal is to store these values in a dictionary. Thank... | 0 | 2016-09-06T15:08:58Z | 39,352,585 | <p>From BeautifulSoup docs you might be using find_all() wrong.
<a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-keyword-arguments" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-keyword-arguments</a></p>
<p>Try:</p>
<pre><code>print (soup.find_all("div",class_="location"... | 0 | 2016-09-06T15:19:08Z | [
"python",
"beautifulsoup"
] |
How to pull div attributes with BeautifulSoup in Python | 39,352,371 | <p>I'm trying to pull this data (lat and lng):</p>
<pre><code><div class="location"
lat="1234"
lng="5678"
>
</code></pre>
<p>This is giving me nothing:</p>
<pre><code>print (soup.find_all("div", { "class" : "location"}))
</code></pre>
<p>My eventual goal is to store these values in a dictionary. Thank... | 0 | 2016-09-06T15:08:58Z | 39,352,602 | <p>Your current <code>print</code> is returning a <em>list</em> of results:</p>
<pre><code>[<div class="location" lat="1234" lng="5678"></div>]
</code></pre>
<p>You can access these by iterating through each result:</p>
<pre><code>for r in results:
print(r['lat'], r['lng'])
</code></pre>
<hr>
<p>A ... | 1 | 2016-09-06T15:19:49Z | [
"python",
"beautifulsoup"
] |
Pandas Dataframe delete row with certain value until that value changes | 39,352,554 | <p>I have a dataframe with zeros at the top of the dataframe. These zeroes act as NAs. I would like to delete them until other values begin to appear. </p>
<p>So, I would like this dataframe: </p>
<pre><code> df_
Out[114]:
A B C
2016-08-27 -0.263963 0.000000 0.693514
... | 2 | 2016-09-06T15:17:24Z | 39,352,707 | <p>You can test if all rows are not equal to <code>0</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow"><code>all</code></a> and <code>axis=1</code>, we use this to mask the df and call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/panda... | 3 | 2016-09-06T15:26:00Z | [
"python",
"pandas",
"dataframe"
] |
Is it possible to add x-axis labels to *every* plot in the Seaborn Factor Plot (Python)? | 39,352,563 | <p>I'm using Seaborn to make a Factor Plot. </p>
<p>In total, I have 4 'sub plots' (and use <code>col_wrap =2</code>, so I have 2 rows, each containing 2 sub plots). Only the 2 sub plots at the very bottom of the grid have x-axis labels (which I believe is the default). </p>
<p>Is it possible to configure the Fact... | 0 | 2016-09-06T15:17:55Z | 39,366,416 | <p>I'm not sure of a way to do this in <code>seaborn</code>, but you can play with the matplotlib <code>Axes</code> instances to do this. </p>
<p>For example, here we'll use <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.setp" rel="nofollow"><code>setp</code></a> to set the <code>xticklabels</cod... | 1 | 2016-09-07T09:40:49Z | [
"python",
"matplotlib",
"seaborn"
] |
NumPy matrix not indexing range correctly [0,0,0,5:53].shape = 43 | 39,352,634 | <p>I have a rather large numpy matrix, and I'm thinking since it is so large this is happening. It has to be some sort of pointer issue.</p>
<p>Anyways, I have the following matrix </p>
<pre><code>(Pdb) input_4d_volume.shape
(26010, 48, 48, 48)
</code></pre>
<p>When I index like the following, no problem: </p>
<pre... | 0 | 2016-09-06T15:21:42Z | 39,352,874 | <p>Python will let you index up to a number larger than the length of the object. For example,</p>
<pre><code>import numpy as np
a = np.arange(0, 10)
a[5:100]
# array([5, 6, 7, 8, 9])
</code></pre>
<p>If your 4-D input array is of shape (26010, 48, 48, 48), and you are slicing on the 4th dimension, you cannot end up ... | 3 | 2016-09-06T15:36:57Z | [
"python",
"numpy"
] |
NumPy matrix not indexing range correctly [0,0,0,5:53].shape = 43 | 39,352,634 | <p>I have a rather large numpy matrix, and I'm thinking since it is so large this is happening. It has to be some sort of pointer issue.</p>
<p>Anyways, I have the following matrix </p>
<pre><code>(Pdb) input_4d_volume.shape
(26010, 48, 48, 48)
</code></pre>
<p>When I index like the following, no problem: </p>
<pre... | 0 | 2016-09-06T15:21:42Z | 39,352,981 | <p>The shape of your numpy array is <code>(26010, 48, 48, 48)</code>, so when you ask for <code>input_4d_volume[0,0,0,n:n+48].shape[0]</code> where <code>n</code> is some positive integer, the answer will be <code>max(48-n,0)</code>. The behaviour you are seeing is correct, because python indexing starts at 0, and acce... | 0 | 2016-09-06T15:42:16Z | [
"python",
"numpy"
] |
Access AWS API Gateway with IAM roles from Python | 39,352,648 | <p>I have an AWS API Gateway that I would like to secure using <a href="http://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html" rel="nofollow" title="IAM Roles">IAM Roles</a> .</p>
<p>I am looking for a package to help me accessing it using Python. I am trying to avoid implementing the entire <a ... | 0 | 2016-09-06T15:22:26Z | 39,357,370 | <p>You can use <a href="https://github.com/DavidMuller/aws-requests-auth" rel="nofollow" title="aws-requests-auth">aws-requests-auth</a> to generate the signature for your request to API Gateway with <strong>execute-api</strong> as the service name. </p>
<pre><code>import requests
from aws_requests_auth.aws_auth impor... | 2 | 2016-09-06T20:31:01Z | [
"python",
"amazon-iam",
"aws-api-gateway"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.