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 |
|---|---|---|---|---|---|---|---|---|---|
Float multiplication | 38,178,475 | <p>In python does anybody know how to save insignificant <code>0</code>, i.e</p>
<pre><code>x=9999.0
y=.01
print x*y
</code></pre>
<p>The output is <code>99.99</code> but i want <code>99.990</code>.Can this happen?</p>
<p>I am not sure if formatting can achieve this.In nutshell i need to save <code>0</code>'s.</p>
... | -4 | 2016-07-04T06:52:09Z | 38,178,620 | <p>You can specify the number of numbers after the decimal point with <a href="https://docs.python.org/2/library/stdtypes.html#string-formatting" rel="nofollow">string formatting</a>. Try this in the console:</p>
<pre><code>>>> print '%.3f' % (9999.0*.01)
99.990
</code></pre>
| 0 | 2016-07-04T07:00:01Z | [
"python",
"python-2.7",
"precision"
] |
Float multiplication | 38,178,475 | <p>In python does anybody know how to save insignificant <code>0</code>, i.e</p>
<pre><code>x=9999.0
y=.01
print x*y
</code></pre>
<p>The output is <code>99.99</code> but i want <code>99.990</code>.Can this happen?</p>
<p>I am not sure if formatting can achieve this.In nutshell i need to save <code>0</code>'s.</p>
... | -4 | 2016-07-04T06:52:09Z | 38,178,623 | <p>Works fine in version 2.7</p>
<pre><code>x=9999.0
y=.01
print '%.3f' % (x*y)
</code></pre>
<p>Read about python formatting <a href="https://pyformat.info/" rel="nofollow">here</a></p>
| 0 | 2016-07-04T07:00:08Z | [
"python",
"python-2.7",
"precision"
] |
Float multiplication | 38,178,475 | <p>In python does anybody know how to save insignificant <code>0</code>, i.e</p>
<pre><code>x=9999.0
y=.01
print x*y
</code></pre>
<p>The output is <code>99.99</code> but i want <code>99.990</code>.Can this happen?</p>
<p>I am not sure if formatting can achieve this.In nutshell i need to save <code>0</code>'s.</p>
... | -4 | 2016-07-04T06:52:09Z | 38,178,689 | <p>You could use the decimal module:</p>
<pre><code>>>> from decimal import *
>>> getcontext().prec = 5
>>> Decimal(9999.0) * Decimal(0.01)
Decimal('99.990')
</code></pre>
| 2 | 2016-07-04T07:04:35Z | [
"python",
"python-2.7",
"precision"
] |
Why does matplotlib extrapolate/plot missing values? | 38,178,587 | <p>I have a situation where sometimes, a whole series of data is not available. I'm real-time plotting values from sensors, and these can be turned on and off via user interaction, and thus I cannot be sure the values are always in a series. A user can start a sensor and later turn it off and on again, but In this case... | 0 | 2016-07-04T06:58:04Z | 38,178,779 | <p>Matplotlib will connect all your consequetive datapoints with lines.</p>
<p>If you want to avoid this you could split your data at the missing x-values, and plot the two splitted lists separately.</p>
| 0 | 2016-07-04T07:10:30Z | [
"python",
"matplotlib",
"plot"
] |
Why does matplotlib extrapolate/plot missing values? | 38,178,587 | <p>I have a situation where sometimes, a whole series of data is not available. I'm real-time plotting values from sensors, and these can be turned on and off via user interaction, and thus I cannot be sure the values are always in a series. A user can start a sensor and later turn it off and on again, but In this case... | 0 | 2016-07-04T06:58:04Z | 38,179,708 | <p>One option would be to add dummy items wherever data is missing (in your case apparently when <code>x</code> changes by more than 1), and set them as masked elements. That way matplotlib skips the line segments. For example:</p>
<pre><code>import numpy as np
import matplotlib.pylab as pl
# Your data, with some add... | 2 | 2016-07-04T08:09:40Z | [
"python",
"matplotlib",
"plot"
] |
Why does matplotlib extrapolate/plot missing values? | 38,178,587 | <p>I have a situation where sometimes, a whole series of data is not available. I'm real-time plotting values from sensors, and these can be turned on and off via user interaction, and thus I cannot be sure the values are always in a series. A user can start a sensor and later turn it off and on again, but In this case... | 0 | 2016-07-04T06:58:04Z | 38,180,232 | <p>Another option is to include <code>None</code> or <code>numpy.nan</code> as values for y. </p>
<p>This, for example, shows a disconnected line:</p>
<pre><code>import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,6,None,7,8])
</code></pre>
| 2 | 2016-07-04T08:39:36Z | [
"python",
"matplotlib",
"plot"
] |
How to resolve nonetype object has no attribute encode error in python 2.7 | 38,178,633 | <p>I was running the following code:</p>
<pre><code>from __future__ import unicode_literals
import xml.etree.ElementTree as ET
tree = ET.parse('dblp_16.xml')
root = tree.getroot()
f = open('hi', 'w')
for country in root.findall('article'):
rank = country.find('year').text
name = country.find('title')
if(i... | 0 | 2016-07-04T07:00:33Z | 38,178,840 | <p>Simply check <code>if name.text is not None</code></p>
<pre><code>from __future__ import unicode_literals
import xml.etree.ElementTree as ET
tree = ET.parse('dblp_16.xml')
root = tree.getroot()
f = open('hi', 'w')
for country in root.findall('article'):
rank = country.find('year').text
name = country.find('... | 0 | 2016-07-04T07:14:11Z | [
"python",
"xml",
"unicode"
] |
'function' object has no attribute 'name' when registering blueprint | 38,178,776 | <p>Here is my project layout:</p>
<pre><code>baseflask/
baseflask/
__init__.py
views.py
resources/
health.py/
wsgi.py/
</code></pre>
<p>Here is my print</p>
<pre><code>from flask import Blueprint
from flask import Response
health = Blueprint('health', __name__)
@health.route("/healt... | -1 | 2016-07-04T07:10:15Z | 38,178,824 | <p>You <strong>masked</strong> the blueprint by re-using the name:</p>
<pre><code>health = Blueprint('health', __name__)
@health.route("/health", methods=["GET"])
def health():
</code></pre>
<p>You can't have both the route and the blueprint use the same name; you replaced the blueprint and are trying to register the... | 3 | 2016-07-04T07:13:22Z | [
"python",
"flask"
] |
Plot csv - define legend labels | 38,178,807 | <p>I created a csv-file (with pandas and the help of a friend) like the one in the picture.</p>
<p><a href="http://i.stack.imgur.com/MdWvs.png" rel="nofollow"><img src="http://i.stack.imgur.com/MdWvs.png" alt="enter image description here"></a></p>
<p>Now I need to plot this file.
The first column is the time and sh... | -1 | 2016-07-04T07:12:28Z | 38,179,062 | <p>You have to open your cvs file with numpy from example. Then, you can plot columns :</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
data = np.genfromtxt("file", delimiter="", dtype=[("time", "f4"), ("column1", "f8"), ("column2", "f8")])
figure_1 = plt.plot(data['time'], data['column1'])
figure... | 0 | 2016-07-04T07:28:09Z | [
"python",
"pandas",
"matplotlib"
] |
ControlSend function is not working in AutoIt (Calling in python) | 38,178,846 | <blockquote>
<p>In my python script i'm converting Autoit script into python script. All the default function in Autoit script is working fine except ControlSend function.Please refer my code below and guide me whats wrong in the script.</p>
</blockquote>
<pre><code> Auto = Dispatch("AutoItX3.Control")
Auto.R... | 0 | 2016-07-04T07:14:23Z | 38,181,194 | <blockquote>
<p>After long struggle , i found a solution . The idea is to run the Autoit script in python script. I used below lines to execute Autoit script directly in python script.</p>
</blockquote>
<pre><code>import os
os.startfile("C:\\test.au3")
</code></pre>
| 0 | 2016-07-04T09:27:14Z | [
"python",
"autoit"
] |
python ftp retrieve only the last file base on filematch | 38,179,066 | <p>Im using python script with FTP connection<br>
Below are the files in my FTP server<br></p>
<p>testing_01.xml<br>
testing_02.xml<br>
testing_03.xml(this is the latest file)</p>
<pre><code>from ftplib import FTP
ftp = FTP('FTP IP') # open FTP connection to MSM
ftp.login(user = 'username',passwd = 'password')
ftp.d... | 0 | 2016-07-04T07:28:16Z | 38,182,466 | <p><a href="https://docs.python.org/2.7/library/ftplib.html#ftplib.FTP.nlst" rel="nofollow"><code>ftp.nlst()</code></a> will return a list of file names. So it would give <code>['testing_01.xml', 'testing_02.xml', 'testing_03.xml']</code>.
The last item on any list has index <code>-1</code>. So to always get the last f... | 0 | 2016-07-04T10:28:25Z | [
"python",
"xml",
"ftp"
] |
Subtracting two matrices and getting absolute value in python | 38,179,248 | <p>Is there an efficient way/function to subtract one matrix from another and writing the absolute values in a new matrix?
I can do it entry by entry but for big matrices, this will be fairly slow...</p>
<p>For example:</p>
<pre><code>X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
for i in range... | 0 | 2016-07-04T07:40:02Z | 38,179,312 | <p>Doing this becomes trivial if you cast your 2D arrays to numpy arrays:</p>
<pre><code>import numpy as np
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
X, Y = np.array(X), np.array(Y)
result = X - Y
</code></pre>
<p>Numpy is designed to work easily and efficiently with matrices. </p>
<p>Al... | 2 | 2016-07-04T07:43:49Z | [
"python",
"matrix"
] |
Subtracting two matrices and getting absolute value in python | 38,179,248 | <p>Is there an efficient way/function to subtract one matrix from another and writing the absolute values in a new matrix?
I can do it entry by entry but for big matrices, this will be fairly slow...</p>
<p>For example:</p>
<pre><code>X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
for i in range... | 0 | 2016-07-04T07:40:02Z | 38,179,323 | <p>I recommend using NumPy</p>
<pre><code>X = numpy.array([
[12,7,3],
[4 ,5,6],
[7 ,8,9]
])
Y = numpy.array([
[5,8,1],
[6,7,3],
[4,5,9]
])
delta_r = numpy.sqrt(X ** 2 - Y ** 2)
</code></pre>
| 0 | 2016-07-04T07:44:13Z | [
"python",
"matrix"
] |
Subtracting two matrices and getting absolute value in python | 38,179,248 | <p>Is there an efficient way/function to subtract one matrix from another and writing the absolute values in a new matrix?
I can do it entry by entry but for big matrices, this will be fairly slow...</p>
<p>For example:</p>
<pre><code>X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[5,8,1],
[6,7,3],
[4,5,9]]
for i in range... | 0 | 2016-07-04T07:40:02Z | 38,179,476 | <p>If you want the absolute element-wise difference between both matrices, you can easily subtract them with NumPy and use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.absolute.html" rel="nofollow"><code>numpy.absolute</code></a> on the resulting matrix. </p>
<pre><code>import numpy as np
X = [[... | 0 | 2016-07-04T07:54:33Z | [
"python",
"matrix"
] |
Finding names in a text file (Text A) using a list in another text file (Text B) and assign values next to the names in Text A (Python) | 38,179,363 | <p>I am a newbie in Python language and I need your help please.</p>
<p>I have 2 different text files. Let's they are Text_A.txt and Text_B.txt.</p>
<p>Text_A.txt contains a list of names as following (they are tab delineated):</p>
<p>Sequence_1 Sequence_2 Sequence_3 Sequence_4
Sequence_5 Seque... | -3 | 2016-07-04T07:46:28Z | 38,179,728 | <p>You may do the following</p>
<pre><code># read each file assuming that your sequence of strings
# is the first line respectively
with open('Text_A.txt', 'r') as f:
seqA = f.readline()
with open('Text_B.txt', 'r') as f:
seqB = f.readline()
# remove end-of-line character
seqA = seqA.strip('\n')
seqB = seqB.... | 0 | 2016-07-04T08:11:02Z | [
"python",
"find",
"assign",
"names"
] |
How to copy a complete ziped folder to target using ftp in python? | 38,179,429 | <p>I have to copy a ziped folder using ftplib as follows:</p>
<pre><code> ftp = FTP('ip')
ftp.login(user='user', passwd = 'pass')
filename= "D:/sample.zip"
ftp.storlines("STOR " + os.path.basename(filename), open(filename,"r"))
</code></pre>
<p>On the remote the sample folder does gets copied but it is just '1kb'... | 0 | 2016-07-04T07:51:05Z | 38,179,537 | <p>Firstly, use <a href="https://docs.python.org/2.7/library/ftplib.html#ftplib.FTP.storbinary" rel="nofollow"><code>storbinary()</code></a> and not <code>storlines</code>. The latter is for ASCII files.</p>
<p>And since zip files are binary, the file should be opened in <a href="https://docs.python.org/2/library/func... | 0 | 2016-07-04T07:58:51Z | [
"python",
"ftp",
"ftplib"
] |
Python read in file: ERROR: line contains NULL byte | 38,179,492 | <p>I would like to parse an .ubx File(=my input file). This file contains many different NMEA sentences as well as raw receiver data. The output file should just contain informations out of GGA sentences. This works fine as far as the .ubx File does not contain any raw messages. However if it contains raw data
I get t... | 0 | 2016-07-04T07:55:18Z | 38,179,560 | <p>I am not quite sure but your file looks pretty binary. You should try to open it as such</p>
<pre><code>with open(INPUT_FILENAME, 'rb') as input_file:
</code></pre>
| 0 | 2016-07-04T07:59:58Z | [
"python",
"parsing",
"nmea"
] |
Python read in file: ERROR: line contains NULL byte | 38,179,492 | <p>I would like to parse an .ubx File(=my input file). This file contains many different NMEA sentences as well as raw receiver data. The output file should just contain informations out of GGA sentences. This works fine as far as the .ubx File does not contain any raw messages. However if it contains raw data
I get t... | 0 | 2016-07-04T07:55:18Z | 38,181,142 | <p>It seems like you did not open the file with correct coding format.
So the raw message cannot be read correctly.</p>
<p>If it is encoded as UTF8, you need to open the file with coding option:</p>
<pre><code>with open(INPUT_FILENAME, 'r', newline='', encoding='utf8') as input_file
</code></pre>
| 0 | 2016-07-04T09:24:42Z | [
"python",
"parsing",
"nmea"
] |
Python read in file: ERROR: line contains NULL byte | 38,179,492 | <p>I would like to parse an .ubx File(=my input file). This file contains many different NMEA sentences as well as raw receiver data. The output file should just contain informations out of GGA sentences. This works fine as far as the .ubx File does not contain any raw messages. However if it contains raw data
I get t... | 0 | 2016-07-04T07:55:18Z | 39,587,931 | <p>Hey if anyone else has this proglem to read in NMEA sentences of uBlox .ubx files
this pyhton code worked for me:</p>
<pre><code>def read_in():
with open('GNGGA.txt', 'w') as GNGGA:
with open('GNRMC.txt','w') as GNRMC:
with open('rover.ubx', 'rb') as f:
for line in f:
#print ... | 0 | 2016-09-20T07:17:11Z | [
"python",
"parsing",
"nmea"
] |
TypeError: __init__() takes exactly 1 argument (4 given) | 38,179,597 | <p><code>mptt-urls</code> raises:</p>
<blockquote>
<p>TypeError at /activities/test/</p>
<p><code>__init__() takes exactly 1 argument (4 given)</code></p>
</blockquote>
<p>This is my url pattern:</p>
<pre><code>url(r'^(?P<path>.*)/', mptt_urls.view(model='activities.models.Category',
... | 0 | 2016-07-04T08:02:21Z | 38,181,381 | <p>I don't know what you are trying to do this with.</p>
<pre><code>url(r'^(?P<path>.*)/', mptt_urls.view(model='activities.models.Category',
view='activities.views.Category', slug_field='slug')),
</code></pre>
<p>There is two way to render a response class based view and function b... | 1 | 2016-07-04T09:35:50Z | [
"python",
"django",
"django-urls",
"django-mptt"
] |
TypeError: __init__() takes exactly 1 argument (4 given) | 38,179,597 | <p><code>mptt-urls</code> raises:</p>
<blockquote>
<p>TypeError at /activities/test/</p>
<p><code>__init__() takes exactly 1 argument (4 given)</code></p>
</blockquote>
<p>This is my url pattern:</p>
<pre><code>url(r'^(?P<path>.*)/', mptt_urls.view(model='activities.models.Category',
... | 0 | 2016-07-04T08:02:21Z | 39,557,686 | <p>This may work for you:</p>
<pre><code>def category(request, path, instance):
l = get_list_or_404(models.Category.objects.all(), slug=path)
return render(
request,
'activities/activity_list.html',
{
'articles': l,
'activities': models.Category.objects.filter(l... | 2 | 2016-09-18T12:34:50Z | [
"python",
"django",
"django-urls",
"django-mptt"
] |
Python BeautifulSoup No tag and return empty | 38,179,618 | <p>I have to get context like above but in html code isn't have tag to get data
and I try to use get div.main-content to test but why data return empty?</p>
<pre><code>import urllib
import urllib.request
import requests
from bs4 import BeautifulSoup
import re
links = ['https://www.ptt.cc/bbs/Gossiping/index'+str(i+1... | 1 | 2016-07-04T08:03:58Z | 38,183,763 | <p>It has an <em>id</em> main-content not a <em>class</em></p>
<pre><code>twice_data1 = soup2.select_one("#main-content")
</code></pre>
<p>Once you do that change, you will get your div.</p>
<p>You should also not be defining your functions repeatedly and as per the second part of my <a href="http://stackoverflow.co... | 1 | 2016-07-04T11:35:31Z | [
"python",
"python-3.x",
"beautifulsoup"
] |
How do you show cost function per iteration in scikit-learn? | 38,179,687 | <p>I've been running some linear/logistic regression models recently, and I wanted to know how you can output the cost function for each iteration. One of the parameters in sci-kit LinearRegression is 'maxiter', but in reality you need to see cost vs iteration to find out what this value really needs to be i.e. is the ... | 0 | 2016-07-04T08:08:35Z | 38,182,345 | <p>One has to understand if there is any iteration (implying computing a cost function) or an analytical exact solution, when fitting any estimator.</p>
<p><strong>Linear Regression</strong></p>
<p>In fact, Linear Regression - ie Minimization of the Ordinary Least Square - is not an algorithm but a minimization probl... | 3 | 2016-07-04T10:22:44Z | [
"python",
"machine-learning",
"scikit-learn"
] |
Numpy max pooling convolution | 38,179,797 | <p>Edit:</p>
<p>What I actually wanted to do is finding local maxima, which is explained good below, and the same solution is also explained here:</p>
<p><a href="http://scikit-image.org/docs/dev/auto_examples/plot_peak_local_max.html" rel="nofollow">http://scikit-image.org/docs/dev/auto_examples/plot_peak_local_max.... | 4 | 2016-07-04T08:14:47Z | 38,180,427 | <p>You could use <a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.ndimage.filters.maximum_filter.html" rel="nofollow">Scipy's maximum_filer</a> -</p>
<pre><code>from scipy.ndimage.filters import maximum_filter
arr*(arr == maximum_filter(arr,footprint=np.ones((3,3))))
</code></pre>
<p>Sample ... | 3 | 2016-07-04T08:50:47Z | [
"python",
"numpy"
] |
Is there a way to automatically convert an object method to an external function? | 38,179,839 | <p>Just to illustrate let's take:</p>
<pre><code>class newobj:
def __init__(self, val):
self.value = val
def mul2(self):
self.value = 2*self.value
</code></pre>
<p>Is there a way to automatically convert the method <code>newobj.mul2</code> to a function <code>mul2</code> that can be called lik... | 0 | 2016-07-04T08:16:54Z | 38,179,893 | <p>Just assign the bound method to a variable:</p>
<pre><code>o = newobj(5)
mul2 = o.mul2
</code></pre>
<p>You don't <em>have</em> to call a method in the same expression, you <em>can</em> just reference the attribute.</p>
<p>Demo:</p>
<pre><code>>>> class newobj:
... def __init__(self, val):
... ... | 3 | 2016-07-04T08:19:47Z | [
"python"
] |
Quicksort: Non-in-place implementation works. In-place implementation exceeds maximum recursion depth. Why? | 38,179,950 | <pre><code>def quicksort_stable(l):
if not l:
return l
else:
pivot = l[0]
return quicksort_stable([x for x in l if x < pivot]) \
+ [x for x in l if x == pivot] \
+ quicksort_stable([x for x in l if x > pivot])
def quicksort_inplace(l):
def p... | 0 | 2016-07-04T08:23:01Z | 38,214,297 | <p>I believe the reason for this behavior is that your list contains lots of repetitions (every element appears ~1000 times), and you "cheated" implementing the <em>stable</em> version by gathering all elements equal to pivot at once and not getting back to them (which is of course great!). </p>
<p>So to actually comp... | 0 | 2016-07-05T23:19:39Z | [
"python",
"recursion",
"stack-overflow",
"quicksort"
] |
ssh-copy-id hanging sometimes | 38,179,980 | <p>This is a "follow up" to my <a href="http://stackoverflow.com/questions/38094614/python-pexepct-child-expectpexpect-eof-hangs-sometimes">question</a> from last week. Basically I am seeing that some python code that ssh-copy-id using pexpect <em>occasionally</em> hangs.</p>
<p>I thought it might be a pexect problem,... | -1 | 2016-07-04T08:25:11Z | 38,184,178 | <p><code>xauth</code> reference smells like you are requesting X11 Forwarding. It will be configured in your <code>~/.ssh/config</code>. That might be the difference in your configuration that can cause the hangs.</p>
| 1 | 2016-07-04T11:56:52Z | [
"python",
"ssh",
"pexpect"
] |
Unexpected SettingWithCopyWarning | 38,180,124 | <p>I've been avoiding most SettingWithCopy warnings by using <code>.loc[: (foo, bar)]</code> construction.</p>
<p>But I don't know how to properly construct one case:</p>
<pre><code>for sec in security_list:
stochs.loc[:, (sec,'entry_signal')][stochs[sec, 'raw_signal'].shift(1) == stochs[sec, 'raw_signal']] = 0 ... | 2 | 2016-07-04T08:33:07Z | 38,180,227 | <p>Change to:</p>
<pre><code>stochs.loc[stochs[sec, 'raw_signal'].shift(1) == stochs[sec, 'raw_signal'], (sec,'entry_signal')] = 0
</code></pre>
<p>what you did is called <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy" rel="nofollow">chained indexing</a> as you were doub... | 2 | 2016-07-04T08:39:28Z | [
"python",
"pandas"
] |
Verify screen name existence | 38,180,269 | <p>I have a django app which uses tweepy to get the last tweet of a specific person, given his/her screen_name. However, as the screen_name field is optional for my application, it is possible that sometimes I have screen_names that are empty or just do not exist.</p>
<p>However, if this occurs (if I use the user_look... | 0 | 2016-07-04T08:41:36Z | 38,184,883 | <p>If your aim is to prevent your application from stopping when Tweepy raises a <code>TweepyError</code> exception, then this is a classic case of using <code>python</code>'s <code>try...except</code> statements.</p>
<pre><code>try:
# do whatever with tweepy here
except TweepyError:
# do what you want to when... | 0 | 2016-07-04T12:33:32Z | [
"python",
"django",
"error-handling",
"tweepy"
] |
Scrapy does not click through all pages | 38,180,300 | <p>I am using Scrapy to crawl through a webshop. The products are dynamically loaded, which is why I'm using Selenium to crawl through the pages. I am starting out to scrape all the categories, which are then called for the main function. </p>
<p>The problem occurs while crawling through each category: The spider is i... | 0 | 2016-07-04T08:43:51Z | 38,199,865 | <p>I have found an answer: </p>
<p>The problem was that since the content of the page was dynamically generated, clicking the <code>NEXT</code>-button did not actually change the url. In conjunction with the <code>DOWNLOAD_DELAY</code>-setting of the project, this meant that the spider stayed on the page for a given a... | 0 | 2016-07-05T09:31:24Z | [
"python",
"selenium",
"scrapy"
] |
What is the invert operation of bytes repr() in python3? | 38,180,331 | <pre><code>a = b'\x00\x01'
ra = repr(a) # ra == "b'\\x00\\x01'"
assert invert_repr(ra) == a
</code></pre>
<p>What is the correct form of invert_repr? string_escape & unicode_escape?</p>
| 0 | 2016-07-04T08:45:41Z | 38,180,380 | <p>Use <code>eval</code> or equivalent:</p>
<pre><code>from ast import literal_eval
a = b'\x00\x01'
ra = repr(a)
assert literal_eval(ra) == eval(ra) == a # no error
</code></pre>
<p><a href="http://stackoverflow.com/q/15197673/2301450"><code>ast.literal_eval</code> is safer than <code>eval</code>.</a></p>
| 2 | 2016-07-04T08:48:39Z | [
"python",
"python-3.x"
] |
Tkinter : How to insert an image to a text widget | 38,180,388 | <p>I'm writing a notepad-like project and I need to insert an image to the Tkinter Text widget (Just like how MS Word does) and I didn't found anything helping me with this.</p>
<p>Here's my code:</p>
<pre><code>from PIL import Image,ImageTk
from tkinter import *
text = Text(root)
root.pack()
#Insert Image
yourIma... | -1 | 2016-07-04T08:48:49Z | 38,182,050 | <p>You can use <code>image_create</code> or <code>window_create</code> example of both in use</p>
<p>This example doesn't use PIL, only PhotoImage which can only take a gif image file.</p>
<p>Example Code:</p>
<pre><code>import tkinter as tk
def add_image():
text.image_create(tk.END, image = img) # Example 1
... | 0 | 2016-07-04T10:09:09Z | [
"python",
"tkinter"
] |
RAM issue with DASK and its from_pandas function | 38,180,447 | <p>i'm trying to use DASK package in Python 3.4 for avoid RAM problems with large datasets, but i've notice a problem.</p>
<p>Using native fucntion "read_csv" i load big dataset into a dask dataframe using less than 150MB of RAM.</p>
<p>The same dataset read with PANDAS DB Connection (using limit and offset options) ... | 1 | 2016-07-04T08:51:40Z | 38,189,196 | <p>One dask.dataframe is composed of many pandas dataframes or, as in the case of functions like <code>read_csv</code> a plan to compute those dataframes on demand. It achieves low-memory execution by executing that plan to compute dataframes lazily. </p>
<p>When using <code>from_pandas</code> the dataframes are alr... | 4 | 2016-07-04T16:39:14Z | [
"python",
"pandas",
"ram",
"dask"
] |
Create .msg file with task without having outlook installed | 38,180,458 | <p>Is there any chance to create a outlook .msg file without having outlook installed.</p>
<p>We use a django backend and need to create a msg file containing a task for importing in outlook. Since we use unix-based servers we dont have any chance to get outlook installed (except wine etc..) </p>
<p>Is there a compo... | 1 | 2016-07-04T08:52:14Z | 38,194,514 | <p>Well the MSG file format is defined here: <a href="https://msdn.microsoft.com/en-us/library/cc463912(v=exchg.80).aspx" rel="nofollow">https://msdn.microsoft.com/en-us/library/cc463912(v=exchg.80).aspx</a> but like all microsoft documention it's anything but readable. All you need to do is to write a bit of python co... | 1 | 2016-07-05T02:45:59Z | [
"python",
"django",
"outlook",
"msg"
] |
Create .msg file with task without having outlook installed | 38,180,458 | <p>Is there any chance to create a outlook .msg file without having outlook installed.</p>
<p>We use a django backend and need to create a msg file containing a task for importing in outlook. Since we use unix-based servers we dont have any chance to get outlook installed (except wine etc..) </p>
<p>Is there a compo... | 1 | 2016-07-04T08:52:14Z | 38,212,655 | <p>Why not create an EML file? It is MIME, so there are hundreds of libraries out there. Outlook will be able to open an EML file just fine.</p>
<p>In your particular case, create a MIME file with the vTodo MIME part as the primary MIME part. </p>
| 1 | 2016-07-05T21:00:42Z | [
"python",
"django",
"outlook",
"msg"
] |
Issue with Resampling and True/False being set to 1 or 0. | 38,180,475 | <p>Okay so I have this code: That reads in this CSV file:</p>
<pre><code>2004-02-27 00:00,7.7,167
2004-02-27 00:05,7.5,169
2004-02-27 00:10,7.2,173
2004-02-27 00:15,7,176
2004-02-27 00:20,6.5,176
2004-02-27 00:25,6,178
2004-02-27 00:30,5.6,184
2004-02-27 00:35,5.5,185
2004-02-27 00:40,5.8,182
2004-02-27 00:45,6.3,178... | 0 | 2016-07-04T08:53:00Z | 38,180,837 | <p>I think this seems to work:</p>
<pre><code>import pandas as pd
names=['Date','Wind Speed','Wind Direction']
df_met = pd.read_csv('Met_Test.csv', index_col=0, names=names, parse_dates=[0])
df1=df_met
df1.insert(2,'Wind_direction_Flag','1')
df1.insert(3,'Wind_Speed_Less_than_4','0')
df1.insert(4,'Middle','0')
df1.ins... | 0 | 2016-07-04T09:10:26Z | [
"python",
"pandas",
"resampling"
] |
Python: Printing nested dictionary in .csv file, how to remove [] and ' | 38,180,589 | <p>Say I have a dictionary:</p>
<pre><code>d = {'Bob': {'Car': ['a = 1.10', 'b = 1.50'], 'House': ['c = 1.20'], 'Hp': 'true', 'Wife': 'false'},
'Sam': {'Car': ['d = 1.40'], 'House': ['c = 1.60'], 'Hp': 'true', 'Wife': 'true'}}
</code></pre>
<p>I want to print it in a table in .csv file.</p>
<p>My desired output... | 0 | 2016-07-04T08:58:24Z | 38,180,746 | <p><code>join</code> the items in the list and update the dictionary. The joining should be done with a semi-colon, to avoid moving items to the next column or having them wrapped with <code>" "</code>:</p>
<pre><code>header = ['Name', 'Hp', 'Wife', 'Car', 'House']
with open("output.csv", "w") as f:
w = csv.DictWr... | 2 | 2016-07-04T09:05:49Z | [
"python",
"python-2.7",
"csv",
"dictionary"
] |
Python: Printing nested dictionary in .csv file, how to remove [] and ' | 38,180,589 | <p>Say I have a dictionary:</p>
<pre><code>d = {'Bob': {'Car': ['a = 1.10', 'b = 1.50'], 'House': ['c = 1.20'], 'Hp': 'true', 'Wife': 'false'},
'Sam': {'Car': ['d = 1.40'], 'House': ['c = 1.60'], 'Hp': 'true', 'Wife': 'true'}}
</code></pre>
<p>I want to print it in a table in .csv file.</p>
<p>My desired output... | 0 | 2016-07-04T08:58:24Z | 38,180,773 | <pre><code>x = ['a = 1.10', 'b = 1.50']
print x
print str(x).replace('[','').replace(']','').replace("'",'')
</code></pre>
| 0 | 2016-07-04T09:07:28Z | [
"python",
"python-2.7",
"csv",
"dictionary"
] |
Python: Printing nested dictionary in .csv file, how to remove [] and ' | 38,180,589 | <p>Say I have a dictionary:</p>
<pre><code>d = {'Bob': {'Car': ['a = 1.10', 'b = 1.50'], 'House': ['c = 1.20'], 'Hp': 'true', 'Wife': 'false'},
'Sam': {'Car': ['d = 1.40'], 'House': ['c = 1.60'], 'Hp': 'true', 'Wife': 'true'}}
</code></pre>
<p>I want to print it in a table in .csv file.</p>
<p>My desired output... | 0 | 2016-07-04T08:58:24Z | 38,182,190 | <p>Here is a way to do it by using <code>str.join()</code> to join the items in the nested lists. The nested lists are detected using <code>isinstance()</code>. If you do not specify a delimiter when creating the csv writer, it will default to comma so this code:</p>
<pre><code>import csv
d = {'Bob': {'Car': ['a = 1.... | 2 | 2016-07-04T10:15:39Z | [
"python",
"python-2.7",
"csv",
"dictionary"
] |
Scrapy: How to apply settings from settings.py file | 38,180,612 | <p>I have specified the names of external files in my <code>settings.py</code> file, I would like to import these on start up. But when I run it, I get the error: <code>AttributeError: 'MySpider' object has no attribute 'settings'</code>. How do I import on start up of the spider?</p>
<p>The code I have so far is: </p... | 0 | 2016-07-04T08:59:28Z | 38,180,816 | <p>This worked for me. </p>
<pre><code>from scrapy.conf import settings
self.crawl_behaviour = settings['CRAWL_BEHAVIOUR']
</code></pre>
| 0 | 2016-07-04T09:09:48Z | [
"python",
"scrapy"
] |
Pandas Merge Bins | 38,180,617 | <p>I have created a distribution using numpy histogram and digitize functions.</p>
<pre><code>_, bins = np.histogram(x, bins=bins)
arr = np.digitize(x, bins) - 1
x = bins[arr[:]]
</code></pre>
<p>Or possibly: </p>
<pre><code>x = pandas.cut(x, bins=bins)
</code></pre>
<p>However as the distribution is very skewed, e... | 1 | 2016-07-04T08:59:30Z | 38,201,440 | <p>As promised, I implemented something in physt, version 0.3.5. You're welcome to use it.</p>
<p>See <a href="http://nbviewer.jupyter.org/github/janpipek/physt/blob/master/doc/Binning2.ipynb#Merging-bins" rel="nofollow">http://nbviewer.jupyter.org/github/janpipek/physt/blob/master/doc/Binning2.ipynb#Merging-bins</a> ... | 1 | 2016-07-05T10:45:15Z | [
"python",
"numpy",
"pandas",
"dataframe",
"histogram"
] |
How to print signatures of all functions/methods in a Python project? | 38,180,661 | <p>I want to extract all Python functions/methods with their signatures from a Python project. I've tried:</p>
<pre><code>$ grep -r ^def *
</code></pre>
<p>but this doesn't show full signatures when parameters span several lines. Any suggestions?</p>
| 0 | 2016-07-04T09:01:33Z | 38,180,731 | <p>You can parse the source using the <a href="https://docs.python.org/2/library/ast.html" rel="nofollow"><code>ast</code> module</a>. It allows you to see exactly the same code structure the interpreter sees. You just need to traverse it and dump out any function definitions you find.</p>
<p>If you want to handle edg... | 0 | 2016-07-04T09:05:07Z | [
"python",
"linux",
"bash"
] |
How to print signatures of all functions/methods in a Python project? | 38,180,661 | <p>I want to extract all Python functions/methods with their signatures from a Python project. I've tried:</p>
<pre><code>$ grep -r ^def *
</code></pre>
<p>but this doesn't show full signatures when parameters span several lines. Any suggestions?</p>
| 0 | 2016-07-04T09:01:33Z | 38,181,014 | <p>You can <a href="https://docs.python.org/2/library/tokenize.html" rel="nofollow">tokenize the file</a> and use that to print function definitions:</p>
<pre><code>import token
from tokenize import generate_tokens
def find_definitions(filename):
with open(filename) as f:
gen = generate_tokens(f.readline)... | 2 | 2016-07-04T09:18:14Z | [
"python",
"linux",
"bash"
] |
How to print signatures of all functions/methods in a Python project? | 38,180,661 | <p>I want to extract all Python functions/methods with their signatures from a Python project. I've tried:</p>
<pre><code>$ grep -r ^def *
</code></pre>
<p>but this doesn't show full signatures when parameters span several lines. Any suggestions?</p>
| 0 | 2016-07-04T09:01:33Z | 38,181,127 | <p>This isn't a place to use regex in my opinion, unless you accept the fact that you'll potentially miss many edge cases.</p>
<p>Instead I'd suggest you use <code>inspect</code> and <code>funcsigs</code> (<code>funcsigs</code> is a backport of changes made in Python 3's <code>inspect</code> module. It includes the si... | 1 | 2016-07-04T09:23:51Z | [
"python",
"linux",
"bash"
] |
Error while loading bulk data into Elasticsearch | 38,180,916 | <p>I am using Elasticsearch in python. I have data in pandas frame(3 columns), then I added two columns _index and _type and converted the data into json with each record using pandas inbuilt method.</p>
<pre><code>data = data.to_json(orient='records')
</code></pre>
<p>This is my data then, </p>
<pre><code>[{"... | 0 | 2016-07-04T09:13:49Z | 38,182,085 | <p><strong>Pandas Data frame to json conversion</strong> is the trick which resolved the problem.</p>
<pre><code>data = data.to_json(orient='records')
data= json.loads(data)
</code></pre>
| 0 | 2016-07-04T10:10:49Z | [
"python",
"json",
"pandas",
"elasticsearch",
"pyelasticsearch"
] |
Customize ONBUILD environment in a dockerfile | 38,180,964 | <p>I am slightly modifying <a href="https://github.com/docker-library/python/blob/682708e7866caccd3f476f1d30ca60c0851249e1/3.5/onbuild/Dockerfile" rel="nofollow">this Dockerfile</a> to support my specific usecase: I need to specify my own <code>PyPi</code> server, where we are publishing our internal libraries. This ca... | 1 | 2016-07-04T09:16:11Z | 38,181,300 | <p>The <a href="https://docs.docker.com/engine/reference/builder/#/onbuild" rel="nofollow"><code>ONBUILD</code> instruction</a> adds to the image a trigger instruction to be executed at a later time, when the image is used as the base for another build. </p>
<p><a href="https://docs.docker.com/engine/reference/builde... | 1 | 2016-07-04T09:31:59Z | [
"python",
"docker",
"dockerfile"
] |
Convert fractions into decimal (fractions are in superscript) | 38,180,999 | <p>I am pulling text from a site and would like to convert the fractions into decimal.</p>
<p>The fractions are in subscript though and look like the following</p>
<p>1¼,4½</p>
<p>is it possible to get around this?</p>
| 2 | 2016-07-04T09:17:43Z | 38,181,265 | <p>You must parse these numbers out from text (depends encoding), use example some parser combinator or similar. Then you can calculate decimals.</p>
| -1 | 2016-07-04T09:30:54Z | [
"python"
] |
Convert fractions into decimal (fractions are in superscript) | 38,180,999 | <p>I am pulling text from a site and would like to convert the fractions into decimal.</p>
<p>The fractions are in subscript though and look like the following</p>
<p>1¼,4½</p>
<p>is it possible to get around this?</p>
| 2 | 2016-07-04T09:17:43Z | 38,181,342 | <p>Try this:</p>
<pre><code>dict = {
'¼':0.25,
'½':0.50,
}
def Convert(line):
return [int(word[:-1])+dict[word[-1]] if word[-1] in dict else int(word) for word in line.split(',')]
</code></pre>
<p>If you have any other such symbols, then simply add them to <code>dict</code>.</p>
| 0 | 2016-07-04T09:33:49Z | [
"python"
] |
Convert fractions into decimal (fractions are in superscript) | 38,180,999 | <p>I am pulling text from a site and would like to convert the fractions into decimal.</p>
<p>The fractions are in subscript though and look like the following</p>
<p>1¼,4½</p>
<p>is it possible to get around this?</p>
| 2 | 2016-07-04T09:17:43Z | 38,181,664 | <p>Building on @barak manos' idea, i would just go and look for all my dictionary keys in every line and replace them on site like so:</p>
<pre><code>dict = {
'¼': '.25',
'½': '.50',
}
def convert(line, dict):
for x in dict:
line = line.replace(x, dict[x])
line = line.replace(' ' + d... | 0 | 2016-07-04T09:50:12Z | [
"python"
] |
Flask SQLAlchemy DB connections with MYSQL | 38,181,140 | <p>I am using falsk SQLAlchemy with MYSQL with all default configuration(pool size and timeout)</p>
<p>I don't understand why do I get out of DB connections from the MYSQL DB?
My server is not that heavy loaded.</p>
<p>Can someone please explain how the flask sql alchemy get and release DB connections?</p>
<p>If I h... | 0 | 2016-07-04T09:24:39Z | 38,229,152 | <p>try this code</p>
<pre><code>import sqlalchemy
dbhost = 'localhost' #host name
dbuser = 'root' #mysql username
dbpass = 'admin' #mysql password
dbname = 'mytable' #database name
engine = sqlalchemy.create_engine('mysql://'+dbuser+':'+dbpass+'@'+dbhost ) # connect to server
DB_URI = 'mysql://' + dbuser + ':' + db... | 0 | 2016-07-06T16:33:51Z | [
"python",
"mysql",
"flask-sqlalchemy"
] |
looped sklearn euclidean distances optimisation | 38,181,150 | <p>Im looking from smart ways to optimise this looped euclidean distance calculation. This calculation is looking for the mean distance from all other vectors. </p>
<p>As my vector arrays are really big to just do: eucl_dist = euclidean_distances(eigen_vs_cleaned)
Im running a loop row by row.</p>
<p>Typical eigen_vs... | 0 | 2016-07-04T09:25:13Z | 38,199,877 | <p>Im no python/numpy guru but this is the first step I took optimising this. it runs way better on my MacPro at least.</p>
<pre><code>from joblib import Parallel, delayed
import multiprocessing
import os
import tempfile
import shutil
from sklearn.metrics.pairwise import euclidean_distances
# Creat a temporary direc... | 0 | 2016-07-05T09:31:50Z | [
"python",
"numpy",
"scipy",
"scikit-learn"
] |
API/JSON Connection | 38,181,183 | <p>I am trying to connect to an API so I can grab data to use in some spatial analytics. This is my first program in Python. I have been able to connect to the API and can grab the fields i need from the resulting JSON file(s). </p>
<p>My main issue is actually combining it all together. As it stands now I have two op... | 0 | 2016-07-04T09:26:48Z | 38,182,790 | <p>Instead of appending everything into a single array like you are currently, if you instead store all values of one iteration into an array and append that to another array you can simply convert that two-dimensional array into a csv file directly using the csv module.</p>
<p><strong>this solution works for python 3... | 0 | 2016-07-04T10:45:08Z | [
"python"
] |
error when trying to use webrtcvad | 38,181,309 | <p>I am trying to do voice activity detection using webrtcvad 2.0.8. This <a href="http://link" rel="nofollow">https://pypi.python.org/pypi/webrtcvad</a> provides the basic procedure. When I try to implement it as follows, I get an error.
my code:</p>
<pre><code>import webrtcvad
from scipy.io import wavfile
import sc... | 1 | 2016-07-04T09:32:24Z | 38,249,075 | <p>webrtcvad expects buffer to be a string with data bytes, not an array of floats. You can do something like </p>
<pre><code>fr = np.int16(Z[100] * 32768).tobytes()
vad.is_speech(fr, fs)
</code></pre>
| 1 | 2016-07-07T15:09:17Z | [
"python",
"voice-recognition"
] |
Read and access twitter response in json format | 38,181,325 | <p>I am reading twitter response as a json and trying to read it's content.</p>
<p>I have applied json loads, even it displays result value as invalid json. Twitter response has been stored into .json file</p>
<pre><code> with open(filename) as f:
for line_terminated in f:
line = line_terminate... | 0 | 2016-07-04T09:32:58Z | 38,181,402 | <blockquote>
<p>Which I can not access as dic</p>
</blockquote>
<p>Eh, No. <code>doc</code> is a dictionary and values can be accessed using the keys:</p>
<pre><code>>>> doc = {u'contributors': None, u'truncated': False}
>>> doc['truncated']
False
</code></pre>
<p>But you have certain values that... | 2 | 2016-07-04T09:36:52Z | [
"python",
"json"
] |
Soup object to text file | 38,181,394 | <p>I referred to a solution on stack over flow regarding this problem but somehow it still isn't working. It shows this error: </p>
<pre><code>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 3604: ordinal not in range(128)
</code></pre>
<p>The code for the program is:</p>
<pre><code>impo... | 0 | 2016-07-04T09:36:43Z | 38,181,704 | <p>I found the solution as follows:</p>
<pre><code>import urllib
from bs4 import BeautifulSoup
fhand = urllib.urlopen('https://en.wikipedia.org/wiki/Michael_Francis_Egan')
soup = BeautifulSoup(fhand).get_text()
f = open("myoutputfile.txt","w")
f.write(soup.encode('utf-8'))
</code></pre>
| 0 | 2016-07-04T09:52:20Z | [
"python"
] |
Running a python script over multiple files to extract messages | 38,181,425 | <p>I have found a handy python script online that allows me to extract the text and attatchments from a .msg file (saved email from outlook)</p>
<p>-link to the script: <a href="https://github.com/mattgwwalker/msg-extractor" rel="nofollow">https://github.com/mattgwwalker/msg-extractor</a></p>
<p>If I run the script f... | 0 | 2016-07-04T09:37:48Z | 38,181,504 | <p>Try glob. It allows you to easily iterate over files. </p>
<pre><code>import glob
files = glob.glob('folder/*.msg')
for file in files:
# whatever you do to individual files goes here
</code></pre>
| 0 | 2016-07-04T09:42:03Z | [
"python",
"email",
"ole",
"extraction"
] |
Ansible cannot import docker-py even though it is installed | 38,181,433 | <p>I checked <a href="http://stackoverflow.com/questions/30350881/centos7-docker-py-doesnt-seem-to-be-installed">this post</a> and followed the fix in both answers and neither worked. I'm opening a new post partly because of that and partly because I'm getting a slightly different error even though the problem might b... | 2 | 2016-07-04T09:38:06Z | 38,183,612 | <p>The requirements for the docker-py module on ansible's documentation for the docker* modules is not really up-to-date, but generally here are some ansible - docker-py pairs that should work:</p>
<ul>
<li><p>Ansible 2.1.0.0 requires docker-py version 1.7.0 at least, which in turn requires at least docker 1.9 install... | 0 | 2016-07-04T11:27:23Z | [
"python",
"docker",
"pip",
"ansible"
] |
What is the difference between using universal_newlines=True (with bufsize=1) and using default arguments with Popen | 38,181,494 | <p>I am trying to read the output of a subprocess called from Python. To do this I am using Popen (because I do not think it is possible to pipe stdout if using subprocess.call).</p>
<p>As of now I have two ways of doing it which, in testing, seem to provide the same results. The code is as follows:</p>
<pre><code>w... | 0 | 2016-07-04T09:41:26Z | 38,182,530 | <blockquote>
<p>What is the difference between using universal_newlines=True (with bufsize=1) and using default arguments with Popen</p>
</blockquote>
<p>The default values are: <strong><em><code>universal_newlines=False</code></em></strong> (meaning input/output is accepted as <strong>bytes</strong>, not Unicode st... | 2 | 2016-07-04T10:31:37Z | [
"python",
"python-3.x",
"subprocess",
"popen"
] |
Query DSL in ElasticSearch - term query | 38,181,507 | <p>I am new to the query DSL in elastic Search. I am trying python to query the index in Elastic Search.
Below is the document I am trying to filter for using the query.</p>
<pre><code>{u'_id': u'5',
u'_index': u'data',
u'_score': 1.0,
u'_source': {u'attributes': {u'Accepts Credit Cards': False,
u'Pa... | 0 | 2016-07-04T09:42:12Z | 38,182,012 | <p>Unless you are specifying the mapping for the field "name" to be {"index": "not_analyzed"} it will default to being "analyzed", which means that that the string value will be 'broken up' when indexed to facilitate full text search.</p>
<p>The "term" query will look for an exact match of the text, but if "Verizon" i... | 0 | 2016-07-04T10:07:19Z | [
"python",
"elasticsearch",
"querydsl"
] |
md5sum shell script and python hashlib.md5 is different | 38,181,554 | <p>I am comparing two qcow2 images file at two different location to see difference.
/opt/images/file.qcow2
/mnt/images/file.qcow2</p>
<p>When i run </p>
<pre><code>md5sum /opt/images/file.qcow2
md5sum /mnt/images/file.qcow2
</code></pre>
<p>both files the checksum is same</p>
<p>But when try to find md5sum using... | 1 | 2016-07-04T09:44:46Z | 38,181,627 | <p>You are hashing the path of the file, not the content ...</p>
<pre><code>hashlib.md5(file1).hexdigest() # file1 = '/path/to/file.ext'
</code></pre>
<p>To <a href="http://stackoverflow.com/a/3431838/956660">hash the content:</a></p>
<pre><code>def md5(fname):
hash_md5 = hashlib.md5()
with open(fname, "rb")... | 4 | 2016-07-04T09:48:43Z | [
"python",
"shell"
] |
md5sum shell script and python hashlib.md5 is different | 38,181,554 | <p>I am comparing two qcow2 images file at two different location to see difference.
/opt/images/file.qcow2
/mnt/images/file.qcow2</p>
<p>When i run </p>
<pre><code>md5sum /opt/images/file.qcow2
md5sum /mnt/images/file.qcow2
</code></pre>
<p>both files the checksum is same</p>
<p>But when try to find md5sum using... | 1 | 2016-07-04T09:44:46Z | 38,181,637 | <p>Try this:</p>
<pre><code>from hashlib import md5
def md5File(filename):
hasher = md5()
blockSize = 16 * 1024 * 1024
with open(filename, 'rb') as f:
while True:
fileBuffer = f.read(blockSize)
if not fileBuffer:
break
hasher.update(fileBuffer)... | 1 | 2016-07-04T09:49:05Z | [
"python",
"shell"
] |
md5sum shell script and python hashlib.md5 is different | 38,181,554 | <p>I am comparing two qcow2 images file at two different location to see difference.
/opt/images/file.qcow2
/mnt/images/file.qcow2</p>
<p>When i run </p>
<pre><code>md5sum /opt/images/file.qcow2
md5sum /mnt/images/file.qcow2
</code></pre>
<p>both files the checksum is same</p>
<p>But when try to find md5sum using... | 1 | 2016-07-04T09:44:46Z | 38,181,988 | <p>How about using the code below:</p>
<pre><code>def isImageLatest(file1,file2):
print('Checking md5sum of {} {}'.format(file1, file2))
if os.path.isfile(file1) and os.path.isfile(file2):
md5File1 = hashlib.md5(open(file1,"rb").read()).hexdigest()
md5File2 = hashlib.md5(open(file2,"rb").read(... | 1 | 2016-07-04T10:06:31Z | [
"python",
"shell"
] |
xlsxwriter is creating a corrupted file | 38,181,624 | <p>I'm using this code to test xlswriter functionnalitues.</p>
<pre><code> import xlsxwriter
# -*- coding: utf-8-sig-*-
workbook = xlsxwriter.Workbook("filename.xlsx")
worksheet = workbook.add_worksheet()
worksheet.add_table(0,0, 1, 11,{'columns': [{'header': 'ID'},
{'head... | 2 | 2016-07-04T09:48:33Z | 38,182,382 | <p>The issue in the second example is that Excel doesn't allow you to have two table headers with the same case-insensitive value ("1" in this case). The following works:</p>
<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook("filename.xlsx")
worksheet = workbook.add_worksheet("hi")
worksheet.add_table(0, ... | 3 | 2016-07-04T10:24:05Z | [
"python",
"excel",
"xlsxwriter"
] |
Use Flask view that requires query args outside of request | 38,181,692 | <p>I have a Flask view that uses <code>request.args</code> to get some query args from the request. I want to call it as a function outside of a request, so <code>request.args</code> won't be available. How can I modify the view function to work independently?</p>
<pre><code>http://localhost:5000/version/perms?arg1=... | 0 | 2016-07-04T09:51:55Z | 38,182,117 | <p>There is support to get URL parts into python variables, but AFAIK it does not work with query parameters, you need to use request.args for that.</p>
<pre><code>from flask import request
@app.route(version + 'perms', methods=['GET'])
def get_perm():
arg1 = request.args.get('arg1')
arg2 = request.args.get('a... | 2 | 2016-07-04T10:11:40Z | [
"python",
"flask"
] |
Iterating through (JSON?) map in Python | 38,181,697 | <p>I have a datastructure like that:</p>
<pre><code>sample_map= {'key1': {'internal_key1': ['value1']},
'key2': {'internal_key2': ['value2']},
}
</code></pre>
<p>I would like to iterate throgh on every line key1 and key2. I would like to get the value of 'internal_key1' and 'value_1'vari... | -2 | 2016-07-04T09:52:10Z | 38,181,736 | <pre><code>for item in sample_map.values():
for k, v in item.items():
print k, v
</code></pre>
| 2 | 2016-07-04T09:54:12Z | [
"python",
"json"
] |
Iterating through (JSON?) map in Python | 38,181,697 | <p>I have a datastructure like that:</p>
<pre><code>sample_map= {'key1': {'internal_key1': ['value1']},
'key2': {'internal_key2': ['value2']},
}
</code></pre>
<p>I would like to iterate throgh on every line key1 and key2. I would like to get the value of 'internal_key1' and 'value_1'vari... | -2 | 2016-07-04T09:52:10Z | 38,181,832 | <p>How about the following:</p>
<pre><code>for k,v in sample_map.iteritems():
print k
for k1,v1 in v.iteritems():
print k1,v1[0]
</code></pre>
<p>This will print the following:</p>
<pre><code>key2
internal_key2 value2
key1
internal_key1 value1
</code></pre>
| 0 | 2016-07-04T09:58:40Z | [
"python",
"json"
] |
Iterating through (JSON?) map in Python | 38,181,697 | <p>I have a datastructure like that:</p>
<pre><code>sample_map= {'key1': {'internal_key1': ['value1']},
'key2': {'internal_key2': ['value2']},
}
</code></pre>
<p>I would like to iterate throgh on every line key1 and key2. I would like to get the value of 'internal_key1' and 'value_1'vari... | -2 | 2016-07-04T09:52:10Z | 38,181,886 | <p>This is called a dictionary (type <a href="https://docs.python.org/2/library/stdtypes.html#dict" rel="nofollow">dict</a>). It does resemble the JSON structure, although JSON is a format in which a string is built to represent a specific structure of data, and <code>dict</code> is a structure of data (that can be con... | 1 | 2016-07-04T10:01:03Z | [
"python",
"json"
] |
TkMessageBox - No Module | 38,181,710 | <pre><code>import TkMessageBox
</code></pre>
<p>When I import TkMessageBox it displays the messsge <em>'ImportError: No module named 'TkMessageBox'</em>.</p>
<p>As far as I know im using python 3.3.2 and Tk 8.5.</p>
<p>Am I using the wrong version of python or importing it wrong ?</p>
<p>Any answers would be extrem... | 1 | 2016-07-04T09:52:46Z | 38,181,986 | <p>In Python3.x things have changed a little bit:</p>
<pre><code> >>> import tkinter
>>> import tkinter.messagebox
>>>
</code></pre>
<p>I mean what we call <code>tkMessageBox</code> in Python2.x becomes <code>tkinter.messagebox</code> in Python3.x</p>
| 1 | 2016-07-04T10:06:14Z | [
"python",
"tkinter",
"tk"
] |
TkMessageBox - No Module | 38,181,710 | <pre><code>import TkMessageBox
</code></pre>
<p>When I import TkMessageBox it displays the messsge <em>'ImportError: No module named 'TkMessageBox'</em>.</p>
<p>As far as I know im using python 3.3.2 and Tk 8.5.</p>
<p>Am I using the wrong version of python or importing it wrong ?</p>
<p>Any answers would be extrem... | 1 | 2016-07-04T09:52:46Z | 38,187,388 | <p>In Python 2.x, to import, you'd say <code>import tkMessageBox</code>. But in Python 3.x, it's been renamed to import <code>tkinter.messagebox</code>.</p>
<p>Hope it helped :))</p>
| 0 | 2016-07-04T14:45:36Z | [
"python",
"tkinter",
"tk"
] |
what is best for string extraction or pattern matching regex / awk / emacs lisp? | 38,181,762 | <p>I am suppose to find if a given file is a media file, not through extension, but through the header information. So i opened some <code>.MOV</code> file format with emacs to just observe what can be done what is inside etc . On analyzing the contents i found that some strings where not only in the first line(header ... | 1 | 2016-07-04T09:55:43Z | 38,181,898 | <p>As you said you are suppose to find if a given file is a media file, not through extension. I can offer you 2 possibility:</p>
<ol>
<li><p>Magic number in file</p>
<p>So have a look at wikipedia definition of magic number for file:</p></li>
</ol>
<blockquote>
<p>Magic numbers are common in programs across many... | 2 | 2016-07-04T10:01:34Z | [
"python",
"regex",
"search",
"awk",
"emacs"
] |
what is best for string extraction or pattern matching regex / awk / emacs lisp? | 38,181,762 | <p>I am suppose to find if a given file is a media file, not through extension, but through the header information. So i opened some <code>.MOV</code> file format with emacs to just observe what can be done what is inside etc . On analyzing the contents i found that some strings where not only in the first line(header ... | 1 | 2016-07-04T09:55:43Z | 38,192,107 | <p>The commands <code>file</code> and <code>strings</code> are a good zeroth order approximation of what you are asking to do. </p>
<p>If the output of <code>file</code> passes your acceptance criteria, pipe the output of <code>strings</code> to a file </p>
| 3 | 2016-07-04T20:54:26Z | [
"python",
"regex",
"search",
"awk",
"emacs"
] |
Data Doesn't Come in Requests Response | 38,181,797 | <p>I am new to python, data scraping, and automation. I am trying to scrape the website given in <code>URL</code>. When I open the <code>URL</code> link in browser all the data is shown however the response of the <code>requests.get()</code> method doesn't give that data.</p>
<p>It would be really helpful if anyone ca... | 1 | 2016-07-04T09:57:25Z | 38,182,805 | <p>I tried with <code>allow_redirects=True</code> and <code>headers</code> param with User Agent, still got noting:</p>
<pre><code>URL = "https://fees.uspto.gov/MaintenanceFees/fees/details?applicationNumber=12814074&patentNumber=7871455"
headers = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36... | 0 | 2016-07-04T10:45:43Z | [
"python",
"beautifulsoup",
"python-requests"
] |
Data Doesn't Come in Requests Response | 38,181,797 | <p>I am new to python, data scraping, and automation. I am trying to scrape the website given in <code>URL</code>. When I open the <code>URL</code> link in browser all the data is shown however the response of the <code>requests.get()</code> method doesn't give that data.</p>
<p>It would be really helpful if anyone ca... | 1 | 2016-07-04T09:57:25Z | 38,182,920 | <p>As per my comment the data you want is dynamically generated so it is simply not in the source you get returned, requests handles redirects for you automatically for get requests so that could also never really be an issue:</p>
<p>You can get the info you want can be done by mimicking an ajax request using a simpl... | 1 | 2016-07-04T10:52:21Z | [
"python",
"beautifulsoup",
"python-requests"
] |
BeautifulSoup encoding.bytes has no attribute called find_all? | 38,181,977 | <pre><code> `self.urlOpen=urllib.request.urlopen("http://facebook.com")
self.content=self.urlOpen.read()
soup=BeautifulSoup(self.content,"html5lib")
self.links=soup.find_all("a")`
</code></pre>
<blockquote>
<p>'charmap' codec can't encode characters in position....</p>
</blockquote>
<p>so when i try to encode... | -1 | 2016-07-04T10:05:49Z | 38,182,373 | <p>What is the issue?<br>
<code>find_all</code> shouldn't be throwing an encoding error, and you shouldn't be calling <code>encode</code> on a <code>bs4.BeautifulSoup</code> object, as <code>encode</code> returns a bytestring - not a soup! - so you can't call <code>find_all</code> on it.</p>
<p>Are you using <code>sou... | 0 | 2016-07-04T10:23:47Z | [
"python",
"encoding",
"utf-8",
"beautifulsoup"
] |
Third order moment calculation - numpy | 38,182,087 | <p>In python, I have an array X with N rows (the number of examples) and n columns (the number of features).</p>
<p>If I want to calculate the second order moment matrix C </p>
<p>C[i,j] = E(x_i x_j)</p>
<p>then I have two possibility:</p>
<ul>
<li><p>First, do the loop:</p>
<pre>
for i in range(N):
for j in r... | 2 | 2016-07-04T10:10:56Z | 38,182,244 | <p>I know it is not perfect in terms of speed, but why not using <code>np.power(x, 3).sum() / N</code>? It is slower than the dot product, but faster than looping.</p>
<pre><code>In [1]: import numpy as np
In [2]: x = np.random.rand(10000)
In [3]: x.dot(x.T)
Out[3]: 3373.6189738897856
In [4]: %timeit(x.dot(x.T))
The s... | 0 | 2016-07-04T10:18:05Z | [
"python",
"algorithm",
"numpy",
"matrix"
] |
Third order moment calculation - numpy | 38,182,087 | <p>In python, I have an array X with N rows (the number of examples) and n columns (the number of features).</p>
<p>If I want to calculate the second order moment matrix C </p>
<p>C[i,j] = E(x_i x_j)</p>
<p>then I have two possibility:</p>
<ul>
<li><p>First, do the loop:</p>
<pre>
for i in range(N):
for j in r... | 2 | 2016-07-04T10:10:56Z | 38,182,350 | <p>You can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>NumPy's einsum notation</code></a> to solve both your second and third order cases.</p>
<p><strong>Second order :</strong></p>
<pre><code>np.einsum('ij,ik->jk',X,X)/N
</code></pre>
<p><strong>Third ... | 3 | 2016-07-04T10:22:54Z | [
"python",
"algorithm",
"numpy",
"matrix"
] |
Numpy/pandas optimization: bins counting | 38,182,101 | <p>I would like to "bin" a <code>numpy.array</code> or <code>pandas.Series</code> <code>x</code> by counting the number <code>N</code> of values between <code>begin</code> and <code>end</code>. The result is stored in a <code>pandas.DataFrame</code>:</p>
<pre><code>import numpy as np
import pandas as pd
bins = pd.Data... | 3 | 2016-07-04T10:11:21Z | 38,182,984 | <p>If <em>"...boundaries have fixed width, as [[min + 0 width, min + 1 width], [min + 1 width, min + 2 width], ..., [max - 1 width, max]]..."</em>, use <code>numpy.histogram</code>:</p>
<pre><code>bins["N"] = numpy.histogram(x, numpy.concatenate([bins["from"], bins["to"].tail(1)]))[0]
</code></pre>
<p>It would be sim... | 2 | 2016-07-04T10:55:26Z | [
"python",
"numpy",
"pandas",
"optimization",
"lambda"
] |
Numpy/pandas optimization: bins counting | 38,182,101 | <p>I would like to "bin" a <code>numpy.array</code> or <code>pandas.Series</code> <code>x</code> by counting the number <code>N</code> of values between <code>begin</code> and <code>end</code>. The result is stored in a <code>pandas.DataFrame</code>:</p>
<pre><code>import numpy as np
import pandas as pd
bins = pd.Data... | 3 | 2016-07-04T10:11:21Z | 38,182,992 | <p>The fact that the intervals are of regular size could be abused to speed up the code quite a bit. Thus, with the parameters set, you can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.bincount.html" rel="nofollow"><code>NumPy's bincount procedure</code></a>, like so -</p>
<pre><code># First ... | 3 | 2016-07-04T10:56:00Z | [
"python",
"numpy",
"pandas",
"optimization",
"lambda"
] |
How to load SVM data from file in OpenCV 3.1? | 38,182,132 | <p>I have a problem with load trained SVM from file. I use Python and OpenCv 3.1.0. I create svm object by: </p>
<pre><code>svm = cv2.ml.SVM_create()
</code></pre>
<p>Next, I train svm and save to file by:</p>
<pre><code>svm.save('data.xml')
</code></pre>
<p>Now i want to load this file in other Python script. In ... | 0 | 2016-07-04T10:12:20Z | 38,956,656 | <p>I think it's a litte bit confusing that there is no svm.load(filepath) method as a counterpart of svm.save(filepath), but when I read the module help it makes sense to me that SVM_load is a child of cv2.ml (sibling of SVM_create).</p>
<p>Be sure that your opencv <strong>master</strong> branch is up-to-date (current... | 0 | 2016-08-15T14:06:52Z | [
"python",
"svm",
"opencv3.1"
] |
Python Logging: INFO,DEBUG Logs not displayed | 38,182,177 | <p>Python Version : 2.7</p>
<p>I am using the below code to display the logs on console. However, INFO and DEBUG logs are not displayed. </p>
<p><strong>Code</strong></p>
<pre><code>import logging
class LogTest():
def __init__(self):
logger_obj = logging.getLogger('Sample Logger')
console_logger ... | 0 | 2016-07-04T10:14:52Z | 38,182,614 | <ol>
<li><p>You're setting log level for stream handler while you have to do it for logger itself (<code>logger_obj</code> in your case). Handler is used to apply additional filters to logs, but it they are first filtered by logger itself.</p></li>
<li><p>DEBUG > INFO, so you have to set level to DEBUG, not INFO (If yo... | 1 | 2016-07-04T10:35:58Z | [
"python",
"python-2.7",
"logging"
] |
Run Python program as administrator from command line | 38,182,418 | <p>I'm trying to run my program as an administrator from the command line. Seems quite easy but I'm struggling.</p>
<p>I started with this, which works fine launched from the Python IDLE:</p>
<pre><code>import dropbox, pymysql, shlex, shutil, subprocess
import logging
import sshtunnel
from sshtunnel import SSHTunnel... | 0 | 2016-07-04T10:25:54Z | 38,201,648 | <blockquote>
<p>is the default of python is 3 ? If not try to execute like this: sudo
python3 ... â @Koffee</p>
</blockquote>
<p>Thanks to @Koffee we have an answer and this thread can be marked as solved and closed.</p>
| 0 | 2016-07-05T10:56:07Z | [
"python",
"python-3.x"
] |
Scrapy, proxy not working | 38,182,456 | <p>I'm trying to make scrapy go through proxy, but without success.</p>
<p>I'm passing to request meta proxy like:</p>
<pre><code>http://zqal.xyz
http://pro6y.com
http://fermatfibonacci.info
http://newproxy.ninja
etc.
</code></pre>
<p>And when I type some random page through shell, displayed page is not the one that... | 1 | 2016-07-04T10:27:46Z | 38,207,507 | <p>Have you ever thought of using Proxicity.io (<a href="https://www.proxicity.io" rel="nofollow">https://www.proxicity.io</a>)? They serve tested proxies at random with every API call. That way, you dont have to worry about proxies being live, etc. You would have to change the rank for middlewares based on what you ha... | 0 | 2016-07-05T15:39:36Z | [
"python",
"proxy",
"scrapy",
"web-crawler",
"scrapy-spider"
] |
Simulate if-in statement in Java | 38,182,463 | <p>I've coded for several months in Python, and now i have to switch to Java for work's related reasons. My question is, there is a way to simulate this kind of statement</p>
<pre><code>if var_name in list_name:
# do something
</code></pre>
<p>without defining an additional <code>isIn()</code>-like boolean functi... | 4 | 2016-07-04T10:28:15Z | 38,182,484 | <p>You're looking for <a href="https://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)" rel="nofollow"><code>List#contains</code></a> which is inherited from <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#contains(java.lang.Object)" rel="nofollow"><code>Col... | 12 | 2016-07-04T10:29:21Z | [
"java",
"python",
"if-statement"
] |
Simulate if-in statement in Java | 38,182,463 | <p>I've coded for several months in Python, and now i have to switch to Java for work's related reasons. My question is, there is a way to simulate this kind of statement</p>
<pre><code>if var_name in list_name:
# do something
</code></pre>
<p>without defining an additional <code>isIn()</code>-like boolean functi... | 4 | 2016-07-04T10:28:15Z | 38,182,594 | <p>You can use List.contains(object), but make sure your class which you have used to create list, is implementing equals for proper equals check. Otherwise you will be able to only get two objects equal only if object itself is same.</p>
| 3 | 2016-07-04T10:35:00Z | [
"java",
"python",
"if-statement"
] |
Simulate if-in statement in Java | 38,182,463 | <p>I've coded for several months in Python, and now i have to switch to Java for work's related reasons. My question is, there is a way to simulate this kind of statement</p>
<pre><code>if var_name in list_name:
# do something
</code></pre>
<p>without defining an additional <code>isIn()</code>-like boolean functi... | 4 | 2016-07-04T10:28:15Z | 38,182,602 | <p>The java.util.ArrayList.contains(Object) method returns true if this list contains the specified element.</p>
<pre><code>List list=new ArrayList();
list.add(1);
list.add(2);
if(list.contains(2)){
//do something
}
</code></pre>
| 2 | 2016-07-04T10:35:12Z | [
"java",
"python",
"if-statement"
] |
Simulate if-in statement in Java | 38,182,463 | <p>I've coded for several months in Python, and now i have to switch to Java for work's related reasons. My question is, there is a way to simulate this kind of statement</p>
<pre><code>if var_name in list_name:
# do something
</code></pre>
<p>without defining an additional <code>isIn()</code>-like boolean functi... | 4 | 2016-07-04T10:28:15Z | 38,182,884 | <p>the contains method of the list data structure is what you're after. You can use this in 1 of two ways:</p>
<pre><code>boolean return_flag = list_name.contains(var_name)
if return_flag{
//do stuff
}
</code></pre>
<p>or</p>
<pre><code>if list_name.contains(var_name){
//do stuff
}
</code></pre>
<p>as in Yas... | 1 | 2016-07-04T10:50:09Z | [
"java",
"python",
"if-statement"
] |
Python Timer consuming too much cpu | 38,182,529 | <p>Running below sometimes fails to alert after 9 hours and more over it's consuming 30% or more CPU, when I check in Task Manager. If anyone can tweak this it would be great.</p>
<pre><code>import time
import ctypes
def timer(hours):
seconds = hours * 3600
start = time.time()
time.clock()
elapsed = 0
... | 1 | 2016-07-04T10:31:34Z | 38,182,659 | <p>Try this:</p>
<pre><code>import time
import ctypes
def timer(hours):
seconds = hours * 3600
start = time.time()
elapsed = 0
while elapsed < seconds:
# Do something once every minute.
time.sleep(60)
elapsed = time.time() - start
elapsed = elapsed//60
ctypes.wind... | 1 | 2016-07-04T10:38:07Z | [
"python",
"ctypes"
] |
Python Timer consuming too much cpu | 38,182,529 | <p>Running below sometimes fails to alert after 9 hours and more over it's consuming 30% or more CPU, when I check in Task Manager. If anyone can tweak this it would be great.</p>
<pre><code>import time
import ctypes
def timer(hours):
seconds = hours * 3600
start = time.time()
time.clock()
elapsed = 0
... | 1 | 2016-07-04T10:31:34Z | 38,182,661 | <p>Wouldn't this achieve the exact same thing? Since you are not doing anything while looping anyways.</p>
<pre><code>import time
import ctypes
def timer(hours):
start = this.time()
time.sleep(hours * 3600)
ctypes.windll.user32.MessageBoxA(0,"Done "+str(hours) + " Hrs", "Done", 0)
</code></pre>
| 1 | 2016-07-04T10:38:14Z | [
"python",
"ctypes"
] |
Add single certificate to requests | 38,182,773 | <p>I am trying to connect to a corporate intranet HTTPS server, which uses an in-house CA, from within Python/requests running on a Linux machine. I have a .pem file that contains our certificate (4096 bit RSA, CSSM_KEYUSE_VERIFY, CA = true).</p>
<p>I put this into a subfolder of <code>/usr/share/ca-certificates</cod... | 1 | 2016-07-04T10:44:03Z | 38,571,168 | <p>Thanks to @stark, I found out that the problem was that my certificate file was expired. With the correct, up-to-date certificate (even in DER format, with the .cer extension), the following syntax now works:</p>
<pre><code>requests.get(download_url, verify = cer_file_path)
</code></pre>
| 0 | 2016-07-25T14:59:46Z | [
"python",
"ssl",
"python-requests"
] |
Python git downloading Jupyter Notebook | 38,182,846 | <p>I am trying to download a Jupyter Notebook from git. I downloaded the notebook by right clicking on the file and saving it.
It is an ipynb file, but the file size seems a bit big to me for the content that it should contain (114 kb). When I click on the Notebook in Jupyter I get the following error: </p>
<p>Unreada... | 0 | 2016-07-04T10:48:06Z | 38,183,170 | <p>You probably downloaded the html github uses to display a notebook. To download the notebook itself, you can use the "raw" file link in github. </p>
| 2 | 2016-07-04T11:04:09Z | [
"python",
"git",
"jupyter",
"jupyter-notebook"
] |
Obtain IP Adress from MAC using python | 38,182,966 | <p>I have a device in my local network and know its MAC Adress. It gets it's IP address automatically via DHCP. I want to obtain this IP.</p>
<p>I dont want to use nmap but scapy would be fine, as I'm importing from a kivy app.</p>
<p>I found:</p>
<pre><code>from scapy.all import srp, Ether, ARP
ans,unans=srp(Ether(... | 1 | 2016-07-04T10:54:35Z | 38,183,110 | <p>If the stucture of summary is always the same (what I assume), then you could <code>import re</code> and use a regex to extract the IP address. </p>
<p>Should be something like:</p>
<pre><code>re.sub(r'.* says (.*) ==> Ether / ARP is.*', r'\1', ans.summary())
</code></pre>
<p>That works for me:</p>
<pre><code... | 0 | 2016-07-04T11:01:16Z | [
"python",
"ip",
"scapy",
"mac-address"
] |
Obtain IP Adress from MAC using python | 38,182,966 | <p>I have a device in my local network and know its MAC Adress. It gets it's IP address automatically via DHCP. I want to obtain this IP.</p>
<p>I dont want to use nmap but scapy would be fine, as I'm importing from a kivy app.</p>
<p>I found:</p>
<pre><code>from scapy.all import srp, Ether, ARP
ans,unans=srp(Ether(... | 1 | 2016-07-04T10:54:35Z | 38,212,155 | <p>Yes, you can do that using scapy. Here is an example of an ARP is-at packet:</p>
<pre><code>###[ Ethernet ]###
dst= 08:00:27:fa:25:8e
src= 08:00:27:b1:af:68
type= 0x806
###[ ARP ]###
hwtype= 0x1
ptype= 0x800
hwlen= 6
plen= 4
op= is-at
hwsrc= 08:00:27:b1:af:68
psrc= 192.... | 2 | 2016-07-05T20:28:05Z | [
"python",
"ip",
"scapy",
"mac-address"
] |
Python Scrapy can't get pseudo class ":not()" | 38,182,972 | <p>It's OK to write</p>
<pre><code>content.css('.text>p::text').extract()
</code></pre>
<p>But</p>
<pre><code>content.css('.text:not(.text .text)>p::text').extract()
</code></pre>
<p>will not work.
It tells me:</p>
<pre><code>SelectorSyntaxError: Expected ')', got <S ' ' at 15>
</code></pre>
<p>Yes, t... | 0 | 2016-07-04T10:54:53Z | 38,197,503 | <p>How about trying <a href="https://developer.mozilla.org/en/docs/Web/CSS/:nth-child" rel="nofollow">nth-child(1)</a>?</p>
<p>So your css would be:</p>
<pre><code>".text:nth-child(1)>p"
</code></pre>
<p>In Scrapy:</p>
<pre><code>In [54]: from scrapy import Selector
In [55]: a
Out[55]: u"<div><div clas... | 0 | 2016-07-05T07:21:40Z | [
"python",
"css-selectors",
"scrapy",
"scrapy-spider"
] |
Exception in thread "main" java.lang.UnsatisfiedLinkError: no jep in java.library.path | 38,183,062 | <p>I have 'libjep.so' file after downloading jep and I also had set the environmental variable <code>LD_LIBRARY_PATH</code> in <code>~./bashrc</code> as shown below:</p>
<pre><code>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib/python2.7/dist-packages/jep/libjep.so
</code></pre>
<p>as well as in runtime</p>
... | 0 | 2016-07-04T10:59:24Z | 38,183,238 | <p>The <code>java.lang.UnsatisfiedLinkError</code> occurs only when if the required library is not in the path or it is already loaded.
Couple of things you need to make sure is :</p>
<p>1) You're performing <code>System.load(....)</code> inside static block so that its executed only once.<br>
2) Also, you can try rem... | 0 | 2016-07-04T11:08:28Z | [
"java",
"python",
"python-2.7",
"python-3.x",
"machine-learning"
] |
Python 3.5 pip version conflict with python 2.7 | 38,183,152 | <p>I am trying to install a software using pip install and my python and pip versions are 3.5. but when I run <code>sudo pip install -e .</code> I get the following error. </p>
<pre><code>Traceback (most recent call last):
File "/usr/local/bin/pip3.5", line 5, in <module>
from pkg_resources import load_ent... | 0 | 2016-07-04T11:03:31Z | 38,183,293 | <p>Your pip version and python versions are separate. It looks like your package requires exactly pip 8.1.0. You have to either upgrade/downgrade to that version first, or modify the software to work with whichever pip you have available.</p>
<p>Also, it may be easier to install the software in a virtual environment r... | 0 | 2016-07-04T11:11:00Z | [
"python",
"pip"
] |
Ignore np.where after first match for Pandas time series data | 38,183,182 | <p>As per the following example I need to make my code ignore the np.where after first match for time series data. </p>
<p>So on the <code>2014-03-04 14:00:00</code> row the np.where gives a 1.0 on the test_output column and, as would be expected, also on the next row. I only want this to trigger once ever. I will ... | 1 | 2016-07-04T11:04:56Z | 38,183,412 | <p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.first_valid_index.html" rel="nofollow"><code>first_valid_index</code></a> on the mask to set the first row:</p>
<pre><code>In [30]:
df.loc[df[df['test_1'] == 1.0].first_valid_index(),'test_output'] = 1.0
df
Out[30]:
... | 2 | 2016-07-04T11:17:40Z | [
"python",
"pandas"
] |
Ignore np.where after first match for Pandas time series data | 38,183,182 | <p>As per the following example I need to make my code ignore the np.where after first match for time series data. </p>
<p>So on the <code>2014-03-04 14:00:00</code> row the np.where gives a 1.0 on the test_output column and, as would be expected, also on the next row. I only want this to trigger once ever. I will ... | 1 | 2016-07-04T11:04:56Z | 38,183,664 | <p>You can get the first index and then change the value</p>
<pre><code>index = np.where(df['test_1'] == 1.0)[0][0]
df.iloc[index]['test_output'] = df.iloc[index]['test_1'] or # =1
</code></pre>
| 0 | 2016-07-04T11:30:07Z | [
"python",
"pandas"
] |
ImageField from Django to PIL Image to send via HttpResponse | 38,183,374 | <p>Im new here. Newbie in Django (and English) here. Im trying to get an image (I get the id of the image using a form via POST) from the database(ImageField), crop it with PIL Image and send it via HttpResponde. It doesnt give an error but when I receive the image "piece.jpg", it is a corrupt file. If I open it using ... | 0 | 2016-07-04T11:15:26Z | 38,183,943 | <p><code>HttpResponse</code> expects string or an iterator. More details in docs:</p>
<p><a href="https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponse.__init__" rel="nofollow">https://docs.djangoproject.com/en/1.9/ref/request-response/#django.http.HttpResponse.<strong>init</strong></a><... | 0 | 2016-07-04T11:45:01Z | [
"python",
"django",
"image",
"python-imaging-library",
"crop"
] |
ImageField from Django to PIL Image to send via HttpResponse | 38,183,374 | <p>Im new here. Newbie in Django (and English) here. Im trying to get an image (I get the id of the image using a form via POST) from the database(ImageField), crop it with PIL Image and send it via HttpResponde. It doesnt give an error but when I receive the image "piece.jpg", it is a corrupt file. If I open it using ... | 0 | 2016-07-04T11:15:26Z | 38,184,330 | <p>This helped me to find the solution! Your code opens the image in the browser (which is ok, because I didnt say I wanted it as a download). To get a download dialog, the code is:</p>
<pre><code> response = HttpResponse(content_type='image/jpg')
cropped_image.save(response, "JPEG")
response['Content-Dispo... | 0 | 2016-07-04T12:05:12Z | [
"python",
"django",
"image",
"python-imaging-library",
"crop"
] |
How to reduce time to execute pytest fixtures | 38,183,579 | <p>The point of my test is to login to web-app, create table entry, approve it, check entry status, remove it and logout. So as there are few similar test cases with common pre-conditions/post-conditions I decided to create fixtures (<code>scope=function</code>). My code (pretty much simplified as there are dozens of l... | 0 | 2016-07-04T11:25:24Z | 38,356,926 | <p>Well it really depends on how your tests code is running, I mean how many operations and integrations it has.
I think that pytest does not expand much time to renderize the scopes unless you have another service such as mysql and real API requests which seems to your case.</p>
<p>Perhaps you may mock your requests ... | 0 | 2016-07-13T16:18:19Z | [
"python",
"selenium",
"py.test"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.