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 |
|---|---|---|---|---|---|---|---|---|---|
python, write the contents of a list to a text file | 38,237,548 | <p>I created a program in python that is used to create/edit user generated lists. I tried to create a save function that will save a list to a text file, but I'm having a problem. It will create the text file but not write the content of the list to the text file.</p>
<pre><code>#!/usr/bin/python
user_list = []
def b... | 0 | 2016-07-07T04:28:46Z | 38,237,580 | <p>Your problem is in this line:</p>
<p><code>for i in user_list:
i.write(user_list, '\n')</code></p>
<p>Change it to this:</p>
<pre><code>for i in user_list:
wr.write(i, '\n')
</code></pre>
<p><strong>EDIT:</strong> And remove <code>user_list</code> parameter from all of your functions because it is a glo... | 2 | 2016-07-07T04:33:27Z | [
"python",
"list",
"writetofile"
] |
matplotlib using text instead of number in y ticks | 38,237,574 | <p>I want my y axis' tick is text label rather than number, and my x is a series of datetime object, I want a plot to represent a track of a man's event during a day, that's the scene. </p>
<p><strong>This is my code :</strong></p>
<pre><code>import datetime
from matplotlib import pyplot as plt
from matplotlib import... | 0 | 2016-07-07T04:32:16Z | 38,238,037 | <p>This should do the trick:</p>
<pre><code>plt.xticks(tick_loc, tick_names)
</code></pre>
<p><code>tick_loc</code> sets the locations of your ticks, and <code>tick_names</code> what to display.</p>
| 0 | 2016-07-07T05:24:30Z | [
"python",
"datetime",
"matplotlib"
] |
matplotlib using text instead of number in y ticks | 38,237,574 | <p>I want my y axis' tick is text label rather than number, and my x is a series of datetime object, I want a plot to represent a track of a man's event during a day, that's the scene. </p>
<p><strong>This is my code :</strong></p>
<pre><code>import datetime
from matplotlib import pyplot as plt
from matplotlib import... | 0 | 2016-07-07T04:32:16Z | 38,240,223 | <p>as @Julien Bernu suggest, I can make my example working by add these two lines:</p>
<pre><code>ax.set_yticks(xrange(len(y_text_dict)))
ax.set_yticklabels(y_text_dict)
</code></pre>
<p>and the resulting plot:
<a href="http://i.stack.imgur.com/O4CXA.png" rel="nofollow">enter image description here</a></p>
| 0 | 2016-07-07T07:52:58Z | [
"python",
"datetime",
"matplotlib"
] |
Indicate external value on matplotlib colorbar | 38,237,614 | <p>I have a scatterplot that is coloured with respect to a third variable. I can create a colorbar for this plot, but would like to also indicate an external level (just with a horizontal line) on the colorbar. </p>
<pre><code>X = np.array([0, 1, 2, 3, 4, 5, 6])
Y = np.array([0, 1, 2, 3, 4, 5, 6])
Z = np.array([0, 1,... | 2 | 2016-07-07T04:38:33Z | 38,237,871 | <p>The colorbar is an axis. You can plot a horizontal line on it. To find out where to plot the line, use the colorbar's norm to map your "special" value to its position on the colorbar axis:</p>
<pre><code>cbar.ax.hlines(cbar.norm(4), 0, 1, color='green')
</code></pre>
| 4 | 2016-07-07T05:05:45Z | [
"python",
"matplotlib",
"colorbar"
] |
Which parse method scrapy used to parse start_urls | 38,237,616 | <p>I want scrapy to scrape some start urls and then follow the links in those pages according to rules. My spider is inherited from <code>CrawlSpider</code> and has <code>start_urls</code> and 'rules' set. But it doesn't seems to use the parse function I defines to parse the start_urls. Here are the codes:</p>
<pre><c... | -2 | 2016-07-07T04:38:53Z | 38,240,489 | <p>1st, the CrawlSpider class uses a default parse() method to deal with ALL requests that doesn't specifies a callback function, in my case including the requests made from start_urls. This parse() method only applies rules to extract links and doesn't parse the pages of start_url at all. That's why I can't scrape any... | 0 | 2016-07-07T08:09:03Z | [
"python",
"scrapy",
"web-crawler"
] |
If statement with no logical operators in python | 38,237,668 | <p>I have the following python code:</p>
<pre><code>value = 1.9
if value:
#do something
else:
#do something else
</code></pre>
<p>What happens here? I can't understand this because <code>value</code> is not Boolean.</p>
| 1 | 2016-07-07T04:44:12Z | 38,237,696 | <blockquote>
<p>Any object can be tested for truth value, for use in an if or while
condition or as operand of the Boolean operations below. The following
values are considered false:</p>
<ul>
<li>None</li>
<li>False</li>
<li>zero of any numeric type, for example, 0, 0L, 0.0, 0j.</li>
<li>any empty s... | 1 | 2016-07-07T04:47:49Z | [
"python"
] |
If statement with no logical operators in python | 38,237,668 | <p>I have the following python code:</p>
<pre><code>value = 1.9
if value:
#do something
else:
#do something else
</code></pre>
<p>What happens here? I can't understand this because <code>value</code> is not Boolean.</p>
| 1 | 2016-07-07T04:44:12Z | 38,237,697 | <p>Python has a concept of truthy-ness where non-Boolean values are basically "coerced" into Boolean ones, as shown <a href="https://docs.python.org/3/library/stdtypes.html#truth-value-testing" rel="nofollow">here</a>:</p>
<blockquote>
<p><strong>4.1 Truth value testing</strong></p>
<p>Any object can be tested ... | 5 | 2016-07-07T04:47:50Z | [
"python"
] |
If statement with no logical operators in python | 38,237,668 | <p>I have the following python code:</p>
<pre><code>value = 1.9
if value:
#do something
else:
#do something else
</code></pre>
<p>What happens here? I can't understand this because <code>value</code> is not Boolean.</p>
| 1 | 2016-07-07T04:44:12Z | 38,237,712 | <p>Check this <a href="https://docs.python.org/2/library/stdtypes.html#truth-value-testing" rel="nofollow">documentation materials</a>. In python as in many programming language. <code>0, '', []</code> kind of values gives <code>False</code> while any other value returns <code>True</code>.</p>
| 0 | 2016-07-07T04:49:17Z | [
"python"
] |
If statement with no logical operators in python | 38,237,668 | <p>I have the following python code:</p>
<pre><code>value = 1.9
if value:
#do something
else:
#do something else
</code></pre>
<p>What happens here? I can't understand this because <code>value</code> is not Boolean.</p>
| 1 | 2016-07-07T04:44:12Z | 38,237,762 | <p>It is going to be False only if value is equal 0 or ""</p>
| 0 | 2016-07-07T04:54:04Z | [
"python"
] |
No module named slack | 38,237,705 | <p>I'm trying test [django-allauth/example] from <a href="https://github.com/pennersr/django-allauth" rel="nofollow">https://github.com/pennersr/django-allauth</a>.</p>
<p>follow the [example/readme.rst], all steps need to test the exmaple as follows:</p>
<pre><code>$ git clone git://github.com/pennersr/django-allaut... | 1 | 2016-07-07T04:48:53Z | 38,237,988 | <p>Make sure you've edited your settings.py in accordance with the documentation found here: <a href="https://django-allauth.readthedocs.io/en/latest/installation.html" rel="nofollow">https://django-allauth.readthedocs.io/en/latest/installation.html</a>. Particularly including 'allauth.socialaccount.providers.slack'.</... | 0 | 2016-07-07T05:19:26Z | [
"python",
"django",
"django-allauth",
"slack"
] |
Django: timezone.now vs timezone.now() | 38,237,777 | <p>I am in the process of upgrading my project from Django 1.8.2 to 1.9.7 and I'm getting this warning:</p>
<pre><code>WARNINGS:
my_app.my_model.date_available: (fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you wa... | 2 | 2016-07-07T04:55:11Z | 38,237,814 | <p>The difference is that <code>timezone.now</code> is a callable that gets executed at runtime, while <code>timezone.now()</code> returns the output of that function.</p>
<p>For the <code>models.DateTimeField</code>, you need to use the callable. Better still, just set <a href="https://docs.djangoproject.com/en/1.9/r... | 5 | 2016-07-07T04:59:11Z | [
"python",
"django",
"timezone"
] |
Django: timezone.now vs timezone.now() | 38,237,777 | <p>I am in the process of upgrading my project from Django 1.8.2 to 1.9.7 and I'm getting this warning:</p>
<pre><code>WARNINGS:
my_app.my_model.date_available: (fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you wa... | 2 | 2016-07-07T04:55:11Z | 38,237,849 | <p>now() gets executed when the model is loaded and returns a datetime object / time string at loading. (hence the Django warning!)
(The model file if fully executed when the server starts) </p>
<p>now will pass on the now method, and will get executed only when the class/model gets instantiated, creating the time ... | 1 | 2016-07-07T05:03:31Z | [
"python",
"django",
"timezone"
] |
Django: timezone.now vs timezone.now() | 38,237,777 | <p>I am in the process of upgrading my project from Django 1.8.2 to 1.9.7 and I'm getting this warning:</p>
<pre><code>WARNINGS:
my_app.my_model.date_available: (fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you wa... | 2 | 2016-07-07T04:55:11Z | 38,237,912 | <p>In <code>self.filter(date_available__lte = timezone.now())</code> you want to make a query to the DB based on the current time. So you need it in string format.</p>
<p>In <code>datetime_released = models.DateTimeField(default=timezone.now)</code> you want default to be current time. So you cannot have a string ther... | 0 | 2016-07-07T05:11:25Z | [
"python",
"django",
"timezone"
] |
Django: timezone.now vs timezone.now() | 38,237,777 | <p>I am in the process of upgrading my project from Django 1.8.2 to 1.9.7 and I'm getting this warning:</p>
<pre><code>WARNINGS:
my_app.my_model.date_available: (fields.W161) Fixed default value provided.
HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you wa... | 2 | 2016-07-07T04:55:11Z | 38,239,673 | <p>In python everything is an object, including functions. This means you can affect a function to a variable:</p>
<pre><code>>>> from django.utils import timezone
>>> foo = timezone.now
>>> foo
<function django.utils.timezone.now>
>>> foo()
datetime.datetime(2016, 7, 7, 9, 11... | 3 | 2016-07-07T07:21:49Z | [
"python",
"django",
"timezone"
] |
one time pad with pad seeded via 'passphrase' | 38,237,834 | <p>Looking for a theoretical discussion here. I personally would (and will continue to) use GPG or just SCP for simply getting a file somewhere where only I can decrypt it or only I can download it. Still a discussion of where the following falls short (and by how much) would help my curiosity.</p>
<p>Suppose I want ... | 1 | 2016-07-07T05:01:44Z | 38,238,045 | <p>A one-time pad's key is truly-random data of the same size as the plaintext, by definition. If you're producing it some other way (e.g. by seeding a PRNG), it isn't a one-time pad, and it doesn't have the one-time pad's unbreakability property.</p>
<p>One-time pads are actually a special type of <a href="https://e... | 3 | 2016-07-07T05:24:57Z | [
"python",
"encryption",
"random"
] |
python filtered input to csv.reader | 38,237,883 | <p>My program reads a csv file but recently the input file was changed to be base64 encoded. So currently the read code is:</p>
<pre><code>with open(uploadFile, 'rb') as csvfile:
spreadSheet = csv.reader(csvfile, delimiter=',')
</code></pre>
<p>I know the csv is a file descriptor and this can't be done, but I wan... | 0 | 2016-07-07T05:07:07Z | 38,238,481 | <p>Try the following</p>
<pre><code>import base64
import csv
with open(uploadFile, 'rb') as csvfile:
decoded = base64.standard_b64decode(csvfile.read()).decode('utf-8')
spreadSheet = csv.reader(decoded.splitlines(), delimiter=',')
</code></pre>
| 0 | 2016-07-07T06:03:19Z | [
"python",
"csv"
] |
Access all the attributes of one-to-one linked model if not found in current model | 38,238,069 | <p>I have a model that is linked to another as <code>OneToOneField</code>. For example:</p>
<pre><code>class Profile(models.Model):
#other fields ...
user = models.OneToOneField(User, null=True, blank=True)
</code></pre>
<p>I would like to get the attribute with dot notation if it exists in Profile or User. I... | 2 | 2016-07-07T05:27:18Z | 38,238,249 | <p>Something like?</p>
<pre><code>def __getattr__(self, name):
if hasattr(self, name):
return getattr(self, name)
elif hasattr(self, "user") and hasattr(self.user, name):
return getattr(self.user, name)
else:
raise AttributeError
</code></pre>
| 1 | 2016-07-07T05:43:23Z | [
"python",
"django"
] |
Access all the attributes of one-to-one linked model if not found in current model | 38,238,069 | <p>I have a model that is linked to another as <code>OneToOneField</code>. For example:</p>
<pre><code>class Profile(models.Model):
#other fields ...
user = models.OneToOneField(User, null=True, blank=True)
</code></pre>
<p>I would like to get the attribute with dot notation if it exists in Profile or User. I... | 2 | 2016-07-07T05:27:18Z | 38,238,250 | <p>There is no need for this method. you know what model has which attribute so why you should call a method blindly? this confuses other co-developers and you should not do this. in worst-case, I would make a property:</p>
<pre><code>@property
def get_name(self):
if hasattr(self, 'name'):
return self.name... | 2 | 2016-07-07T05:43:27Z | [
"python",
"django"
] |
Why are these lines of code in python only outputting the same answer? | 38,238,133 | <p>I'm trying to get this program to return all possible multiples of 3 and 5 below 1001 and then add them all together and print it but for some reason these lines of code only seem to be printing one number and that number is the number 2 which is obviously wrong. Can someone point me in the right direction to why th... | -4 | 2016-07-07T05:33:25Z | 38,238,195 | <p>You've got a few mistakes:</p>
<ul>
<li>x is a boolean type</li>
<li>Your loop never ends</li>
<li>adding values to mimic lists?</li>
</ul>
<h1>Edit</h1>
<p>Didn't see the part where you wanted sum, so you could employ a for-in loop or just a simple one like so:</p>
<pre><code>sum = 0
for i in range(1001):
i... | 2 | 2016-07-07T05:38:32Z | [
"python",
"math"
] |
Why are these lines of code in python only outputting the same answer? | 38,238,133 | <p>I'm trying to get this program to return all possible multiples of 3 and 5 below 1001 and then add them all together and print it but for some reason these lines of code only seem to be printing one number and that number is the number 2 which is obviously wrong. Can someone point me in the right direction to why th... | -4 | 2016-07-07T05:33:25Z | 38,238,265 | <p>In your code:
1. <code>x=n<1001</code> - generates a boolean value; on which we can't perform a mathematical operation.</p>
<ol start="2">
<li>In while loop:
your variable n,x are not changing; they are constant to same value for all the iterations.</li>
</ol>
<p>Solution 1:
Below code will help you out.</p... | 0 | 2016-07-07T05:45:31Z | [
"python",
"math"
] |
Why are these lines of code in python only outputting the same answer? | 38,238,133 | <p>I'm trying to get this program to return all possible multiples of 3 and 5 below 1001 and then add them all together and print it but for some reason these lines of code only seem to be printing one number and that number is the number 2 which is obviously wrong. Can someone point me in the right direction to why th... | -4 | 2016-07-07T05:33:25Z | 38,238,276 | <pre><code>true=1
false=0
</code></pre>
<p>so:</p>
<pre><code>x = n<1001
</code></pre>
<p>we have x=1 because 0<1001 is true</p>
<pre><code>s = x%3 + x%5
</code></pre>
<p>the remainder of 1/3 is 1 and 1/5 is 1</p>
| 0 | 2016-07-07T05:46:28Z | [
"python",
"math"
] |
python - prevent IOError: [Errno 5] Input/output error when running without stdout | 38,238,139 | <p>I have a script that runs automatically on server through cronjob and it import and run several other scripts.</p>
<p>Some of them use prints, which naturally creates <code>IOError: [Errno 5] Input/output error</code> because the script runs without any SSH / terminal connected, so there's no proper stdout setup.</... | 0 | 2016-07-07T05:34:12Z | 38,238,281 | <p>Modifying the builtin or changing <code>sys.stdout</code> <em>should</em> work (except for subprocessesâbut you ruled those out) as long as you do it early enough. If not, though, there's a lower level trick that's much easier:</p>
<ul>
<li><p>run your python scripts with I/O redirection that discards output:</p... | 1 | 2016-07-07T05:47:17Z | [
"python",
"python-2.7",
"stdout"
] |
how to use python-numpy-brodcasting | 38,238,144 | <p>I have a trouble with python broadcasting</p>
<p>there is two numpy list</p>
<pre><code>x = np.array([[1,2,3],[4,5,6]])
y = np.array([0,1,1])
</code></pre>
<p>I'd like to calculate</p>
<pre><code>x : [[1,2,3],
[4,5,6]]
</code></pre>
<p>to </p>
<pre><code>x : [[1-y[0], 2-y[1], 3-y[2]],
[4-y[0], 5-y[1... | -6 | 2016-07-07T05:34:26Z | 38,238,779 | <p>I don't see how you got: <br></p>
<pre><code>x : [[0,-3,-3],
[3,0,0]]
</code></pre>
<p>But the easiest way to do what you ask for is just:</p>
<pre><code>import numpy as np
X = ([1,2,3],[4,5,6])
y = np.array([0,1,1])
print X-y
</code></pre>
<p>Output:</p>
<blockquote>
<p>[ [1 1 2]<br>
[4 4 5] ]</p>
<... | 2 | 2016-07-07T06:28:37Z | [
"python",
"numpy",
"numpy-broadcasting"
] |
MongoDB Notification in Python | 38,238,183 | <p>I am using MongoDB with Python web application. I want to know notification from mongodb whatever i changed in mongodb. i am using the code:</p>
<pre><code>from pymongo import Connection
import time
MONGO_CONNECTION = MongoClient(settings.MONGO_CONNECTION_URL+"/"+settings.MONGO_DATABASE['NAME'], safe=True, j=True)
... | 1 | 2016-07-07T05:37:35Z | 38,239,588 | <p>import pymongo
from pprint import pprint
from collections import OrderedDict
import collections
from operator import itemgetter</p>
<p>c=pymongo.Connection("mongodb://enter your ip address")</p>
<p>username='learning'
password='************'</p>
<p>c['learning'].authenticate(username,password)
print "connection c... | 0 | 2016-07-07T07:16:20Z | [
"python",
"mongodb"
] |
tensorflow 'module' object has no attribute 'contrib' | 38,238,192 | <p>i installed tensorflow(on python 2.7,debian linux) using the pip method as shown in official documentation:
<a href="https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html#pip-installation" rel="nofollow">https://www.tensorflow.org/versions/r0.9/get_started/os_setup.html#pip-installation</a></p>
<p>Test... | 0 | 2016-07-07T05:38:16Z | 38,238,736 | <p>Problem solved, turns i had 2 tensorflow versions installed:</p>
<ol>
<li>When launching $python , it used 0.6 version(which didnt had contrib module)</li>
<li>When launching $sudo python ,it had the latest 0.9 version and everything works as the documentation.</li>
</ol>
| 0 | 2016-07-07T06:24:53Z | [
"python",
"machine-learning",
"tensorflow"
] |
python opencv won't write video using Video-writer object? | 38,238,208 | <p>I am trying to save a OpenCV video stream using video writer object when the button is pressed but it saves only 5.5kb file.</p>
<pre><code>def OnRecord(self, evt):
capture = cv2.VideoCapture(0)
if not(capture.isOpened()):
print "Error"
# video recorder
fourcc = cv2.cv.CV_FOURCC(*'XVID')
... | 2 | 2016-07-07T05:39:54Z | 38,238,635 | <p><code>video_writer = cv2.VideoWriter.open("output.avi", fourcc, 20, (640, 480),True)</code> </p>
<p>gives me error. I tried </p>
<p><code>video_writer = cv2.VideoWriter("output.avi", fourcc, 20, (640, 480), True)</code> </p>
<p>and it works.</p>
<p>Also make sure you <code>release</code> <code>capture</code> and... | 0 | 2016-07-07T06:15:53Z | [
"python",
"opencv",
"raspberry-pi2"
] |
python (pandas): recombine groupby statements | 38,238,215 | <p>I have a some data that represents results in time at many different sites. I want to find the quartile break down of my results and also the max and min dates for each site.</p>
<p>Finding each of these is easy enough:</p>
<pre><code>#quartiles
q = df.groupby(['site_id', 'datum']).quantile([0.25,0.5,0.75])
#max ... | 2 | 2016-07-07T05:40:37Z | 38,238,427 | <p>This is one way to do it:</p>
<pre><code>pd.concat([d_max, d_min, q.unstack().result], axis=1, keys=['max', 'min', 'quantiles'])
</code></pre>
<p><a href="http://i.stack.imgur.com/vzgDQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/vzgDQ.png" alt="enter image description here"></a></p>
| 3 | 2016-07-07T05:58:23Z | [
"python",
"pandas"
] |
Is it possible to convert timestamps to miliseconds with Python? | 38,238,237 | <p><strong>For example i have an array with some timestamps:</strong></p>
<pre><code> 14:34:56.600
14 = hour
34 = minute
56 = seconds
600 = milliseconds
</code></pre>
<p>After the conversion I want to have a single number in milliseconds. Is this possible? </p>
| 0 | 2016-07-07T05:42:46Z | 38,238,329 | <p>This should get the job done:</p>
<pre><code>def toMS(t):
t = t.split(':')
t = t[:-1] + t[-1].split('.')
t = list(map(int, t))
ms = t[0]*3600*1000 + t[1]*60*1000 + t[2]*1000 + t[3]
return ms
</code></pre>
| 1 | 2016-07-07T05:51:27Z | [
"python",
"timestamp"
] |
devpi - pip install setup.cfg MissingSectionHeaderError - virtualenv | 38,238,277 | <p>I have a really simply python package which I'm building/uploading to a devpi repo running on my laptop. </p>
<p>When I attempt to pip install it I get the following error:</p>
<pre><code>MissingSectionHeaderError: File contains no section headers.
file: setup.cfg, line: 1
'[\n'
</code></pre>
<p>My package doesn... | 1 | 2016-07-07T05:46:31Z | 38,410,452 | <p>I haven't had any issues after I downgraded the pip versions in all my virtualenvs from <code>pip==1.8.2</code> to <code>pip==8.1.1</code></p>
| 0 | 2016-07-16T10:56:18Z | [
"python",
"python-2.7",
"pip",
"virtualenv",
"devpi"
] |
Transmit data between php server and Python desktop program and keep connection Alive | 38,238,369 | <p>i'd like to make a set up where a piece of software running on a computer (python) connects to the web-server and sends very small bits of data intermittently to the web-server and i'd like to have it a persistent connection -- one connection for, say, one day. i want to absolutely minimize the amount of data sent b... | 0 | 2016-07-07T05:54:00Z | 38,238,478 | <p>Of the top of my head 'persistent connection = keep alive headers` but that is not the best way to go with this. Have a look at websockets. PHP also has an implementation for the same <a href="http://socketo.me" rel="nofollow">here</a>
Basically the issue is PHP+apache is not designed for long process, it terminates... | 0 | 2016-07-07T06:02:56Z | [
"php",
"python",
"networking",
"server",
"push"
] |
Is there a Python inbuilt way to know why my thread exited and at what time? | 38,238,431 | <p>I have a complex code written in Python which has lot of threads and many try-catch blocks. I am using the Python's threading module for my threads. Is there a Python inbuilt way to know why my thread exited and at what time? There is some race condition in my code which I am unable to narrow down. Printing fault in... | 0 | 2016-07-07T05:58:46Z | 38,238,670 | <p>An example of informative logging based on <a href="https://docs.python.org/3.2/howto/logging-cookbook.html" rel="nofollow">this</a>, containing all the information you need, and you can change the format and add/remove attributes for more/less information you want to present in the output log.</p>
<pre><code>impor... | 0 | 2016-07-07T06:19:22Z | [
"python",
"python-multithreading"
] |
matplot program gives unresponsive window when run | 38,238,612 | <p>You'll notice that there is a bunch of missing code, it's for all the games being called from the menu. I removed it because it is long and not needed for my question. My issue is only with a particular function, <code>display_data</code>. When I call it from the menu, matplot opens in a new window and just crash... | 3 | 2016-07-07T06:14:38Z | 38,238,681 | <p>I had a similar problem a while back, try setting this line</p>
<pre><code>plt.show()
</code></pre>
<p>to</p>
<pre><code>plt.show(block=True)
</code></pre>
<p>According to the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show" rel="nofollow">docs</a> this overrides the blocking behaviour ... | 4 | 2016-07-07T06:20:14Z | [
"python",
"python-3.x",
"matplotlib"
] |
python3 singleton pattern with "with" statement | 38,238,778 | <p>I want to write a class with singleton pattern to provide some persistent data storage using pickle/dict:</p>
<pre><code>@singleton
class Pdb:
def __init__(self):
self.cache = None
self.dirty = False
try:
with open("data.pck","rb") as fp:
self.cache = pickle.l... | 0 | 2016-07-07T06:28:34Z | 38,238,899 | <blockquote>
<p>If I do it by "with" statement, I will need to pass the instance to each function that I call:</p>
</blockquote>
<p>No, you don't. Just use your singleton:</p>
<pre><code># global
db = Pdb()
# any other context
with db:
</code></pre>
<p>All that is required is that the expression <em>produces</em>... | 1 | 2016-07-07T06:36:31Z | [
"python",
"python-3.x",
"contextmanager"
] |
Drop and read index using SQLAlchemy | 38,238,858 | <p>I want to do a bulk insertion in SQL alchemy and would prefer to remove an index prior to making the insertion, reading it when the insertion is complete.</p>
<p>I see adding and removing indexes is supported by Alembic for migrations, but is this possible with SQLAlchemy? If so, how?</p>
| 0 | 2016-07-07T06:34:24Z | 38,949,945 | <p>The best method is to just execute sql. In this case<code>session.execute("DROP INDEX ...")</code></p>
| 0 | 2016-08-15T05:52:34Z | [
"python",
"sqlalchemy",
"migration"
] |
Python check if any element in a list is a key in dictionary | 38,238,861 | <p><strong>What would be the Pythonic way to check if ANY element in a list is a key in a dictionary?</strong></p>
<p>Example, I have a list of fruits:</p>
<pre><code>fruits = ['apples', 'bananas', 'pears']
</code></pre>
<p>And want to check if ANY fruit is a key in my dictionary, examples:</p>
<pre><code>fruit_dic... | 4 | 2016-07-07T06:34:31Z | 38,238,886 | <p>Pass a generator that iterates over the list to <code>any</code>:</p>
<pre><code>fruits = ['apples', 'bananas', 'pears']
fruit_dict1 = {'apples': 4, 'oranges': 3, 'dragonfruit': 4}
print(any(list_item in fruit_dict1 for list_item in fruits))
>> True
fruit_dict2 = {'oranges': 3, 'dragonfruit': 9, 'pineapples... | 2 | 2016-07-07T06:35:58Z | [
"python",
"list",
"dictionary"
] |
Python check if any element in a list is a key in dictionary | 38,238,861 | <p><strong>What would be the Pythonic way to check if ANY element in a list is a key in a dictionary?</strong></p>
<p>Example, I have a list of fruits:</p>
<pre><code>fruits = ['apples', 'bananas', 'pears']
</code></pre>
<p>And want to check if ANY fruit is a key in my dictionary, examples:</p>
<pre><code>fruit_dic... | 4 | 2016-07-07T06:34:31Z | 38,238,937 | <p>Let's define your variables:</p>
<pre><code>>>> fruits = ['apples', 'bananas', 'pears']
>>> fruit_dict1 = {'apples': 4, 'oranges': 3, 'dragonfruit': 4}
>>> fruit_dict2 = {'oranges': 3, 'dragonfruit': 9, 'pineapples': 4}
</code></pre>
<p>Now, let's test for membership:</p>
<pre><code>>... | 3 | 2016-07-07T06:39:00Z | [
"python",
"list",
"dictionary"
] |
Python check if any element in a list is a key in dictionary | 38,238,861 | <p><strong>What would be the Pythonic way to check if ANY element in a list is a key in a dictionary?</strong></p>
<p>Example, I have a list of fruits:</p>
<pre><code>fruits = ['apples', 'bananas', 'pears']
</code></pre>
<p>And want to check if ANY fruit is a key in my dictionary, examples:</p>
<pre><code>fruit_dic... | 4 | 2016-07-07T06:34:31Z | 38,238,988 | <p>Try this</p>
<pre><code>In [1]: any([i in fruit_dict1 for i in fruits])
Out[1]: True
In [2]: any([i in fruit_dict2 for i in fruits])
Out[2]: False
</code></pre>
<p><strong>Working</strong></p>
<pre><code>In [11]: [i in fruit_dict2 for i in fruits]
Out[11]: [False, False, False]
</code></pre>
<p>Which check the e... | 4 | 2016-07-07T06:42:33Z | [
"python",
"list",
"dictionary"
] |
Python check if any element in a list is a key in dictionary | 38,238,861 | <p><strong>What would be the Pythonic way to check if ANY element in a list is a key in a dictionary?</strong></p>
<p>Example, I have a list of fruits:</p>
<pre><code>fruits = ['apples', 'bananas', 'pears']
</code></pre>
<p>And want to check if ANY fruit is a key in my dictionary, examples:</p>
<pre><code>fruit_dic... | 4 | 2016-07-07T06:34:31Z | 38,239,660 | <pre><code>set(fruits) & set(fruit_dict1.keys())
</code></pre>
<p>or using Counter</p>
<pre><code>from collections import Counter
any(Counter(fruits) & Counter(fruit_dict1.keys()))
</code></pre>
| 0 | 2016-07-07T07:20:30Z | [
"python",
"list",
"dictionary"
] |
error in python install module | 38,238,920 | <p>I need to install a module <code>txsckjs</code>,but when I run <code>pip install txsockjs</code> it shows me some error and I don't know what happened.</p>
<p>The error is following:</p>
<pre><code>(venv)lk@linux-7hhe:~/MyImprove/project> pip install txsockjs
Collecting txsockjs
Using cached txsockjs-1.2.2.ta... | 0 | 2016-07-07T06:37:45Z | 38,239,101 | <p>It is possible that the version of Python you are using is not compatible with the given module.</p>
<p><a href="http://i.stack.imgur.com/siun7.png" rel="nofollow"><img src="http://i.stack.imgur.com/siun7.png" alt="enter image description here"></a></p>
<p>I have Python 3.5.2 and was able to reporduce your error. ... | 1 | 2016-07-07T06:49:06Z | [
"python",
"module",
"syntax-error"
] |
error in python install module | 38,238,920 | <p>I need to install a module <code>txsckjs</code>,but when I run <code>pip install txsockjs</code> it shows me some error and I don't know what happened.</p>
<p>The error is following:</p>
<pre><code>(venv)lk@linux-7hhe:~/MyImprove/project> pip install txsockjs
Collecting txsockjs
Using cached txsockjs-1.2.2.ta... | 0 | 2016-07-07T06:37:45Z | 38,239,143 | <p>Try replacing <code>except Exception, e</code> with <code>except Exception as e</code> in txsockjs/setup.py.</p>
<p>As underlined by SilentMonk and Saket, Python version matters in this case. See <a href="http://stackoverflow.com/questions/2535760/python-try-except-comma-vs-as-in-except">Python tryâ¦except comma v... | 0 | 2016-07-07T06:51:23Z | [
"python",
"module",
"syntax-error"
] |
REST Framework: 404 on GET | 38,238,983 | <p>I wrote an <code>@api_view</code>, but <code>rest_framework</code>doesn't want to register it. So I get 404 when send a request on <code>api/main-filter/</code>. Why?</p>
<p><strong>rest.py</strong></p>
<pre><code>@api_view(['GET'])
def main_filter_options(request):
r = {
'regions': models.Region.objec... | 1 | 2016-07-07T06:42:12Z | 38,239,396 | <p>Routers only work with <code>ViewSets</code>, not <code>APIView</code> nor function based views.</p>
<p>You need to write an explicit url just like you do with regular Django views.</p>
| 1 | 2016-07-07T07:06:09Z | [
"python",
"django",
"rest",
"django-rest-framework"
] |
Scrapy: Multiple crawler in one project | 38,239,023 | <p>I have written a web crawler using scrapy with proxies. Since I always need a pool of random proxies to avoid being banned, I decide to write another crawler that scrapes a website providing free available IPs. </p>
<p>Currently, I have the two spiders in two separate scrapy projects with different settings, pipeli... | 0 | 2016-07-07T06:44:36Z | 38,245,545 | <p>You can have 2 spiders in 1 project but you'd have to run 2 different commands anyway to crawl. What you can do is create a script that starts the process independently.</p>
<pre><code>import subprocess
p1=subprocess.Popen(["scrapy","crawl", "spider"])
p2=subprocess.Popen(["scrapy","crawl", "spider2"])
</code></pre... | 0 | 2016-07-07T12:31:06Z | [
"python",
"scrapy"
] |
Python subprocess exhibits different behavior in command line and GUI console while streaming ouput | 38,239,036 | <p>I am using subprocess of python27 lib to run a big python file(execute.py) from another python file(sample.py).</p>
<p>If I run the sample.py (which has subprocess statements) in windows command line,it is running properly and streaming the live output well.</p>
<p>But in the python GUI console,when I run the GUI ... | -1 | 2016-07-07T06:45:23Z | 38,240,690 | <p>When you run script in command line: the output will send directly to the terminal.
The Python GUI console(IDLE) base on tkinter tool kit so when you run the script:
the output will send to the buffer. The GUI tool take a bit of time to show the buffer to screen. Therefore the time to show the output will be longer... | 0 | 2016-07-07T08:21:26Z | [
"python",
"python-2.x"
] |
Python subprocess exhibits different behavior in command line and GUI console while streaming ouput | 38,239,036 | <p>I am using subprocess of python27 lib to run a big python file(execute.py) from another python file(sample.py).</p>
<p>If I run the sample.py (which has subprocess statements) in windows command line,it is running properly and streaming the live output well.</p>
<p>But in the python GUI console,when I run the GUI ... | -1 | 2016-07-07T06:45:23Z | 38,240,717 | <p>Do not set <code>stdout</code> or <code>stderr</code> if you want them to go to an outer (controlling) process.</p>
<pre><code>cmdlist = ["python", "execute.py","name","xyz"]
proc = subprocess.Popen(cmdlist)
# do other stuff here if you like
self.output.write(
"\n Finished process (%s)\n" % proc.wait() # wait un... | 0 | 2016-07-07T08:23:13Z | [
"python",
"python-2.x"
] |
Finding edges of road using opencv | 38,239,043 | <p>I am interested in finding the edges of the road. The output image should have only edges marked.
Here is one of my input image:</p>
<p><a href="http://i.stack.imgur.com/qlLXo.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/qlLXo.jpg" alt="enter image description here"></a></p>
<p>But the edges in output ar... | -1 | 2016-07-07T06:45:55Z | 38,240,386 | <p>Result can be seen <a href="http://imgur.com/Lpxtbj3" rel="nofollow">here</a>. Not perfect, but best I could do. Idea taken from <a href="http://www.pyimagesearch.com/2014/04/21/building-pokedex-python-finding-game-boy-screen-step-4-6/" rel="nofollow">here</a></p>
<p>The code works for this image on the assumption ... | 0 | 2016-07-07T08:02:59Z | [
"python",
"opencv",
"image-processing",
"computer-vision"
] |
Exception during list comprehension. Are intermediate results kept anywhere? | 38,239,281 | <p>When using try-except in a for loop context, the commands executed so far are obviously done with</p>
<pre><code>a = [1, 2, 3, 'text', 5]
b = []
try:
for k in range(len(a)):
b.append(a[k] + 4)
except:
print('Error!')
print(b)
</code></pre>
<p>results with </p>
<pre><code>Error!
[5, 6, 7]
</code><... | 18 | 2016-07-07T06:59:15Z | 38,239,480 | <p>The list comprehension intermediate results are kept on an internal CPython stack, and are not accessible from the Python expressions that are part of the list comprehension.</p>
<p>Note that Python executes the <code>[.....]</code> <strong>first</strong>, which produces a list object, and only <strong>then</strong... | 26 | 2016-07-07T07:10:30Z | [
"python",
"list-comprehension"
] |
Exception during list comprehension. Are intermediate results kept anywhere? | 38,239,281 | <p>When using try-except in a for loop context, the commands executed so far are obviously done with</p>
<pre><code>a = [1, 2, 3, 'text', 5]
b = []
try:
for k in range(len(a)):
b.append(a[k] + 4)
except:
print('Error!')
print(b)
</code></pre>
<p>results with </p>
<pre><code>Error!
[5, 6, 7]
</code><... | 18 | 2016-07-07T06:59:15Z | 38,240,321 | <p>Let's look at the bytecode:</p>
<pre><code>>>> def example():
... c=[]
... try:
... c = [a[k] + 4 for k in range(len(a))]
... except:
... print('Error!')
... print(c)
...
>>> import dis
>>> dis.dis(example)
--- removed some instructions
... | 11 | 2016-07-07T07:59:14Z | [
"python",
"list-comprehension"
] |
re.finditer search string not found - how to implement | 38,239,343 | <p>In a python script I am using re.finditer for finding strings inside a text file.</p>
<p>How do I know if re.finditer does not find a specific string?</p>
<p>I tried with</p>
<pre><code>for n in re.finditer("string",line2):
if n.start() == "":
print("empty")
</code></pre>
<p>But this does not work. <... | -3 | 2016-07-07T07:02:24Z | 38,239,539 | <p>With those requirements, you could do something like:</p>
<pre><code>n = re.finditer(pattern, line2)
try:
first_item = next(n)
#do something with the rest of the iterable eg:
print(first_item)
for item in n:
print(n)
except StopIteration:
print("empty")
</code></pre>
| 0 | 2016-07-07T07:13:56Z | [
"python",
"text"
] |
re.finditer search string not found - how to implement | 38,239,343 | <p>In a python script I am using re.finditer for finding strings inside a text file.</p>
<p>How do I know if re.finditer does not find a specific string?</p>
<p>I tried with</p>
<pre><code>for n in re.finditer("string",line2):
if n.start() == "":
print("empty")
</code></pre>
<p>But this does not work. <... | -3 | 2016-07-07T07:02:24Z | 38,239,738 | <p>If the regex pattern is not matched anywhere in the text you're searching, <code>finditer</code> will return an empty iterable. That is, your <code>for</code> loop will never run the code in the indented block.</p>
<p>There are a few ways you could detect this. One might be to set an initial value for the <code>n</... | 0 | 2016-07-07T07:25:50Z | [
"python",
"text"
] |
re.finditer search string not found - how to implement | 38,239,343 | <p>In a python script I am using re.finditer for finding strings inside a text file.</p>
<p>How do I know if re.finditer does not find a specific string?</p>
<p>I tried with</p>
<pre><code>for n in re.finditer("string",line2):
if n.start() == "":
print("empty")
</code></pre>
<p>But this does not work. <... | -3 | 2016-07-07T07:02:24Z | 38,245,221 | <p>In Python, all control structures have an optional <code>else</code> branch.</p>
<pre><code>line2 = 'no match'
for n in re.finditer("string",line2):
print('match')
else:
print("empty")
</code></pre>
<p>Demo: <a href="http://ideone.com/OMVHg4" rel="nofollow">http://ideone.com/OMVHg4</a></p>
| 0 | 2016-07-07T12:14:40Z | [
"python",
"text"
] |
run python script with pyspark settings | 38,239,353 | <p>I have Spark configuration in spark-defaults.conf, xml files: core-site.xml, hive-site.xml, and I exported environment variables. When I run pyspark console:</p>
<pre><code>$ pyspark --master yarn
</code></pre>
<p>and then:</p>
<pre><code>>>> sqlContext.sql("show tables").show()
</code></pre>
<p>everyth... | 0 | 2016-07-07T07:03:14Z | 38,241,280 | <p>My understanding is that when you run the PySpark Shell, Spark is instantiated with support for Hive i.e <code>HiveContext</code>, which defaults to <code>SQLContext</code>.</p>
<p>But while running a Python Program or the Python Interpreter, as in your case, the SQLContext does not come with Hive support.</p>
<p>... | 0 | 2016-07-07T08:56:10Z | [
"python",
"pyspark"
] |
IOError for oauth2.request when used with mod_wsgi + Apache | 38,239,355 | <p>For a third party API, I'm using oauth2 module, I have following code:
Which works well when I use <code>python run.py</code> but throws <code>IOError</code> permission denied when using <code>apache +mod_wsgi</code> configuration.</p>
<p>Here is the error:</p>
<pre><code>ERROR: Traceback (most recent call last):
... | 0 | 2016-07-07T07:03:18Z | 38,242,285 | <p>There was an issue with permissions to my virtualenv. Following file had permission issues. </p>
<pre><code>myenv/lib/python2.7/site-packages/httplib2-0.9.2-py2.7.egg/httplib2/cacerts.txt
</code></pre>
<p>And this simple fix fixed my issue:</p>
<pre><code>chmod -R 755 /home/trex/workspace/myenv
</code></pre>
| 1 | 2016-07-07T09:43:46Z | [
"python",
"apache",
"flask",
"mod-wsgi"
] |
Creating tokens from list of sentences is returning characters instead of words | 38,239,429 | <pre><code>from nltk.tokenize import sent_tokenize
text = open(path).read().lower().decode("utf8")
sent_tokenize_list = sent_tokenize(text)
tokens = [w for w in itertools.chain(*[sent for sent in sent_tokenize_list])]
</code></pre>
<p>The last line, "tokens", returns characters instead of words. </p>
<p>Why is this... | 0 | 2016-07-07T07:07:48Z | 38,239,676 | <p>Because <a href="http://www.nltk.org/api/nltk.tokenize.html#nltk.tokenize.sent_tokenize" rel="nofollow"><code>sent_tokenize</code></a> returns a list of string sentences and <a href="https://docs.python.org/3/library/itertools.html#itertools.chain" rel="nofollow"><code>itertools.chain</code></a> chains iterables to ... | 2 | 2016-07-07T07:22:00Z | [
"python",
"text",
"nlp",
"nltk",
"tokenize"
] |
Creating tokens from list of sentences is returning characters instead of words | 38,239,429 | <pre><code>from nltk.tokenize import sent_tokenize
text = open(path).read().lower().decode("utf8")
sent_tokenize_list = sent_tokenize(text)
tokens = [w for w in itertools.chain(*[sent for sent in sent_tokenize_list])]
</code></pre>
<p>The last line, "tokens", returns characters instead of words. </p>
<p>Why is this... | 0 | 2016-07-07T07:07:48Z | 38,239,805 | <p>May be you should to use <code>word_tokenize</code> instead of <code>sent_tokenize</code>?</p>
<pre><code>from nltk.tokenize import work_tokenize
text = open(path).read().lower().decode("utf8")
tokens = word_tokenize(text)
</code></pre>
<p><a href="http://www.nltk.org/api/nltk.tokenize.html#nltk.tokenize.word_tok... | 1 | 2016-07-07T07:29:49Z | [
"python",
"text",
"nlp",
"nltk",
"tokenize"
] |
Creating tokens from list of sentences is returning characters instead of words | 38,239,429 | <pre><code>from nltk.tokenize import sent_tokenize
text = open(path).read().lower().decode("utf8")
sent_tokenize_list = sent_tokenize(text)
tokens = [w for w in itertools.chain(*[sent for sent in sent_tokenize_list])]
</code></pre>
<p>The last line, "tokens", returns characters instead of words. </p>
<p>Why is this... | 0 | 2016-07-07T07:07:48Z | 38,258,012 | <p>Firstly, if the file is in 'utf8' and you're using Python2, it'll be better if you use the <code>encoding='utf8'</code> parameter in <a href="https://docs.python.org/2/library/io.html" rel="nofollow"><code>io.open()</code></a>:</p>
<pre><code>import io
from nltk import word_tokenize, sent_tokenize
with io.open('f... | 1 | 2016-07-08T02:17:57Z | [
"python",
"text",
"nlp",
"nltk",
"tokenize"
] |
python - FIX protocol simple test logon | 38,239,594 | <p>I just started trying to connect to my broker through the FIX protocol.</p>
<p>The broker gave me:</p>
<ul>
<li>an IP:port address to connect to</li>
<li>a "sendercompid" </li>
<li>a "targetcompid"</li>
<li>a password</li>
</ul>
<p>I would like, as a first test, simply send a logon message to the broker and hopef... | -2 | 2016-07-07T07:16:36Z | 38,241,265 | <p>Well, there's no standard python library for that.</p>
<p>You mentioned <a href="https://github.com/quickfix/quickfix/tree/master/src/python" rel="nofollow">quickfix</a>, what is a big project that seems maintained, and has documentation.</p>
<p>Looking for other third-party libraries, there is a smaller one, yet ... | 1 | 2016-07-07T08:55:14Z | [
"python",
"linux",
"fix"
] |
Find value in dataframe row - create new column highlighting next row match | 38,239,617 | <p>I'm trying to find a value in a Pandas dataframe row and create a new column highlighting if the next row is a match. So for the following example:</p>
<pre><code>rng = pd.DataFrame( {'test_1': ['A', 'A','A', 'A', 'B','B', 'A' , 'A', 'A', 'A','A' , 'A', 'A', 'A',]}, index = pd.date_range('4/2/2014', periods=14, f... | 2 | 2016-07-07T07:18:08Z | 38,239,838 | <p>You can define a func that takes your value and returns whether any rows meets your condition, this will work for any value you pass, the boolean series is then cast to <code>int</code> so it converts <code>True</code> and <code>False</code> to <code>1</code> and <code>0</code> respectively:</p>
<pre><code>In [220]... | 2 | 2016-07-07T07:31:15Z | [
"python",
"pandas"
] |
Django websockets implementation | 38,239,618 | <p>I'm new to python and Django and i'm trying to implement websockets in Django.<br>
What i do is i'm following the steps described in <a href="https://websockets.readthedocs.io/en/stable/intro.html#browser-based-example" rel="nofollow">websockets documentation</a><br>
The problem is that the server side command descr... | 0 | 2016-07-07T07:18:10Z | 38,240,301 | <p>Django's request/response cycle is strictly synchronous. What you are trying to do is not possible in a normal Django view.</p>
<p>You might be interested in <a href="http://channels.readthedocs.io/en/latest/" rel="nofollow">Django Channels</a>, a project that aims to remove this limitation.</p>
| 1 | 2016-07-07T07:58:16Z | [
"python",
"django",
"websocket",
"django-views"
] |
Django websockets implementation | 38,239,618 | <p>I'm new to python and Django and i'm trying to implement websockets in Django.<br>
What i do is i'm following the steps described in <a href="https://websockets.readthedocs.io/en/stable/intro.html#browser-based-example" rel="nofollow">websockets documentation</a><br>
The problem is that the server side command descr... | 0 | 2016-07-07T07:18:10Z | 38,240,307 | <p>You can't really do this. I can't say why you're getting the exact errors you're getting, but a GET request to a Django view needs to return a response after some finite time, not run forever, otherwise the browser (or other parts in between like Nginx) will see the non-response as a timeout. If you want to run a we... | 1 | 2016-07-07T07:58:28Z | [
"python",
"django",
"websocket",
"django-views"
] |
How to set index of QTreeView as first item in tree automatically | 38,239,819 | <p>I have a program that when clicking an item in a QTreeView shows details about the item and at the click of a button you can open the file, however if no file is selected the program closes. I have tried <code>setCurrentIndex()</code> however I'm not sure if I'm using it right at the only exampled i can find are PyQ... | 0 | 2016-07-07T07:30:32Z | 38,302,664 | <p><code>self.file_model.index(0,0)</code> just gives you the information of the root directory, in your case, <code>C:</code>. What you need to do, is wait for the <code>directoryLoaded( QString )</code> signal to be emitted, then choose the index at <code>(0, 0)</code></p>
<p>Here is the simplified version of the co... | 1 | 2016-07-11T08:45:42Z | [
"python",
"pyqt5",
"qtreeview"
] |
selenium python click link open in other window, need same | 38,239,869 | <pre><code>myLink = myDriver.find_element_by_xpath ('....')
myLink.click()
bmyLink = WebDriverWait(myDriver, 10).until(ExConditions.presence_of_element_located((By.XPATH, '.....')))
</code></pre>
<p>I use <code>selenium</code> with <code>Firefox</code> driver <code>Python</code> 3.5. I noted that after <code>click()</... | 0 | 2016-07-07T07:32:59Z | 38,240,337 | <p>If after first <code>click()</code>.. open a new window, you need to switch that new window first then go to find the link as below :-</p>
<pre><code>myLink = myDriver.find_element_by_xpath ('....')
myLink.click()
currentWindow = myDriver.current_window_handle
#store current window for backup to switch back
for ... | 2 | 2016-07-07T08:00:09Z | [
"python",
"selenium"
] |
Latex not displayed correctly in matplotlib | 38,239,882 | <p>When executing the following code in python using jupyter/ipython, the Latex symbols are not displayed correctly. Any Idea why this could be?</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
x = np.linspace(0,3)
y = np.sin(x)
plt.plot(x,y)
plt.title(r'$\beta \rho \lambda \xi$',f... | 2 | 2016-07-07T07:33:55Z | 38,239,998 | <p>IPython notebook uses <a href="https://www.mathjax.org" rel="nofollow">MathJax</a> to render LaTeX inside html/markdown. Just put your LaTeX math inside $$.</p>
<pre><code>$$c = \sqrt{a^2 + b^2}$$
</code></pre>
<p><a href="http://i.stack.imgur.com/M51xG.png" rel="nofollow"><img src="http://i.stack.imgur.com/M51xG.... | 2 | 2016-07-07T07:40:51Z | [
"python",
"matplotlib",
"latex",
"jupyter"
] |
what is the difference between var.op.name and var.name in tensorflow? | 38,240,050 | <p>I have one point confusing. Here is the example code:</p>
<pre><code>opt = tf.train.GradientDescentOptimizer(1e-4)
grads_and_vars = opt.compute_gradients(total_loss)
for grad, var in grads_and_vars:
print(var.op.name)
</code></pre>
<p>the output is: <code>conv1/filt conv1/bias</code></p>
<p>and... | 0 | 2016-07-07T07:43:45Z | 38,240,380 | <p>From my understanding, OP is just added to initialize all variables. The :0 is just the first output, so if there was another conv1/filt it would be presented as conv1/filt:1.</p>
| 0 | 2016-07-07T08:02:28Z | [
"python",
"tensorflow",
"deep-learning"
] |
what is the difference between var.op.name and var.name in tensorflow? | 38,240,050 | <p>I have one point confusing. Here is the example code:</p>
<pre><code>opt = tf.train.GradientDescentOptimizer(1e-4)
grads_and_vars = opt.compute_gradients(total_loss)
for grad, var in grads_and_vars:
print(var.op.name)
</code></pre>
<p>the output is: <code>conv1/filt conv1/bias</code></p>
<p>and... | 0 | 2016-07-07T07:43:45Z | 38,241,255 | <p><code>op.name</code> is the name of the Operation, while <code>var.name</code> is the name of the Tensor. Operation is the thing that allocates memory, and produces outputs available on endpoints :0, :1, etc. Tensor is an output of an operation, so it corresponds to some endpoint. In this case <code>conv1/filt</code... | 1 | 2016-07-07T08:54:41Z | [
"python",
"tensorflow",
"deep-learning"
] |
Frequent Patter growth in R or Python | 38,240,190 | <p>Apriori algorithm is old and slow. Frequent pattern trees are much faster. However, I can't find frequent pattern tree libraries neither in R or in Python.
I'm sure they exists somewhere.
I'm not talking about home made code that can be found on the internet somewhere.
Does anyone know any Frequent Pattern Library?<... | 0 | 2016-07-07T07:51:02Z | 38,243,827 | <p>Take a look at this link and see if it provides what you need:</p>
<p><a href="http://www.borgelt.net/pyfim.html" rel="nofollow">PyFIM - Frequent Item Set Mining for Python</a></p>
| 0 | 2016-07-07T11:01:46Z | [
"python"
] |
Frequent Patter growth in R or Python | 38,240,190 | <p>Apriori algorithm is old and slow. Frequent pattern trees are much faster. However, I can't find frequent pattern tree libraries neither in R or in Python.
I'm sure they exists somewhere.
I'm not talking about home made code that can be found on the internet somewhere.
Does anyone know any Frequent Pattern Library?<... | 0 | 2016-07-07T07:51:02Z | 38,248,275 | <p>FP-Growth is one algorithm which extracts frequent itemsets based on trees. For R please take a look here <a href="https://en.wikibooks.org/wiki/Data_Mining_Algorithms_In_R/Frequent_Pattern_Mining/The_FP-Growth_Algorithm" rel="nofollow">https://en.wikibooks.org/wiki/Data_Mining_Algorithms_In_R/Frequent_Pattern_Minin... | 1 | 2016-07-07T14:35:45Z | [
"python"
] |
Making new list of lists from elements of some other lists | 38,240,194 | <p>I have below list of lists:</p>
<pre><code>Points = [['A', 1.01, 0.11], ['B', 0.97, 0.14], ['C', 1.05, 0.15], ['D', 0.96, 0.14], ['E', 1.55, 0.22], ['F', 1.06, 0.04], ['G', 0.88, 0.15], ['H', 0.80, 0.21], ['I', 0.87, 0.19], ['J', 0.80, 0.30]]
Origin = [['J', 0.80, 0.30]]
Distance = [0.28, 0.23, 0.30, 0.22, 0.75, ... | -4 | 2016-07-07T07:51:14Z | 38,240,269 | <p>This is how you can do it.</p>
<pre><code>list = []
for i in range(len(Points)):
element = []
element.append(Points[i][0])
element.append(Origin[0][0])
element.append(Distance[i])
list.append(element)
print list
</code></pre>
| 0 | 2016-07-07T07:56:07Z | [
"python",
"list"
] |
Making new list of lists from elements of some other lists | 38,240,194 | <p>I have below list of lists:</p>
<pre><code>Points = [['A', 1.01, 0.11], ['B', 0.97, 0.14], ['C', 1.05, 0.15], ['D', 0.96, 0.14], ['E', 1.55, 0.22], ['F', 1.06, 0.04], ['G', 0.88, 0.15], ['H', 0.80, 0.21], ['I', 0.87, 0.19], ['J', 0.80, 0.30]]
Origin = [['J', 0.80, 0.30]]
Distance = [0.28, 0.23, 0.30, 0.22, 0.75, ... | -4 | 2016-07-07T07:51:14Z | 38,247,042 | <p>A pythonic implementation.</p>
<pre><code>[i.append(Origin[0][0]) for i in Points]
print [[item1[0],item1[-1],item2] for item1,item2 in zip(Points,Distance)]
</code></pre>
<p><strong>Result</strong></p>
<pre><code>[['A', 'J', 0.28], ['B', 'J', 0.23], ['C', 'J', 0.3], ['D', 'J', 0.22], ['E', 'J', 0.75], ['F', 'J',... | 0 | 2016-07-07T13:40:51Z | [
"python",
"list"
] |
Python: sorting a zip based on length and weight | 38,240,236 | <p>In Python 2, assume we have two lists:</p>
<pre><code>list1 = [["A"],["A","B"],["B","D"],["C"],["A","B","D"]]
list2 = [5,10,10,15,10]
</code></pre>
<p>I want to sort list1 based on list2 (weights) in descending and whenever the weight of two items are the same (for example both x = ["A","B","D"] and y = ["B","D"] ... | 0 | 2016-07-07T07:53:34Z | 38,240,402 | <p>In order to sort by several parameters your <code>key</code> function should return a tuple:</p>
<pre><code>In [6]: sorted(zip(list1, list2), key=lambda x: (x[1], len(x[0])), reverse=True)
Out[6]:
[(['C'], 15),
(['A', 'B', 'D'], 10),
(['A', 'B'], 10),
(['B', 'D'], 10),
(['A'], 5)]
</code></pre>
<p>The <code>k... | 5 | 2016-07-07T08:03:30Z | [
"python",
"sorting"
] |
Python: sorting a zip based on length and weight | 38,240,236 | <p>In Python 2, assume we have two lists:</p>
<pre><code>list1 = [["A"],["A","B"],["B","D"],["C"],["A","B","D"]]
list2 = [5,10,10,15,10]
</code></pre>
<p>I want to sort list1 based on list2 (weights) in descending and whenever the weight of two items are the same (for example both x = ["A","B","D"] and y = ["B","D"] ... | 0 | 2016-07-07T07:53:34Z | 38,240,406 | <p>Your key function needs to tell <code>sort</code> to check the length of the <code>list1</code> item when the <code>list2</code> weights are identical. You can do that by making the key a tuple, like this:</p>
<pre><code>list1 = [["A"],["A","B"],["B","D"],["C"],["A","B","D"]]
list2 = [5,10,10,15,10]
zipped = zip(l... | 3 | 2016-07-07T08:03:52Z | [
"python",
"sorting"
] |
Remove child xml element with specific attribute in python | 38,240,273 | <p>my first question </p>
<p>I am trying to clear up eshop database dump of products that either don't have price or quantity set. So I only get ready to sell products. I am trying to do this via python script.
After the script failed to do what I intended I tried making testing script.</p>
<p>input file test.xml</p>... | 0 | 2016-07-07T07:56:18Z | 38,240,646 | <p>The problem is that you modify the tree while you iterate over it.</p>
<p>Instead of</p>
<pre><code>for child in root:
</code></pre>
<p>use</p>
<pre><code>for child in tree.findall('.//StoItem'):
</code></pre>
<p>See this <a href="http://stackoverflow.com/questions/22817530/elementtree-element-remove-jumping-it... | 0 | 2016-07-07T08:18:43Z | [
"python",
"xml"
] |
Pychecker index error on first run | 38,240,391 | <p>I've just installed pychecker on windows 7 Pro using "python setup.py install". When I run it on my script using the command:</p>
<pre><code>c:\Python26\Scripts\pychecker -#100 finaltest17.py
</code></pre>
<p>I get the following error/traceback:</p>
<pre><code>C:\Users\....\ToBeReleased>C:\Python26\python.exe ... | -1 | 2016-07-07T08:03:09Z | 38,246,245 | <p>Problem resolved.
I found the following support request on SourceForge which refers to a need to use short format (8.3) path and filenames in pychecker.bat and not long format as is allowed in newer versions of Windows.
<a href="https://sourceforge.net/p/pychecker/support-requests/7/#96cb" rel="nofollow">https://sou... | 0 | 2016-07-07T13:04:10Z | [
"python",
"python-2.6",
"pychecker"
] |
pandas dataframe reshape after pivot | 38,240,407 | <p>The pivot code:</p>
<pre><code>result = pandas.pivot_table(result, values=['value'], index=['index'], columns=['columns'], fill_value=0)
</code></pre>
<p>The result: </p>
<pre><code> value value value
columns col1 col2 col3
index
idx1 14 1 1
idx2 2 0 1
idx3 ... | 1 | 2016-07-07T08:03:52Z | 38,240,451 | <p>You need remove <code>index name</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#changes-to-rename" rel="nofollow"><code>rename_axis</code></a> (new in <code>pandas</code> <code>0.18.0</code>):</p>
<pre><code>df = df.rename_axis(None)
</code></pre>
<p>If need also remove <code>columns ... | 2 | 2016-07-07T08:06:36Z | [
"python",
"pandas",
"dataframe",
"pivot-table"
] |
pandas dataframe reshape after pivot | 38,240,407 | <p>The pivot code:</p>
<pre><code>result = pandas.pivot_table(result, values=['value'], index=['index'], columns=['columns'], fill_value=0)
</code></pre>
<p>The result: </p>
<pre><code> value value value
columns col1 col2 col3
index
idx1 14 1 1
idx2 2 0 1
idx3 ... | 1 | 2016-07-07T08:03:52Z | 38,240,685 | <p>Consider this dataframe:</p>
<pre><code>results = pd.DataFrame(
[
[14, 1, 1],
[2, 0, 1],
[6, 0, 0]
],
pd.Index(['idx1', 'idx2', 'idx3'], name='index'),
pd.MultiIndex.from_product([['value'], ['col1', 'col2', 'col3']], names=[None, 'columns'])
)
print results
value ... | 1 | 2016-07-07T08:21:16Z | [
"python",
"pandas",
"dataframe",
"pivot-table"
] |
Unable to print additional detail (tag_name & region) while subtracting 2 sets() | 38,240,495 | <p>I have 2 pickel files which hold the IPaddress along with the ports , aws_tags and region information assocaiated with them. This is basically a port scanner which has a method which prints when a new IP addresss is found. This is done by subtracting the NEW_pickel_scan with OLD_pickel_scan as follows :</p>
<pre><c... | 0 | 2016-07-07T08:09:19Z | 38,240,585 | <pre><code> result_new_hosts = self.curr_hosts - self.prev_hosts
print mapping[result_new_hosts]
</code></pre>
<p><code>result_new_hosts</code> is a <code>set</code>, and as the error says, sets are unhashable therefore can't be stored or looked up in a dictionary.</p>
<p>Instead, you should search each individual ... | 1 | 2016-07-07T08:14:23Z | [
"python",
"pickle",
"nmap",
"port-scanning"
] |
"Can't assign to function call" Python error | 38,240,666 | <pre><code>import sys
import os.path
class Juvenile(object):
def createJuv(self, pop, rate):
self.pop = pop
self.rate = rate
def displayJuvpop(self):
return self.pop
def displayjuvRate(self):
return self.rate
class Adult(object):
def createAd(self, pop, rate, brate):
... | -2 | 2016-07-07T08:20:01Z | 38,240,722 | <p>Your <code>display*pop()</code> functions return a <strong>value</strong>, not a variable. You can't assign to that function result. Just assign directly to the attributes:</p>
<pre><code>a.pop = newjuv
b.pop = newsen
c.pop = newadu
</code></pre>
| 1 | 2016-07-07T08:23:23Z | [
"python"
] |
type error while parsing json output python | 38,240,681 | <p>i'm trying to parse some fields of a json, that is an output for a command line. but i can't access to any field, i've always this error : </p>
<pre><code>TypeError: 'int' object has no attribute '__getitem__'
</code></pre>
<p>my json output is like this : </p>
<pre><code>{"result":"success","totalresults":"1","s... | 0 | 2016-07-07T08:21:02Z | 38,240,827 | <p>The problem is that <code>subprocess.call</code> returns the <em>resultcode</em> of the execution; which is either 0 (if successful) or any other positive integer if there is an error condition.</p>
<p>Now, when you execute <code>output['result']</code>, it is the same as doing <code>0['result']</code> which doesn'... | 2 | 2016-07-07T08:30:29Z | [
"python",
"json",
"subprocess",
"whmcs"
] |
Create new variable based on groupby in Python | 38,240,686 | <p>I have a dataframe as below:</p>
<p><strong>I/P:</strong></p>
<pre><code>id day start location value match
4413869 16080 360 5000 2 1
4413869 16080 360 5000 3 1
4413869 16080 360 5000 5 1
4413869 16080 360 5000 16 1
4413869 16080 360 5015 1 1
4413869 16080 361 -1 ... | 1 | 2016-07-07T08:21:17Z | 38,241,121 | <p>Use <code>cumsum</code> over <code>match</code> in your <code>groupby</code></p>
<pre><code>df['new_var'] = df.groupby(['id', 'day', 'start', 'location']).match.cumsum()
df.head()
</code></pre>
<p><a href="http://i.stack.imgur.com/XuH5l.png" rel="nofollow"><img src="http://i.stack.imgur.com/XuH5l.png" alt="enter i... | 0 | 2016-07-07T08:47:31Z | [
"python",
"pandas"
] |
How do I read twitter data saved in a txt file? | 38,240,799 | <p>I have used the twitter streaming API to gather a large number of tweets in python.</p>
<p>All tweets are dumped in a txt file.</p>
<pre><code>{"created_at":"Sun Jul 03 15:23:11 +0000 2016","id":749624538015621120,"id_str":"749624538015621120","text":"Et hop un petit muldo dor\u00e9-indigo #enroutepourlaG2","sourc... | -5 | 2016-07-07T08:29:02Z | 38,241,103 | <p>Since what you have is valid JSON, you can use a JSON parser:</p>
<pre><code>import json
json_string = r'''{"created_at":"Sun Jul 03 15:23:11 +0000 2016","id":749624538015621120,"id_str":"749624538015621120","text":"Et hop un petit muldo dor\u00e9-indigo #enroutepourlaG2","source":"\u003ca href=\"http:\/\/twitter.... | 1 | 2016-07-07T08:46:07Z | [
"python",
"regex",
"twitter",
"tweepy",
"data-cleaning"
] |
Can i dereference an lxml.etree.AncestorsIterator? | 38,240,891 | <p>I'm using lxml to manipulate a dbschema expressed in an xml file. It looks something like this:</p>
<pre><code><Tables>
<Table name = "table1">
<Columns>
<Column name="COL1">...</Column>
<Column name="COL2">...
<References>
<Reference>TABLENAME</Reference&... | 1 | 2016-07-07T08:34:04Z | 38,243,895 | <p>You can do it using an xpath to get both the ancestors you want</p>
<pre><code>x = """<?xml version="1.0" encoding="utf-8"?>
<Tables>
<Table name = "table1">
<Columns>
<Column name="COL1">...</Column>
<Column name="COL2">...
<References>
<Reference>TABLE... | 0 | 2016-07-07T11:05:41Z | [
"python",
"lxml"
] |
Can i dereference an lxml.etree.AncestorsIterator? | 38,240,891 | <p>I'm using lxml to manipulate a dbschema expressed in an xml file. It looks something like this:</p>
<pre><code><Tables>
<Table name = "table1">
<Columns>
<Column name="COL1">...</Column>
<Column name="COL2">...
<References>
<Reference>TABLENAME</Reference&... | 1 | 2016-07-07T08:34:04Z | 38,244,182 | <p>As you are interested in only the first result of the iterator, you can use the <code>next</code> method to get the first element, and avoid the unclear/unnecessary <code>for</code> loop.</p>
<pre><code>xml_string = """
<Tables>
<Table name = "table1">
<Columns>
<Column name="COL1">...</C... | 0 | 2016-07-07T11:21:29Z | [
"python",
"lxml"
] |
Installing python3 and beautifulsoup coding in Xcode to Mac | 38,240,926 | <p>I followed this url from:<a href="http://i.stack.imgur.com/6q3ua.png" rel="nofollow">https://stringpiggy.hpd.io/mac-osx-python3-dual-install/</a> and checked python version.</p>
<pre><code>Python --version
>> Python 3.5.2
which python3
>> /Library/Frameworks/Python.framework/Versions/3.5/bin/python3
e... | 1 | 2016-07-07T08:36:24Z | 38,241,692 | <p>You have named your script <em>python.py</em> so that is why you are seeing the error:</p>
<pre><code>padraic@home:~$ touch python.py
padraic@home:~$ echo "import urllib.request" > python.py
padraic@home:~$ cat python.py
import urllib.request
padraic@home:~$ python python.py
Traceback (most recent call last):... | 0 | 2016-07-07T09:16:59Z | [
"python",
"xcode",
"osx",
"python-3.x",
"beautifulsoup"
] |
Python: Check if any of the words in a list are present in a document | 38,240,963 | <p>I am trying to 'teach' myself Python. Currently I am using the free Python course available on Udacity. I am also reading HTLPTHW. </p>
<p>One of the modules is a bit dated, and asks that you use the URLLIB module for a website that is now defunct. What it did was state True / False, based on if a curse word was pr... | 2 | 2016-07-07T08:38:17Z | 38,241,140 | <p>Let's try to do it explicitly : </p>
<pre><code>def check_profanity(document_to_check):
Word_db = ["F***","S***","A**"]
with open(document_to_check) as quotes: # let's open the document
for line in quotes: # parse it line by line
for word in Word_db: ... | 0 | 2016-07-07T08:48:23Z | [
"python",
"list",
"keyword"
] |
Python: Check if any of the words in a list are present in a document | 38,240,963 | <p>I am trying to 'teach' myself Python. Currently I am using the free Python course available on Udacity. I am also reading HTLPTHW. </p>
<p>One of the modules is a bit dated, and asks that you use the URLLIB module for a website that is now defunct. What it did was state True / False, based on if a curse word was pr... | 2 | 2016-07-07T08:38:17Z | 38,242,061 | <p>Since you already read the contents of the file in <code>read_text()</code> you don't have to read the file again in <code>check_profanity()</code></p>
<p>Also, the line <code>if str(Word_db) in quotes.read():</code> converts the list to a string and checks if it is present in the file. It is equivalent to:</p>
<p... | 0 | 2016-07-07T09:33:52Z | [
"python",
"list",
"keyword"
] |
Selecting items in a dataframe until a certain date (python, datetime) | 38,241,027 | <p>I have a dataframe DF having a column 'myDate' such that:</p>
<pre><code>>>> type(DF['myDate'][0])
3: <type 'datetime.date'>
>>> print(DF['myDate'][0])
2013-06-15
</code></pre>
<p>So, the column is of type "datetime.date".
In order to select only the items belonging to the year 2014 I tried... | 0 | 2016-07-07T08:41:38Z | 38,241,061 | <p>You have an excessive pair of <code>[]</code>:</p>
<p><code>DF[[DF['myDate'] < datetime.date(year = 2015, month = 1, day = 1)]]</code></p>
<p>should be</p>
<p><code>DF[DF['myDate'] < datetime.date(year = 2015, month = 1, day = 1)]</code></p>
| 1 | 2016-07-07T08:43:37Z | [
"python",
"datetime",
"dataframe"
] |
Python: open file in network drive | 38,241,052 | <p>I am trying to use a script to open a file inside a network drive using python. The script is given below:</p>
<pre><code>import os
import subprocess
file_path = r"O:\XXXX\test.xls"
subprocess.Popen(filepath, shell=True)
</code></pre>
<p>The network drive requires sign in but I always by default sign it the momen... | 0 | 2016-07-07T08:42:53Z | 38,245,362 | <p>I think this could help you</p>
<pre><code>import subprocess
file_path = r"X:\dir\excelfile.xlsx"
#~ also this works
#~ file_path = r"\\server\dir\excelfile.xlsx"
subprocess.call(file_path,shell = True)
</code></pre>
| 0 | 2016-07-07T12:22:07Z | [
"python",
"subprocess"
] |
Python: open file in network drive | 38,241,052 | <p>I am trying to use a script to open a file inside a network drive using python. The script is given below:</p>
<pre><code>import os
import subprocess
file_path = r"O:\XXXX\test.xls"
subprocess.Popen(filepath, shell=True)
</code></pre>
<p>The network drive requires sign in but I always by default sign it the momen... | 0 | 2016-07-07T08:42:53Z | 38,258,058 | <p>Thanks to @J.F. Sebastian's suggestion. replacing <code>subprocess.Popen(filepath, shell=True)</code> with <code>os.startfile(filepath)</code> works.</p>
| 1 | 2016-07-08T02:23:37Z | [
"python",
"subprocess"
] |
Input shape for Keras LSTM/GRU language model | 38,241,134 | <p>I am trying to train a language model on word level in Keras. </p>
<p>I have my X and Y, both with the shape (90582L, 517L)</p>
<p>When I try fit this model:</p>
<pre><code>print('Build model...')
model = Sequential()
model.add(GRU(512, return_sequences=True, input_shape=(90582, 517)))
model.add(Dropout(0.2))
mod... | 0 | 2016-07-07T08:48:01Z | 38,246,784 | <p>It depends on what you are trying to do. I guess that your data of shape (90582, 517) is a set of 90582 samples with 517 words each. If so, you have to transform your words into word vectors (=embeddings) in order for them to be meaningful. Then you will have the shape (90582, 517, embedding_dim), which can be handl... | 1 | 2016-07-07T13:28:37Z | [
"python",
"nlp",
"keras",
"lstm",
"language-model"
] |
Weighted average using numpy.average | 38,241,174 | <p>I have an array:</p>
<pre><code>In [37]: bias_2e13 # our array
Out[37]:
[1.7277990734072355,
1.9718263893212737,
2.469657573252167,
2.869022991373125,
3.314720313010104,
4.232269039271717]
</code></pre>
<p>The error on each value in the array is:</p>
<pre><code>In [38]: bias_error_2e13 # the error on each v... | 1 | 2016-07-07T08:50:02Z | 38,241,281 | <p>Because all of the errors have the same <em>relative weight</em>. Supplying a <code>weight</code> parameter <strong>does not</strong> change the actual values you are averaging, it just indicates the weight with which each value value contributes to the average. In other words, after multiplying each value passed by... | 4 | 2016-07-07T08:56:12Z | [
"python",
"python-2.7",
"numpy",
"average",
"weighted-average"
] |
Weighted average using numpy.average | 38,241,174 | <p>I have an array:</p>
<pre><code>In [37]: bias_2e13 # our array
Out[37]:
[1.7277990734072355,
1.9718263893212737,
2.469657573252167,
2.869022991373125,
3.314720313010104,
4.232269039271717]
</code></pre>
<p>The error on each value in the array is:</p>
<pre><code>In [38]: bias_error_2e13 # the error on each v... | 1 | 2016-07-07T08:50:02Z | 38,241,299 | <p>From scipy.org about numpy average: "An array of weights associated with the values in a. Each value in a contributes to the average according to its associated weight."
That means that the errors contribute relative to the average! So a multiplication of the erros with the same factor doesn't change anything! Try m... | 0 | 2016-07-07T08:57:11Z | [
"python",
"python-2.7",
"numpy",
"average",
"weighted-average"
] |
Regular expression in python replace | 38,241,211 | <p>Is there any way using regular expression in python to replace all the occurrences of <code>,</code> (comma) after the flower braces <code>{</code></p>
<p>Data is of the following format in a file - <code>abc.json</code></p>
<pre><code>{
"Key1":"value1",
"Key2":"value2"
},
{
"Key1":"value3",
"Key2":"value4"
},
{... | 0 | 2016-07-07T08:52:18Z | 38,241,389 | <p>Test Source: <a href="https://regex101.com/r/wT6uU2/1" rel="nofollow">https://regex101.com/r/wT6uU2/1</a></p>
<pre><code>import re
p = re.compile(ur'},')
test_str = u"{\n\"Key1\":\"value1\",\n\"Key2\":\"value2\"\n},\n\n{\n\"Key1\":\"value3\",\n\"Key2\":\"value4\"\n},\n\n{\n\"Key1\":\"value5\",\n\"Key2\":\"value6\"\... | 1 | 2016-07-07T09:01:27Z | [
"python",
"json",
"regex",
"jq"
] |
Regular expression in python replace | 38,241,211 | <p>Is there any way using regular expression in python to replace all the occurrences of <code>,</code> (comma) after the flower braces <code>{</code></p>
<p>Data is of the following format in a file - <code>abc.json</code></p>
<pre><code>{
"Key1":"value1",
"Key2":"value2"
},
{
"Key1":"value3",
"Key2":"value4"
},
{... | 0 | 2016-07-07T08:52:18Z | 38,241,443 | <p>This works:</p>
<pre><code>import re
s="""{
"Key1":"value1",
"Key2":"value2"
},
{
"Key1":"value3",
"Key2":"value4"
},
{
"Key1":"value5",
"Key2":"value6"
}"""
pattern=re.compile(r'(?P<data>{.*?}),', re.S)
print pattern.findall(s)
s1=pattern.sub(r'\g<data>', s)
print s1
</code></pre>
| 0 | 2016-07-07T09:04:21Z | [
"python",
"json",
"regex",
"jq"
] |
Regular expression in python replace | 38,241,211 | <p>Is there any way using regular expression in python to replace all the occurrences of <code>,</code> (comma) after the flower braces <code>{</code></p>
<p>Data is of the following format in a file - <code>abc.json</code></p>
<pre><code>{
"Key1":"value1",
"Key2":"value2"
},
{
"Key1":"value3",
"Key2":"value4"
},
{... | 0 | 2016-07-07T08:52:18Z | 38,244,067 | <p>If you intend to process the resulting JSON in jq, it's probably easier to wrap it in brackets <code>[{...}, {...}]</code> to make it a JSON array. Then, you can use <code>.[]</code> in jq to unwrap the array.</p>
| 0 | 2016-07-07T11:15:04Z | [
"python",
"json",
"regex",
"jq"
] |
Regular expression in python replace | 38,241,211 | <p>Is there any way using regular expression in python to replace all the occurrences of <code>,</code> (comma) after the flower braces <code>{</code></p>
<p>Data is of the following format in a file - <code>abc.json</code></p>
<pre><code>{
"Key1":"value1",
"Key2":"value2"
},
{
"Key1":"value3",
"Key2":"value4"
},
{... | 0 | 2016-07-07T08:52:18Z | 38,250,586 | <p>Before you even consider other options, you really should go back to the source that generated that file and make sure it actually outputs <em>valid</em> json.</p>
<p>That said, you could use JQ to manipulate the contents as a raw string to add brackets, then parse it as an array to them spit out the contents.</p>
... | 0 | 2016-07-07T16:19:12Z | [
"python",
"json",
"regex",
"jq"
] |
What is the correct way to add elements to a csr_matrix? | 38,241,386 | <p>I have a csr_matrix, let's say I called:</p>
<pre><code>import scipy.sparse as ss
mat = ss.csr.csr_matrix((50, 100))
</code></pre>
<p>Now I want to modify some of the values on this matrix. I call:</p>
<pre><code>mat[0,1]+=1
</code></pre>
<p>And I get:</p>
<pre><code>SparseEfficiencyWarning: Changing the sparsi... | 1 | 2016-07-07T09:01:20Z | 38,250,662 | <p>You can control the appearance of warnings. The default is to show them once during a run, and then be silent. You can change that to raise an error, be completely silent, or issue the warning every time.</p>
<p>A common way of creating a sparse matrix is to create the 3 <code>coo</code> style arrays, with all no... | 0 | 2016-07-07T16:23:18Z | [
"python",
"scipy",
"sparse-matrix"
] |
TensorFlow: Remember LSTM state for next batch (stateful LSTM) | 38,241,410 | <p>Given a trained LSTM model I want to perform inference for single timesteps, i.e. <code>seq_length = 1</code> in the example below. After each timestep the internal LSTM (memory and hidden) states need to be remembered for the next 'batch'. For the very beginning of the inference the internal LSTM states <code>init_... | 5 | 2016-07-07T09:02:40Z | 38,417,699 | <p>Tensorflow, best way to save state in RNNs? was actually my original question. The code bellow is how I use the state tuples. </p>
<pre><code>with tf.variable_scope('decoder') as scope:
rnn_cell = tf.nn.rnn_cell.MultiRNNCell \
([
tf.nn.rnn_cell.LSTMCell(512, num_proj = 256, state_is_tuple = True),... | 3 | 2016-07-17T03:41:51Z | [
"python",
"tensorflow",
"lstm",
"recurrent-neural-network",
"stateful"
] |
TensorFlow: Remember LSTM state for next batch (stateful LSTM) | 38,241,410 | <p>Given a trained LSTM model I want to perform inference for single timesteps, i.e. <code>seq_length = 1</code> in the example below. After each timestep the internal LSTM (memory and hidden) states need to be remembered for the next 'batch'. For the very beginning of the inference the internal LSTM states <code>init_... | 5 | 2016-07-07T09:02:40Z | 39,954,167 | <p>I found out it was easiest to save the whole state for all layers in a placeholder.</p>
<pre><code>init_state = np.zeros((num_layers, 2, batch_size, state_size))
...
state_placeholder = tf.placeholder(tf.float32, [num_layers, 2, batch_size, state_size])
</code></pre>
<p>Then unpack it and create a tuple of LSTMS... | 0 | 2016-10-10T08:28:03Z | [
"python",
"tensorflow",
"lstm",
"recurrent-neural-network",
"stateful"
] |
python MYSQLdb execute() result doesn't match fetch result | 38,241,440 | <p>Here is our code:</p>
<pre><code>db = get_connection()
try:
cursor = db.cursor()
if not cursor.execute("SELECT id FROM test WHERE name = %s", ['name']) > 0:
return None
return cursor.fetchone()[0]
finally:
db.close()
</code></pre>
<p>But sometimes, it will cause some excption.</p>
<bloc... | 0 | 2016-07-07T09:04:05Z | 38,241,522 | <p>The <a href="http://mysql-python.sourceforge.net/MySQLdb.html#some-examples" rel="nofollow">MySQLDB User Guide</a> says that <code>fetchone()</code> returns <code>None</code> when there are no more rows to fetch. I think this means that your result set was empty.</p>
| -1 | 2016-07-07T09:08:17Z | [
"python",
"mysql-python"
] |
Integration openstack &opendaylight | 38,241,463 | <p><strong>strong text</strong>i need your help , i would like to do intergartion between openstack liberty(devstack) and opendaylight Beryllium. some one who know whow? i check lot of in internet but always the same documentation .</p>
| 0 | 2016-07-07T09:05:16Z | 38,247,806 | <p>Hmm, well, you could consult the OPNFV (Open Platform for Network Function Virtualization) project. OPNFV builds an integrated release of OpenStack with OpenDaylight as the SDN controller.</p>
| 0 | 2016-07-07T14:15:30Z | [
"python",
"openstack",
"openflow",
"opendaylight"
] |
Integration openstack &opendaylight | 38,241,463 | <p><strong>strong text</strong>i need your help , i would like to do intergartion between openstack liberty(devstack) and opendaylight Beryllium. some one who know whow? i check lot of in internet but always the same documentation .</p>
| 0 | 2016-07-07T09:05:16Z | 38,259,360 | <p>Refer this blog on <a href="http://www.cloudenablers.com/blog/opendaylight-integration-with-openstack/" rel="nofollow">Openstack(kilo) integration with Opendaylight(Lithium)</a>
This would help you through the steps on deploying OpenDaylight and integrating it with Openstack to address use case specific to networkin... | 0 | 2016-07-08T05:20:45Z | [
"python",
"openstack",
"openflow",
"opendaylight"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.