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 |
|---|---|---|---|---|---|---|---|---|---|
Connecting to remote linux machine via python subprocess using PuTTY or plink throws error | 37,768,508 | <p>I am trying to execute few scripts in remote linux machine from windows host machine. I am hoping to achieve this using python subprocess +putty/plink.
When I try Putty or plink commands from windows cmd, it works fine. But if I try the same command using python subprocess, I get a lot of errors.</p>
<pre><code>C:\... | 0 | 2016-06-11T21:04:37Z | 37,768,585 | <p>I highly advise against using PuTT or in general every external program to connect to shh and then interface with pipes.</p>
<p>Using the python library <a href="https://github.com/paramiko/paramiko" rel="nofollow">paramiko</a> this can be done much better.</p>
<p>For example:</p>
<pre><code># ... connect like on... | 2 | 2016-06-11T21:15:17Z | [
"python",
"linux",
"windows",
"ssh",
"putty"
] |
How can I create an auto-delete function for CouchDB in Python | 37,768,520 | <p>I'm new to Python and CouchDB and I'm trying to write an auto-trading script. As such, I only care about the most recent 400 documents in a given database/table (trading data). To fill in a few blanks:</p>
<ol>
<li><p>I have one Python program that is reading FOREX trading data and writing summary statistics to a ... | 1 | 2016-06-11T21:06:57Z | 37,912,468 | <p>As the number of docs ramaining is so small compared to the rest that you want to purge, i would try to do a selective replication to a new database with a post to _replicate and adding the 400 relevant ids in the doc_ids array. (<a href="http://docs.couchdb.org/en/1.6.1/api/server/common.html#post--_replicate" rel=... | 0 | 2016-06-19T22:28:57Z | [
"python",
"couchdb"
] |
py.test traceback path display | 37,768,689 | <p>Currently when py.test prints tracebacks, it either prints a full path such as:</p>
<pre><code>/usr/local/lib/python2.7/dist-packages/xarray/core/dataarray.py:744:
</code></pre>
<p>...or it prints a path from the directory that it's run from, such as:</p>
<pre><code>delphi/delphi/model/risk_manager.py:176:
</c... | 0 | 2016-06-11T21:31:56Z | 37,838,466 | <p>Humm I don't think there is a way to tell pytest to print as you like.
But there is a plugin for pytest-pycharm that should help you : pytest-pycharm</p>
<pre><code>$ pip install pytest-pycharm
</code></pre>
<p>I never used this plugin because I work with vim =) but let me if this works.</p>
| 0 | 2016-06-15T14:34:48Z | [
"python",
"py.test"
] |
Export_to_png only saves background | 37,768,691 | <p>I recently learnt about the Python framework kivy and started to follow <a href="https://kivy.org/docs/tutorials/firstwidget.html" rel="nofollow">the simple paint app tutorial</a>. Now I want to save what was drawn as a .png file but instead of the colored dots it only exports the black background.</p>
<p>This is m... | 0 | 2016-06-11T21:32:26Z | 37,771,014 | <p>You are missing one thing - <code>Widget</code> won't set its size and position automatically to whole <code>Window</code> size, but only to default ones i.e. <code>pos = [0, 0]</code> <code>size = [100, 100]</code> because <code>Window != Layout</code> and even adding it to something that doesn't inherit from a <co... | 1 | 2016-06-12T05:26:57Z | [
"python",
"kivy"
] |
Trying to append values to a numpy array of vector features | 37,768,719 | <p>I have a set of feature vectors for sentences I have obtained using:</p>
<pre><code>with open(sys.argv[1]) as trainingSentences:
sentence2region2value = json.loads(trainingSentences.read())
train_wordlist = []
for sentence,locations in sentence2region2value.iteritems():
train_wordlist.append(" ".join(se... | -1 | 2016-06-11T21:37:23Z | 37,769,486 | <p>Your problem expression isn't very readable, and I have to guess at what some variables look like, but I'll comment on it:</p>
<pre><code>for prediction in sentence2region2value["sentence"]["parsedsentence"].iteritems():
</code></pre>
<p>So <code>prediction</code> will be a pair of values, <code>(key, value)</code... | 0 | 2016-06-11T23:49:16Z | [
"python",
"numpy",
"dictionary",
"logistic-regression"
] |
Pandas - Category variable and group by - is this a bug? | 37,768,741 | <p>I came across a strange result while playing around with Pandas and I am not sure why this would work like this. Wondering if it is a bug.</p>
<pre><code>cf = pd.DataFrame({'sc': ['b' , 'b', 'c' , 'd'], 'nn': [1, 2, 3, 4], 'mvl':[10, 20, 30, 40]})
df = cf.groupby('sc').mean()
df.loc['b', 'mvl']
</code></pre>
<p>Th... | 5 | 2016-06-11T21:40:25Z | 37,768,980 | <p>This may be a pandas bug. The difference is due to the fact that when you group on a categorical variable, you get a categorical index. You can see it more simply without any groupby:</p>
<pre><code>nocat = pandas.Series(['a', 'b', 'c'])
cat = nocat.astype('category', categories=['a', 'b', 'c'], ordered=True)
xno... | 3 | 2016-06-11T22:20:32Z | [
"python",
"pandas"
] |
Why isn't kv binding of the screen change working? | 37,768,760 | <p>I've defined two buttons: one in kv and one in Python. They are located in different screens and are used to navigate between them. What I found strange is that the button that was defined in Python successfully switched the screen, while the one defined in kv did not. Perhaps I'm not accessing the <code>App</code> ... | 0 | 2016-06-11T21:42:55Z | 37,769,956 | <p>That's a subtle difference between kv and python: In kv you actually have to write the <a href="https://kivy.org/docs/api-kivy.lang.html#value-expressions-on-property-expressions-ids-and-reserved-keywords" rel="nofollow">callback as a function call (a python expression)</a>, in this case:</p>
<pre><code>on_release:... | 0 | 2016-06-12T01:34:07Z | [
"python",
"python-3.x",
"kivy"
] |
BeautifulSoup findAll HTML class with multiple variable class inputs | 37,768,815 | <p>I have the following code which scrapes a website for divs with the class "odd" or "even". I'd like to make "odd" and "even" an argument my function takes in, which would allow me to add other divs as well. Here is my code:</p>
<pre><code>#
# Imports
#
import urllib2
from bs4 import BeautifulSoup
import re
import ... | 1 | 2016-06-11T21:51:52Z | 37,769,356 | <p>Don't put <em>args</em> in a list, <em>args</em> is already a <em>tuple</em> so just pass that:</p>
<pre><code>body = soup.findAll("tr", args)
</code></pre>
<p>If you <code>[args]</code>, you would end up with something like <code>[("odd","even")]</code>.</p>
<p>Also <code>str([i for i in body])</code> makes no r... | 0 | 2016-06-11T23:24:16Z | [
"python",
"beautifulsoup",
"args"
] |
Class that inherits `int` gets odd ghost like variable assignments | 37,768,842 | <p>For lack of a better title, this is what I got so far.</p>
<pre><code>class cordinate(int):
def __new__(self, *args, **kwargs):
self.x = args[0]
self.y = args[1]
## Try to get pixel [0,0] and see what it got:
if self.x == 0 and self.y == 0:
print('New Here')
... | 2 | 2016-06-11T21:56:26Z | 37,768,914 | <p>As you can see from <a href="https://docs.python.org/3/reference/datamodel.html#object.__new__" rel="nofollow">the data model documentation</a>, the first argument to <code>__new__</code> is the class (conventionally <code>cls</code>), not the instance (conventionally <code>self</code>). Therefore you are setting cl... | 3 | 2016-06-11T22:07:21Z | [
"python",
"class",
"python-3.x",
"inheritance"
] |
Setting values at negative indexes | 37,768,903 | <p>For this LinkedList class I'm creating. What would be the best way to go about fixing my <code>__setitem__</code> method body? </p>
<pre><code>class LinkedList:
class Node:
def __init__(self, val, prior=None, next=None):
self.val = val
self.prior = prior
self.next = ... | 0 | 2016-06-11T22:06:27Z | 37,769,259 | <p>Your <code>__delitem__</code> doesn't decrement your length. So when you use <code>self.length</code> in the <code>_normalize_idx</code> for negative values it breaks. If you test negative numbers before you do the <code>del</code> test you will probably find it works fine.</p>
<pre><code>tc.assertEqual(len(lst), l... | 0 | 2016-06-11T23:06:42Z | [
"python",
"doubly-linked-list"
] |
Scrape data form ClickTracking | 37,769,099 | <p>I would like to scrap the data from a website but I encountered a small problem which I do not have the smallest idea how to solve. ( my first scraping tool , using beautifulsoup and requests )
I need the telephone number on the right "07xx xxx xxx"</p>
<p>When I firstly open the page and request it, I get this :
<... | 1 | 2016-06-11T22:40:03Z | 37,769,321 | <p>You just need to pass the ID from the url i.e <code>6rqd4</code> to <a href="http://olx.ro/ajax/misc/contact/phone" rel="nofollow">http://olx.ro/ajax/misc/contact/phone</a>:</p>
<pre><code>In [22]: import requests
In [23]: requests.get("http://olx.ro/ajax/misc/contact/phone/6rqd4").json()
Out[23]: {'value': '078... | 1 | 2016-06-11T23:17:28Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
How to make string interpreted as bytes? | 37,769,113 | <p>Python 2 <code>str</code> compatable with <code>bytes</code>, but on Python 3 <code>str</code> is <code>unicode</code>.</p>
<p>I working on porting some project to Python3, but with support Python2.7.
This prodject has tests with many string constants. Also there is few <code>'...'.join(...)</code> and <code>'...'.... | 1 | 2016-06-11T22:42:31Z | 37,769,216 | <p>In Py3</p>
<pre><code>>>> '123ü'.encode('utf-8')
b'123\xc3\xbc'
</code></pre>
<p>or</p>
<pre><code>>>> bytes('123ü', 'utf-8')
b'123\xc3\xbc'
</code></pre>
<p>But you probably want to have it the other way around, and use UTF-8 in Py2 for easier transition. Using </p>
<pre><code># -*- coding:... | 3 | 2016-06-11T22:58:58Z | [
"python",
"unit-testing",
"python-3.x"
] |
Python socket networking - ValueError: list.remove(x): x not in list | 37,769,141 | <p>I'm new in python so please bear with me, I have a script basically about socket networking, sometimes I get the following error when running the script:</p>
<pre><code>Traceback (most recent call last):
File "socks", line 293, in <module>
server.main_loop()
File "socks", line 210, in main_loop
se... | 0 | 2016-06-11T22:47:56Z | 37,769,199 | <p>Check if the item you have exists in the list before attempting to remove or just use a <code>try-except</code></p>
<pre><code>if item in lst:
lst.remove(item)
else:
pass # you may print some message or log something
# OR
try:
lst.remove(item)
except ValueError:
pass # you may print some message o... | 0 | 2016-06-11T22:57:24Z | [
"python"
] |
how to open chrome in incognito mode from Python | 37,769,148 | <p>This works, in powershell:</p>
<pre><code>Start-Process chrome.exe -ArgumentList @( '-incognito', 'www.foo.com' )
</code></pre>
<p>How can this be achieved from Python?</p>
| 4 | 2016-06-11T22:48:53Z | 37,769,161 | <p>Use the <code>os</code> module to execute the command.</p>
<pre><code>import os
os.system("C:\Program Files (x86)\Google\Chrome\Application\chrome.exe -ArgumentList @( '-incognito', 'www.foo.com'" )
</code></pre>
<p>More information on <strong><code>os.system</code></strong> can be found <a href="https://docs.pyth... | 1 | 2016-06-11T22:51:22Z | [
"python",
"python-2.7",
"google-chrome",
"python-webbrowser"
] |
how to open chrome in incognito mode from Python | 37,769,148 | <p>This works, in powershell:</p>
<pre><code>Start-Process chrome.exe -ArgumentList @( '-incognito', 'www.foo.com' )
</code></pre>
<p>How can this be achieved from Python?</p>
| 4 | 2016-06-11T22:48:53Z | 37,769,305 | <pre><code>import subprocess
subprocess.Popen(["C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", "-incognito", "www.google.com"])
</code></pre>
| 1 | 2016-06-11T23:16:01Z | [
"python",
"python-2.7",
"google-chrome",
"python-webbrowser"
] |
how to open chrome in incognito mode from Python | 37,769,148 | <p>This works, in powershell:</p>
<pre><code>Start-Process chrome.exe -ArgumentList @( '-incognito', 'www.foo.com' )
</code></pre>
<p>How can this be achieved from Python?</p>
| 4 | 2016-06-11T22:48:53Z | 37,769,315 | <p>On my computer intboolstring's approach does not work and an alternative and more feature-full approach would be to use call() from the subprocess module though it is still possible with system() if the command is changed.</p>
<pre><code>from subprocess import call
call("\"C:\Path\To\chrome.exe\" -incognito www.foo... | 2 | 2016-06-11T23:16:59Z | [
"python",
"python-2.7",
"google-chrome",
"python-webbrowser"
] |
learn python the hard way ex 24 function not working, no error message | 37,769,312 | <p>The function part of this program (everything after <code>def</code>) is not working. I have no error messages, and I believe I've typed everything the way Zed did. What's wrong?</p>
<pre><code>print "Let's practice everything."
print 'You\'d need to know \'bout escapes with \\ that do \n newlines and \t tell'
# n... | -3 | 2016-06-11T23:16:43Z | 37,769,324 | <p>Your code never <em>calls</em> the function. And that's because you put the code that should call it <em>too far indented</em>.</p>
<p>Your function should only be defined as this:</p>
<pre><code>def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
... | 2 | 2016-06-11T23:18:02Z | [
"python",
"python-2.7"
] |
HDFStore append to dataset - works for smaller subset, breaks for larger subset | 37,769,337 | <p>I am loading a high dimensional dataset (90*80000) into a chunked pandas dataframe. Using HDF5store I want to write this dataset to .hdf5.
I am partitioning the dataset into a matrix <strong>90*6</strong> and anpther <strong>90*remaining columns</strong>.</p>
<p>I am using the approaches outlined in the cookbook an... | 0 | 2016-06-11T23:20:20Z | 37,808,101 | <p>This is a workaround that works nicely now. I dropped using HDF5Store, though.
Basically I am creating a dataset using h5py and overallocate it, then trim empty rows afterwards:</p>
<pre><code>reader = pd.read_csv(datafile, delim_whitespace=True, chunksize=args.chunksize, names=header, skiprows=1)
max_rows_est = 8... | 0 | 2016-06-14T09:29:41Z | [
"python",
"pandas",
"hdf5"
] |
Trying to return results from twitter in my django app but I get nothing | 37,769,388 | <p>I am Trying to return results from twitter in my django app but I get nothing. I'm following tutorial example. Today is the first day I've tried to use twitter and django.
this is my code in my view</p>
<pre><code>import twitter
CONSUMER_KEY = 'CONSUMER_KEY'
CONSUMER_SECRET = 'CONSUMER_SECRET'
OAUTH_TO... | 0 | 2016-06-11T23:30:33Z | 37,769,920 | <p>If your twitter API is not already installed, use:-</p>
<pre><code>python -m pip install python-twitter
</code></pre>
<p>The Following code will show the US trends:-</p>
<pre><code>import twitter
api = twitter.Api(consumer_key="your consumer_key",
consumer_secret="your consumer secret",
... | 0 | 2016-06-12T01:26:21Z | [
"python",
"django",
"twitter"
] |
How do I specify particular points for discretization in Pyomo? | 37,769,392 | <p>I have a continuous-time Pyomo model of the form:</p>
<pre><code>from pyomo.environ import *
from pyomo.dae import *
m = ConcreteModel()
m.t = ContinuousSet(bounds=(0,150))
m.T = Param(default=150)
m.S = Var(m.t, bounds=(0,None))
m.Sdot = DerivativeVar(m.S)
discretizer = TransformationFactory('dae.... | 0 | 2016-06-11T23:31:08Z | 39,111,884 | <p>You can force the discretizer to include specific points by adding them to the <code>ContinuousSet</code> <em>before</em> discretizing the model (see the online <a href="https://software.sandia.gov/downloads/pub/pyomo/PyomoOnlineDocs.html#_dae_modeling_components" rel="nofollow">documentation</a>). The easiest way ... | 1 | 2016-08-23T22:50:00Z | [
"python",
"optimization",
"pyomo"
] |
Understanding Python map function + range | 37,769,435 | <p>I'm trying to understand the difference between these lines of code:</p>
<pre><code>list(''.join(map(lambda x: str(x * 3), range(1, 4))))
</code></pre>
<p>Out: <code>['3', '6', '9']</code> as expected.</p>
<p>However: </p>
<pre><code>list(''.join(map(lambda x: str(x * 5), range(1, 4))))
</code></pre>
<p>outputs... | 1 | 2016-06-11T23:38:09Z | 37,769,452 | <p>You first <em>joined</em> all strings together into one big string, and then converted that string to a list, which always results in all the individual characters being pulled out as elements:</p>
<pre><code>>>> list(map(lambda x: str(x * 5), range(1, 4)))
['5', '10', '15']
>>> ''.join(map(lambda... | 9 | 2016-06-11T23:42:42Z | [
"python",
"python-3.x",
"map-function"
] |
Understanding Python map function + range | 37,769,435 | <p>I'm trying to understand the difference between these lines of code:</p>
<pre><code>list(''.join(map(lambda x: str(x * 3), range(1, 4))))
</code></pre>
<p>Out: <code>['3', '6', '9']</code> as expected.</p>
<p>However: </p>
<pre><code>list(''.join(map(lambda x: str(x * 5), range(1, 4))))
</code></pre>
<p>outputs... | 1 | 2016-06-11T23:38:09Z | 37,769,694 | <p>All numbers in the first snippet are single digit numbers, so joining them and splitting them won't make a difference. See <a href="http://stackoverflow.com/a/37769452/2607571">Martijn Pieters answer</a>. In the second it will make a difference because some are two digit numbers.</p>
<p>Example:</p>
<pre><code>[3,... | 2 | 2016-06-12T00:31:57Z | [
"python",
"python-3.x",
"map-function"
] |
Push button GPIO.FALLING event getting triggered twice | 37,769,460 | <p>This is my first attempt at coding a Raspberry Pi and a hardware push button on a breadboard. The program is simple, when a button press is detected, turn on an LED on the breadboard for 1 second. My code seems to work, but strangely every so often one button push triggers the callback function twice. I'm a total... | 2 | 2016-06-11T23:43:47Z | 37,771,734 | <p>I found a solution. Using the code <a href="http://raspberrypi.stackexchange.com/questions/28955/unwanted-multiple-presses-when-using-gpio-button-press-detection">here</a>, solved my problem. </p>
<p>If you're like me, and getting random duplicate button press events when using GPIO.add_event_detect, try the linke... | 0 | 2016-06-12T07:21:27Z | [
"python",
"raspberry-pi",
"raspberry-pi2",
"gpio"
] |
TensorFlow/Sklearn Deep Neural Network classifier type error | 37,769,860 | <p>I'm trying to build a Deep Neural Network classifier modeled after the example in the TensorFlow directory. The code of the example is shown here:</p>
<pre><code>def main(unused_argv):
# Load dataset.
iris = learn.datasets.load_dataset('iris')
x_train, x_test, y_train, y_test = cross_validation.train_test... | 1 | 2016-06-12T01:09:29Z | 37,779,137 | <p>After doing a little digging, I found a solution. If you look in the following directory in the TensorFlow package:</p>
<pre><code>tensorflow.contrib.learn.python.learn.datasets
</code></pre>
<p>You can find a file called <em>base.py</em> which has the csv file loading functions. Basically, I just modified the fun... | 0 | 2016-06-12T21:13:36Z | [
"python",
"scikit-learn",
"tensorflow",
"data-type-conversion",
"deep-learning"
] |
sort integers positive then negative | 37,769,939 | <p>I have a dictionary of <code>'name': Obj</code> entries, where each <code>Obj</code> has a <code>num</code> parameter that takes a signed integer. I want to convert this into an <code>OrderedDict</code> where the entries are sorted by positive <code>Obj.num</code> values, then negative numbers.</p>
<p>Sorting over... | 1 | 2016-06-12T01:31:04Z | 37,769,955 | <p>reverse the sort, use <code>x >= 0</code> to get the positive numbers first, <code>-</code> the numbers to put the negative numbers at the at the end and keep the order of positive from lowest to highest.</p>
<pre><code>l = [-5, -2, -1, 1, 2, 10, 100]
print(sorted(l, key=lambda x: (x >= 0, -x), reverse=True... | 3 | 2016-06-12T01:33:53Z | [
"python",
"sorting",
"numpy",
"dictionary"
] |
Python: how to separate certain number-text combination from string? | 37,770,043 | <p>for example: a=['Now is 20m before 10h','OK 15s after 6 punctual']. I want time_fragment=['20m','15s']. </p>
<p>I've seen answers that used split function and import re, but didn't see anything to address a number-text combination case. This has a bit text mining involved so the data is messy. </p>
| 0 | 2016-06-12T01:57:23Z | 37,770,141 | <p>If you only want the times before the word "before", you can use a <a href="http://www.regular-expressions.info/lookaround.html" rel="nofollow">lookahead</a> in you regex. </p>
<pre><code>import re
s = 'Now is 20m before 10h'
rgx = re.compile(r'[0-9]+[hms](?= *before)')
print rgx.findall(s) # ['20m']
</code></pre>
| 1 | 2016-06-12T02:17:26Z | [
"python"
] |
Python - Compare string to random item from list | 37,770,052 | <p>Looking through a lot of existing questions and not seeing quite the same scenario. I'm working through the basics of Python and trying to create the ubiquitous Rock, Paper, Scissors game. However, I've got a variable equal to the user's guess which I can't get to compare successfully against a randomly selected ite... | 1 | 2016-06-12T01:58:50Z | 37,770,117 | <p>You need to use <code>random.choice(rps)</code> which returns an element of the original list rather than <code>random.sample(rps,1)</code> which returns a list of size 1 from the original list.</p>
| 3 | 2016-06-12T02:12:11Z | [
"python",
"variables"
] |
How to get the raw page source? | 37,770,089 | <p>Consider a URL like <a href="https://groups.yahoo.com/api/v1/groups/concatenative/messages/300" rel="nofollow">https://groups.yahoo.com/api/v1/groups/concatenative/messages/300</a> . This is an <code>application/json</code> response:</p>
<p><a href="http://i.stack.imgur.com/dtlpP.png" rel="nofollow"><img src="http:... | 0 | 2016-06-12T02:06:53Z | 37,838,680 | <p>You can send AJAX to get the json directly with JSExecutor. See example below:</p>
<pre><code>driver.get("https://groups.yahoo.com/api/v1/groups/concatenative/messages/300")
driver.set_script_timeout(10)
response = driver.execute_async_script(
"console.log('Start AJAX');" +
"var callback = arguments[argumen... | 1 | 2016-06-15T14:44:40Z | [
"python",
"json",
"selenium"
] |
Operation timed out error in Cassandra cluster | 37,770,165 | <p>My cluster size is 6 machines and I often times receive this error message and I don't really know how to solve this:</p>
<pre><code>code=1100 [Coordinator node timed out waiting for replica nodes' responses] message="Operation timed out - received only 0 responses." info={'received_responses': 0, 'required_respons... | 0 | 2016-06-12T02:25:38Z | 37,773,728 | <p>I think you shouldn't use a batch statement in this case because you are tying to use the batch to perform a big number of operations for different partition keys, it leads to timeout exceptions. You should use batches to keep tables in sync but not for performance optimization.
You can find more about misusing batc... | 2 | 2016-06-12T11:33:11Z | [
"python",
"cassandra",
"datastax",
"datastax-enterprise"
] |
List comprehension - Iterating over nested lists | 37,770,296 | <p>I am trying to write a function that searches nested lists in their entirety to return all lists that contain a certain word, but this only returns <code>None</code></p>
<pre><code>word = "what song?"
def searchSong(mp3_list, word):
search = input((word))
match = [i for i in mp3_list if search in i[2]]
for... | 1 | 2016-06-12T02:55:40Z | 37,770,329 | <p>'heaven' is present in the second element in <code>["Eric Clapton","Tears in heaven","Rush"]</code>, but you're checking the <em>third</em> element (<code>i[2]</code>). Python arrays are indexed starting from 0, not 1. (But you appear to know this, as your second example looks for "ar" in <code>i[2]</code>, which ... | 1 | 2016-06-12T03:03:35Z | [
"python",
"list",
"list-comprehension"
] |
List comprehension - Iterating over nested lists | 37,770,296 | <p>I am trying to write a function that searches nested lists in their entirety to return all lists that contain a certain word, but this only returns <code>None</code></p>
<pre><code>word = "what song?"
def searchSong(mp3_list, word):
search = input((word))
match = [i for i in mp3_list if search in i[2]]
for... | 1 | 2016-06-12T02:55:40Z | 37,770,338 | <pre><code>mp3_list = [["Eric Clapton","Tears in heaven","Rush"],["Neil Young", "Heart of gold", "Harvest"]]
match = [i for i in mp3_list for j in i if 'heaven' in j]
match
Out[7]: [['Eric Clapton', 'Tears in heaven', 'Rush']]
li = [["0", "20", "ar"], ["20", "40", "asdasd"], ["50", "199", "bar"]]
match = [i for i in ... | 1 | 2016-06-12T03:05:13Z | [
"python",
"list",
"list-comprehension"
] |
How can I tell between these two buttons in Selenium? | 37,770,309 | <p>I'm running Selenium on Python and I can't figure out how to tell these buttons apart so that I can click one with Selenium. I need to click option 1. I can't figure out how to get any important data tags off of them, but I'm very very new to this!</p>
<pre><code><tbody>
<tr>
<td>TOP1 ... | 2 | 2016-06-12T02:58:49Z | 37,771,018 | <p>Option 1, 3 and 4 won't work, since they are not a correct xpath (you don't have <code>title</code> attribute, <code>button</code> is not a class, and <code>option_1</code> is not part of the button text); option 2 would return first element, so it should work for first button on the page, but usually it's better to... | 1 | 2016-06-12T05:27:43Z | [
"python",
"html",
"selenium"
] |
How can I tell between these two buttons in Selenium? | 37,770,309 | <p>I'm running Selenium on Python and I can't figure out how to tell these buttons apart so that I can click one with Selenium. I need to click option 1. I can't figure out how to get any important data tags off of them, but I'm very very new to this!</p>
<pre><code><tbody>
<tr>
<td>TOP1 ... | 2 | 2016-06-12T02:58:49Z | 37,771,156 | <p>The ones that you tried does not matched to whats in the markup, first you need to add classes for your buttons, if you gonna yung @class.</p>
<p>But still what you are doing is wrong, you need to use List to get the rows of the table, if this table is dynamic. First add classes for your table rows and buttons:</p... | 1 | 2016-06-12T05:55:18Z | [
"python",
"html",
"selenium"
] |
make multiple lists based on pattern python | 37,770,311 | <p>I have a .txt file with info on just about each line. I'd like to create a list of everything, and have each list item be a list with each line of info separated by a br. visually, im given this:</p>
<pre><code>234
CS434
3.00
M
09/32/394/23 - 232/32/34
435
eS234
4.01
G
09/44/346/01 - 123/23/54
979
js443
3.03
E
09... | 0 | 2016-06-12T02:59:50Z | 37,770,372 | <pre><code>>>> [x.rstrip('\n').split('\n') for x in open('file').read().split('\n\n')]
[['234', 'CS434', '3.00', 'M', '09/32/394/23 - 232/32/34'],
['435', 'eS234', '4.01', 'G', '09/44/346/01 - 123/23/54'],
['979', 'js443', '3.03', 'E', '09/23/111/24 - 344/23/22']]
</code></pre>
<p>Or, making sure that the f... | 3 | 2016-06-12T03:10:22Z | [
"python",
"list",
"python-2.7"
] |
Improve speed of spark app | 37,770,354 | <p>This is part of my python-spark code which parts of it run too slow for my needs.
Especially this part of the code, which I would really like to improve it's speed but don't know how to. It currently takes around 1 minute for 60 Million data rows and I would like to improve it to under 10 seconds.</p>
<pre><code>sq... | 1 | 2016-06-12T03:06:30Z | 37,770,646 | <p>First you should figure out what's actually taking the most amount of time.</p>
<p>For example determine how long just reading the data takes </p>
<pre><code>axes = sqlContext
.read
.format("org.apache.spark.sql.cassandra")
.options(table="axes", keyspace=source)
.load()
.count()
</code></pre>
<p>Increa... | 4 | 2016-06-12T04:07:42Z | [
"python",
"apache-spark",
"cassandra",
"pyspark",
"datastax-enterprise"
] |
Function is printing multiple times | 37,770,379 | <p>I've written a function that takes as input a positive integer n and recursively returns a list of factorial values 1!, 2!, . . . , n!.</p>
<p>However, I can't get it to print the list just a single time. I've tried placing the print statement in various loops/locations and it always prints at least 3 times. I've a... | 0 | 2016-06-12T03:12:05Z | 37,770,402 | <p>Change the print statement to <code>return my_list</code>:</p>
<pre><code>def calc_Factorial(my_list, n, x, e):
if not my_list:
my_list.append(n-(n-1))
calc_Factorial(my_list, n, x, e)
else:
if len(my_list) < n:
my_list.append(my_list[e]*x)
calc_Factorial... | 1 | 2016-06-12T03:18:00Z | [
"python",
"function",
"recursion"
] |
Function is printing multiple times | 37,770,379 | <p>I've written a function that takes as input a positive integer n and recursively returns a list of factorial values 1!, 2!, . . . , n!.</p>
<p>However, I can't get it to print the list just a single time. I've tried placing the print statement in various loops/locations and it always prints at least 3 times. I've a... | 0 | 2016-06-12T03:12:05Z | 37,770,410 | <pre><code>def calc_Factorial(my_list, n, x, e):
if not my_list:
my_list.append(n-(n-1))
return calc_Factorial(my_list, n, x, e)
else:
if len(my_list) < n:
my_list.append(my_list[e]*x)
return calc_Factorial(my_list, n, x+1, e+1)
if len(my_list) == n:
... | 1 | 2016-06-12T03:18:52Z | [
"python",
"function",
"recursion"
] |
Function is printing multiple times | 37,770,379 | <p>I've written a function that takes as input a positive integer n and recursively returns a list of factorial values 1!, 2!, . . . , n!.</p>
<p>However, I can't get it to print the list just a single time. I've tried placing the print statement in various loops/locations and it always prints at least 3 times. I've a... | 0 | 2016-06-12T03:12:05Z | 37,770,433 | <p>The value is being printed multiple times because you are using <code>print</code> inside the recursive function. You should return instead of printing inside the recursive function.</p>
<pre><code>def calc_Factorial(my_list, n, x, e):
if not my_list:
my_list.append(n-(n-1))
return calc_Factorial(my_list... | 1 | 2016-06-12T03:22:45Z | [
"python",
"function",
"recursion"
] |
Function is printing multiple times | 37,770,379 | <p>I've written a function that takes as input a positive integer n and recursively returns a list of factorial values 1!, 2!, . . . , n!.</p>
<p>However, I can't get it to print the list just a single time. I've tried placing the print statement in various loops/locations and it always prints at least 3 times. I've a... | 0 | 2016-06-12T03:12:05Z | 37,770,484 | <p>What you're seeing is because of this part:</p>
<pre><code>if len(my_list) < n:
my_list.append(my_list[e]*x)
calc_Factorial(my_list, n, x+1, e+1)
if len(my_list) == n:
print(my_list)
</code></pre>
<p>After the first if statement, the function will continue to execute, and now
n == len(my_list)... | 0 | 2016-06-12T03:33:16Z | [
"python",
"function",
"recursion"
] |
Removing QLineEdit proxy widget from QGraphicsScene on returnPressed | 37,770,446 | <p>What I would like to do is have a QLineEdit appear in my QGraphicsView when a QGraphicsTextItem is added to the scene. The line edit is only being used to set the text of the QGraphicsItem when double-clicked and needs to be removed when the return key is pressed.</p>
<p>I'm having trouble getting the QLineEdit to ... | 0 | 2016-06-12T03:25:20Z | 37,770,694 | <p>In Qt, a simple method of removing widgets from the screen is to hide them, that is if you are not worried by that; perhaps you just want to get rid of it, otherwise use</p>
<pre><code>myWidget.setVisible(False)
</code></pre>
<p>or</p>
<pre><code>myWidget.hide();
</code></pre>
<p>You can reuse that widget by cal... | 1 | 2016-06-12T04:18:50Z | [
"python",
"qt",
"pyqt4",
"pyside"
] |
applying function to all columns in an numpy array | 37,770,523 | <p>I am extremely new to numpy. </p>
<p>Just wondering why does this not work.</p>
<pre><code>print items['description']
</code></pre>
<p>Yields</p>
<pre><code>0 ÐÑодам Ðамаз 6520 20 Ñонн
1 ÐеÑÑ Ð² ÑÑнинге.
2 ТелеÑоÐ... | 0 | 2016-06-12T03:41:11Z | 37,770,557 | <p>Your getting that error because <code>'Series' object has no attribute 'split'</code>. Mainly, the <code>.astype(str)</code> does not return a single long string like you think it does</p>
<pre><code>items = pd.DataFrame({'description': ['bob loblaw', 'john wayne', 'lady gaga loves to sing']})
sentence = items['des... | 1 | 2016-06-12T03:49:55Z | [
"python",
"numpy"
] |
parsing python asciitree output and print 'labelled bracket notation' | 37,770,675 | <p>Google SyntaxNet gives an output
like ..</p>
<pre><code>saw VBD ROOT
+-- Alice NNP nsubj
| +-- , , punct
| +-- reading VBG rcmod
| +-- who WP nsubj
| +-- had VBD aux
| +-- been VBN aux
| +-- about IN prep
| +-- SyntaxNet NNP pobj
+-- , , punct
+-- Bob NNP dobj
+-- i... | 3 | 2016-06-12T04:15:11Z | 37,774,668 | <p>Instead of parsing the tree, you can make SyntaxNet output everything in conll format which is easier to parse. The conll format for your sentence looks like this:</p>
<pre><code>1 Alice _ NOUN NNP _ 10 nsubj _ _
2 , _ . , _ 1 punct ... | 3 | 2016-06-12T13:13:26Z | [
"python",
"syntaxnet"
] |
Scrapy not parsing response in make_requests_from_url loop | 37,770,678 | <p>I'm trying to get scrapy to grab a URL from a message queue, and then scrape that URL. I have the loop going just fine and grabbing the URL from the queue, but it never enters the <code>parse()</code> method once it has a url, it just continues to loop (and sometimes the url comes back around even though I've delete... | 0 | 2016-06-12T04:15:17Z | 37,871,315 | <p>Would I be right to assume that if this works:</p>
<pre><code>import scrapy
import random
class ExampleSpider(scrapy.Spider):
name = "example"
allowed_domains = ["example.com"]
def __init__(self):
super(ExampleSpider, self).__init__()
self.url = None
def start_requests(self):
... | 1 | 2016-06-17T00:21:34Z | [
"python",
"scrapy"
] |
Counting amount of times a mutation occurs in a .maf file | 37,770,736 | <p>I'm trying to count the number of mutations in a MAF file. I originally wrote this code in python and it worked perfectly fine, but when I translated it to Java it stopped working. In the output file the number of mutations is always one. What am I doing wrong here?</p>
<pre><code>package dev.suns.bioinformatics;
... | 1 | 2016-06-12T04:29:30Z | 37,770,816 | <p>In java you need to compare strings using equals function. This should work-</p>
<pre><code>else if(newGene.equals(geneSymbol)){
#This is here I am having trouble. I have this if-statement to check if the gene appears more than once in the .maf file, but nothing is ever entering this.
count+... | 0 | 2016-06-12T04:47:01Z | [
"java",
"python",
"bioinformatics"
] |
Why does 'itsdangerous' module return the signed text? | 37,770,769 | <p>I'm wondering if anyone tell me why the 'itsdangerous' module returns the signed text as a portion of the string. As in:</p>
<pre><code>>>> import itsdangerous
>>>
>>> secret = 'my-secret-key'
>>> token = itsdangerous.TimedSerializer(secret)
>>> token.dumps('my-user-id'... | 1 | 2016-06-12T04:35:59Z | 37,770,793 | <p>The purpose of itsdangerous is not encrypting your data, it just a simple tool to detect tampered data.</p>
<blockquote>
<p>... When you get the data back you can easily ensure that nobody
tampered with it. <a href="http://pythonhosted.org/itsdangerous/" rel="nofollow"><sup>1</sup></a></p>
</blockquote>
<p>The... | 4 | 2016-06-12T04:41:50Z | [
"python",
"encryption"
] |
Why does 'itsdangerous' module return the signed text? | 37,770,769 | <p>I'm wondering if anyone tell me why the 'itsdangerous' module returns the signed text as a portion of the string. As in:</p>
<pre><code>>>> import itsdangerous
>>>
>>> secret = 'my-secret-key'
>>> token = itsdangerous.TimedSerializer(secret)
>>> token.dumps('my-user-id'... | 1 | 2016-06-12T04:35:59Z | 37,770,797 | <p><code>itsdangerous</code> signs the text or any other data so it can be transmitted via unsafe channels and then checked on the other end or upon retrieval from a database where it was store that it wasn't changed/tampered.</p>
<p>So it creates a signature, adds it to the signed data and then checks upon retrieval ... | 1 | 2016-06-12T04:42:18Z | [
"python",
"encryption"
] |
Return data from database using Flask, Flask-sqlalchemy, and jQuery | 37,770,804 | <p>I want div.disp to get the id of the data to be added to the database, it works for the first add but for the next ones, it will be the same id as the the first add.</p>
<pre><code>@app.route('/')
@app.route('/index')
def index():
tsklst = models.User.query.order_by('id asc').all()
last = tsklst[len(tsklst)... | 0 | 2016-06-12T04:43:18Z | 37,771,114 | <p>It will be much better to return a json type object from <code>_add</code> endpoint rather than render a template</p>
<pre><code>@app.route('/_add')
def add_():
toDo = request.args.get('task')
u = models.User(task = str(toDo))
db.session.add(u)
db.session.commit()
task = {}
task['id'] = u.i... | 1 | 2016-06-12T05:47:24Z | [
"jquery",
"python",
"flask",
"flask-sqlalchemy"
] |
Return data from database using Flask, Flask-sqlalchemy, and jQuery | 37,770,804 | <p>I want div.disp to get the id of the data to be added to the database, it works for the first add but for the next ones, it will be the same id as the the first add.</p>
<pre><code>@app.route('/')
@app.route('/index')
def index():
tsklst = models.User.query.order_by('id asc').all()
last = tsklst[len(tsklst)... | 0 | 2016-06-12T04:43:18Z | 37,771,336 | <p>my friend solved the problem for me:</p>
<pre><code>content ="<div class='disp' id='"+str(u.id)+'><div class='left'>"+$('#txtTask').val()+"</div><input type='checkbox' class='chkbk'></div>"
return content
</code></pre>
| 0 | 2016-06-12T06:25:09Z | [
"jquery",
"python",
"flask",
"flask-sqlalchemy"
] |
pyqt QLabel not rendered while another thread update its text | 37,770,813 | <p>I have a GUI program built on PyQt5, which constantly receive messages. The GUI has a QLabel showing the number of messages received, and a QThread trying to receive messages and update counter in an infinite loop in the run(). Here is the code:</p>
<pre><code>class ReceiveThread(QtCore.QThread):
def __init__(s... | 0 | 2016-06-12T04:45:58Z | 37,782,626 | <p>Only the main GUI thread can update the GUI. You should not directly interact with GUI objects outside the main thread. If you want to communicate with the main thread from worker threads, you need to use <code>Signals</code> and <code>Slots</code></p>
<pre><code>class Dialog(QtGui.QDialog):
def __init__(sel... | 1 | 2016-06-13T05:52:33Z | [
"python",
"pyqt",
"pyqt5"
] |
Store modules in project folder | 37,770,833 | <p>Some times i need to use modules which are not a part of default python installation and some times even packages like Anaconda or Canopy does not include them. So every time I move my project to another machine or just reinstall python i need to download them again. So my question is. Is there a way to store neces... | 0 | 2016-06-12T04:51:02Z | 37,771,167 | <p>You can use <a href="https://docs.python.org/3/library/venv.html" rel="nofollow">virtual environment</a> or <a href="https://www.docker.com" rel="nofollow">docker</a> to install the required modules in your project dir so it is isolated from your system Python installation. In fact, you don't need Python installed o... | 0 | 2016-06-12T05:57:36Z | [
"python"
] |
How to save Matplotlib.pyplot.loglog to file? | 37,770,860 | <p>I am trying to generate the log-log plot of a vector, and save the generated plot to file. </p>
<p>This is what I have tried so far:</p>
<pre><code>import matplotlib.pyplot as plt
...
plt.loglog(deg_distribution,'b-',marker='o')
plt.savefig('LogLog.png')
</code></pre>
<p>I am using Jupyter Notebook, in which I g... | 1 | 2016-06-12T04:56:49Z | 37,792,791 | <p>Notice that pyplot has the concept of the current figure and the current axes. All plotting commands apply to the current axes. So, make sure you plot in the right axes. Here is a WME.</p>
<pre><code>import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.loglog(range(100), 'b-',marker='o')
plt.savefig('test.... | 1 | 2016-06-13T14:47:32Z | [
"python",
"matplotlib",
"save",
"loglog"
] |
Tensorflow: Creating a graph in a class and running it ouside | 37,770,911 | <p>I believe I am having a hard time understanding how graphs work in tensorflow and how to access them. My intuition is that the lines under 'with graph:' will form the graph as a single entity. Hence, I decided to create a class that would build a graph when instantiated and would possess a function that would run th... | 0 | 2016-06-12T05:04:52Z | 37,774,076 | <p>The nodes <code>prediction</code>, <code>cost</code>, and <code>optimizer</code> are local variables created in the method <code>__init__</code>, they cannot be accessed in the method <code>launchG</code>.</p>
<p>The easiest fix would be to declare them as attributes of your class <code>Graph</code>:</p>
<pre clas... | 0 | 2016-06-12T12:11:08Z | [
"python",
"class",
"session",
"graph",
"tensorflow"
] |
How can I group by date the output in Django? | 37,770,931 | <p>I need to show something like this in my template:</p>
<p><strong>11 June</strong></p>
<ul>
<li>Data 1</li>
<li>Data 2</li>
</ul>
<p><strong>10 June</strong></p>
<ul>
<li>Data 3</li>
<li>Data 4</li>
</ul>
<p>My view:</p>
<pre><code>def Inicio(request):
g = Gastos.objects.all()
return render(request, 'p... | 0 | 2016-06-12T05:08:18Z | 37,771,821 | <p><code>lista</code> is a dictionary so we are free to apply <code>items</code> function on a dictionary to get key, value pair. So the code should be like,</p>
<pre><code>{% for key, value in lista.items %}
<h3>{{key}}</h3>
{% for g in value %}
<li>{{g.producto}}</li>
{% e... | 0 | 2016-06-12T07:35:18Z | [
"python",
"django",
"django-templates",
"django-views"
] |
Sort QuerySet based on the higher of two different fields | 37,771,086 | <p>I have this model:</p>
<pre><code>class ScoringModel(model.Model):
red_score = models.SmallIntegerField()
blue_score = models.SmallIntegerField()
</code></pre>
<p>I'm trying to sort a query set based on whichever is greater between the two. Now, taking the sum of them wouldn't work because that means a sco... | 0 | 2016-06-12T05:43:07Z | 37,771,667 | <p>I can suggest you to see this answer </p>
<p><a href="http://stackoverflow.com/a/1875616/5518973">http://stackoverflow.com/a/1875616/5518973</a></p>
<p>you can use mysql function GREATEST(field1, field2) instead of Sum and then order by that extra field.</p>
| 1 | 2016-06-12T07:11:42Z | [
"python",
"django",
"python-3.x",
"django-models",
"django-queryset"
] |
tkinter maximum recursion depth exceeded while generating an event | 37,771,117 | <p>I'm trying to bind mouse motions (pressed/unpressed) with some methods.
I tried to handle mouse motions while mouse button is pressed with '' and the other with just ''.
I found that when I just have ..bind('', somemethod1), somemethod1 is called regardless of mouse button press, but when I also have ..bind('', some... | 1 | 2016-06-12T05:48:01Z | 37,771,369 | <p>It creates an infinite loop. </p>
<p>You are listening for <code><Button1-Motion></code>, and when you get it, you create more <code><Motion></code> <strong>while the Button is pressed</strong> (because it's only generated when the button-1 event is caught). So you're generating <em>another</em> <code>&... | 2 | 2016-06-12T06:29:24Z | [
"python",
"events",
"tkinter"
] |
Python, why I get different result between .py and shell when I use generator yield? | 37,771,137 | <p>I am learning coroutine, I have found a pdf named "A Curious Course On Coroutines and Concurrecy".
There is a flaky example:</p>
<pre><code>def countdown(n):
print("Counting down from", n)
while n >= 0:
newvalue = (yield n)
# If a new value got sent in, reset n with it
if newvalue is not None:
... | 1 | 2016-06-12T05:52:05Z | 37,771,202 | <p>In interactive mode, Python auto-prints the <code>repr</code> of any expression statement that evaluates to something other than <code>None</code>. This excludes expression statements inside functions and classes, but it includes expression statements in loops, such as this one:</p>
<pre><code>>>> for n in... | 2 | 2016-06-12T06:03:23Z | [
"python",
"generator"
] |
Creating a new numpy array with modified element data type | 37,771,153 | <p>I had expected the following to create a new numpy array from the shape of an existing array but with modified element data type. My original array is an image with 8bit RGB pixels. I want to create a new array using same shape but with uint16 data type. The purpose is then to convert the image into 16bit pixels and... | 1 | 2016-06-12T05:55:04Z | 37,771,366 | <p>The <code>np.</code>:</p>
<pre><code>In [2]: np.zeros((3,4),dtype=np.uint16)
Out[2]:
array([[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]], dtype=uint16)
</code></pre>
<p><code>'uint16'</code> (the string) would have worked as well.</p>
<p><code>int</code> and <code>float</code> are Python names; almost... | 1 | 2016-06-12T06:29:04Z | [
"python",
"arrays",
"numpy"
] |
NumPy IFFT introducing black bars in OaA Convolution Algorithm | 37,771,182 | <p>I'm having trouble diagnosing and fixing this error. I'm trying to write the OaA algorithm, described <a href="https://etd.ohiolink.edu/!etd.send_file?accession=wright1432747175&disposition=inline#page=33" rel="nofollow">in this paper</a>.</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Quick ... | 3 | 2016-06-12T05:59:05Z | 38,384,551 | <p>Your problem is, that your kernel seems to be in the middle:</p>
<p><a href="http://i.stack.imgur.com/42trT.png" rel="nofollow"><img src="http://i.stack.imgur.com/42trT.png" alt="wrong kernel"></a></p>
<p>But it is not - there is also a shift (11, 11) involved, which becomes obvious when you look at the results of... | 3 | 2016-07-14T21:28:01Z | [
"python",
"algorithm",
"numpy",
"convolution"
] |
Sympy TypeError: cannot determine truth value of Relational when dumping to YAML | 37,771,211 | <p>I'm getting this error when trying to dump a sympy expression to YAML:</p>
<pre><code>TypeError: cannot determine truth value of Relational
</code></pre>
<p>What I am trying to dump is a set with 2 <code>sympy.Symbol</code> objects. I'm not sure why sympy tries to evaluate it as a <code>StrictLessThan</code> objec... | 3 | 2016-06-12T06:04:51Z | 37,771,717 | <p>The representer tries to sort the set, which is dumped in a similar way as a dict, by sorting its items by key-value pairs and then dumping those. I don't know the details of <code>sympy</code>, but for the sorting a representation of the key and value need be knows (for a set only the key is used) and that is often... | 2 | 2016-06-12T07:18:59Z | [
"python",
"yaml",
"sympy",
"pyyaml"
] |
Install pyenchant on a Windows 64-bit machine | 37,771,227 | <p>I want to install PyEnchant for spell checking and it requires <a href="http://www.abisource.com/projects/enchant/" rel="nofollow">enchant</a> installed on my machine. But all the .exe files I could find were for win32 systems. Is there any other way to install it on Windows 64-bit machine?</p>
| 0 | 2016-06-12T06:07:23Z | 37,773,225 | <p>Currently there is no 64-bit version of Enchant.</p>
<p>PyEnchant can do your spelling check under Python 32 bit - if you have to use 64 bit Python then you will need to build Enchant and PyEnchant for 64 bit and resolve any issues yourself. This isn't trivial unfortunately.</p>
<p>Note that 32 bit Python works fi... | 2 | 2016-06-12T10:32:54Z | [
"python",
"windows",
"pyenchant"
] |
Avoid downloadable files in Python Urlopen | 37,771,237 | <p>I am building a web crawler using python. But the <code>urlopen(url)</code> download the files in the page. I just want to read the html, and skip if the url points to a downloadable file.</p>
<p>I have tried using timeouts</p>
<pre><code>urlopen(url, timeout = 5).read()
</code></pre>
<p>so that large files can b... | 2 | 2016-06-12T06:08:43Z | 37,771,357 | <p>You can use the <code>Content-Type</code> HTTP header to find out if it's HTML or something else:</p>
<pre><code>x= urlopen(url)
if 'text/html' in x.headers.get('Content-Type'):
x= x.read()
</code></pre>
| 3 | 2016-06-12T06:27:45Z | [
"python",
"urllib"
] |
Avoid downloadable files in Python Urlopen | 37,771,237 | <p>I am building a web crawler using python. But the <code>urlopen(url)</code> download the files in the page. I just want to read the html, and skip if the url points to a downloadable file.</p>
<p>I have tried using timeouts</p>
<pre><code>urlopen(url, timeout = 5).read()
</code></pre>
<p>so that large files can b... | 2 | 2016-06-12T06:08:43Z | 37,771,480 | <p>To narrow the amount of file content to check, check <code>retcode</code> before checking file content.</p>
<pre><code>doc = urllib.urlopen(url, timeout=5)
if doc and doc.getCode() == 200 and doc.headers.get('Content-Type').startswith("text/html"):
x = doc.read()
</code></pre>
| 1 | 2016-06-12T06:45:26Z | [
"python",
"urllib"
] |
Avoid downloadable files in Python Urlopen | 37,771,237 | <p>I am building a web crawler using python. But the <code>urlopen(url)</code> download the files in the page. I just want to read the html, and skip if the url points to a downloadable file.</p>
<p>I have tried using timeouts</p>
<pre><code>urlopen(url, timeout = 5).read()
</code></pre>
<p>so that large files can b... | 2 | 2016-06-12T06:08:43Z | 37,771,598 | <p>you can achieve this by <a href="http://docs.python-requests.org/en/master/" rel="nofollow">python requests</a> </p>
<pre><code>In [8]: import requests
In [9]: h = requests.head("http://stackoverflow.com/questions/37771237/avoid-downloadable-files-in-python-urlopen")
In [10]: if "text/html" in h.headers["content... | 2 | 2016-06-12T07:00:52Z | [
"python",
"urllib"
] |
Will using the Django ORM in a python library cause trouble? | 37,771,256 | <p>I've enjoyed using Django quite a bit over the years. Right now I'm working for a company that is building some shared internal libraries for accessing information from our databases. Right now things are terribly sloppy - lots of inline SQL code. Some colleagues were working on doing some accessing code, and it occ... | 0 | 2016-06-12T06:11:47Z | 37,914,431 | <p>OK, here's my own attempt to answer the question after some research.</p>
<p>I can create a baseclass for my models anywhere in the library as follows:</p>
<pre><code>from django.db import models
from django.apps import apps
import django.conf
django.conf_settings.configure(
DATABASES = ...
)
apps.populate((... | 0 | 2016-06-20T03:56:09Z | [
"python",
"django",
"database",
"orm"
] |
Detect text area in an image using python and opencv | 37,771,263 | <p>I want to detect the text area of images using python 2.7 and opencv 2.4.9
and draw a rectangle area around it. Like shown in the example image below.</p>
<p>I am new to image processing so any idea how to do this will be appreciated.</p>
<p><a href="http://i.stack.imgur.com/a4VWN.jpg" rel="nofollow"><img src="htt... | 3 | 2016-06-12T06:12:46Z | 38,554,331 | <p>There are multiple ways to go about detecting text in an image.</p>
<p>I recommend looking at <a href="http://stackoverflow.com/questions/23506105/extracting-text-opencv">this question here</a>, for it may answer your case as well. Although it is not in python, the code can be easily translated from c++ to python (... | 4 | 2016-07-24T16:38:21Z | [
"python",
"opencv",
"image-processing",
"ocr"
] |
How to use Marionette web driver in robotframework after upgrade browser to Firefox 47 | 37,771,277 | <p>I was using robotframework Selenium2Library to run test in Firefox.
As I upgrade Firefox to version 47, I found Firefox will crash at the beginning when Firefox starts. The issue is in github issue list as follow link:
<a href="https://github.com/SeleniumHQ/selenium/issues/2110" rel="nofollow">https://github.com/Se... | 4 | 2016-06-12T06:15:47Z | 37,842,250 | <p>Selenium2Library does not support passing in desired capabilities for local webdrivers. But you can change the default capabilities for Firefox and it will apply to all future webdriver instances for a given browser type until the interpreter (Python) exits. I was able to run simple tests with Firefox 47, Selenium 2... | 2 | 2016-06-15T17:42:36Z | [
"python",
"selenium",
"firefox",
"webdriver",
"robotframework"
] |
Read/write kivy widget attributes with python | 37,771,303 | <p>I have a basic, working knowledge of Python I'm trying to teach myself kivy. I'd like to be able to have Python read and write data to kivy widgets. </p>
<p>Imagine there's an address book app that inserts the date and time into a TextInput. When the app starts, just have Python get the date and time and insert ... | 1 | 2016-06-12T06:19:41Z | 37,772,470 | <p>If you want some widget to have an extra functionality (example: loading current date at app start), then create a custom version of that widget, which meets requirements. And reading values of widgets within a rule is very simple. Example:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app ... | 1 | 2016-06-12T09:03:15Z | [
"python",
"widget",
"kivy",
"textinput"
] |
Read/write kivy widget attributes with python | 37,771,303 | <p>I have a basic, working knowledge of Python I'm trying to teach myself kivy. I'd like to be able to have Python read and write data to kivy widgets. </p>
<p>Imagine there's an address book app that inserts the date and time into a TextInput. When the app starts, just have Python get the date and time and insert ... | 1 | 2016-06-12T06:19:41Z | 37,823,751 | <p>So based on what you said above (and lots of reading about --init--, self and **kwargs, although I still don't understand what super() does) this is my code. I like your name DateInput so I used it.</p>
<p>Python file: address.py</p>
<pre><code>from kivy.app import App
from kivy.uix.gridlayout import GridLayout
... | 0 | 2016-06-14T23:26:05Z | [
"python",
"widget",
"kivy",
"textinput"
] |
Read/write kivy widget attributes with python | 37,771,303 | <p>I have a basic, working knowledge of Python I'm trying to teach myself kivy. I'd like to be able to have Python read and write data to kivy widgets. </p>
<p>Imagine there's an address book app that inserts the date and time into a TextInput. When the app starts, just have Python get the date and time and insert ... | 1 | 2016-06-12T06:19:41Z | 37,827,379 | <p>A guy named spinningD20 on the FreeNode IRC channel for kivy showed me this.</p>
<p>There's an even easier way than adding a custom widget. As long as you just want to insert a value into the TextInput when the app starts up...</p>
<p>address.py</p>
<pre><code>from kivy.app import App
from kivy.uix.gridlayout i... | -1 | 2016-06-15T06:10:53Z | [
"python",
"widget",
"kivy",
"textinput"
] |
Read/write kivy widget attributes with python | 37,771,303 | <p>I have a basic, working knowledge of Python I'm trying to teach myself kivy. I'd like to be able to have Python read and write data to kivy widgets. </p>
<p>Imagine there's an address book app that inserts the date and time into a TextInput. When the app starts, just have Python get the date and time and insert ... | 1 | 2016-06-12T06:19:41Z | 37,861,910 | <p>spinningD20 here. To be fair, I answered his immediate question, but also followed it up with an explanation of encapsulating it into a custom widget:</p>
<pre><code>from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
impor... | 0 | 2016-06-16T14:20:08Z | [
"python",
"widget",
"kivy",
"textinput"
] |
Read/write kivy widget attributes with python | 37,771,303 | <p>I have a basic, working knowledge of Python I'm trying to teach myself kivy. I'd like to be able to have Python read and write data to kivy widgets. </p>
<p>Imagine there's an address book app that inserts the date and time into a TextInput. When the app starts, just have Python get the date and time and insert ... | 1 | 2016-06-12T06:19:41Z | 38,109,435 | <p>Another example, explaining how to populate text inputs with current date through a parent grid layout, avoiding App class to keep it clean:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.uix.gridlayout impor... | 0 | 2016-06-29T20:26:04Z | [
"python",
"widget",
"kivy",
"textinput"
] |
copying between two s3 buckets throws 404 error | 37,771,313 | <p>I have two s3 buckets, take "srcs3bck" and "dsts3bck", i have a text file in srcs3bck. I tried the answer suggested in <a href="http://stackoverflow.com/questions/30161700/how-to-move-files-between-two-amazon-s3-buckets-using-boto">StackOverFlow question</a> to copy the source to destination. But when i do i am gett... | 1 | 2016-06-12T06:21:37Z | 37,771,421 | <p>The copy_key method is actually looking for the bucket name, not the bucket object. So try this instead:</p>
<pre><code>for i in x: dst.copy_key(i.key,src.name,i.key)
</code></pre>
| 3 | 2016-06-12T06:37:04Z | [
"python",
"amazon-web-services",
"amazon-s3",
"boto3"
] |
mac - pip install pymssql error | 37,771,434 | <p>I use mac(Ver. 10.11.5). I want to install module pymssql for python.
In terminal, I input <code>sudo -H pip install pymssql</code>, <code>pip install pymssql</code>, <code>sudo pip install pymssql</code> . But error occur.</p>
<p>The directory '/Users/janghyunsoo/Library/Caches/pip/http' or its parent directory i... | 3 | 2016-06-12T06:38:34Z | 38,002,724 | <p>I was able to work around this by reverting to an older version of FreeTDS through Homebrew before running the pip install.</p>
<pre><code>brew unlink freetds; brew install homebrew/versions/freetds091
</code></pre>
<p>The solution was found by andrewmwhite at:
<a href="https://github.com/pymssql/pymssql/issues/43... | 8 | 2016-06-23T22:10:13Z | [
"python",
"osx",
"python-2.7",
"pymssql"
] |
how do I get the full list of data when queried JIRA through command line | 37,771,466 | <p>When I query JIRA from the command line using their REST api with this query: </p>
<p><code>project = PROJECTNAME AND "Build Info" ~ BUILDNAME</code> </p>
<p>It only shows a maximum of 50 results even though there are a total of 892. When queried from the JIRA UI, it shows the full list, so it looks like there is ... | 1 | 2016-06-12T06:43:40Z | 37,783,029 | <p>50 is a default value for "maxResults" parameter. Here's API documentation <a href="https://docs.atlassian.com/jira/REST/latest/#api/2/search-search" rel="nofollow">https://docs.atlassian.com/jira/REST/latest/#api/2/search-search</a></p>
<p>You need to use the startAt param and loop to get all your results, or use ... | 0 | 2016-06-13T06:24:42Z | [
"python",
"jira-rest-api"
] |
TypeError: list indices must be integers, not unicode (Telepot retreive name) | 37,771,482 | <p>I started to learn Python by myself week ago.</p>
<p>I tried to make a bot that retrieve the name of the sender of the chat in a group. I am using Python with Telepot.</p>
<pre><code>>>> from pprint import pprint
>>> import telepot
>>> response = bot.getUpdates()
pprint(response)
[{u'mes... | 2 | 2016-06-12T06:45:38Z | 37,771,507 | <p>Square brackets in a representation mean that you have a list, and lists must be indexed using an integer or slice. Try indexing by <code>[0]</code> before attempting to access any contained dictionaries.</p>
| 1 | 2016-06-12T06:48:51Z | [
"python",
"typeerror"
] |
TypeError: list indices must be integers, not unicode (Telepot retreive name) | 37,771,482 | <p>I started to learn Python by myself week ago.</p>
<p>I tried to make a bot that retrieve the name of the sender of the chat in a group. I am using Python with Telepot.</p>
<pre><code>>>> from pprint import pprint
>>> import telepot
>>> response = bot.getUpdates()
pprint(response)
[{u'mes... | 2 | 2016-06-12T06:45:38Z | 37,771,568 | <p>Use <a href="https://docs.python.org/2/library/stdtypes.html#dict.get" rel="nofollow"><code>get()</code></a> instead of a list to access values in a dictionary. This method returns a value for a given key in a dictionary (or <code>None</code> if the key is not available):</p>
<pre><code>sender1 = response[0][u'mes... | 0 | 2016-06-12T06:56:38Z | [
"python",
"typeerror"
] |
__init__ not being called for double inherited class | 37,771,540 | <p>I have the following code:</p>
<pre><code>from form_utils import forms as betterforms
from django.db import models
class FilterForm(betterforms.BetterForm):
def __init__(self, *args, **kwargs):
super(FilterForm, self).__init__(*args, **kwargs)
print('filter form __init__')
...
class NewEn... | 4 | 2016-06-12T06:52:33Z | 37,771,633 | <p>Presumably, BetterForm does not call super, so the chain stops there.</p>
<p>The only thing you can do is to swap the order of classes in the declaration:</p>
<pre><code>class NewEntityForm(FileFormMixin, FilterForm):
</code></pre>
<p>Although of course this might affect any other methods that are defined in both... | 3 | 2016-06-12T07:06:08Z | [
"python",
"django"
] |
__init__ not being called for double inherited class | 37,771,540 | <p>I have the following code:</p>
<pre><code>from form_utils import forms as betterforms
from django.db import models
class FilterForm(betterforms.BetterForm):
def __init__(self, *args, **kwargs):
super(FilterForm, self).__init__(*args, **kwargs)
print('filter form __init__')
...
class NewEn... | 4 | 2016-06-12T06:52:33Z | 37,771,659 | <p>You can refer to the parent classes explicitly when invoking their <code>__init__</code> methods. For example:</p>
<pre><code>class Foo(object):
def __init__(self, x):
self.x = x
class Bar(object):
def __init__(self, y):
self.y = y
class Baz(Foo, Bar):
def __init__(self, x, y):
... | 0 | 2016-06-12T07:10:08Z | [
"python",
"django"
] |
__init__ not being called for double inherited class | 37,771,540 | <p>I have the following code:</p>
<pre><code>from form_utils import forms as betterforms
from django.db import models
class FilterForm(betterforms.BetterForm):
def __init__(self, *args, **kwargs):
super(FilterForm, self).__init__(*args, **kwargs)
print('filter form __init__')
...
class NewEn... | 4 | 2016-06-12T06:52:33Z | 37,771,738 | <p><strong>tl;dr</strong></p>
<p>From your posted MRO of <code>NewEntityForm</code> you see the class <code>BaseForm</code>. <a href="https://github.com/django/django/blob/ec6121693f112ae33b653b4364e812722d2eb567/django/forms/forms.py#L72-98" rel="nofollow">In the source of django.forms.forms.BaseForm</a> you can also... | 3 | 2016-06-12T07:21:59Z | [
"python",
"django"
] |
Selenium Compound class names not permitted | 37,771,604 | <p>I have the below code that clicks on an element to pop up a screen and copy the text in it</p>
<pre><code>el1 = driver.find_element_by_id("keyDev-A")
el1.click()
el2 = driver.find_element_by_class_name("content")
print(el2.text)
</code></pre>
<p>However, when I tried to get <code>selenium</code> to click on the bu... | 0 | 2016-06-12T07:01:18Z | 37,772,835 | <p><a href="http://stackoverflow.com/questions/37771604/selenium-compound-class-names-not-permitted#comment63011467_37771604">Leon's comment</a> leads to the correct information that compound class names are no longer supported. What you could do instead is try using css selectors. In your case, the following line of c... | 2 | 2016-06-12T09:47:38Z | [
"python",
"selenium"
] |
Protecting against Manipulating form input with Django Forms | 37,771,688 | <p>I have a question to protect attackers from manipulating form inputs.</p>
<p>Let's say I have a rental request from a customer. In Django, there is a <code>create_rental</code> URL, say <code>rent-website.com/customer/1/create_rental</code>.</p>
<p>Because in <code>urls.py</code></p>
<pre><code>url(r'^customer/(?... | 1 | 2016-06-12T07:14:10Z | 37,772,067 | <p>This is a matter of implementing your own logic regarding which objects each user can access, it has nothing to do with the framework itself.</p>
<p>Having said that, take a look at <a href="https://django-guardian.readthedocs.io/en/stable/" rel="nofollow">Django Guardian</a>:</p>
<blockquote>
<p>django-guardian... | 0 | 2016-06-12T08:12:38Z | [
"python",
"django",
"forms"
] |
Call function twice or more in a loop | 37,771,716 | <p>I use the code below with <code>lambda</code> to call function once in a loop, it works but now I am trying to call the function for specific times like 3 times in a loop, I looked for it and found some solutions but they call function for specific times if there is no loop, when I try it in a loop, nothing changes.... | 2 | 2016-06-12T07:18:53Z | 37,771,881 | <p>You should work with a decorator, that makes it clear, what you intend to do:</p>
<pre><code>class call_three_times(object):
def __init__(self, func):
self.func = func
self.count = 0
def __call__(self, *args, **kw):
self.count += 1
if self.count <= 3:
return s... | 5 | 2016-06-12T07:46:30Z | [
"python",
"python-2.7",
"function",
"loops",
"lambda"
] |
Call function twice or more in a loop | 37,771,716 | <p>I use the code below with <code>lambda</code> to call function once in a loop, it works but now I am trying to call the function for specific times like 3 times in a loop, I looked for it and found some solutions but they call function for specific times if there is no loop, when I try it in a loop, nothing changes.... | 2 | 2016-06-12T07:18:53Z | 37,772,198 | <p>Another approach is to use function instead of class:</p>
<pre><code>def call_three_times(func, *args, **kwargs):
def wrapper(*args, **kwargs):
wrapper.called += 1
return func(*args, **kwargs) if wrapper.called <= 3 else None
wrapper.called = 0
return wrapper
@call_three_times
def f... | 2 | 2016-06-12T08:31:44Z | [
"python",
"python-2.7",
"function",
"loops",
"lambda"
] |
Unable to import outputSchema from pigutil in python | 37,771,731 | <p>This might be pretty basic question, i am new to pig and python area.
I am trying to import outputSchema from pigutil.</p>
<p>The outputSchema is used as following inside the python UDF :-</p>
<pre><code> @outputSchema('HistorySchema:bag{t:(SomeKey:int,ScdColumnNew:chararray,ScdColumnOld:int, activeFlag:chararray,... | -1 | 2016-06-12T07:20:51Z | 37,847,032 | <p>from pig_util import outputSchema</p>
<p><a href="http://help.mortardata.com/technologies/pig/writing_python_udfs#toc_4UsingtheoutputSchemaDecoratorinPython" rel="nofollow">http://help.mortardata.com/technologies/pig/writing_python_udfs#toc_4UsingtheoutputSchemaDecoratorinPython</a></p>
| 0 | 2016-06-15T22:42:30Z | [
"python",
"pig-udf"
] |
Python: distribute two packages from the same codebase | 37,771,822 | <p>suppose I have this project <code>xxxx</code>, I'd like to distribute two packages for it:
<code>xxxx</code> and <code>xxxx-lite</code>, the difference is that <code>xxxx</code> has some extra dependencies for extra features, while <code>xxxx-lite</code> does not.</p>
<p>I tried to have one <code>setup.py</code> an... | 0 | 2016-06-12T07:35:32Z | 37,771,858 | <p>You can use <a href="http://setuptools.readthedocs.io/en/latest/setuptools.html?highlight=extras_require#declaring-extras-optional-features-with-their-own-dependencies" rel="nofollow" title="extras-require"><code>extras-require</code></a></p>
<p>Related to <a href="http://stackoverflow.com/questions/19096155/setupt... | 0 | 2016-06-12T07:42:33Z | [
"python",
"pip",
"setuptools",
"pypi"
] |
changing the side effect of a mock object's method created with patch | 37,772,036 | <p>Hello I want to test a view of django. Inside of the view I create two objects which I want to mock some of their methods. The test looks like this</p>
<pre><code>@mock.patch('payments_system.views.FirstObject')
@mock.patch('payments_system.helper_functions.SecondObject')
def test_make_payment_view_with_success(sel... | 0 | 2016-06-12T08:09:37Z | 37,784,842 | <p>I finnaly managed to solve my issue. What I did was the following:</p>
<p>in the test function</p>
<pre><code>mock_object1_instance = MockFirstObject1.return_value
mock_object1_instance.get_value.side_effect = get_value_side_effect
</code></pre>
<p>the same I did for the other mock object. </p>
| 0 | 2016-06-13T08:20:14Z | [
"python",
"django",
"unit-testing",
"mocking",
"python-mock"
] |
DjangoUnicodeDecodeError during calling form.errors with EmailField | 37,772,066 | <p>I am porting my site to django 1.9 and don't know how to resolve this issue correctly.</p>
<p>In my form I have usual EmailField from django forms. If validation fails, it shoud be message about it (I pass <code>'form_errors': form.errors}</code> to context for manipulating).</p>
<p>But in that case django returns... | 0 | 2016-06-12T08:12:37Z | 37,774,396 | <p>Well. The problem is in translations. In this case - Russian localization.
No idea why translation from "native" django localization files failed.
But for all who have similar problem:</p>
<ol>
<li><p>Create (if still not) locale file (<a href="https://docs.djangoproject.com/en/1.9/topics/i18n/translation/#locali... | 1 | 2016-06-12T12:44:19Z | [
"python",
"json",
"django",
"unicode",
"django-1.9"
] |
elements of sets in python must be mutable or immutable? | 37,772,232 | <p>I was reading sets in python <a href="http://www.python-course.eu/sets_frozensets.php" rel="nofollow">http://www.python-course.eu/sets_frozensets.php</a> and got confusion that whether the elements of sets in python must be mutable or immutable? Because in the definition section they said "A set contains an unordere... | 2 | 2016-06-12T08:35:41Z | 37,772,259 | <p>When you pass the <a href="https://docs.python.org/2/library/stdtypes.html#set" rel="nofollow"><code>set()</code></a> constructor built-in any <em>iterable</em>, it builds a set out of the elements provided in the iterable. So when you pass <code>set()</code> a list, it creates a set containing the objects within th... | 2 | 2016-06-12T08:39:05Z | [
"python",
"set"
] |
elements of sets in python must be mutable or immutable? | 37,772,232 | <p>I was reading sets in python <a href="http://www.python-course.eu/sets_frozensets.php" rel="nofollow">http://www.python-course.eu/sets_frozensets.php</a> and got confusion that whether the elements of sets in python must be mutable or immutable? Because in the definition section they said "A set contains an unordere... | 2 | 2016-06-12T08:35:41Z | 37,772,295 | <p>You seem to be confusing initialising a set with a list:</p>
<pre><code>a = set([1, 2])
</code></pre>
<p>with adding a list to an existing set:</p>
<pre><code>a = set()
a.add([1, 2])
</code></pre>
<p>the latter will throw an error, where the former initialises the set with the <em>values from the list</em> you p... | 1 | 2016-06-12T08:43:00Z | [
"python",
"set"
] |
Using soffice within python, Command works in terminal but not in Python subprocess | 37,772,250 | <p>I am having the most frustrating problem with libreoffice in Python </p>
<p>when I run the following in terminal I have no problem at all, the pdf file is produced where I want it and life is dandy:</p>
<pre><code>cd /Applications/LibreOffice.app/Contents/MacOS/
./soffice --convert-to pdf --outdir {output_folder}... | 0 | 2016-06-12T08:38:04Z | 37,772,887 | <p>It's because you need to <strong>change the current working directory</strong>, not just give an absolute path to the command. </p>
<pre><code>subprocess.Popen(["/Applications/LibreOffice.app/Contents/MacOS/soffie", "--convert-to", "pdf", "--outdir", "{output_folder} ", "{path_to_docx_file}/{title}.docx"])
</code><... | 0 | 2016-06-12T09:54:16Z | [
"python",
"pdf",
"soffice"
] |
How to count all occurrences of a word in a string using python | 37,772,253 | <p>I'm trying to find the number of times 'bob' occurs in a string of characters like 'abdebobdfhbobob'.</p>
<p>My code (that I found through another stackoverflow question) is:</p>
<pre><code>s = 'abdebobdfhbobob'
print 'The number of times bob occurs is: ' + str(s.count('bob'))
</code></pre>
<p>This code prints ... | 2 | 2016-06-12T08:38:23Z | 37,772,301 | <p>Based on <a href="https://docs.python.org/3/library/stdtypes.html#str.count" rel="nofollow">documentation</a>, <code>str.count()</code> return the number of non-overlapping occurrences of substring sub in the range <code>[start, end]</code>. You can use a <a href="http://www.regular-expressions.info/lookaround.html"... | 4 | 2016-06-12T08:43:35Z | [
"python",
"python-2.7"
] |
How to count all occurrences of a word in a string using python | 37,772,253 | <p>I'm trying to find the number of times 'bob' occurs in a string of characters like 'abdebobdfhbobob'.</p>
<p>My code (that I found through another stackoverflow question) is:</p>
<pre><code>s = 'abdebobdfhbobob'
print 'The number of times bob occurs is: ' + str(s.count('bob'))
</code></pre>
<p>This code prints ... | 2 | 2016-06-12T08:38:23Z | 37,772,347 | <p>If you don't want to use regular expressions you can create all triplets from the string using <code>zip</code> and then use <code>list.count</code>:</p>
<pre><code>>>> word = 'bob'
>>> triplets = (''.join(k) for k in zip(*[s[i:] for i in range(len(word))]))
>>> triplets.count(word)
3
</c... | 0 | 2016-06-12T08:48:05Z | [
"python",
"python-2.7"
] |
How to count all occurrences of a word in a string using python | 37,772,253 | <p>I'm trying to find the number of times 'bob' occurs in a string of characters like 'abdebobdfhbobob'.</p>
<p>My code (that I found through another stackoverflow question) is:</p>
<pre><code>s = 'abdebobdfhbobob'
print 'The number of times bob occurs is: ' + str(s.count('bob'))
</code></pre>
<p>This code prints ... | 2 | 2016-06-12T08:38:23Z | 37,772,412 | <p>We can just check all possible candidates:</p>
<pre><code>def count_substrings(sub, main):
n = len(sub)
return sum(sub == main[i : i+n] for i in range(len(main) - n + 1))
s = 'abdebobdfhbobob'
sub = 'bob'
print('The number of times %s occurs is: %d' % (sub, count_substrings(sub, s))) # 3
</code></pre>
| 0 | 2016-06-12T08:56:17Z | [
"python",
"python-2.7"
] |
Tensorflow: Tensor.set_shape() ValueError: 'image' must be fully defined | 37,772,329 | <p>I want to use <code>tf.image.resize_image_with_crop_or_pad</code> to crop a part of the input image. But there comes an error: <code>ValueError: 'image' must be fully defined</code>. And I checked the <a href="http://stackoverflow.com/questions/34746777/why-do-i-get-valueerror-image-must-be-fully-defined-when-transf... | 0 | 2016-06-12T08:46:33Z | 37,772,881 | <p>The problem is at the line</p>
<pre><code>example.set_shape = ([256,256,3])
</code></pre>
<p>You're overriding the method <code>tf.Tensor.set_shape</code> and setting it to a value.</p>
<p><code>set_shape</code> is a method, thus you have to call it properly:</p>
<pre><code>example.set_shape([256,256,3])
</code>... | 1 | 2016-06-12T09:53:28Z | [
"python",
"tensorflow",
"deep-learning"
] |
Jira search all issues in a project with status Done or Closed | 37,772,349 | <p>I am trying to list all isues in a project with status <code>Done or Closed</code>. When I run a JQL-query with advanced search I get: 3096 issues in the project. However when I run it with python I get around 50 issues.</p>
<pre><code>#/usr/bin/python
import jira.client
from jira.client import JIRA
options = {'se... | 2 | 2016-06-12T08:48:14Z | 37,772,795 | <p>From the docs at <a href="https://pythonhosted.org/jira/" rel="nofollow">https://pythonhosted.org/jira/</a>:</p>
<pre><code>search_issues(jql_str, startAt=0, maxResults=50, validate_query=True,
fields=None, expand=None, json_result=None)
</code></pre>
<p>Note the <code>maxResults</code> argument. I ... | 4 | 2016-06-12T09:42:15Z | [
"python",
"jira",
"jql",
"python-jira"
] |
Jira search all issues in a project with status Done or Closed | 37,772,349 | <p>I am trying to list all isues in a project with status <code>Done or Closed</code>. When I run a JQL-query with advanced search I get: 3096 issues in the project. However when I run it with python I get around 50 issues.</p>
<pre><code>#/usr/bin/python
import jira.client
from jira.client import JIRA
options = {'se... | 2 | 2016-06-12T08:48:14Z | 37,774,000 | <p>The answer of Martin Bonner is ok, but I'm just posting an answer to add more clarification.</p>
<p>The <em><a href="https://pythonhosted.org/jira/#searching" rel="nofollow">search_issues</a></em> method uses the JIRA REST API to run the JQL query, so you can also look at the <a href="https://docs.atlassian.com/jir... | 2 | 2016-06-12T12:02:33Z | [
"python",
"jira",
"jql",
"python-jira"
] |
Is there anyway to control memory usage of python process? | 37,772,388 | <p>Is there anyway to control memory usage of python process just like JVM process ? Thanks</p>
| 2 | 2016-06-12T08:52:45Z | 39,227,419 | <p>No. Not like you can in Java. If you're running on Linux then you could use <code>ulimit</code> to limit the amount of memory allowed by processes spawned by the current one:</p>
<pre><code>$ ulimit -Sv 1048576 # soft virtual memory limit of 1GB
$ ./yourscript.py
</code></pre>
| 0 | 2016-08-30T12:24:30Z | [
"python"
] |
Python: append to an array of empty lists | 37,772,414 | <p>How to declare an array of empty lists to be appended later on?</p>
<p>I have a file which contain user-movie data like this: <strong>UserID::MovieID::Rating::Time</strong> but the amount of entries for each UserIDs may differ. (Ex: UserID=1 may have 2 entries and UserID=2 may have 5 entries.)</p>
<p><strong>1::11... | -1 | 2016-06-12T08:56:18Z | 37,772,462 | <p>One of the options is to use <code>dict</code> like below.</p>
<pre><code>num_user_id = 2418
user_adj_list = [None]*num_user_id
path = "/home/Desktop/ml-1m/ratings.dat"
source_file = open(path)
# line = UserID::MovieID::Rating::Timestauser_adj_list
user_adj_list = dict()
for line in source_file:
u... | 0 | 2016-06-12T09:02:05Z | [
"python"
] |
Filter values inside Python generator expressions | 37,772,551 | <p>I have a dictionary <code>dct</code> for which I want each of its values to be summed provided their corresponding keys exist in a specified list <code>lst</code>.</p>
<p>The code I am using so far is:</p>
<pre><code>sum(dct[k] for k in lst)
</code></pre>
<p>In the above generator expression I would like to handl... | 4 | 2016-06-12T09:14:27Z | 37,772,619 | <pre><code>sum(dct[k] for k in lst if k in dct)
</code></pre>
| 1 | 2016-06-12T09:21:19Z | [
"python",
"dictionary",
"keyerror"
] |
Filter values inside Python generator expressions | 37,772,551 | <p>I have a dictionary <code>dct</code> for which I want each of its values to be summed provided their corresponding keys exist in a specified list <code>lst</code>.</p>
<p>The code I am using so far is:</p>
<pre><code>sum(dct[k] for k in lst)
</code></pre>
<p>In the above generator expression I would like to handl... | 4 | 2016-06-12T09:14:27Z | 37,772,622 | <p>You can simply use <a href="https://docs.python.org/3/library/stdtypes.html#dict.get" rel="nofollow"><code>.get()</code></a> to attempt to get the value for the key from the dictionary, and should it not be found will return <code>None</code>, or your provided default parameter which would be 0 in this case. </p>
<... | 2 | 2016-06-12T09:21:23Z | [
"python",
"dictionary",
"keyerror"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.