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
Rsync filters in a python loop
37,956,484
<p>After reading the man page on filtering rules and looking here: <a href="http://stackoverflow.com/questions/35364075/using-rsync-filter-to-include-exclude-files">Using Rsync filter to include/exclude files</a></p> <p>I don't understand why the code below doesn't work.</p> <pre><code>import subprocess, os from ftp...
1
2016-06-22T00:01:34Z
38,002,614
<p>This part of the rsync man page contained the info I needed to solve my problem:</p> <blockquote> <p>Note that, when using the --recursive (-r) option (which is implied by -a), every subcomponent of every path is visited from the top down, so include/exclude patterns get applied recursively to each subcomp...
0
2016-06-23T22:00:33Z
[ "python", "ftp", "subprocess", "rsync" ]
Sending data over serial in python from different functions
37,956,517
<p>I program in C++ and C# normally and am trying to get accustomed to how python works so forgive me if this is a fairly basic question.</p> <p>I'd like to open a serial connection in python over RS-232 and send data from various functions. Here's the functions that I have to open a serial port and send data:</p> <p...
0
2016-06-22T00:04:48Z
37,956,595
<p>You can use the <code>global</code> keyword in your <code>main</code> function to assign the public variable:</p> <pre><code>ser = None def sendData(data): data += "\r\n" ser.write(data.encode()) def main(): global ser ser = serial.Serial('/dev/ttyUSB0', 115200) while 1: #misc code her...
2
2016-06-22T00:13:54Z
[ "python", "pyserial" ]
Rabbitmq hello world connection doesn't work on localhost
37,956,700
<p>I take hello world example from tutorial:</p> <pre><code>import pika connection = pika.BlockingConnection(pika.ConnectionParameters( host='localhost')) channel = connection.channel() channel.queue_declare(queue='hello') channel.basic_publish(exchange='', routing_key='hello', ...
0
2016-06-22T00:27:06Z
37,959,914
<p>This is an authentication problem, please read:</p> <p><a href="http://stackoverflow.com/questions/22850546/cant-access-rabbitmq-web-management-interface-after-fresh-install/22854222#22854222">Can&#39;t access RabbitMQ web management interface after fresh install</a></p> <p>and this:</p> <p><a href="http://stacko...
0
2016-06-22T06:13:05Z
[ "python", "rabbitmq" ]
gzipped data "not a gzipped file", but I think it is
37,956,810
<p>This:</p> <pre><code>H4sIAAAAAAAEAO29B2AcSZYlJi9tynt/SvVK1+B0oQiAYBMk2JBAEOzBiM3mkuwdaUcjKasqgcplVmVdZhZAzO2dvPfee++999577733ujudTif33/8/XGZkAWz2zkrayZ4hgKrIHz9+fB8/Ih7/Hu8WZXqZ101RLT/7aHe881GaL6fVrFhefPbRuj3fPvjo9zh63FTZ6tHp8jIvq1We0ivL5hE+++yjeduuHt2920zn+SJrxvQVPh9X9cVd/HI315fufqSvvWsK+9bV1dX46h433tvZ2b37e3/x/DU...
0
2016-06-22T00:44:10Z
37,956,954
<p>Using @Rhymoid's suggestion, your code should look something like this (untested):</p> <pre><code>#!/usr/bin/env python import logging import gzip import StringIO from base64 import b64decode logging.basicConfig(filename='out.log', level=logging.DEBUG) compressed_data = 'H4sIAAAAAAAEAO29B2AcSZYlJi9tynt/SvVK1+B0o...
1
2016-06-22T01:04:26Z
[ "python", "gzip" ]
Index.names is not assigned after using concat
37,956,894
<p>After running the following code, <code>index.names</code> returns <code>[None]</code> but I'm expecting <code>['Server']</code>. Can you reproduce this? Is this expected behavior, if so why?</p> <pre><code>import pandas as pd try: from io import StringIO except ImportError: from StringIO import StringIO data1...
0
2016-06-22T00:55:53Z
37,956,940
<p>I see you've got an <a href="https://github.com/pydata/pandas/issues/13475" rel="nofollow">issue</a> - I think it likely is a bug, here is a workaround:</p> <pre><code>In [93]: df1.join(df2, how='outer') Out[93]: Cores_1 Cores_2 Server S000 20.0 NaN S003 -20.0 NaN S1...
1
2016-06-22T01:01:52Z
[ "python", "pandas" ]
Replacing a subset of rows in pandas dataframe with a Series object
37,956,922
<p>I have a column, <code>data['sign']</code> that is <code>+/-1</code> when the value in <code>data['quantity']</code> is positive/negative. When I try to convert the values in <code>data['quantity']</code> according to their sign in the <code>data['sign']</code> column, it doesn't work:</p> <pre><code>data.loc[data....
0
2016-06-22T00:59:51Z
37,957,020
<p>I would try:</p> <pre><code>data['quantity'] = data['sign'] * data['quantity'] </code></pre>
1
2016-06-22T01:14:34Z
[ "python", "pandas" ]
How to allow empty form field in django
37,956,994
<p>I am currently having trouble with the one I am working on. I would like to allow empty uuid field save to database.</p> <p>this is my code</p> <p>models.py</p> <pre><code>mission_id = models.UUIDField(null=True, blank=True) </code></pre> <p>forms.py</p> <pre><code>class SomeForm(ModelForm): class Meta:...
0
2016-06-22T01:11:41Z
37,957,383
<p>since UUID field uses the <a href="https://docs.python.org/2/library/uuid.html" rel="nofollow">Python's UUID class</a>, the problem occurs <a href="https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L2378" rel="nofollow">here</a></p> <p>example:</p> <pre><code>&gt;&gt;&gt; import uuid...
0
2016-06-22T02:05:57Z
[ "python", "django", "forms" ]
Connect to gitlab production postgresql database with psycopg2?
37,957,085
<p>I am trying to connect to GitLab production (installed with omnibus package) postgresql database with psycopg2. </p> <p>My configuration is like below:</p> <pre><code>onn = psycopg2.connect(database="gitlabhq_production", user="gitlab-psql", host="/var/opt/gitlab/postgresql", port="5432") </code></pre> <p>It give...
0
2016-06-22T01:24:41Z
37,957,371
<p>Peer authentication works by checking the user the process is running as. In your command line example you switch to <code>gitlab-psql</code> using <code>sudo</code>.</p> <p>There are two ways to fix this:</p> <ol> <li><p>Assign a password to the <code>gitlab-psql</code> postgres user (<em>not</em> the system user...
1
2016-06-22T02:04:40Z
[ "python", "postgresql", "gitlab", "psycopg2" ]
Python Script with QGis - Python.exe Stopped Working
37,957,100
<p>I purchased <a href="https://www.packtpub.com/application-development/building-mapping-applications-qgis" rel="nofollow">this book called Building Mapping Applications with QGIS</a> and I am trying to work through one of the exercises. There is one script that I try to run that crashes python, generating the error m...
1
2016-06-22T01:27:32Z
37,977,204
<p>One thing that seems suspect is that you're creating a gui element without giving it a parent - <code>QgsMapCanvas()</code> - and then trying to manually <code>show()</code> it before adding it to a layout. You should never have to call <code>show()</code> on subwidgets, and all subwidgets should be parented to the...
1
2016-06-22T20:00:23Z
[ "python", "python-2.7", "pyqt", "pyqt4", "qgis" ]
Python Script with QGis - Python.exe Stopped Working
37,957,100
<p>I purchased <a href="https://www.packtpub.com/application-development/building-mapping-applications-qgis" rel="nofollow">this book called Building Mapping Applications with QGIS</a> and I am trying to work through one of the exercises. There is one script that I try to run that crashes python, generating the error m...
1
2016-06-22T01:27:32Z
38,175,594
<p>I was fortunate enough to get in touch with the author of the book so I will share his response here:</p> <blockquote> <p>I suspect I may know what the problem is...after looking at this reader's problems in more depth, I've discovered that something has changed in newer versions of QGIS, and the example code...
0
2016-07-04T00:43:45Z
[ "python", "python-2.7", "pyqt", "pyqt4", "qgis" ]
Why my GPU piece of code run much slower then cpu
37,957,129
<p>This is one of the standard example code we find every where...</p> <pre><code>import time import numpy import pycuda.gpuarray as gpuarray import pycuda.cumath as cumath import pycuda.autoinit size = 1e7 t0 = time.time() x = numpy.linspace(1, size, size).astype(numpy.float32) y = numpy.sin(x) t1 = time.time() c...
0
2016-06-22T01:30:54Z
37,958,544
<p>It looks like <code>pycuda</code> introduces some additional overhead the first time you call the <code>cumath.sin()</code> function (~400ms on my system). I suspect this is due to the need to compile CUDA code for the function being called. More importantly, this overhead is independent of the size of the array bei...
1
2016-06-22T04:26:47Z
[ "python", "gpu", "pycuda" ]
how to use returned values from python
37,957,256
<p>So I have a function like this one below called analysis1.py :</p> <pre><code>import glob import panda as pd def my_function(test_path): path=test_path +"\\"+ "*mainlog.txt" files =glob.glob(path) for name in files: lines=[line.rstrip('\n')for line in open(name)] if "a:" in lines: ...
-3
2016-06-22T01:49:52Z
37,957,304
<p>I don't think you understand how functions work in Python. Functions are like your pocket tools in the world of programming. You can use them anytime you want and they will <code>return</code> you something -- Like a calculator returns 2 when you type 1+1.</p> <p>Similarly, all you need to do is run the function (w...
0
2016-06-22T01:56:31Z
[ "python" ]
how to use returned values from python
37,957,256
<p>So I have a function like this one below called analysis1.py :</p> <pre><code>import glob import panda as pd def my_function(test_path): path=test_path +"\\"+ "*mainlog.txt" files =glob.glob(path) for name in files: lines=[line.rstrip('\n')for line in open(name)] if "a:" in lines: ...
-3
2016-06-22T01:49:52Z
37,957,326
<p>Before your <code>if returned_value</code> lines, add this:</p> <pre><code>returned_value = my_function(test_path) </code></pre> <p>This will assign the value returned from <code>my_function</code> to <code>returned_value</code>. At that point, your <code>if</code> statements will begin checking the value to see i...
0
2016-06-22T01:59:07Z
[ "python" ]
how to use returned values from python
37,957,256
<p>So I have a function like this one below called analysis1.py :</p> <pre><code>import glob import panda as pd def my_function(test_path): path=test_path +"\\"+ "*mainlog.txt" files =glob.glob(path) for name in files: lines=[line.rstrip('\n')for line in open(name)] if "a:" in lines: ...
-3
2016-06-22T01:49:52Z
37,957,332
<p>Your problem is that the variables: <code>k_1</code> .. <code>k_5</code> are not defined to hold values. Define them first somewhere. It seems like you are looking for something equivalent of an <code>enum</code>. </p> <pre><code>from enum import Enum KType = Enum('KType', 'k_1 k_2 k_3 k_4 k_5') </code></pre> <p>...
0
2016-06-22T01:59:40Z
[ "python" ]
Find the differences between nested dictionaries which contain lists
37,957,372
<p>I want to extract the differences between two nested dictionaries and I want the result to include the full dictionary keypath. I have installed Python2.7 and DeepDiff, which appears to be the best option for what I am trying to achieve. I am trying to determine how to change the output of DeepDiff so it provides th...
0
2016-06-22T02:04:48Z
37,958,022
<p>The issue is exactly what the traceback tells you: you are trying to add a dictionary to a string, which is of course not what you want. Specifically, when you add <code>knownAPs</code> (type <code>dict</code>) to <code>fullkeypath</code> (type <code>str</code>) you get an error, because <code>dict</code> doesn't kn...
0
2016-06-22T03:26:30Z
[ "python", "dictionary" ]
Convert case of a pandas DataFrame column
37,957,377
<p>I have a DataFrame where the case of a particular column is inconsistent and I want to make it consistent:</p> <pre><code>In [1]: df = pd.DataFrame({"vals":["alpha","Beta","GAMMA"]}) In [2]: df Out[2]: vals 0 alpha 1 Beta 2 GAMMA </code></pre> <p>Is there is an easy, pythonic way to replace each value wi...
2
2016-06-22T02:05:00Z
37,957,410
<p>you can do:</p> <pre><code>df['vals'] = df['vals'].apply(lambda x: x.upper()) </code></pre>
2
2016-06-22T02:09:03Z
[ "python", "pandas" ]
Convert case of a pandas DataFrame column
37,957,377
<p>I have a DataFrame where the case of a particular column is inconsistent and I want to make it consistent:</p> <pre><code>In [1]: df = pd.DataFrame({"vals":["alpha","Beta","GAMMA"]}) In [2]: df Out[2]: vals 0 alpha 1 Beta 2 GAMMA </code></pre> <p>Is there is an easy, pythonic way to replace each value wi...
2
2016-06-22T02:05:00Z
37,957,417
<p>This should work for you:</p> <pre><code>df['vals'] = map(lambda x: x.upper(), df['vals']) </code></pre> <p>Or even:</p> <pre><code>df['vals'] = df['vals'].apply(lambda x: x.upper()) </code></pre> <hr> <p>Ps.: in recent versions you may also:</p> <pre><code>df['vals'] = df['vals'].str.upper() </code></pre>
2
2016-06-22T02:09:48Z
[ "python", "pandas" ]
Convert case of a pandas DataFrame column
37,957,377
<p>I have a DataFrame where the case of a particular column is inconsistent and I want to make it consistent:</p> <pre><code>In [1]: df = pd.DataFrame({"vals":["alpha","Beta","GAMMA"]}) In [2]: df Out[2]: vals 0 alpha 1 Beta 2 GAMMA </code></pre> <p>Is there is an easy, pythonic way to replace each value wi...
2
2016-06-22T02:05:00Z
37,957,861
<p>You can make the changes inplace directly on your dataframe:</p> <blockquote> <p><code>df["vals"].apply(lambda x: x.upper())</code></p> </blockquote> <p>Here <code>.upper()</code> will work whether your elements are of type <code>str</code> or <code>unicode</code>.</p>
0
2016-06-22T03:08:53Z
[ "python", "pandas" ]
Multiprocessing - limit CPU usage
37,957,446
<p>I have a code that I managed to paralelize thank to <a href="http://stackoverflow.com/questions/37950778/parallelizing-a-dictionary-comprehension">this question</a>:</p> <pre><code> 1| def function(name, params): 2| results = fits.open(name) 3| &lt;do something more to results&gt; 4| return results 5| ...
0
2016-06-22T02:13:54Z
37,972,103
<p>Consider using <code>multiprocessing.pool.ThreadPool</code>. It provides the same API as <code>multiprocessing.Pool</code> but abstracts the workload to a collection of Threads instead. Note that if your CPU supports Hyper-threading then it will most likely distribute the workload over physical cores.</p>
1
2016-06-22T15:15:32Z
[ "python", "python-2.7", "multiprocessing", "cpu-usage", "pool" ]
How to use signal between different modules
37,957,600
<p>I know how to use signal in a module or class like this:</p> <pre><code> class A (QObject): def __init__(self): QObject.__init__(self) def afunc (self, i): self.emit(SIGNAL("doSomePrinting(int)"), i) def bfunc(self, i): print "Hello World!", i sys.exit() if __name_...
0
2016-06-22T02:35:16Z
37,960,197
<p>"a.py"<br> The class A has a signal called my_signal and we have defined a method_for_signal in our class.</p> <pre><code>from PyQt4 import QtCore, QtGui class A(QObject): my_signal = QtCore.pyqtSignal(str) def __init__(): super(A, self).__init__() self.name = "ABCDEFGHIJKLM" def meth...
0
2016-06-22T06:29:28Z
[ "python", "qt", "pyqt" ]
Fast vectorised datetime.combine()
37,957,728
<p>I have a large dataframe with a pair of columns, one representing time, and one - date. Unfortunately, both are of the datetime type already (appearing like "2016-01-01 00:00:00" and "1900-01-01 14:23:14" accordingly in resulting csv)</p> <p>I need to combine them together, and to do it fast. The only way I found s...
1
2016-06-22T02:54:47Z
37,958,506
<p>Let:</p> <pre><code>df = pd.DataFrame([pd.DatetimeIndex(["2016-01-01 00:00:00", "1900-01-01 14:23:14"])] * 10000, columns=['DATE', 'TIME']) </code></pre> <p>Then:</p> <pre><code>df.DATE + (df.TIME - pd.DatetimeIndex(df.TIME).date) </code></pre>
1
2016-06-22T04:22:00Z
[ "python", "datetime", "numpy", "pandas" ]
For loop python information
37,957,795
<p>Heres the deal, I have certain entries in my database. I'm calling a django: </p> <pre><code>variables = Variable.objects.order_by('foo').values('foo') </code></pre> <p>Then I have a for statement that executes on each variable found:</p> <pre><code>for x in variables: #doing something.... </code></pre> <p>My...
0
2016-06-22T03:02:02Z
37,958,163
<p>That's the way the solution could be implemented using multiprocessing library.</p> <p>We'll use <code>Pool</code>, <code>apply_async</code> and <code>Queue</code></p> <pre><code># globals MAX_PROCESSES = 50 my_queue = multiprocessing.Manager().Queue() # queue to store our values stop_event = multiprocessing.Event...
0
2016-06-22T03:41:55Z
[ "python", "for-loop", "while-loop", "multiprocessing", "pooling" ]
neo4j BOLT check if connection is open and count number of connections
37,957,833
<p>Using the BOLT Neo4j driver in python:</p> <pre><code>driver = GraphDatabase.driver("bolt://localhost", auth=basic_auth('neo4j', 'password'), encrypted=True, trust=TRUST_ON_FIRST_USE) session = driver.session() </code...
1
2016-06-22T03:06:10Z
37,961,918
<p>There's no public API to do this. Bear in mind also that session != connection; the former is an API abstraction, the latter an implementation detail.</p> <p>Can I ask what you are actually trying to achieve?</p>
0
2016-06-22T07:58:31Z
[ "python", "neo4j", "server", "connection" ]
Python Visual Studio extension doesn't show errors
37,957,872
<p>I'm used to use VS to code C++ and Eclipse to code python but lately I have tried VS for both languages. </p> <p>I found something very difficult to understand that while VS autocompletes it doesn't warn you about errors before runtime.</p> <p><a href="http://i.stack.imgur.com/Q87eR.png" rel="nofollow"><img src="h...
3
2016-06-22T03:09:49Z
38,173,176
<p>In order to get the python detailed IntelliSense support in VS2015 you have to install python tools for visual studio which provide the following:</p> <ol> <li>CPython, PyPy, IronPython and more</li> <li>Detailed IntelliSense</li> <li>Interactive debugging</li> <li>Integrated with Visual Studio features</li> <li>Fr...
1
2016-07-03T18:39:11Z
[ "python", "visual-studio", "ide", "warnings", "ptvs" ]
Python Visual Studio extension doesn't show errors
37,957,872
<p>I'm used to use VS to code C++ and Eclipse to code python but lately I have tried VS for both languages. </p> <p>I found something very difficult to understand that while VS autocompletes it doesn't warn you about errors before runtime.</p> <p><a href="http://i.stack.imgur.com/Q87eR.png" rel="nofollow"><img src="h...
3
2016-06-22T03:09:49Z
38,206,720
<p>It seems that with a regular Python installation (2.x or 3.x in 32bit or 64bit) there are limited "warnings" (hovering over an undefined variable gives "unknown type"), but Syntax Highlighting / Intellisense doesn't seem to work. </p> <p><strong>Intellisense NOT Working:</strong></p> <p><a href="http://i.stack.img...
0
2016-07-05T14:59:25Z
[ "python", "visual-studio", "ide", "warnings", "ptvs" ]
Best location for log.conf in python package
37,957,963
<p>I am using the native logging utility while writing a python package. What is the best location for logging.conf?</p> <p>I have the following package structure</p> <pre><code>/package setup.py .gitingore .... /dist __init__.py dosomething.py /utils /submodule1 submodule1.py...
0
2016-06-22T03:20:07Z
37,959,666
<p>Not easy to answer. I post this because it's way too long for a comment.</p> <p>The answer may depend on the rest of your package's organization (like, have you only this conf file, or some others? May other conf file show up some day later?).</p> <p>Here is how I organize this. Though I can't say it's the <em>bes...
1
2016-06-22T05:56:32Z
[ "python", "logging", "package" ]
Cython - Why is the index assignment statement inside my loop still yellow?
37,958,128
<p>I am trying to learn <code>Cython</code> and trying to write a speedy version of a bootstrapping function. My main loop has one pesky statement which is still yellow and I can't figure out why it's yellow. I would really appreciate help, thank you.</p> <pre><code>import numpy as np cimport numpy as np from libc.std...
0
2016-06-22T03:38:29Z
37,959,808
<p>Cython still generates code that checks for zero division:</p> <pre><code>if (unlikely(RAND_MAX == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 26; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } </code></pre> <p>and for in...
0
2016-06-22T06:06:16Z
[ "python", "numpy", "cython" ]
Automatically round Django's DecimalField according to the max_digits and decimal_places attributes before calling save()
37,958,130
<p>I want to automatically round Django's DecimalField according to the max_digits and decimal_places attributes before calling save() function in ModelForm.</p> <p>currently using the following:</p> <ul> <li>django 1.8</li> <li>python 2.7</li> </ul> <p>What I have tried so far.</p> <p><a href="https://djangosnippe...
2
2016-06-22T03:38:54Z
37,958,300
<p>If you are assigning directly to a model instance, you don't need to worry about it. The field object will quantize the value (rounding it) to the decimal point level you set in your model definition.</p> <p>If you are dealing with a <code>ModelForm</code>, the default <code>DecimalField</code> will require that an...
2
2016-06-22T03:58:05Z
[ "python", "django" ]
Automatically round Django's DecimalField according to the max_digits and decimal_places attributes before calling save()
37,958,130
<p>I want to automatically round Django's DecimalField according to the max_digits and decimal_places attributes before calling save() function in ModelForm.</p> <p>currently using the following:</p> <ul> <li>django 1.8</li> <li>python 2.7</li> </ul> <p>What I have tried so far.</p> <p><a href="https://djangosnippe...
2
2016-06-22T03:38:54Z
37,963,167
<p>You are mainly getting the error because <code>forms.DecimalField</code> has separate validators from <code>models.DecimalField</code>:</p> <pre><code>data = {'amount': 1.12345 } class NormalForm(forms.Form): amount = forms.DecimalField(max_digits = 19, decimal_places = 2) normal_form = NormalForm(data) norma...
2
2016-06-22T08:57:24Z
[ "python", "django" ]
how to read rows of a column from csv file on python?
37,958,166
<pre><code>activity=csv.reader(open('activity(delimited).csv') data = np.array([activity]) url_data = data[:, 70] </code></pre> <p>I am trying to extract a column from the CSV file. This column has a list of URLs that I would like to read. However every time I run these few lines, I get:-</p> <p>IndexError: too many ...
1
2016-06-22T03:42:15Z
37,958,265
<p>There are a bunch of <strong>very similar</strong> issues on StackOverflow [<a href="http://stackoverflow.com/questions/28036812/indexerror-too-many-indices-for-array">post 1</a>], [<a href="http://stackoverflow.com/questions/29199585/indexerror-too-many-indices-numpy-array-with-1-row-and-2-columns">post 2</a>].</p>...
0
2016-06-22T03:53:18Z
[ "python", "csv", "url" ]
Convert class 'pandas.indexes.numeric.Int64Index' to numpy
37,958,278
<p>I am isolating some row ids from a Pandas dataframe, like this: </p> <pre><code>data = df.loc[df.cell == id] rows = df.index print(type(rows)) &lt; class 'pandas.indexes.numeric.Int64Index'&gt; </code></pre> <p>I want to convert rows to a numpy array so I can save it to a mat file using sio.savemat. This is retur...
1
2016-06-22T03:55:41Z
37,958,335
<p>try <code>rows = df.index.values</code> instead</p>
4
2016-06-22T04:02:09Z
[ "python", "numpy", "pandas", "dataframe" ]
Django - reduce the number of queries in ORM
37,958,296
<p>I used related_name in a Django template to look the foreign key record, and call the count method. Because I have so many "Main" record, the for loop inside the template will create too many queries to the database. If there an easy way for me to reduce the number of queries to the database? Please see below for my...
0
2016-06-22T03:57:46Z
37,958,552
<p>You can use <a href="https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-querysethttps://docs.djangoproject.com/en/1.9/topics/db/aggregation/#generating-aggregates-for-each-item-in-a-queryset" rel="nofollow">annotations</a> to do this logic all in one query:</p> <pr...
2
2016-06-22T04:27:31Z
[ "python", "django", "django-models", "orm" ]
Python shell not running crawler
37,958,332
<p>i had to try this code</p> <pre><code>import scrapy from scrapy.cmdline import execute from scrapy.spider import BaseSpider from scrapy.selector import HtmlXPathSelector from metacritic.items import MetacriticItem class MetacriticSpider(scrapy.spider): name = "metacritic" # Name of the spider, to be used when crawl...
0
2016-06-22T04:01:52Z
37,958,745
<pre><code>from scrapy.spider import BaseSpider ... class MetacriticSpider(scrapy.spider): </code></pre> <p>As you can see, scrapy.spider is a module name. Your class tries to inherit from it. Typically, your class should inherit from another class- probably BaseSpider in this case.</p>
0
2016-06-22T04:46:49Z
[ "python", "scrapy", "pycharm" ]
Comparing characters in strings
37,958,360
<p>I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.</p> <p>For instance,</p> <pre><code>a = "HORSE" b = "TIGER" </code></pre> <p>And it would return 5 (as all characters in the same position are different)</p> <p>...
0
2016-06-22T04:05:15Z
37,958,454
<p>You could do something like this:</p> <pre><code>def getDifferences(a,b): count = 0 for i in range(0, len(a)): if a[i] is not b[i]: count += 1 return count </code></pre> <p>The only thing that you will have to implement yourself here is checking for the size of the strings. In my example, if <cod...
0
2016-06-22T04:16:07Z
[ "python", "string", "comparison", "character" ]
Comparing characters in strings
37,958,360
<p>I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.</p> <p>For instance,</p> <pre><code>a = "HORSE" b = "TIGER" </code></pre> <p>And it would return 5 (as all characters in the same position are different)</p> <p>...
0
2016-06-22T04:05:15Z
37,958,480
<p>try this:</p> <pre><code>def Differences(one, two): if len(two) &lt; len(one): one, two = two, one res = len(two) - len(one) for i, chr in enumerate(one): res += two[i] != chr return res </code></pre> <p>it's important to make the first check of their size in case the second string...
0
2016-06-22T04:19:24Z
[ "python", "string", "comparison", "character" ]
Comparing characters in strings
37,958,360
<p>I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.</p> <p>For instance,</p> <pre><code>a = "HORSE" b = "TIGER" </code></pre> <p>And it would return 5 (as all characters in the same position are different)</p> <p>...
0
2016-06-22T04:05:15Z
37,958,489
<p>As matters for complexity and runtime, calling list() each iteration is not efficient, since it splits the strings, allocates memory and on... The correct way to do it, is to iterate the <strong>index</strong> of the lists, than compare them by it, something like:</p> <pre><code>def str_compare(l1, l2): assert l...
0
2016-06-22T04:20:17Z
[ "python", "string", "comparison", "character" ]
Comparing characters in strings
37,958,360
<p>I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.</p> <p>For instance,</p> <pre><code>a = "HORSE" b = "TIGER" </code></pre> <p>And it would return 5 (as all characters in the same position are different)</p> <p>...
0
2016-06-22T04:05:15Z
37,958,495
<p>There are a couple problems with:</p> <pre><code>def Differences(one, two): difference = [] for i in list(one): if list(one)[i] != list(two)[i]: difference = difference+1 return difference </code></pre> <p>Firstly <code>list(one)</code> is <code>['H', 'O', 'R', 'S', 'E']</code> when...
0
2016-06-22T04:21:01Z
[ "python", "string", "comparison", "character" ]
Comparing characters in strings
37,958,360
<p>I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.</p> <p>For instance,</p> <pre><code>a = "HORSE" b = "TIGER" </code></pre> <p>And it would return 5 (as all characters in the same position are different)</p> <p>...
0
2016-06-22T04:05:15Z
37,958,526
<p>I would probably just iterate over both of them at the same time with zip and a list comprehension and then take length of the list:</p> <pre><code>a='HORSE' b='TIGER' words=zip(a,b) incorrect=len([c for c,d in words if c!=d]) print(incorrect) </code></pre> <p>Zipping pairs lists together index-for-index, stoppi...
1
2016-06-22T04:25:01Z
[ "python", "string", "comparison", "character" ]
Comparing characters in strings
37,958,360
<p>I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.</p> <p>For instance,</p> <pre><code>a = "HORSE" b = "TIGER" </code></pre> <p>And it would return 5 (as all characters in the same position are different)</p> <p>...
0
2016-06-22T04:05:15Z
37,958,587
<p><code>sum([int(i!=j) for i,j in zip(a,b)])</code> would do the trick</p>
1
2016-06-22T04:30:00Z
[ "python", "string", "comparison", "character" ]
Comparing characters in strings
37,958,360
<p>I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.</p> <p>For instance,</p> <pre><code>a = "HORSE" b = "TIGER" </code></pre> <p>And it would return 5 (as all characters in the same position are different)</p> <p>...
0
2016-06-22T04:05:15Z
37,958,643
<p>use <code>zip</code> to iterate over both strings consecutively</p> <pre><code>&gt;&gt;&gt; def get_difference(str_a, str_b): ... """ ... Traverse two strings of the same length and determine the number of ... indexes in which the characters differ ... """ ... ... # confirm inputs are strings ....
0
2016-06-22T04:35:02Z
[ "python", "string", "comparison", "character" ]
Comparing characters in strings
37,958,360
<p>I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.</p> <p>For instance,</p> <pre><code>a = "HORSE" b = "TIGER" </code></pre> <p>And it would return 5 (as all characters in the same position are different)</p> <p>...
0
2016-06-22T04:05:15Z
37,959,320
<p>Find out for yourself</p> <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; a = "HORSE" &gt;&gt;&gt; list(a) ['H', 'O', 'R', 'S', 'E'] &gt;&gt;&gt; list(a)[2] 'R' &gt;&gt;&gt; for i in list(a): ... i ... 'H' 'O' 'R' 'S' 'E' &gt;&gt;&gt; list(a)['R'] Traceback (most recent call last): File "&lt;stdi...
0
2016-06-22T05:33:01Z
[ "python", "string", "comparison", "character" ]
Comparing characters in strings
37,958,360
<p>I'm trying to create a function that compares characters in the same position of two strings of same length and returns the count of their differences.</p> <p>For instance,</p> <pre><code>a = "HORSE" b = "TIGER" </code></pre> <p>And it would return 5 (as all characters in the same position are different)</p> <p>...
0
2016-06-22T04:05:15Z
37,993,191
<pre><code>a = "HORSE" b = "TIGER" a_list=[] b_list=[] for l in a_list: a_list.append(l) for k in b_list: b_list.append(k) difference = len(a) for i in a_list: for x in b_list: if a_list[i] == b_list[x]: difference = difference - 1 print(difference) </code></pre> <p>See if this works...
0
2016-06-23T13:33:53Z
[ "python", "string", "comparison", "character" ]
Django class-based-view access context data from get_queryset
37,958,554
<pre><code>class ProfileContextMixin(generic_base.ContextMixin, generic_view.View): def get_context_data(self, **kwargs): context = super(ProfileContextMixin, self).get_context_data(**kwargs) profile = get_object_or_404(Profile, user__username=self.request.user) context['profile'] = profile...
0
2016-06-22T04:27:40Z
37,959,458
<p>You can move getting profile out of <code>get_context_data</code> to upper function, like <code>dispatch</code>, or use <a href="https://docs.djangoproject.com/en/1.9/ref/utils/#django.utils.functional.cached_property" rel="nofollow"><code>cached_property</code></a> decorator. This way your profile will be stored in...
1
2016-06-22T05:43:35Z
[ "python", "django" ]
Logger with a global scope?
37,958,568
<p>How can I implement a global logger for all of my python files? Some relevant SE questions are <a href="http://stackoverflow.com/a/7621969/4056146">one</a> and <a href="http://stackoverflow.com/a/7622029/4056146">two</a>, but neither do exactly what I want, simply. I want the log file output to be seen in the cons...
0
2016-06-22T04:29:09Z
37,958,569
<p>You do it like this:</p> <p>main.py</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import log import test logger = log.setup_custom_logger('root') def main(): logger.info("informational message") logger.debug("debugging message") logger.critical("critical message") test.test_message() ...
0
2016-06-22T04:29:09Z
[ "python", "logging", "global" ]
How to change the file from excel to csv when download data from web by python request module?
37,958,619
<p>I am using python to download files from webpage, and after I submit the request, I get the headers like below:</p> <blockquote> <blockquote> <blockquote> <p>r.headers</p> </blockquote> </blockquote> </blockquote> <pre><code>{'Content-Disposition': 'attachment; filename=SABR_Download.xls', 'Cont...
0
2016-06-22T04:32:47Z
37,958,860
<p>Unless the site you're downloading from provides a specific URL for downloading in a CSV format, you will have to download the Excel spreadsheet and parse it to get what you think is a reasonable translation of the data.</p> <p>There is a Python module called <code>xlrd</code> that can help you with this: <a href="...
0
2016-06-22T04:57:27Z
[ "python", "csv", "request" ]
Iterating over a list value in a dictionary
37,958,748
<p>I have a parent class: </p> <pre><code>class Animal(object): animalFoods = {'Elephant': ['Grass', 'Trees'], 'Turtle': 'Fish'} def animal_food(self): foods = Animal.animalFoods[self.__class__.__name__] for food in foods: return food </code></pre> <p>Then I have a subclass: </p>...
0
2016-06-22T04:46:53Z
37,958,812
<p><code>return food</code> will immediately end execution of your <code>animal_food</code>; it will not attempt to complete the loop. If you wanted to get very fancy, you could use <code>yield food</code> to turn the method into a generator, but probably for this example you just want to replace the method body comple...
3
2016-06-22T04:52:39Z
[ "python", "python-3.x", "dictionary" ]
Iterating over a list value in a dictionary
37,958,748
<p>I have a parent class: </p> <pre><code>class Animal(object): animalFoods = {'Elephant': ['Grass', 'Trees'], 'Turtle': 'Fish'} def animal_food(self): foods = Animal.animalFoods[self.__class__.__name__] for food in foods: return food </code></pre> <p>Then I have a subclass: </p>...
0
2016-06-22T04:46:53Z
37,958,847
<p>Please see here:</p> <pre><code>foods = Animal.animalFoods[self.__class__.__name__] for food in foods: return food </code></pre> <p>for <code>foods</code>, it is right, which is <code>['Grass', 'Trees']</code>.</p> <p>But you do <code>for food in foods: return food</code>. the <code>return</code> just return ...
0
2016-06-22T04:56:05Z
[ "python", "python-3.x", "dictionary" ]
Iterating over a list value in a dictionary
37,958,748
<p>I have a parent class: </p> <pre><code>class Animal(object): animalFoods = {'Elephant': ['Grass', 'Trees'], 'Turtle': 'Fish'} def animal_food(self): foods = Animal.animalFoods[self.__class__.__name__] for food in foods: return food </code></pre> <p>Then I have a subclass: </p>...
0
2016-06-22T04:46:53Z
37,958,861
<p>Once a function or a method returns a value the for loop execution will halt.</p> <p>If you merely wanted to print the items you could add the <code>print</code> statement to the class method <code>animal_food()</code> like this:</p> <pre><code>def animal_food(self): foods = Animal.animalFoods[self.__class__.__n...
0
2016-06-22T04:57:27Z
[ "python", "python-3.x", "dictionary" ]
which tokenizer is better to be used with nltk
37,958,781
<p>I have started learning <code>nltk</code> and following <a href="https://pythonprogramming.net/stop-words-nltk-tutorial/?completed=/tokenizing-words-sentences-nltk-tutorial/" rel="nofollow">this</a> tutorial. First we use the built-in tokenizer by using <code>sent_tokenize</code> and later we use <code>PunktSentence...
1
2016-06-22T04:49:43Z
37,960,210
<p>Sentences and words are often manually tokenized. There exist various corpora that deal with POS tagging for words according to the sentence contexts. <code>PunktSentenceTokenizer</code> is employed when your data(sentences and words) needs to be trained to achieve a uniform understanding of how the words should be ...
1
2016-06-22T06:30:15Z
[ "python", "nltk", "tokenize" ]
which tokenizer is better to be used with nltk
37,958,781
<p>I have started learning <code>nltk</code> and following <a href="https://pythonprogramming.net/stop-words-nltk-tutorial/?completed=/tokenizing-words-sentences-nltk-tutorial/" rel="nofollow">this</a> tutorial. First we use the built-in tokenizer by using <code>sent_tokenize</code> and later we use <code>PunktSentence...
1
2016-06-22T04:49:43Z
37,960,971
<p>Looking at the <a href="http://www.nltk.org/_modules/nltk/tokenize.html#sent_tokenize" rel="nofollow">source code</a> for <code>sent_tokenize()</code> reveals that this method currently uses the pre-trained punkt tokenizer, so it is the equivalent to <code>PunktSentenceTokenizer</code>. Whether or not you will need ...
3
2016-06-22T07:13:28Z
[ "python", "nltk", "tokenize" ]
Error building sasl for python 3.5.1
37,958,793
<p>To connect to Hive using Python 3.5.1 I was able to install pyhs2, thrift and Pyhive. But during installation of sasl which is needed by phyhs2, got this error.</p> <pre><code> running install running build running build_py creating build creating build\lib.win32-3.5 creating build\lib.win32-...
0
2016-06-22T04:50:44Z
37,959,006
<p>Python is struggling to find a C++ compiler that matches the compiler that was used to compile your version of Python for Windows. For Python 3.5 on Windows, you need Visual C++ 14.0. A quick fix for this version is to install <a href="https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx" rel=...
0
2016-06-22T05:10:54Z
[ "python", "python-3.x", "hive", "sasl" ]
Need help parsing Cisco output
37,958,897
<p>I am having some issue trying to parse the mrib table of a router. I have been able to parse some of it out but having issue. For example I have the following output:</p> <pre class="lang-none prettyprint-override"><code>(192.168.1.1,232.0.6.8) RPF nbr: 55.44.23.1 Flags: RPF Up: 4w1d Incoming Interface List ...
2
2016-06-22T05:00:22Z
37,961,646
<p>Assumes your input is complete and well formatted:</p> <pre><code>matcher = re.compile( r'\((?P&lt;range&gt;[^\)]+)\)|' r'(?P&lt;incoming&gt;\s+Incoming Interface List)|' r'(?P&lt;outgoing&gt;\s+Outgoing Interface List)|' r'\s+(?P&lt;interface&gt;TenGigE0[^\s]+)' ) with open('router_table.txt', 'r'...
0
2016-06-22T07:44:25Z
[ "python", "regex", "parsing", "ciscoconfparse" ]
Need help parsing Cisco output
37,958,897
<p>I am having some issue trying to parse the mrib table of a router. I have been able to parse some of it out but having issue. For example I have the following output:</p> <pre class="lang-none prettyprint-override"><code>(192.168.1.1,232.0.6.8) RPF nbr: 55.44.23.1 Flags: RPF Up: 4w1d Incoming Interface List ...
2
2016-06-22T05:00:22Z
37,967,646
<p>Well, if you're able to use the newer <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><strong><code>regex module</code></strong></a> in <code>Python</code>, you can define subpatterns and use the following approach: </p> <ol> <li>Define subpatterns for the IP address in the beginning</li> <li>... as we...
2
2016-06-22T12:10:16Z
[ "python", "regex", "parsing", "ciscoconfparse" ]
Anaconda ipython qtconsole launcher
37,958,974
<p>I am using Kubuntu 16.04 with kde 5.6.4. I have installed anaconda python 3.5 which includes <strong>ipython qtconsole</strong>.</p> <p>To launch ipython qtconsole, I have to type <code>ipython qtconsole</code> in terminal. Is there anyway I can create a launcher for it?</p> <p>I know there a package, but it doesn...
7
2016-06-22T05:08:02Z
38,206,342
<p>Try creating <a href="https://techbase.kde.org/Development/Tutorials/Desktop_File" rel="nofollow">a Desktop file</a>, with an absolute path to the required <code>ipython</code>, such as:</p> <pre><code>[Desktop Entry] Type=Application Exec=/anaconda/bin/ipython qtconsole %u Name=Jupyter Console GenericName=Qt Appli...
3
2016-07-05T14:41:56Z
[ "python", "ipython", "anaconda", "qtconsole" ]
Regex in python for not matching word
37,958,984
<p>I am reviewing java code and there are so many classes to check, I made a regex to find a method written in java that doesn't close IO stream within finally block. </p> <p><code>(?s)(?&lt;=public|private|protected).<code>(?&lt;!finally).*?.close\(\)\;</code></code></p> <p>For some reason this doesn't work and...
3
2016-06-22T05:08:58Z
37,959,473
<p>Your regex should probably be : <code>(?s)(?&lt;=public|private|protected)((?!finally).)*close\(\)\;</code>. Demo on <a href="https://regex101.com/r/cI2wY0/1" rel="nofollow">regex101</a>.</p> <p><strong>Explanation</strong> : <code>((?!finally).)*</code> verify that the rest of the string does not contain <code>fin...
1
2016-06-22T05:44:46Z
[ "java", "python", "regex", "review" ]
Python NameError global name is not defined - variable does not find its value in Thread
37,959,088
<p>I am struck at one point in my python code. I am trying to call a thread class object in my class to show a loading bar while my actual function fetches the values. I have 2 class files progress.py which has the loading code and my gmond_class.py which has the actual function which fetch the values. I am confused wi...
0
2016-06-22T05:16:45Z
37,959,128
<p>That's because you haven't actually defined <code>stop</code>. Just saying <code>global stop</code> doesn't do that - it only says that <code>stop</code> should be looked up in the global scope instead of local (anyway).</p> <p>To actually define <code>stop</code> you have to assign a value to it, for example <code...
2
2016-06-22T05:19:39Z
[ "python", "multithreading", "python-2.6" ]
Memory Error while opening sql script in python
37,959,093
<p>I'm trying to open a sql script in python but this piece of code is giving Memory error as the sql script is very huge(22GB!). </p> <pre><code> # Open and read the file as a single buffer fd = open('prob.sql', 'r') sqlFile = fd.read() fd.close() </code></pre>
1
2016-06-22T05:17:02Z
37,961,064
<p>Avoid the <code>read()</code> function in this case since it tries to load the entire file. </p> <p>You could iterate through the file line by line:</p> <pre><code>with open('prob.sql', 'r') as fd: for line in fd: do_something(line) </code></pre> <p>With the <code>with</code> construct you don't need ...
0
2016-06-22T07:18:34Z
[ "python", "file" ]
Python 3.x - iloc throws error - "single positional indexer is out-of-bounds"
37,959,214
<p>I am scraping election data from a website and trying to store it in a dataframe </p> <pre><code>import pandas as pd import bs4 import requests columns = ['Candidate','Party','Criminal Cases','Education','Age','Total Assets','Liabilities'] df = pd.DataFrame(columns = columns) ind=1 url = requests.get("http://my...
1
2016-06-22T05:26:18Z
37,960,270
<p>THis is a workaround. I get the same iloc error with my pandas version. This modified code overcomes it by creating a blank record (by creating a 1-row dataframe and appending to existing one) each iteration before assigning values to them.</p> <pre><code>import pandas as pd import bs4 import requests columns = ...
0
2016-06-22T06:34:14Z
[ "python", "indexing", "dataframe", "web-scraping" ]
Python 3.x - iloc throws error - "single positional indexer is out-of-bounds"
37,959,214
<p>I am scraping election data from a website and trying to store it in a dataframe </p> <pre><code>import pandas as pd import bs4 import requests columns = ['Candidate','Party','Criminal Cases','Education','Age','Total Assets','Liabilities'] df = pd.DataFrame(columns = columns) ind=1 url = requests.get("http://my...
1
2016-06-22T05:26:18Z
37,960,827
<p><code>DataFrame.iloc</code> cannot enlarge its target object. This used to be the error message, but has changed since version 0.15.</p> <p>In general a <code>DataFrame</code> is not meant to be built row at a time. It is very inefficient. Instead you should create a more traditional data structure and populate a <...
4
2016-06-22T07:05:38Z
[ "python", "indexing", "dataframe", "web-scraping" ]
PM2 doesn't log Python3 print statements
37,959,217
<p>I'm using PM2 to run a Python program in the background like so</p> <p><code>pm2 start helloworld.py</code></p> <p>and it works perfectly fine. However, within <code>helloworld.py</code> I have several print statements that act as logs. For example, when a network request comes in or if a database value is updated...
1
2016-06-22T05:26:44Z
38,276,868
<p>Check the folder #HOME/.pm2/logs</p> <p>See for example the folder structure section here: <a href="http://pm2.keymetrics.io/docs/usage/quick-start/" rel="nofollow">http://pm2.keymetrics.io/docs/usage/quick-start/</a></p> <p>Also consider using a configuration file with an explicit logs folder that is relative to ...
0
2016-07-08T23:46:37Z
[ "python", "pm2" ]
PM2 doesn't log Python3 print statements
37,959,217
<p>I'm using PM2 to run a Python program in the background like so</p> <p><code>pm2 start helloworld.py</code></p> <p>and it works perfectly fine. However, within <code>helloworld.py</code> I have several print statements that act as logs. For example, when a network request comes in or if a database value is updated...
1
2016-06-22T05:26:44Z
39,378,255
<p>This question is a few months old, so maybe you figured this out a while ago, but it was one of the top google hits when I was having the same problem so I thought I'd add what I found.</p> <p>Seems like it's an issue with how python buffers sys.stdout. In some platforms/instances, when called by say pm2 or nohup, ...
1
2016-09-07T20:12:08Z
[ "python", "pm2" ]
python selenium how to get certain text
37,959,281
<p>Is this possible in selenium, I think it's possible in urllib but I'm not sure.</p> <pre><code>if "@gmail.com" in html: print the string that includes the @gmail </code></pre> <blockquote> <p>ex: it will find <code>@gmail.com</code>, then it will print the string that is >connected too it <code>stackoverflow@gm...
0
2016-06-22T05:30:37Z
37,959,419
<p>yes, it is possible. What you want to achieve is:</p> <ol> <li>look through the entire HTML document for any <code>@gmail.com</code>, </li> <li>If there is a match, find out the whole email address.</li> </ol> <p>What you can do is basically:</p> <ol> <li><code>entireDocument = findElement(By.xpath("/html"))</cod...
0
2016-06-22T05:40:24Z
[ "python", "python-2.7", "python-3.x", "selenium" ]
python selenium how to get certain text
37,959,281
<p>Is this possible in selenium, I think it's possible in urllib but I'm not sure.</p> <pre><code>if "@gmail.com" in html: print the string that includes the @gmail </code></pre> <blockquote> <p>ex: it will find <code>@gmail.com</code>, then it will print the string that is >connected too it <code>stackoverflow@gm...
0
2016-06-22T05:30:37Z
37,964,007
<p>Yes this is possible. You can request the entire HTML of a page using <code>page_source</code>. Then you can check if <code>@gmail.com</code> is in this <code>page_source</code>.</p> <pre><code>source = driver.page_source domain = '@gmail.com' if domain in source: # Cut off the string behind @gmail.com (the mai...
0
2016-06-22T09:33:08Z
[ "python", "python-2.7", "python-3.x", "selenium" ]
Trying to send a mail using smtplib in python. Mail body comes alongwith subject line
37,959,395
<p>This is a weird issue that is bugging me since the past 2 days. I wrote a simple send mail function that uses smtplib to send emails with image as attachment.</p> <p>The problem is the body part gets concatenated to the Subject line. If I dont use a MIME message and just a string, they are separated out correctly. ...
0
2016-06-22T05:38:33Z
37,961,276
<blockquote> <p>I was hoping that creating a string in the subject should parse for newline and automatically pick the 2nd line onwards as body</p> </blockquote> <p>No such guarantees are made anywhere in the documentation. You're joining the subject and body and setting them as the subject, so that's what you get.<...
0
2016-06-22T07:28:03Z
[ "python", "email", "email-attachments", "smtplib" ]
Trying to send a mail using smtplib in python. Mail body comes alongwith subject line
37,959,395
<p>This is a weird issue that is bugging me since the past 2 days. I wrote a simple send mail function that uses smtplib to send emails with image as attachment.</p> <p>The problem is the body part gets concatenated to the Subject line. If I dont use a MIME message and just a string, they are separated out correctly. ...
0
2016-06-22T05:38:33Z
37,961,687
<p>I created <a href="http://github.com/kootenpv/yagmail" rel="nofollow">yagmail</a> to make it very easy to send attachments.</p> <pre><code>import yagmail yag = yagmail.SMTP(username, password) yag.send(to="myfriend@gmail.com", subject="Daily digest " + str(datetime.datetime.now()), contents="Goo...
0
2016-06-22T07:46:42Z
[ "python", "email", "email-attachments", "smtplib" ]
Django autoconversion of strings to datetimes
37,959,466
<p>Testing with SQLite, Django will converts strings to datetimes automatically when saving to the database, but discard updates from invalid strings without erroring. Is this behavior consistent across all Django database backends? Where is this documented? Also, how do I determine if a datetime in string form that...
1
2016-06-22T05:44:08Z
37,959,912
<blockquote> <p>SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values</p> </blockquote> <p><a href="https://www.sqlite.org/datatype3.html#section_2_2" rel="no...
2
2016-06-22T06:12:51Z
[ "python", "django", "sqlite", "datetime" ]
Dynamodb max value
37,959,515
<p>I'm using Dynamodb. I have a simple Employee table with fields like id, name, salary, doj, etc. What is the equivalent query of <code>select max(salary) from employee</code> in dynamodb?</p>
2
2016-06-22T05:47:33Z
37,960,297
<p>There is no cheap way to achieve this in Dynamodb. There is no inbuild function to determine the max value of an attribute without retrieving all items and calculate programmatically.</p>
0
2016-06-22T06:35:43Z
[ "python", "amazon-dynamodb", "boto3" ]
Dynamodb max value
37,959,515
<p>I'm using Dynamodb. I have a simple Employee table with fields like id, name, salary, doj, etc. What is the equivalent query of <code>select max(salary) from employee</code> in dynamodb?</p>
2
2016-06-22T05:47:33Z
37,960,397
<p>Not sure about <code>boto3</code> but in<code>boto</code> can be run this way</p> <pre><code>from boto.dynamodb2.table import Table table = Table("employee") values = list(table.query_2(reverse=True, limit=1)) MAXVALUE = values[0][salary] </code></pre>
0
2016-06-22T06:42:28Z
[ "python", "amazon-dynamodb", "boto3" ]
Dynamodb max value
37,959,515
<p>I'm using Dynamodb. I have a simple Employee table with fields like id, name, salary, doj, etc. What is the equivalent query of <code>select max(salary) from employee</code> in dynamodb?</p>
2
2016-06-22T05:47:33Z
37,960,735
<p>You can model your schema something like:</p> <ul> <li><code>employee_id</code>, as partition-key</li> <li><code>salary</code>, as sort-key of the table or local secondary index.</li> </ul> <p>Then, <code>Query</code> your table for given <code>employee_id</code>, with <code>ScanIndexForward</code> as false, and p...
0
2016-06-22T07:00:29Z
[ "python", "amazon-dynamodb", "boto3" ]
Odd behavior when rendering string with DOT in Jinja2
37,959,554
<p>This is my code: </p> <pre><code>file = 'http://www.example.com/cdn/.eJwdyjsKksjdbf-sjhdfb-kajsfbnksj' link = '%s/cdn/%s' % (self.base_url, file) app.log.debug('link is: %s' % link) return template.render(link_text=link_text, link=link) </code></pre> <p>Here the output of the log is as below: </p> <pre><code>2...
0
2016-06-22T05:50:19Z
37,960,041
<p>You need to mark your html as safe, otherwise Jinja performs autoescaping. This is as simple as:</p> <pre><code>from jinja import Markup ... return template.render(link_text=link_text, link=Markup(link)) </code></pre> <p>The other way you can do this is from the html template itself - just mark the variable as sa...
1
2016-06-22T06:20:14Z
[ "python", "templates", "jinja2" ]
Converting log time stamp Date Time offset/dst to epoch time
37,959,615
<p>I am trying to convert date/time stamps that look like this:</p> <p>20160131|235501[-0700/0] 20160621|225549[-0600/1]</p> <p>to epoch time. These come from a remote machine that is in a different time zones so I need a method that works only with the time stamps and not the local machine time.</p> <p>I've found ...
0
2016-06-22T05:53:12Z
38,007,535
<p>There's surely a more pythonic way to do this but if you can install <a href="https://labix.org/python-dateutil" rel="nofollow">dateutil</a> maybe something like this works:</p> <pre><code># epoch_date.py import datetime from dateutil.parser import parse import re raw_dts = '20160131|235501[-0700/0] 20160621|2...
0
2016-06-24T07:07:38Z
[ "python", "time", "epoch" ]
How can I make this work? Should I use requests or urllib.error for exceptions?
37,959,642
<p>I am trying to handle the exceptions from the http responses. </p> <p>The PROBLEM with my code is that I am forced to use and IF condition to catch http error codes</p> <pre><code>if page.status_code != requests.codes.ok: page.raise_for_status() </code></pre> <p>I do not believe this is the right way to do it...
1
2016-06-22T05:54:42Z
37,966,179
<p>You could catch a <a href="http://docs.python-requests.org/en/master/_modules/requests/exceptions/" rel="nofollow">RequestException</a> if you want to catch all the exceptions:</p> <pre><code>import requests try: r = requests.get(........) except requests.RequestException as e: print(e.message) </code></pr...
1
2016-06-22T11:05:46Z
[ "python", "python-3.x", "exception", "beautifulsoup", "python-requests" ]
Secure Python REST APIs
37,959,682
<p>I am trying to write some REST APIs in python, to begin with I started to write Authenticate code. I found sample code for authenticate on one of the site:</p> <pre><code>from functools import wraps from flask import request, Response def check_auth(username, password): """This function is called to check if a...
3
2016-06-22T05:57:29Z
37,960,533
<p>Looks like you are not passing username and password correctly to authenticate. Value of <code>username</code> and <code>password</code> you should get from the <code>auth</code> variable. So try changing the <code>requires_auth</code> funtion as:</p> <pre><code>def requires_auth(f): @wraps(f) def decorated...
0
2016-06-22T06:50:26Z
[ "python", "rest", "authentication", "flask" ]
Secure Python REST APIs
37,959,682
<p>I am trying to write some REST APIs in python, to begin with I started to write Authenticate code. I found sample code for authenticate on one of the site:</p> <pre><code>from functools import wraps from flask import request, Response def check_auth(username, password): """This function is called to check if a...
3
2016-06-22T05:57:29Z
37,968,917
<p>This is a working example of flask-authorization. </p> <pre><code>from functools import wraps from flask import Flask,Response,request, abort app = Flask(__name__) def check_auth(name,passw): return (name=='admin' and passw=='pass') def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): ...
1
2016-06-22T13:04:06Z
[ "python", "rest", "authentication", "flask" ]
run unittests from a command prompt
37,959,719
<p>I have created python files and unittests but I do not understand how can i run all the tests in one go from command prompt.</p> <p>file structure</p> <pre><code>- py - __init__.py - file1.py - file2.py - tests __init__.py - test_file1.py - test_file2.py </code></pre> <p>Please let me know the same. w...
0
2016-06-22T06:00:07Z
37,959,850
<p>Below is a snip from Nose's documentation (since you've tagged <code>nose</code>)</p> <blockquote> <p><strong>nose collects tests automatically from python source files, directories and packages found in its working directory (which defaults to the current working directory).</strong> Any python source file, dire...
3
2016-06-22T06:08:49Z
[ "python", "unit-testing", "nose" ]
run unittests from a command prompt
37,959,719
<p>I have created python files and unittests but I do not understand how can i run all the tests in one go from command prompt.</p> <p>file structure</p> <pre><code>- py - __init__.py - file1.py - file2.py - tests __init__.py - test_file1.py - test_file2.py </code></pre> <p>Please let me know the same. w...
0
2016-06-22T06:00:07Z
37,960,071
<p>For simple discovery, you can use the built-in command-line functionality of the <code>unittest</code> module</p> <pre><code>$ cd /path/to/your/project/tests $ python -m unittest discover </code></pre> <p>Or, if your <code>tests</code> directory has an <code>__init__.py</code>, you can do</p> <pre><code>$ cd /pat...
1
2016-06-22T06:21:56Z
[ "python", "unit-testing", "nose" ]
Converting Data frame into a dict with columns as key inside key
37,959,724
<p>I have a pandas data frame.</p> <pre><code> mac_address no. of co_visit no. of random_visit 0 00:02:1a:11:b0:b9 1 2 1 00:02:71:d6:04:84 1 1 2 00:05:33:34:2f:f2 1 3 3 00:08:22:04:c4:fb ...
1
2016-06-22T06:00:23Z
37,959,919
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.T.html" rel="nofollow">pandas.DataFrame.T</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html" rel="nofollow">to_dict()</a>.</p> <pre><code>df.set_index('mac_address').T.to_di...
1
2016-06-22T06:13:11Z
[ "python", "python-2.7", "dictionary", "pandas", "dataframe" ]
How can I plot theano.tensor value?
37,959,740
<p>To visualize TensorType(float64, matrix) as an image using imshow, How could I that?I cannot directly use imshow on Tensor since it gives me this error</p> <pre><code>mat is not a numpy array, neither a scalar </code></pre> <p>When I try to convert datatype to array using numpy.asarray I get</p> <pre><code> mat ...
0
2016-06-22T06:01:07Z
37,960,602
<p>Theano tensors are symbolic variables, with no value attached to them. If you want to plot something it is probably a shared variable (the weights of your network), in which case you can grab the values with <code>my_shared.get_value()</code>, or the output of the network when you pass an input, in which case I beli...
0
2016-06-22T06:53:54Z
[ "python", "debugging", "opencv", "theano" ]
How do I set up a virtual server using Django and mod_wsgi with Apache?
37,959,934
<p>I've been trying to run a server from my own machine, so that other people can see my site.</p> <p>I have apache installed on linux, and have altered my WSGI config, so that it points to my django project.</p> <p>My questions are, how do I know that WSGI is referencing my project, and how do I get the server up an...
-3
2016-06-22T06:14:31Z
37,960,721
<p>Try this <a href="https://www.digitalocean.com/community/tutorials/how-to-run-django-with-mod_wsgi-and-apache-with-a-virtualenv-python-environment-on-a-debian-vps" rel="nofollow">link</a>, which is a tutorial from DigitalOcean.</p> <p>Copied here to ensure it is maintained with the answer:</p> <p><strong>Prerequis...
-1
2016-06-22T06:59:36Z
[ "python", "django", "apache", "apache2", "mod-wsgi" ]
Python: Intelligent eval of conditions
37,959,942
<p>I have conditions within strings (in python condition notation), e.g. like so:</p> <pre><code>my_str = "0 and (not (1 and 0) or B_undefined_variable)" </code></pre> <p>I want to compute the condition result (In a mathematical sense). I'm using <code>eval</code> (No worries I know it is evil ;-)).</p> <pre><code>m...
0
2016-06-22T06:14:52Z
37,960,228
<p>If you understand the dangers of <code>eval</code> and just want to return a special value (e.g. 9999) for undefined variables what you can do is customizing the dictionary used by <code>eval</code>:</p> <pre><code>import collections d = collections.defaultdict(lambda : 9999) d['x'] = 21 d['y'] = 2 print(eval('x * ...
1
2016-06-22T06:30:58Z
[ "python", "conditional", "eval" ]
Compose two SVG files in python
37,959,974
<p>I would like to compose two SVG files (say a.svg and b.svg) in python in a very simple way: b.svg should be centered vertically and horizontally over a.svg</p> <p>What is the easiest way to achieve that? I've seen libraries like svgwrite and svg_stack but I don't think they do what I want.</p>
0
2016-06-22T06:16:57Z
37,960,632
<p>Take a look at <a href="http://opencv.org/" rel="nofollow">OpenCV</a>. It's a powerful image library with a friendly learning curve. </p>
-2
2016-06-22T06:55:10Z
[ "python", "svg" ]
Python Email, [Errno 10061] No connection could be made because the target machine actively refused it
37,960,035
<p>I want to send a mail in using python, below is my code, but I got the error 10061 at the end, hope anyone can help me, thanks!</p> <pre><code>import smtplib fromaddr = 'XXX@XX.com' toaddrs = 'XXX@XX.com ' msg = 'Why,Oh why!' username = 'XXXXXX' password = 'XXXXXX' server = smtplib.SMTP('smtp.gmail.com:587') se...
0
2016-06-22T06:19:38Z
37,960,169
<p>as far as i know Gmail and other companies have security to prevent emails beeing sent from unknown sources, here is a link to turn that kind of security of:</p> <p><a href="https://www.google.com/settings/security/lesssecureapps" rel="nofollow">https://www.google.com/settings/security/lesssecureapps</a></p> <p>th...
0
2016-06-22T06:27:40Z
[ "python", "smtp", "gmail" ]
Python Email, [Errno 10061] No connection could be made because the target machine actively refused it
37,960,035
<p>I want to send a mail in using python, below is my code, but I got the error 10061 at the end, hope anyone can help me, thanks!</p> <pre><code>import smtplib fromaddr = 'XXX@XX.com' toaddrs = 'XXX@XX.com ' msg = 'Why,Oh why!' username = 'XXXXXX' password = 'XXXXXX' server = smtplib.SMTP('smtp.gmail.com:587') se...
0
2016-06-22T06:19:38Z
37,960,424
<p>As mentioned by Cid-EL, <strong><a href="https://www.google.com/settings/security/lesssecureapps" rel="nofollow">You have to enable less secure apps in GMAIL settings</a></strong></p> <p>However, It's not secure to turn on that perticular option.</p> <p>Gmail provides API's to perform mail operations. GMAIL API's ...
2
2016-06-22T06:44:08Z
[ "python", "smtp", "gmail" ]
Multi-threaded code keeps printing even after KeyboardInterrupt
37,960,126
<p>I have a very simple multi-threaded python code with two threads trying to pop and print from a queue. I use a lock to ensure mutual exclusion. Everything works fine, except:</p> <ol> <li>If I import python's in-built <code>Queue</code>, the program exits on <code>KeyboardInterrup</code> from the terminal</li> <li>...
2
2016-06-22T06:24:56Z
37,960,517
<p>Your problem is not your custom <code>Queue</code> v/s python's <code>Queue</code>. It is something else altogether. Further, even with python's <code>Queue</code> implementation you would see the same behaviour.</p> <p>This is because your main thread dies when your press <code>ctrl+C</code> before it is able to s...
2
2016-06-22T06:49:40Z
[ "python", "multithreading" ]
Bin all values of a dataframe into percentiles in pandas
37,960,216
<p>I have a dataframe with all numeric columns:</p> <pre><code>import pandas as pd import numpy as np np.random.seed(1001) df = pd.DataFrame(np.random.randn(10, 2), columns=['A', 'B']) </code></pre> <p>I want to create common quantiles which includes all values of <code>A</code> and <code>B</code>. There are some mis...
1
2016-06-22T06:30:18Z
37,960,655
<p>I think you can first <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> <code>DataFrame</code>, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.qcut.html" rel="nofollow"><code>qcut</code></a> and then <a href="h...
0
2016-06-22T06:55:58Z
[ "python", "numpy", "pandas", "dataframe", "bins" ]
plotting a logistic regression :ValueError: x and y must have same first dimension
37,960,302
<p>When I run my code I get an error message:</p> <blockquote> <p>ValueError: x and y must have same first dimension.</p> </blockquote> <pre><code>import numpy as np from matplotlib import pyplot as plt from sklearn.linear_model import LogisticRegression x1 = np.array([0,0.6,1.2,1.5,1.8,2.5,3.3,3.9,4,4.9,5.1]) y...
0
2016-06-22T06:35:56Z
37,960,366
<p>When calling <code>plot</code>, the two first arguments x and y must lists or arrays of the same length.</p> <p>Your <code>x2</code> and <code>y2</code> are not of the same length.</p> <p>To avoid the issue in the future, there are better ways to create an array filled with only one value, for example:</p> <pre><...
2
2016-06-22T06:40:11Z
[ "python", "numpy", "matplotlib", "scikit-learn" ]
Hyperspectral Image Processing with Python
37,960,372
<p>How do you read into memory a hyperspectral image (3d) using python's enthought canopy distribution?</p>
0
2016-06-22T06:40:33Z
37,965,067
<p>Installing <a href="http://www.spectralpython.net/" rel="nofollow">Spectral Python (Spy)</a> is the best way to go:</p> <pre><code>C:\Users\Me&gt; pip install spectral </code></pre> <p>Once you get the module installed, reading a hyperspectral image into memory can be readily accomplished by:</p> <pre><code>&gt;&...
1
2016-06-22T10:16:55Z
[ "python", "enthought" ]
How to change the x-axis unit in matplotlib?
37,960,419
<p>I have data of x-axis from 0 to 700 hours. Each hour has data. But I want to show day as a unit for my x-axis. Currently, the x-axis is like <code>[1..2..3...713]</code> . But I want them to be like <code>[1..5..10..15...29]</code>. I still want to plot all the individual 24 hours values between days instead of hou...
1
2016-06-22T06:43:46Z
37,961,181
<p>Make a separate array X of x-values whose units are as you want. This way, when you plot the data it is already in the correct format! Just make sure you add a xlabel to indicate the units (which should always be done anyways).</p> <p>As example between meters and nanometers : </p> <pre><code>from pylab import * ...
1
2016-06-22T07:23:44Z
[ "python", "numpy", "matplotlib" ]
No such option error in python-zipline
37,960,471
<p>I am a newbie to zipline. I am following the beginner tutorial to get familiar with it. And when I tried to run the algorithm as taught by tutorial in the ipython cell:</p> <pre><code>from zipline.api import order_target, record, symbol, history import numpy as np import pandas as pd from zipline.examples import b...
3
2016-06-22T06:46:22Z
38,194,721
<p>I ran this command <code>$ zipline ingest</code> which defaulted to fetching quantopian-quandl data bundle.</p> <p>After that finished downloading I removed the offending switch: <code>--symbols AAPL</code> and the tutorial seemed to run correctly.</p>
1
2016-07-05T03:17:59Z
[ "python", "quantitative-finance", "zipline" ]
How to run ssh -vvv host through a python script?
37,960,661
<p>I would like to check the authentication method (whether public key or password or both) of a bunch of IP addresses through SSH -vvv host command using a python script that does not require password.</p> <p>basically I am interested in the below line of the result:</p> <pre><code>debug1: Authentications that can c...
0
2016-06-22T06:56:24Z
37,960,929
<pre><code>import paramiko client = SSHClient() client.load_system_host_keys() try: client.connect('ssh.example.com') except AuthenticationException as e: print ('got exception {}'.format(e.__dict__)) except : print ('got exception: NOT AUTH !!!') </code></pre> <p>now just loop it as many times. no need fo...
0
2016-06-22T07:11:34Z
[ "python", "shell", "ssh" ]
How to run ssh -vvv host through a python script?
37,960,661
<p>I would like to check the authentication method (whether public key or password or both) of a bunch of IP addresses through SSH -vvv host command using a python script that does not require password.</p> <p>basically I am interested in the below line of the result:</p> <pre><code>debug1: Authentications that can c...
0
2016-06-22T06:56:24Z
37,962,093
<p>You could try to use</p> <pre><code>ssh -o KbdInteractiveAuthentication=no -o PasswordAuthentication=no -vvv </code></pre> <p>That instructs the client not to try keyboard interactive or password authentication, but the server will still send which methods it supports. It may still ask for confirmation if the host...
1
2016-06-22T08:05:50Z
[ "python", "shell", "ssh" ]
Xcode gives error while using Python.framework in iOS ,undefined symbol for architecture i386
37,960,704
<p>Undefined symbols for architecture i386:</p> <blockquote> <p>"_PyInt_AsLong", referenced from: _main in main.o</p> <p>"_PyInt_FromLong", referenced from: _main in main.o</p> <p>"_PyString_FromString", referenced from: _main in main.o</p> </blockquote> <p>ld: symbol(s) not found ...
0
2016-06-22T06:58:54Z
38,047,376
<p>Replacing </p> <ol> <li>PyUnicode_AsUTF8 or PyUnicode_FromString for _PyString_FromString</li> <li>PyLong_AsLong for _PyInt_AsLong</li> <li>PyLong_FromLong for _PyInt_FromLong</li> </ol> <p>solved my problem.</p>
0
2016-06-27T06:41:30Z
[ "python", "ios", "objective-c", "xcode" ]
Count frequency of a letter in text file without using built-in dict data structure OR count function in Python
37,960,800
<p>I am working on a program that counts the number of words and letters in a text file. The program should also display the number of times each letter is used in the file. I have included my code for counting the words and letters. I need help with finding the best way display the letter frequency without using count...
0
2016-06-22T07:03:43Z
37,961,303
<p>Your code should work with minor adjustments. Try this:</p> <pre><code>number_of_lines = 0 number_of_words = 0 number_of_chars = 0 with open(r'myfile.txt', 'r') as f: for line in f: number_of_lines += 1 word_list = line.split() number_of_words += len(word_list) number_of_chars +...
0
2016-06-22T07:29:16Z
[ "python", "count", "frequency", "letter" ]
Count frequency of a letter in text file without using built-in dict data structure OR count function in Python
37,960,800
<p>I am working on a program that counts the number of words and letters in a text file. The program should also display the number of times each letter is used in the file. I have included my code for counting the words and letters. I need help with finding the best way display the letter frequency without using count...
0
2016-06-22T07:03:43Z
37,963,049
<p>use this code instead</p> <pre><code>f=open() num_lines = 0 num_words = 0 num_char = 0s while str: str=f.readline() words=str.split() num_words+=len(words) num_lines+=1 for a in words: num_char+=len(a) f.close() </code></pre>
0
2016-06-22T08:52:12Z
[ "python", "count", "frequency", "letter" ]
py2exe generated .exe shows error message on windows systems
37,960,842
<p>I have developed a python openCV based OCR system and generated an .exe file using py2exe. The problem is it shows an error message on several Windows systems.</p> <p>Error message:</p> <p><code>Exception in Tkinter callback Traceback &lt;most recent call last&gt;: File "Tkinter.pyc", line 1536, in __cal...
0
2016-06-22T07:06:35Z
37,976,122
<p>Maybe it is not an option, but py2exe is not the only tool on the market. </p> <p>What about using PyInstaller. In this <a href="http://stackoverflow.com/questions/36237678/how-do-you-include-subprocess-with-py2exe">question</a> there is also no answer given, but it is mentioned that after switching to PyInstaller ...
0
2016-06-22T18:52:44Z
[ "python", "opencv", "tkinter", "ocr", "py2exe" ]
TFS REST upload attachment permission problems
37,960,880
<p>I'm implementing TFS to our service. I'm using OAuth2, and it is working like a charm. I'm requesting permission scopes "<strong>vso.work_write vso.project</strong>" but somehow I'm not able to upload attachments. I'm getting 403 Forbidden from the server. As MS documentation is full of holes on this subject can may...
0
2016-06-22T07:08:46Z
37,964,104
<p>So.... This one is painful, but <strong>it looks like I do not need project name in the URL when uploading attachments</strong>. That was the mistake. Scope permissions are fine. (at the moment I'm testing with everything enabled) but I will post my final status if something will be different.</p> <p>Too bad servic...
0
2016-06-22T09:37:09Z
[ "python", "rest", "tfs", "permissions" ]
Value Error during merging two data frame
37,960,901
<p>I have 2 data frames:</p> <pre><code>visit_final.iloc[0:10] Out[48]: mac_address no. of visit during peak hour 0 00:02:1a:11:b0:b9 1 1 00:02:71:d6:04:84 1 2 00:05:33:34:2f:f2 1 3 00:08:22:04:c4:fb ...
0
2016-06-22T07:10:07Z
37,962,219
<p>The problem in your code: you are trying to merge to objects of type string...</p> <pre><code>final = pd.merge("a","b", how = 'outer', on =['mac']) </code></pre> <p>But you should rather:</p> <pre><code>final = pd.merge(a, b, how = 'outer', on =['mac']) </code></pre> <p>So just remove the quotation marks around ...
1
2016-06-22T08:11:47Z
[ "python", "python-2.7", "merge" ]
Unable to conditionally execute if block in Python
37,960,974
<p>I am assigning the value of a system environment variable. Based on the value of this variable - true or false, I have the if and else block to be executed. When the value of that variable is false, it is executing the else block successfully, but if the value of the variable is true, then it is not executing the s...
-4
2016-06-22T07:13:38Z
37,961,451
<p>Can you print <code>type(isMtEnabled)</code> ? If the result is boolean, replace your if by something like :</p> <pre><code>if isMtEnabled : (... body ...) </code></pre>
-1
2016-06-22T07:35:39Z
[ "python" ]
Python script slower as .exe than as .py
37,961,026
<p>I'm writing an app in Python that uses among others <em>PySide</em> for the GUI and also <a href="https://pypi.python.org/pypi/modbus_tk" rel="nofollow"><em>modbus_tk</em></a> for Modbus communications between my PC and an embedded controller.</p> <p>I've noticed that <strong>when I byte-compile my script to a Wind...
0
2016-06-22T07:16:32Z
37,962,258
<p>From <a href="https://en.wikipedia.org/wiki/Py2exe" rel="nofollow">https://en.wikipedia.org/wiki/Py2exe</a></p> <blockquote> <p>Although this program transforms a .py file to an .exe, it does not make it run faster as py2exe just bundles the Python bytecode rather than converting it to machine-code. It may even r...
1
2016-06-22T08:13:48Z
[ "python", "performance", "pyside", "py2exe", "modbus" ]
Regex and renaming file error
37,961,049
<p>I was writing a little program that finds all files with given prefix, let's say <code>'spam'</code> for this example, in a folder and locates gaps in numbering and renames subsequent folders to fill the gap. Below illustrates a portion of the program that locates the files using a regex and renames it:</p> <pre><c...
1
2016-06-22T07:17:42Z
37,961,923
<p>There are two problems here: </p> <p>Your <code>newNumber</code> needs to be a string if you want it to be <code>005</code> as the first two <code>0</code> are dropped when it is being interpreted as an integer.</p> <p>Your next problem is indeed in your substitution. By using the string formating you effectively ...
1
2016-06-22T07:58:41Z
[ "python" ]