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 |
|---|---|---|---|---|---|---|---|---|---|
Deleting DataFrame rows in Pandas based on column value - multiple values to remove | 38,109,137 | <p>I have a list of values (not known in advance, in a Python list) that a column in my Panda DataFrame must not have for all rows.</p>
<p>All recipes on the Web (like <a href="http://stackoverflow.com/questions/18172851/deleting-dataframe-row-in-pandas-based-on-column-value">this one</a>) show how to do it with only ... | 2 | 2016-06-29T20:07:38Z | 38,109,241 | <p>You can do negative <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-with-isin">isin()</a> indexing:</p>
<pre><code>In [57]: df
Out[57]:
a b c
0 1 2 2
1 1 7 0
2 3 7 1
3 3 2 7
4 1 3 1
5 3 4 2
6 0 7 1
7 5 4 3
8 6 1 0
9 3 2 0
In [58]: my_list = [1, 7, 8]
... | 5 | 2016-06-29T20:13:56Z | [
"python",
"pandas",
"filter",
"dataframe"
] |
Deleting DataFrame rows in Pandas based on column value - multiple values to remove | 38,109,137 | <p>I have a list of values (not known in advance, in a Python list) that a column in my Panda DataFrame must not have for all rows.</p>
<p>All recipes on the Web (like <a href="http://stackoverflow.com/questions/18172851/deleting-dataframe-row-in-pandas-based-on-column-value">this one</a>) show how to do it with only ... | 2 | 2016-06-29T20:07:38Z | 38,109,370 | <p>you could also use <code>np.in1d</code>. From <a href="http://stackoverflow.com/a/38083418/2336654">http://stackoverflow.com/a/38083418/2336654</a></p>
<p>For your use case:</p>
<pre><code>df[~np.in1d(df.b, my_list)]
</code></pre>
<h3>Demonstration</h3>
<pre><code>from string import ascii_letters, ascii_lowerca... | 5 | 2016-06-29T20:22:12Z | [
"python",
"pandas",
"filter",
"dataframe"
] |
Deleting DataFrame rows in Pandas based on column value - multiple values to remove | 38,109,137 | <p>I have a list of values (not known in advance, in a Python list) that a column in my Panda DataFrame must not have for all rows.</p>
<p>All recipes on the Web (like <a href="http://stackoverflow.com/questions/18172851/deleting-dataframe-row-in-pandas-based-on-column-value">this one</a>) show how to do it with only ... | 2 | 2016-06-29T20:07:38Z | 38,110,564 | <p>I decided to add another answer with timings for different methods and different dtypes - it would be too long for one answer...</p>
<p><strong>Timings against 1M rows DF for the following dtypes: int32, int64, float64, object (string):</strong></p>
<p><a href="http://i.stack.imgur.com/NdPNZ.png" rel="nofollow"><i... | 1 | 2016-06-29T21:44:32Z | [
"python",
"pandas",
"filter",
"dataframe"
] |
Running flask with fcgi | 38,109,224 | <p>I'm reading through <a href="http://fgimian.github.io/blog/2014/02/14/serving-a-python-flask-website-on-hostmonster/" rel="nofollow">http://fgimian.github.io/blog/2014/02/14/serving-a-python-flask-website-on-hostmonster/</a> , trying to deploy a flask app on shared hosting.</p>
<p>I'm using <a href="https://github.... | 0 | 2016-06-29T20:12:32Z | 38,109,318 | <p>You don't. <code>manage.py</code> is for managing the local development. <code>fcgi.py</code> is for setting up the production app. <code>fcgi.py</code> already imports the app factory and tells it what environment to use (<code>create_app('production')</code>), so unless there's something wrong with that call you... | 1 | 2016-06-29T20:19:08Z | [
"python",
"flask"
] |
cv2 import error on Jupyter notebook | 38,109,270 | <p>I'm trying to import <strong>cv2</strong> on <strong>Jupyter notebook</strong> but I get this error:</p>
<pre><code>ImportError: No module named cv2
</code></pre>
<p>I am frustrated because I'm working on this simple issue for hours now. it works on Pycharm but not on Jupiter notebook. I've already installed cv2 i... | 0 | 2016-06-29T20:16:02Z | 38,110,537 | <p>Is your python path looking in the right place? Check where python is looking for the module. Within the notebook try:</p>
<pre><code>import os
os.sys.path
</code></pre>
<p>Is the <code>cv2</code> module located in any of those directories? If not your path is looking in the wrong place. If it is overlooking the i... | 1 | 2016-06-29T21:42:41Z | [
"python",
"opencv",
"jupyter-notebook"
] |
Global name 'paramiko' not defined when using module in web2py | 38,109,285 | <p>I am running the source version of web2py from an Ubuntu VM and Python 2.7. I'm trying to use the Paramiko library for SSH functionality, but the following code gives this error:</p>
<p><strong>Code</strong></p>
<p><code>from paramiko import client</code></p>
<p><strong>Error</strong></p>
<pre><code>Traceback (m... | -1 | 2016-06-29T20:17:01Z | 38,111,397 | <p>Your import statement is:</p>
<pre><code>from paramiko import client
</code></pre>
<p>But in your code, you have:</p>
<pre><code>except paramiko.ssh_exception.AuthenticationException
</code></pre>
<p>In order to reference <code>paramiko</code>, you must import it:</p>
<pre><code>import paramiko
</code></pre>
| 1 | 2016-06-29T22:59:07Z | [
"python",
"python-2.7",
"web2py",
"web2py-modules"
] |
How can I avoid getting duplicate paths from os.walk | 38,109,351 | <p>I have the following directory structure</p>
<pre><code>/mnt/type/split/v2/doc/RESOURCE_ID/YYYY/FY/DOCUMENT_ID
</code></pre>
<p>for example, one path might be</p>
<pre><code>/mnt/type/split/v2/doc/100045/2008/FY/28
</code></pre>
<p>where </p>
<pre><code>RESOURCE_ID = 100045
YYYY = 2008
DOCUMENT_ID = 28
</code><... | 1 | 2016-06-29T20:21:03Z | 38,109,720 | <p><code>os.walk()</code> will <em>recursively</em> walk a directory structure. For each directory you encounter, you start <em>another recursive call</em>. So for every directory, you recursively walk that directory plus all nested directories. That includes nested directories. By kicking off a search for <code>/mnt/t... | 1 | 2016-06-29T20:44:51Z | [
"python",
"os.walk"
] |
How to test a model in tensor flow? | 38,109,489 | <p>I'm following this tutorial: </p>
<p><a href="https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html#mnist-for-ml-beginners" rel="nofollow">https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html#mnist-for-ml-beginners</a></p>
<p>What I want to be able to do is pass in ... | 1 | 2016-06-29T20:29:51Z | 38,110,031 | <p>your tf.Session.run op needs a fetches
tf.Session.run(fetches, feed_dict=None, options=None, run_metadata=None)</p>
<p><a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/client.html#session-management" rel="nofollow">https://www.tensorflow.org/versions/r0.9/api_docs/python/client.html#session-managem... | 0 | 2016-06-29T21:06:14Z | [
"python",
"tensorflow"
] |
How to test a model in tensor flow? | 38,109,489 | <p>I'm following this tutorial: </p>
<p><a href="https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html#mnist-for-ml-beginners" rel="nofollow">https://www.tensorflow.org/versions/r0.9/tutorials/mnist/beginners/index.html#mnist-for-ml-beginners</a></p>
<p>What I want to be able to do is pass in ... | 1 | 2016-06-29T20:29:51Z | 39,110,059 | <p>You're getting the <code>TypeError</code> because you are using a (mutable) <code>numpy.ndarray</code> as a key for your dictionary but the key should be a <code>tf.placeholder</code> and the value a <code>numpy</code> array. </p>
<p>The following adjustment fixes this problem:</p>
<pre><code>x_placeholder = tf.pl... | 0 | 2016-08-23T20:22:27Z | [
"python",
"tensorflow"
] |
python .txt file is identifying one letter at a time instead of a word in a .txt | 38,109,499 | <p>first i wold like to say im a very basic programmer so if you can please try not to be complicated however anything is helpful.</p>
<p>I have a .txt file to define a keyword list eg:</p>
<pre><code>pig,dog,cat
</code></pre>
<p>My real list is much bigger but has the same format.</p>
<p>I want the user to input s... | -1 | 2016-06-29T20:30:26Z | 38,109,548 | <p>You're looking through the string of the file path, not the contents.</p>
<p>To loop through the file, you'd want to do something like this:</p>
<pre><code>with open('D:\Program Files (x86)\Python Programming\python.txt') as fl:
if any(word in start_question for word in fl):
print("yes")
else:
prin... | 1 | 2016-06-29T20:33:27Z | [
"python"
] |
optional nargs variable in argparse | 38,109,570 | <p>How I can do conditional loop with argparse with variable nargs? So, basically, it should run with or without argument.
I am trying:</p>
<pre><code>parser = argparse.ArgumentParser(description="output parser")
group = parser.add_mutually_exclusive_group()
group.add_argument("--dos", help="get DOSCAR for plot",
... | 2 | 2016-06-29T20:34:59Z | 38,109,758 | <p>You need to replace nargs = "?" with nargs = "*". Setting nargs to "?" means there will be 1 optional argument. What you want is a list of optional arguments, which is "*". Like so.</p>
<pre><code>import argparse
parser = argparse.ArgumentParser(description="output parser")
group = parser.add_mutually_exclusive_gro... | 0 | 2016-06-29T20:47:37Z | [
"python",
"argparse"
] |
optional nargs variable in argparse | 38,109,570 | <p>How I can do conditional loop with argparse with variable nargs? So, basically, it should run with or without argument.
I am trying:</p>
<pre><code>parser = argparse.ArgumentParser(description="output parser")
group = parser.add_mutually_exclusive_group()
group.add_argument("--dos", help="get DOSCAR for plot",
... | 2 | 2016-06-29T20:34:59Z | 38,110,119 | <p>Simplifying your parser in a Ipython session:</p>
<pre><code>In [1004]: parser=argparse.ArgumentParser()
In [1005]: parser.add_argument('--dos', nargs='?')
In [1007]: parser.parse_args('--dos 111'.split())
Out[1007]: Namespace(dos='111')
</code></pre>
<p>In this case <code>args.dos</code> will be the string '... | 3 | 2016-06-29T21:11:38Z | [
"python",
"argparse"
] |
optional nargs variable in argparse | 38,109,570 | <p>How I can do conditional loop with argparse with variable nargs? So, basically, it should run with or without argument.
I am trying:</p>
<pre><code>parser = argparse.ArgumentParser(description="output parser")
group = parser.add_mutually_exclusive_group()
group.add_argument("--dos", help="get DOSCAR for plot",
... | 2 | 2016-06-29T20:34:59Z | 38,120,639 | <p>thanks to all the people who replied, and specially @hpaulj. But none of them really solve my problem. So, I took other way. I am posting this here for completeness.</p>
<pre><code>#!/usr/bin/python3
import argparse
parser = argparse.ArgumentParser(description="output parser")
group = parser.add_mutually_exclusive... | 0 | 2016-06-30T10:35:36Z | [
"python",
"argparse"
] |
Map a number to an id in python | 38,109,760 | <p>Suppose I have a numpy array like: [11, 30, 25]. These numbers represent categories of the objects corresponding to the indices. I know there are just 20 categories but for some reason they are numbered from 11 to 29. I'd like to convert them to numbers in 0:19 and back. What would by a pythonic way to do this? Pref... | 2 | 2016-06-29T20:47:41Z | 38,110,015 | <p>Let's say <code>arr</code> is the input array of categories. </p>
<p><strong>Forward Process/Encoding :</strong> From categories to IDs</p>
<p>To perform the encoding, use <code>np.unique</code> alongwith its optional <code>return_inverse</code> argument to give us IDs that would have values from <code>0</code> to... | 4 | 2016-06-29T21:05:11Z | [
"python",
"numpy"
] |
Map a number to an id in python | 38,109,760 | <p>Suppose I have a numpy array like: [11, 30, 25]. These numbers represent categories of the objects corresponding to the indices. I know there are just 20 categories but for some reason they are numbered from 11 to 29. I'd like to convert them to numbers in 0:19 and back. What would by a pythonic way to do this? Pref... | 2 | 2016-06-29T20:47:41Z | 38,110,022 | <p>To be able to easily convert back-and-forth, I would use the <code>sklearn.preprocessing</code> module <code>LabelEncoder</code>:</p>
<pre><code>In [7]: from sklearn.preprocessing import LabelEncoder
In [8]: encoder = LabelEncoder()
In [9]: encoder.fit(range(11,31))
Out[9]: LabelEncoder()
In [10]: encoder.transf... | 3 | 2016-06-29T21:05:41Z | [
"python",
"numpy"
] |
Nested for loops using multiprocessing | 38,109,830 | <p>I have a quick question regarding multiprocessing in python. </p>
<p>I am conducting a rather large grid search over three parameters and the computation is taking ~14 hours to complete. I would like to shrink this run time down by using multiprocessing. </p>
<p>A very simplified example of my code is here:</p>
<... | 0 | 2016-06-29T20:53:19Z | 38,113,474 | <p>This doesn't solve your multiprocessing problem but it might make your process faster.</p>
<p>Your <em>pattern</em> of using nested loops to construct n-d coordinates and then operating on them can be <em>vectorize</em>d using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="no... | 1 | 2016-06-30T03:24:44Z | [
"python",
"multiprocessing",
"grid-search"
] |
Nested for loops using multiprocessing | 38,109,830 | <p>I have a quick question regarding multiprocessing in python. </p>
<p>I am conducting a rather large grid search over three parameters and the computation is taking ~14 hours to complete. I would like to shrink this run time down by using multiprocessing. </p>
<p>A very simplified example of my code is here:</p>
<... | 0 | 2016-06-29T20:53:19Z | 38,250,020 | <p>As per user wwii's suggestions, I have rewrote the example above by using numpy's meshgrid and getting rid of the nested for loops for just a single loop. Here is an example of the working code. </p>
<pre><code>import numpy as np
import time
a_range = np.arange(14, 18, 1)
b_range = np.arange(1000, 2200, 200)
c_ra... | 0 | 2016-07-07T15:52:42Z | [
"python",
"multiprocessing",
"grid-search"
] |
OpenCV Python - cv2 Module not found | 38,109,860 | <p>Even though I believe I have installed correctly OpenCV, I cannot overcome the following problem. When I start a new python project from IDLE (2.7) the cv2 module is imported successfully. If I close IDLE and try to run the .py file, an error message is displayed that says "ImportError: No module named cv2". Then if... | 0 | 2016-06-29T20:55:25Z | 38,110,151 | <p>Try to reinstall it by <code>sudo apt-get install python-opencv</code>,
But first you may check out something you might be skipping.
Make sure the script you are running on the terminal is on the same python version/ location as on IDLE.
Maybe your IDLE is running on a different interpreter(different location).
Ope... | 0 | 2016-06-29T21:13:34Z | [
"python",
"python-2.7",
"opencv"
] |
How to do arithmetic on tidy data in pandas? | 38,109,894 | <p>I have a <code>DataFrame</code> in "<a href="http://vita.had.co.nz/papers/tidy-data.pdf" rel="nofollow">tidy</a>" format (columns are variables, rows are observations) containing time series data for several different conditions. I'd like to normalize the data to the zero-hour time point for each condition.</p>
<p>... | 0 | 2016-06-29T20:57:13Z | 38,110,180 | <p>You want to use <code>groupby</code> and <code>diff</code>:</p>
<pre><code>df['food_eaten'] = -df.groupby(['animal', 'meal'])['food_left'].diff()
</code></pre>
<p>Follow that with fillna() if you want zeroes rather than NaN for situations where nothing was eaten. While this doesn't directly generalize you now have... | 0 | 2016-06-29T21:15:37Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How to do arithmetic on tidy data in pandas? | 38,109,894 | <p>I have a <code>DataFrame</code> in "<a href="http://vita.had.co.nz/papers/tidy-data.pdf" rel="nofollow">tidy</a>" format (columns are variables, rows are observations) containing time series data for several different conditions. I'd like to normalize the data to the zero-hour time point for each condition.</p>
<p>... | 0 | 2016-06-29T20:57:13Z | 38,124,788 | <p>You can create a new column based on the transformed data, as a one-liner, it would be:</p>
<pre><code>df['food_eaten'] = df.set_index(['time']).groupby(['animal', 'meal']).
transform(lambda x: x[0] - x).values
</code></pre>
<p>df</p>
<pre><code> animal meal time food_left food_e... | 1 | 2016-06-30T13:37:36Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How can I get an asymmetric many-to-many self-relationship to show up for both parties in a Django restful response? | 38,109,935 | <p>I currently have 2 relevant classes in my model: A <code>UserProfile</code> class and a <code>FriendInvite</code> class in <code>models.py</code></p>
<pre><code>class UserProfile(models.Model):
user = models.OneToOneField(User)
username = models.TextField()
friends = models.ManyToManyField('self',throug... | 0 | 2016-06-29T20:59:32Z | 38,134,007 | <p>My current solution is to define a method in the <code>UserProfile</code> class and use queries to get the set of objects I want. I still want to know if there are other ways to do this, though.</p>
<pre><code>...
from itertools import chain
from django.db.models import Q
class UserProfile(models.Model):
...
... | 0 | 2016-06-30T22:06:05Z | [
"python",
"django",
"django-rest-framework",
"manytomanyfield"
] |
How to store data with Time Module in python | 38,109,943 | <p>I want to write a very simple program which calculates how much you earned with work during the month (it's just for practicing). Idea is next: every time you run the program it prints out today's date and asks user to enter the amount of hour he worked. Then it calculates today's and whole month earnings and prints... | 0 | 2016-06-29T20:59:53Z | 38,110,485 | <p>As plamut said, you need some storage. Here is a program to get you started that will give interaction like so:</p>
<pre>
Enter 'print' or some hours, format like 12.34, 0.56,etc
1.00
Enter 'print' or some hours, format like 12.34, 0.56,etc
2.01
Enter 'print' or some hours, format like 12.34, 0.56,etc
print
You ha... | 0 | 2016-06-29T21:39:06Z | [
"python",
"time"
] |
How to close the ends of a cylinder in matplotlib | 38,109,960 | <p>I am trying to make a 'closed' cylinder in matplotlib but I am not sure how to go about doing this. So far I have a cylinder with the ends open, the code for this is as follows:</p>
<pre><code>#make a cylinder without the ends closed
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
... | 1 | 2016-06-29T21:01:21Z | 38,112,824 | <p>A quick and easy way that's similar to your other code is to generate a surface using strips from <code>r=0</code> to <code>r=R</code>. Right before <code>plt.show()</code> add the following lines:</p>
<pre><code>R = np.array([0,R])
# cap at t=0
X, Y, Z = [p0[i] + np.outer(R, np.sin(theta)) * n1[i] + np.outer(R, n... | 1 | 2016-06-30T02:05:28Z | [
"python",
"matplotlib"
] |
How to read images and labels to batches in tensorflow from separate files with shared keys? | 38,109,979 | <p>I am trying to use the convolutional network code on cifar-10 from the tensorflow tutorial with my own images (various sizes). Now the images and labels are stored separately with image names as keys. I was wondering how to modify the following function in cifar10_input.py. Thanks.</p>
<pre><code>def read_cifar10(f... | 1 | 2016-06-29T21:02:53Z | 38,110,251 | <p>if you look at <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/io_ops.html#FixedLengthRecordReader" rel="nofollow">https://www.tensorflow.org/versions/r0.9/api_docs/python/io_ops.html#FixedLengthRecordReader</a> it seemed that the reader.read op is reading the image and the label</p>
<p>result.ke... | 0 | 2016-06-29T21:20:52Z | [
"python",
"image",
"label",
"tensorflow"
] |
Adding non standard Python library to Beaker Lab notebook | 38,109,980 | <p>I would like to use fiona (and a few other third party libraries from Github) in my Beaker Lab notebook and it's not included in the default installation. </p>
<p>Is there a way to install new Python packages?</p>
| 1 | 2016-06-29T21:02:54Z | 38,124,394 | <p>To use python packages in a Python 2 Notebook you should first use the My Cloud Resources to create a directory âp2packagesâ in your scratch space.</p>
<p>Then you can append the path to your sys.path variable. This should be done in every notebook that requires your custom packages.</p>
<pre><code>sys.path.ap... | 0 | 2016-06-30T13:19:21Z | [
"python",
"beaker-notebook"
] |
Transpose list subset dimension? | 38,110,034 | <p>I have a list with 2 cells, each of them is 3 dimension array, one is 3 by 4 by 5, the other is 6 by 7 by 8. Need to transpose the subset in the list to be like: 5 by 4 by 3, and 8 by 7 by 6, I used <code>array.transpose([2,1,0])</code>, got the error <code>axes don't match</code>.</p>
| 1 | 2016-06-29T21:06:35Z | 38,110,208 | <p>Try using the <code>numpy.ndarray.transpose()</code> function instead. Seems like that's closer to what you're looking for.</p>
<p>Documentation:
<a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.transpose.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarra... | 2 | 2016-06-29T21:17:38Z | [
"python",
"arrays",
"list",
"numpy",
"transpose"
] |
Extract Hidden Layer Vector from RNN Tensoflow | 38,110,068 | <p>I'm very unfamiliar with TensorFlow, but I'm trying to get a project working.</p>
<p>I've trained an LSTM using the following code: <a href="https://github.com/sherjilozair/char-rnn-tensorflow" rel="nofollow">https://github.com/sherjilozair/char-rnn-tensorflow</a></p>
<p>This is great, and using sample.py I get gr... | 1 | 2016-06-29T21:08:42Z | 38,110,423 | <p>perhaps you have not seen this, <a href="https://www.tensorflow.org/versions/r0.9/how_tos/variables/index.html" rel="nofollow">https://www.tensorflow.org/versions/r0.9/how_tos/variables/index.html</a></p>
| 0 | 2016-06-29T21:34:40Z | [
"python",
"tensorflow",
"lstm",
"recurrent-neural-network"
] |
Memory error issue when running scipy interpolation (interp1d) | 38,110,094 | <p>I have tried to run scipy 1d-interpolation (interp1d) with various interpolation methods. Data is an array with 525600 numbers. When I ran it with simpler methods such as 'linear', 'nearest' or 'zero', it worked fine, but when I used 'cubic' or 'quadratic', it resulted 'memory error as below:</p>
<pre><code>Traceba... | 0 | 2016-06-29T21:10:13Z | 38,133,958 | <p>Spline interpolation in interp1d uses full matrices. Better use splev/splrep combo, UnivariateSpline, or CubicSpline (to be available in the future scipy version).</p>
| 1 | 2016-06-30T22:01:31Z | [
"python",
"memory",
"scipy",
"interpolation"
] |
Scraping webpage with selenium (python) | 38,110,108 | <p>Hi I would like to scrap what is selected in the following image:</p>
<p><a href="http://i.stack.imgur.com/uazuz.jpg" rel="nofollow">Image Code</a></p>
<p>I know i could use the following code to get the text:</p>
<pre><code>cell = driver.find_elements_by_xpath(".//*[@id='ip_selection1233880116name']")
print cel... | 1 | 2016-06-29T21:11:04Z | 38,110,157 | <p>Use contains to catch just the name presuming the numbers all all that change, for a single element you should also use <code>find_element</code> as opposed to <code>find_elements</code> :</p>
<pre><code>find_element_by_xpath("//*[contains(@id,'ip_selection') and contains(@id,'name')]")
</code></pre>
<p>You could... | 0 | 2016-06-29T21:13:56Z | [
"python",
"selenium",
"xpath",
"web-scraping"
] |
In Pandas, how to convert a string to a datetime object with milliseconds? | 38,110,263 | <p>I have a column of event's timestamp in my dataframe, looks like "2016-06-10 18:58:25:675", the last 3 digits are milliseconds, is there a efficient way to transform this column to a Pandas datatime type?</p>
<p>When I try: </p>
<pre><code>pd.to_datetime('2016-06-10 18:57:35:317')
</code></pre>
<p>An error occurs... | 1 | 2016-06-29T21:21:53Z | 38,110,323 | <p>Normally there is a period / full-stop between the seconds and microseconds. </p>
<p>Since your data does not have that you can specify how your data is formatted:</p>
<pre><code>pd.to_datetime('2016-06-10 18:57:35:317', format='%Y-%m-%d %H:%M:%S:%f')
</code></pre>
| 2 | 2016-06-29T21:26:57Z | [
"python",
"pandas",
"timestamp"
] |
In Pandas, how to convert a string to a datetime object with milliseconds? | 38,110,263 | <p>I have a column of event's timestamp in my dataframe, looks like "2016-06-10 18:58:25:675", the last 3 digits are milliseconds, is there a efficient way to transform this column to a Pandas datatime type?</p>
<p>When I try: </p>
<pre><code>pd.to_datetime('2016-06-10 18:57:35:317')
</code></pre>
<p>An error occurs... | 1 | 2016-06-29T21:21:53Z | 38,110,324 | <p>Something like this should work</p>
<pre><code>pd.to_datetime('2016-06-10 18:57:35:317', format="%Y-%m-%d %H:%M:%S:%f")
</code></pre>
<p>You can look up datetime formats <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="nofollow">here</a></p>
| 3 | 2016-06-29T21:26:57Z | [
"python",
"pandas",
"timestamp"
] |
NumPy: Dot product for many small matrices at once | 38,110,296 | <p>I have a long array of 3-by-3 matrices, e.g.,</p>
<pre><code>import numpy as np
A = np.array([
[[1, 2, 3],
[3, 4, 5],
[4, 5, 1]],
[[2, 0, 3],
[5, 1, 5],
[4, 2, 1]]
])
</code></pre>
<p>and for each of the small matrices, I would like to perform an outer product <code>dot(a, a.T)</... | 1 | 2016-06-29T21:25:01Z | 38,110,345 | <p>Looking closely at the code and trying to get a bigger picture reveals some information there. The first axis needs alignment between <code>A</code> and its transposed version as we are iterating through the first axis for both these versions in the code. Then, there is reduction along the third axis in both <code>A... | 1 | 2016-06-29T21:29:07Z | [
"python",
"arrays",
"numpy",
"vectorization",
"dot-product"
] |
NumPy: Dot product for many small matrices at once | 38,110,296 | <p>I have a long array of 3-by-3 matrices, e.g.,</p>
<pre><code>import numpy as np
A = np.array([
[[1, 2, 3],
[3, 4, 5],
[4, 5, 1]],
[[2, 0, 3],
[5, 1, 5],
[4, 2, 1]]
])
</code></pre>
<p>and for each of the small matrices, I would like to perform an outer product <code>dot(a, a.T)</... | 1 | 2016-06-29T21:25:01Z | 38,110,396 | <p>You can obtain the list of transposed matrices as <code>A.swapaxes(1, 2)</code>, and the list of products you want as <code>A @ A.swapaxes(1, 2)</code>.</p>
<pre><code>import numpy as np
A = np.array([
[[1, 2, 3],
[3, 4, 5],
[4, 5, 1]],
[[2, 0, 3],
[5, 1, 5],
[4, 2, 1]]
])
B = np.a... | 2 | 2016-06-29T21:32:28Z | [
"python",
"arrays",
"numpy",
"vectorization",
"dot-product"
] |
Can someone explain how arrays and scalars are handled in a Python code snippet | 38,110,408 | <p>I have this code snippet I am trying to understand that is in python. I don't understand how scalars operate on arrays in all cases. In most code I read it makes sense that operations work on each value of an array.</p>
<pre><code>sig_sq_samples = beta*invgamma.rvs(alpha,size=n_samples)
var_norm = sqrt(sig_sq_sampl... | 0 | 2016-06-29T21:33:09Z | 38,110,712 | <p>In the line</p>
<pre><code>mu_samples = norm.rvs(mean_norm,scale=var_norm,size=n_samples)
</code></pre>
<p><code>n_samples</code> has the same size as <code>var_norm</code>, so what is happening is that for the ith sample of <code>n_samples</code>, it generates it using the ith scale parameter of <code>var_norm</c... | 0 | 2016-06-29T21:54:56Z | [
"python",
"arrays",
"numpy",
"scipy",
"sqrt"
] |
Can someone explain how arrays and scalars are handled in a Python code snippet | 38,110,408 | <p>I have this code snippet I am trying to understand that is in python. I don't understand how scalars operate on arrays in all cases. In most code I read it makes sense that operations work on each value of an array.</p>
<pre><code>sig_sq_samples = beta*invgamma.rvs(alpha,size=n_samples)
var_norm = sqrt(sig_sq_sampl... | 0 | 2016-06-29T21:33:09Z | 38,113,282 | <pre><code>sig_sq_samples = beta*invgamma.rvs(alpha,size=n_samples)
</code></pre>
<p>if
invgamma.rvs() - returns an array of numeric values
beta - is a scalar value</p>
<p>then</p>
<pre><code>sig_sq_samples = beta*invgamma.rvs(alpha,size=n_samples)
</code></pre>
<p>produces another array of the same size. ... | 0 | 2016-06-30T03:02:14Z | [
"python",
"arrays",
"numpy",
"scipy",
"sqrt"
] |
How to test my trained Tensor Flow model | 38,110,414 | <p>I currently have a regression model that tries to predict a value based on 25 other ones. </p>
<p>Here is the code I currently gave </p>
<pre><code>import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
rng = np.random
learning_rate = 0.11
training_epochs = 1000
display_step = 50
X = np.random... | 0 | 2016-06-29T21:33:27Z | 38,110,501 | <p>Typically, you split your training set into two pieces: roughly 2/3 for training and 1/3 for testing (opinions vary on the proportions). Train your model with the first set. Check the training accuracy (run the training set back through the model to see how many it gets right).</p>
<p>Now, run the remainder (test... | 0 | 2016-06-29T21:39:50Z | [
"python",
"machine-learning",
"tensorflow",
"linear-regression",
"deep-learning"
] |
Interpreter: Python built-in functions not defined? | 38,110,430 | <p>I was going through the basics of Python, and testing out some built-in functions in the interpreter. The documentation I was looking at was talking about Python 3... I am using Python 2.7.3. </p>
<pre><code>>>> x = '32456'
>>> x
'32456'
>>> isalpha(x)
Traceback (most recent call last):
... | 0 | 2016-06-29T21:35:00Z | 38,110,458 | <p><code>isalpha</code> is a method for strings, not a builtin function as you suppose.</p>
<pre><code>>>> '34r'.isalpha()
False
>>> '45'.isalpha()
False
>>> 'rt'.isalpha()
True
</code></pre>
<p>To use <code>sin</code>, you need to import: <code>from math import sin</code></p>
| 1 | 2016-06-29T21:36:48Z | [
"python",
"python-2.7"
] |
Interpreter: Python built-in functions not defined? | 38,110,430 | <p>I was going through the basics of Python, and testing out some built-in functions in the interpreter. The documentation I was looking at was talking about Python 3... I am using Python 2.7.3. </p>
<pre><code>>>> x = '32456'
>>> x
'32456'
>>> isalpha(x)
Traceback (most recent call last):
... | 0 | 2016-06-29T21:35:00Z | 38,110,469 | <p>For <code>sin(3.3)</code> you have to <code>import math</code>, then call <code>math.sin(3.3)</code>.</p>
| 0 | 2016-06-29T21:37:23Z | [
"python",
"python-2.7"
] |
Interpreter: Python built-in functions not defined? | 38,110,430 | <p>I was going through the basics of Python, and testing out some built-in functions in the interpreter. The documentation I was looking at was talking about Python 3... I am using Python 2.7.3. </p>
<pre><code>>>> x = '32456'
>>> x
'32456'
>>> isalpha(x)
Traceback (most recent call last):
... | 0 | 2016-06-29T21:35:00Z | 38,110,566 | <p><code>isalpha()</code> is not a function but a method of the <code>str</code> type. If you have to, you can extract it as an unbound method and give it a name as a function:</p>
<pre><code>>>> "hello".isalpha()
True
>>> "31337".isalpha()
False
>>> isalpha = str.isalpha
>>> isalph... | 2 | 2016-06-29T21:44:33Z | [
"python",
"python-2.7"
] |
Using Python and 3 aiohttp to find the URL after redirect when timeout | 38,110,433 | <p>I'm currently trying to audit a large number of redirect URL handles to make sure that their destinations are still valid. </p>
<p>I'm using aiohttp to go through the large volume in order to produce a report. </p>
<pre><code>try:
with aiohttp.Timeout(timeout):
async with session.get(url) as resp:
... | 0 | 2016-06-29T21:35:11Z | 38,242,556 | <p>The only way to do it is disabling redirects by <code>allow_redirects=False</code> and performing redirections manually.</p>
| 0 | 2016-07-07T09:57:06Z | [
"python",
"redirect",
"aiohttp"
] |
Python error: 'bool' not iterable | 38,110,446 | <p>I'm trying to run a code:</p>
<pre><code>import os
from os import listdir
for f in sorted(os.listdir("/path")):
if f in f.startswith("20"):
for f in sorted(os.listdir(f)):
if f.endswith(".txt"):
pass
else:
try:
os.system("/path/... | 0 | 2016-06-29T21:36:13Z | 38,110,482 | <pre><code>if f in f.startswith("20"):
</code></pre>
<p>is not valid. <code>startswith</code> returns a <code>bool</code> the <code>in</code> keyword trys to check for containment inside your <code>bool</code>. That only works for iterables (which <code>bool</code> is not). You probably want:</p>
<pre><code>if f.s... | 4 | 2016-06-29T21:38:22Z | [
"python"
] |
Text files: writing on sepates lines | 38,110,503 | <p>Propose we have this simple function:</p>
<pre><code>X():
A = open("File.txt", "w")
A.write("cbcobcebviue")
A.close
</code></pre>
<p>In the file we would see "cbcobcebviue". My questions is how do we write on separate lines without over-writing producing something like this,
aaaa (Line1)
aaxsxs (Line2)
aa... | -2 | 2016-06-29T21:39:56Z | 38,110,646 | <p>From the <a href="https://docs.python.org/2/library/functions.html#open" rel="nofollow">docs</a>:</p>
<blockquote>
<p>The most commonly-used values of mode are 'r' for reading, 'w' for writing (truncating the file if it already exists), and 'a' for
appending (which on some Unix systems means that all writes app... | 0 | 2016-06-29T21:51:40Z | [
"python",
"file"
] |
Text files: writing on sepates lines | 38,110,503 | <p>Propose we have this simple function:</p>
<pre><code>X():
A = open("File.txt", "w")
A.write("cbcobcebviue")
A.close
</code></pre>
<p>In the file we would see "cbcobcebviue". My questions is how do we write on separate lines without over-writing producing something like this,
aaaa (Line1)
aaxsxs (Line2)
aa... | -2 | 2016-06-29T21:39:56Z | 38,110,698 | <p>You need to add a new line character <code>'\n'</code> to your string:</p>
<pre><code>A = open("File.txt", "w")
A.write("cbcobcebviue\n")
# ^
A.close()
</code></pre>
<blockquote>
<p>newline, also known as a line ending, end of line (EOL), or line
break, is a special character or sequence of... | 1 | 2016-06-29T21:53:44Z | [
"python",
"file"
] |
How do you turn multiple lines of text in a file into one line of text in python? | 38,110,665 | <p>I have a text file with a number value on every line and I am trying to condense all the values onto a single line with a space between them. This is what I have so far but it's not working: </p>
<pre><code>for line in f1:
line = line.rstrip('\n')
f2.write(line)
f1.close()
f2.close()
</code></pre>
| 0 | 2016-06-29T21:52:30Z | 38,110,750 | <p>This will do:</p>
<pre><code>with open("f1", "r") as f1:
with open("f2", "w") as f2:
f2.write(" ".join(map(lambda x: x.strip("\n"), f1.readlines())))
</code></pre>
<p>Take all lines form f1, strip the "\n", join them with <code>" "</code> and write that string to the new file.</p>
| 0 | 2016-06-29T21:57:58Z | [
"python",
"string",
"list",
"file",
"lines"
] |
How do you turn multiple lines of text in a file into one line of text in python? | 38,110,665 | <p>I have a text file with a number value on every line and I am trying to condense all the values onto a single line with a space between them. This is what I have so far but it's not working: </p>
<pre><code>for line in f1:
line = line.rstrip('\n')
f2.write(line)
f1.close()
f2.close()
</code></pre>
| 0 | 2016-06-29T21:52:30Z | 38,110,767 | <p>Just print them with a space inbetween:</p>
<pre><code>...
for i, line in enumerate(f1):
space = " " if i != 0 else ""
line = line.rstrip('\n')
f2.write(space + line)
f1.close()
f2.close()
</code></pre>
<p>If the files aren't <em>huge</em> (i.e. they fit in memory), an easier way would be:</p>
<pre>... | 3 | 2016-06-29T21:59:25Z | [
"python",
"string",
"list",
"file",
"lines"
] |
How do you turn multiple lines of text in a file into one line of text in python? | 38,110,665 | <p>I have a text file with a number value on every line and I am trying to condense all the values onto a single line with a space between them. This is what I have so far but it's not working: </p>
<pre><code>for line in f1:
line = line.rstrip('\n')
f2.write(line)
f1.close()
f2.close()
</code></pre>
| 0 | 2016-06-29T21:52:30Z | 38,110,774 | <p>If you are in Python 2.7+ or Python 3.x, and the size of the file is not prohibitive, you could probably do it in memory:</p>
<pre><code>with open(filename1, 'r') as fin, open(filename2, 'w+') as fout:
lines = fin.readlines()
cleaned = [line.strip() for line in lines]
joined = ' '.join(cleaned)
fout... | 1 | 2016-06-29T21:59:58Z | [
"python",
"string",
"list",
"file",
"lines"
] |
Python import error: 'No module named' | 38,110,681 | <p>Just installed python, and am running into this error:</p>
<blockquote>
<p>ImportError: No module named 'semanticnet'</p>
</blockquote>
<p>here are my imports:</p>
<pre><code>import semanticnet as sn
import sys
</code></pre>
<p>I've tried the solution on this site that suggests adding:</p>
<pre><code>sys.path... | 0 | 2016-06-29T21:53:09Z | 38,110,778 | <p>You need to install that library, if you're on windows which it seems because of your "C://" first install setuptools.</p>
<blockquote>
<p><a href="https://pypi.python.org/pypi/setuptools" rel="nofollow">https://pypi.python.org/pypi/setuptools</a></p>
</blockquote>
<p>Using Windows 8 (which includes PowerShell 3... | 0 | 2016-06-29T22:00:19Z | [
"python",
"python-import"
] |
Python import error: 'No module named' | 38,110,681 | <p>Just installed python, and am running into this error:</p>
<blockquote>
<p>ImportError: No module named 'semanticnet'</p>
</blockquote>
<p>here are my imports:</p>
<pre><code>import semanticnet as sn
import sys
</code></pre>
<p>I've tried the solution on this site that suggests adding:</p>
<pre><code>sys.path... | 0 | 2016-06-29T21:53:09Z | 38,110,782 | <p>I think you don't have the module installed..
try <code>pip install semanticnet</code> on the Prompt Command first(I believe that you installed pip when you installed python), then when the installation is complete, just run python and try some ´import semanticnet` on the python command line...</p>
| 0 | 2016-06-29T22:00:26Z | [
"python",
"python-import"
] |
Make new DataFrame only with rows whose ID is not contained in second DataFrame | 38,110,711 | <p>There are two DataFrames. One df1 contain events, and one of columns is ID.
Other df2 contain just ID-s.</p>
<p>How would be best to crate df3 which contain just rows whose ID is not present in df2.</p>
<p>Looks like this type of query is not supported in Spark SQL:</p>
<p>sqlContext.sql(""" SELECT * FROM table_d... | 0 | 2016-06-29T21:54:51Z | 38,120,066 | <p>Spark SQL will support this type of subqueries starting from Spark version 2.0 (more information is available on <a href="https://databricks.com/blog/2016/06/17/sql-subqueries-in-apache-spark-2-0.html" rel="nofollow">Databricks blog</a>).</p>
<p>A way to do this in older versions of Spark would be the following:</p... | 1 | 2016-06-30T10:09:50Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql"
] |
How to use Python Requests to login to website, store cookie, then access another page on the website? | 38,110,760 | <p>I'm trying to login into website using a Python script, store the cookie I receive, and then use that same cookie to access member-only parts of the website. I've read several posts and answers about this topic, but none of the answers have worked for me. </p>
<p>Here is the HTML code for the website login page I'm... | 2 | 2016-06-29T21:58:37Z | 38,110,852 | <p>You should be posting all the required data, you can use <em>bs4</em> to parse the login page to get the values you need:</p>
<pre><code>from requests import session
from bs4 import BeautifulSoup
data = {
'username': 'MY_USERNAME',
'password': 'MY_PASSWORD'
}
head = {"User-Agent":"Mozilla/5.0 (X11; Linux ... | 1 | 2016-06-29T22:06:37Z | [
"python",
"python-2.7",
"cookies",
"python-requests"
] |
Django model for a Postgres view | 38,110,785 | <p><strong>Edit:</strong> There seems to be some confusion about what I'm asking. That model is for the <a href="https://www.postgresql.org/docs/9.4/static/sql-createview.html" rel="nofollow">Postgres view</a> that I created in migration 0009. I was under the impression that Django won't generate a migration for a mode... | 1 | 2016-06-29T22:00:46Z | 38,188,332 | <p>Django does create a migration for each newly added table in your app regardless of whether it's a managed model or not. However there is a very important and subtle difference when you use the <code>managed=False</code> setting. The resultant migration is a dummy. It does not execute any SQL at all.</p>
<p>To conf... | 0 | 2016-07-04T15:38:59Z | [
"python",
"django",
"postgresql"
] |
Cannot scan QR code using zbar | 38,110,888 | <p><a href="http://i.stack.imgur.com/zclcr.png" rel="nofollow">My QR code</a></p>
<p>When I run my code I´m always getting "[]" as output, which means that Zbar can´t read the QR... There is something wrong with my image format? I can´t figure out why this is not working.</p>
<p><strong>My code:</strong></p>
<pre... | 0 | 2016-06-29T22:10:03Z | 38,111,710 | <p>Not sure what the actual problem is, but I was able to get this working using Pil (or Pillow) instead of cv2. </p>
<pre><code>import cv2
import Image
import zbar
import sys
class ImageSource(object):
def __init__(self,source):
self.is_camera = type(source)==int
if self.is_camera:
s... | 0 | 2016-06-29T23:30:32Z | [
"python",
"opencv",
"zbar"
] |
pygame.font not working and not showing any errors also | 38,110,911 | <p>Everything is working fine except that font thing, i don't know why it's happening and it's not even showing any error. And not displaying the Text on screen.</p>
<pre><code># import library here
import pygame
import time
import sys
# display init
display_width = 800
display_height = 600
# game initialization don... | -1 | 2016-06-29T22:12:30Z | 38,271,844 | <p>The reason you see nothing is because you haven't <strong><em>updated</em></strong> or <strong><em>'flipped'</em></strong> the display. After you've created the text Surface and blit it to the gameDisplay Surface you have to update/'flip' the display so it becomes visible to the user.</p>
<p>So, between <code>messa... | 0 | 2016-07-08T16:48:28Z | [
"python",
"fonts",
"pygame"
] |
python itertools with islice error | 38,111,000 | <p>I'm still learning python and I have the code below but it is not working:</p>
<pre><code>from itertools import *
startword = ["start",]
stopword = ["stop",]
text = "this is a text that starts with some test stuff and then after that it stop right here!"
for i in islice(text.split(" "), startword, stopword):
... | -3 | 2016-06-29T22:19:47Z | 38,111,053 | <p>You need to calculate the index of 'start' and 'stop' and then you provide
two integer values, not strings:</p>
<pre><code>for i in islice(text.split(" "), startword_index, stopword_index):
print i
</code></pre>
| 0 | 2016-06-29T22:25:26Z | [
"python"
] |
python itertools with islice error | 38,111,000 | <p>I'm still learning python and I have the code below but it is not working:</p>
<pre><code>from itertools import *
startword = ["start",]
stopword = ["stop",]
text = "this is a text that starts with some test stuff and then after that it stop right here!"
for i in islice(text.split(" "), startword, stopword):
... | -3 | 2016-06-29T22:19:47Z | 38,111,184 | <p>In this particular case, <code>islice</code> is a poor choice; you have all the data in memory, in a realized sequence, so <code>islice</code> is just wasting time iterating the leading values. There are many better ways to handle this, either using <code>index</code> to find the <code>start</code> and <code>end</co... | 1 | 2016-06-29T22:38:45Z | [
"python"
] |
How can I use use a regex to match characters that aren't included in certain words? | 38,111,004 | <p>Suppose I want to return all occurrences of 'lep' in a string in Python, but not if an occurrence is in a substring like 'filepath' or 'telephone'. Right now I am using a combination of negative lookahead/lookbehind:</p>
<pre><code>(?<!te|fi)lep(?!hone|ath)
</code></pre>
<p>However, I do want 'telepath' and 'fi... | 0 | 2016-06-29T22:20:09Z | 38,111,827 | <p>You can place lookaheads inside lookbehinds (and vice-versa; any combination, really, so long as every lookbehind has a fixed length). That allows you to combine the two conditions into one (<em>doesn't begin with X <strong>and</strong> end with Y</em>):</p>
<pre><code>lep(?<!telep(?=hone))(?<!filep(?=ath))
... | 1 | 2016-06-29T23:45:53Z | [
"python",
"regex",
"negative-lookahead",
"negative-lookbehind"
] |
how to index a numpy array using conditions? | 38,111,010 | <p>Suppose I have an array like this:</p>
<pre><code>a = np.array([[2,1],
[4,2],
[1,3],...]
</code></pre>
<p>I want to retrieve the elements of the second column where the corresponding elements in the first column match some condition. So something like</p>
<pre><code>a[a[:,0] == np.arra... | 0 | 2016-06-29T22:20:44Z | 38,111,461 | <p>While this uses <code>list</code> to collect results and requires a <code>for</code> loop, this collects the second column values once the first column has passed some criteria (in a <code>list</code> of acceptable results in this case).</p>
<pre><code>a = np.array([[2, 1],
[4, 2],
[1, 3... | 0 | 2016-06-29T23:04:54Z | [
"python",
"arrays",
"numpy"
] |
how to index a numpy array using conditions? | 38,111,010 | <p>Suppose I have an array like this:</p>
<pre><code>a = np.array([[2,1],
[4,2],
[1,3],...]
</code></pre>
<p>I want to retrieve the elements of the second column where the corresponding elements in the first column match some condition. So something like</p>
<pre><code>a[a[:,0] == np.arra... | 0 | 2016-06-29T22:20:44Z | 38,112,660 | <p>You could create a mask based off of your first column, and then use that to mask off the second column.</p>
<pre><code>import numpy as np
a = np.array([[2, 1],
[4, 2],
[1, 3]])
mask = np.logical_or(a[:,0] == 2, a[:,0] == 4)
b = a[:,1][mask]
print(b)
</code></pre>
<p>Returns:</p>
... | 0 | 2016-06-30T01:42:10Z | [
"python",
"arrays",
"numpy"
] |
I get the following error when trying to send a message to my phone number from my Twilio number | 38,111,055 | <p>I get the following error when trying to send a message to my phone number from my Twilio number</p>
<pre><code> from twilio.rest import TwilioRestClient as TRC
client = TRC('AC**********************edc','a7b***************************3d2') # connect to an account
client.messages.create(from_='+17*******... | 0 | 2016-06-29T22:25:32Z | 38,111,171 | <p>Have you made sure to add the <code>from_</code> number to your Twilio account on your <a href="https://www.twilio.com/user/account/phone-numbers" rel="nofollow">Account's phone numbers page</a>. <a href="https://www.twilio.com/docs/api/errors/21606" rel="nofollow">Error 21606</a> may have more information regarding... | 2 | 2016-06-29T22:37:13Z | [
"python",
"twilio"
] |
I get the following error when trying to send a message to my phone number from my Twilio number | 38,111,055 | <p>I get the following error when trying to send a message to my phone number from my Twilio number</p>
<pre><code> from twilio.rest import TwilioRestClient as TRC
client = TRC('AC**********************edc','a7b***************************3d2') # connect to an account
client.messages.create(from_='+17*******... | 0 | 2016-06-29T22:25:32Z | 38,125,582 | <p>The twilio number (Your from number: should be sms-enabled) that you have bought doesn't seem to have Capabilities of sending smses.</p>
| 0 | 2016-06-30T14:07:14Z | [
"python",
"twilio"
] |
Tensorflow implementation of word2vec | 38,111,129 | <p>The Tensorflow tutorial <a href="https://www.tensorflow.org/versions/r0.9/tutorials/word2vec/index.html#vector-representations-of-words" rel="nofollow">here</a> refers to their basic implementation which you can find on github <a href="https://github.com/tensorflow/tensorflow/blob/r0.9/tensorflow/examples/tutorials/... | 4 | 2016-06-29T22:32:34Z | 38,540,523 | <p>There is a parameter named <code>num_skips</code> which denotes the number of (input, output) pairs generated from the single window: [skip_window target skip_window]. So <code>num_skips</code> restrict the number of context words we would use as output words. And that is why the generate_batch function <code>assert... | 0 | 2016-07-23T10:04:33Z | [
"python",
"tensorflow",
"word2vec"
] |
python-docx - replacing characters | 38,111,130 | <p>I am trying to build a small program in which I open a docx document and replace characters by others, to do some old school caesar-style encrypting, after checking the documentation: [ <a href="https://python-docx.readthedocs.io" rel="nofollow">https://python-docx.readthedocs.io</a> ] I am afraid I can't find the o... | 0 | 2016-06-29T22:32:45Z | 38,111,181 | <p>The API documentation is indexed (i.e. its table of contents appears) on the page you link to and describes all the objects and methods. <a href="https://python-docx.readthedocs.io/en/latest/#api-documentation" rel="nofollow">https://python-docx.readthedocs.io/en/latest/#api-documentation</a></p>
| 1 | 2016-06-29T22:38:21Z | [
"python",
"text",
"docx",
"python-docx"
] |
python-docx - replacing characters | 38,111,130 | <p>I am trying to build a small program in which I open a docx document and replace characters by others, to do some old school caesar-style encrypting, after checking the documentation: [ <a href="https://python-docx.readthedocs.io" rel="nofollow">https://python-docx.readthedocs.io</a> ] I am afraid I can't find the o... | 0 | 2016-06-29T22:32:45Z | 38,111,432 | <p>I think I found something useful in case future readers might be interested. The problem with python-docx is I could get paragraphs individually and it would take a lot of time. I don't even know if titles, footers and headers count as paragraphs.</p>
<p>But there is a library called textract that can read docx and... | 0 | 2016-06-29T23:01:54Z | [
"python",
"text",
"docx",
"python-docx"
] |
how to make SQLAlchemy to_json function that doesnt add column type to ouput? | 38,111,176 | <p>I have an association object that accesses two fields in its to_json function. One is a string and one is a decimal number</p>
<p>here is the object:</p>
<pre><code>class DrinkIngredient(db.Model):
__tablename__ = 'drink_ingredient'
drink_id = db.Column(db.Integer, db.ForeignKey("drink.id"), primary_key=Tr... | 0 | 2016-06-29T22:37:44Z | 38,111,338 | <p>Use the json module to output proper json.</p>
<pre><code>from simplejson import dumps
def to_json(self):
json_drinkIngredient = dumps({
"ingredient": self.ingredient.name,
"amount": self.units
})
return json_drinkIngredient
</code></pre>
<p>About your second question, the reason is th... | 0 | 2016-06-29T22:53:59Z | [
"python",
"json",
"sqlalchemy",
"flask-sqlalchemy"
] |
How to minimize forecast error with fmin? | 38,111,320 | <p>I'm trying to minimize forecast error by choosing the right "fall out rate" (r). I'm still fairly new to Pandas and brand new to SciPy. Please help!</p>
<pre><code>import pandas as pd
from scipy.optimize import fmin
data = pd.DataFrame({'Division': [1,2,3]*3,
'Month': ['May','May','May','June'... | 0 | 2016-06-29T22:52:02Z | 38,208,567 | <p>So I learned a few things about fmin during this project:</p>
<p>-Arguments must be in array format so I made the return_array helper function.</p>
<p>-The variable you want to optimize must be listed first in the function you want to minimize. So for me it had to be e(r,c,u,s), not e(c,u,s,r).</p>
<pre><code>#ca... | 0 | 2016-07-05T16:41:01Z | [
"python",
"python-2.7",
"scipy"
] |
Is it possible to reset a Cycler object | 38,111,332 | <p>E.g., if shape of <code>lines1</code> and <code>lines2</code> were <code>(3,101)</code> with</p>
<pre><code> plt.plot(x, lines1, linewidth=3)
plt.plot(x, lines2, linewidth=1)
</code></pre>
<p>I have a blue, green, red line with width equal to 3, and a cyan, magenta and yellow line with width equal to 1.</p>
<p>B... | 0 | 2016-06-29T22:53:22Z | 38,111,647 | <p>Asking a question implies reaching a better understanding of the problem, doesn't it?</p>
<p>The statement below does the trick,</p>
<pre><code>plt.gca().set_prop_cycle(plt.rcParams['axes.prop_cycle'])
</code></pre>
<p><code><edit></code>Even simpler,<code>plt.gca().set_prop_cycle(None)</code>, see <strong>... | 1 | 2016-06-29T23:22:12Z | [
"python",
"matplotlib"
] |
Is it possible to reset a Cycler object | 38,111,332 | <p>E.g., if shape of <code>lines1</code> and <code>lines2</code> were <code>(3,101)</code> with</p>
<pre><code> plt.plot(x, lines1, linewidth=3)
plt.plot(x, lines2, linewidth=1)
</code></pre>
<p>I have a blue, green, red line with width equal to 3, and a cyan, magenta and yellow line with width equal to 1.</p>
<p>B... | 0 | 2016-06-29T22:53:22Z | 38,111,656 | <p>The value in <code>plt.rcParams</code> is the underlying <code>Cycler</code> but the <code>Axes</code> objects hold a reference to an iterator over that object (see <a href="https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_base.py#L169" rel="nofollow">here</a>, it is actually a <code>itertoo... | 1 | 2016-06-29T23:23:16Z | [
"python",
"matplotlib"
] |
Can't import Pyperclip | 38,111,340 | <p>I am having trouble importing Pyperclip in IDLE.<br>
I am running windows 7 (64-bit).<br>
I have Python 3.5.2 Installed on: C:\Python\Python35.<br>
I opened command prompt and initiated the install by typing pip install pyperclip after changing directory to C:\Python\Python35\Scripts.
It successfully installed Pype... | 0 | 2016-06-29T22:54:02Z | 38,127,468 | <p>It unpacked pyperclip in the wrong directory. I copied the entire pyperclip folder and put it in C:/python/python35, now it works as it should. Seems like a noob mistake on my part, but it took me a long time to figure this out. I hope this helps someone in the future.</p>
| 1 | 2016-06-30T15:26:23Z | [
"python",
"python-3.x",
"python-3.5",
"pyperclip"
] |
cherry py auto download file | 38,111,377 | <p>I'm currently building cherry py app for my projects and at certain function I need auto starting download a file.</p>
<p>After zip file finish generating, I want to start downloading to client
So after images are created, they are zipped and sent to client</p>
<pre><code>class Process(object):
exposed = True
... | 0 | 2016-06-29T22:57:29Z | 38,131,584 | <p>Just create a zip archive in memory and then return it using <code>file_generator()</code> helper function from <code>cherrypy.lib</code>. You may as well <code>yield</code> HTTP response to enable streaming capabilities (keep in mind to set HTTP headers prior to doing that).
I wrote a simple example (based on your ... | 0 | 2016-06-30T19:18:57Z | [
"python",
"cherrypy"
] |
User input in subprocess call? | 38,111,484 | <p>I am working to automate the Wig tool in python, which will involve including a URL.</p>
<p>Currently I take in user input (a URL) but am having difficulty adding it to the end of the subprocess call.</p>
<pre><code>import subprocess
var = raw_input("Enter a URL: ")
subprocess.call('python3 wig.py ', var)
</code... | 2 | 2016-06-29T23:07:10Z | 38,111,518 | <p>Pass the arguments as a list as @PadraicCunningham suggests:</p>
<pre><code>args = ['python3','wig.py']
args.append(var)
subprocess.call(args)
</code></pre>
<p>If your argument list becomes long and complicated you can bring in <code>shlex</code>:</p>
<pre><code>import shlex
args = shlex.split('python3 wig.py {}'... | 2 | 2016-06-29T23:09:56Z | [
"python",
"subprocess"
] |
Self referencing variables passed during the instantiation of a class | 38,111,585 | <p>I'm not sure if I'm using the correct terminology, but here's my code:</p>
<pre><code>class Candidate(object):
def __init__(self, party_code, state, age=random.randint(35, 70),
social_index=(1 if party_code == 'dem' else -1 if party_code == 'rep' else 0),
econ_index=(-1 if pa... | 0 | 2016-06-29T23:15:34Z | 38,111,943 | <p>Assuming you want <code>social_index</code> and <code>econ_index</code> to be parameters your code would look like:</p>
<pre><code>class Candidate(object):
def __init__(self, party_code, state, age=None,
social_index=None, econ_index=None):
if age is None:
age=random.randint(35, ... | 0 | 2016-06-29T23:58:44Z | [
"python",
"class",
"scope",
"instantiation"
] |
python isbn 13 digit validate | 38,111,620 | <p>I need to write a function that validates a 13 digit ISBN. It needs to start with 978 or 979, end with a single digit, and the remaining sections need to be at least 1 digit in length. I need some help to make this work, I don't understand why it never returns true</p>
<pre><code>def validate(s)
lst = s.split("-")... | 0 | 2016-06-29T23:20:16Z | 38,111,752 | <p>You should use regular expression and this is exactly why it is used for:</p>
<pre><code>>>> import re
>>> def validate(isbn):
isbn_regex = re.compile('^(978|979)-\d+-\d+-\d$')
return isbn_regex.search(isbn) is not None
>>> print validate('978-12-12-2')
True
</code></... | 1 | 2016-06-29T23:36:03Z | [
"python",
"isbn"
] |
python isbn 13 digit validate | 38,111,620 | <p>I need to write a function that validates a 13 digit ISBN. It needs to start with 978 or 979, end with a single digit, and the remaining sections need to be at least 1 digit in length. I need some help to make this work, I don't understand why it never returns true</p>
<pre><code>def validate(s)
lst = s.split("-")... | 0 | 2016-06-29T23:20:16Z | 38,112,052 | <p>An ISBN-13 consists of five groups of numbers and the last digit is a check digit. Here's a function to make sure there are five groups, exactly 13 digits, and validates the check digit. It works with your samples:</p>
<pre><code>import re
def validate(s):
d = re.findall(r'\d',s)
if len(d) != 13:
... | 0 | 2016-06-30T00:15:00Z | [
"python",
"isbn"
] |
python isbn 13 digit validate | 38,111,620 | <p>I need to write a function that validates a 13 digit ISBN. It needs to start with 978 or 979, end with a single digit, and the remaining sections need to be at least 1 digit in length. I need some help to make this work, I don't understand why it never returns true</p>
<pre><code>def validate(s)
lst = s.split("-")... | 0 | 2016-06-29T23:20:16Z | 38,112,055 | <p>ISBN-13 requires 13 digits to be valid. Your code does not check that all characters are digits (excluding the <code>-</code> separator), nor does it check the actual length. Also, five parts are required, and you could be verifying the check digit.</p>
<p>Specifically your code fails to ever return <code>True</cod... | 1 | 2016-06-30T00:15:32Z | [
"python",
"isbn"
] |
python isbn 13 digit validate | 38,111,620 | <p>I need to write a function that validates a 13 digit ISBN. It needs to start with 978 or 979, end with a single digit, and the remaining sections need to be at least 1 digit in length. I need some help to make this work, I don't understand why it never returns true</p>
<pre><code>def validate(s)
lst = s.split("-")... | 0 | 2016-06-29T23:20:16Z | 38,112,158 | <p>Error 1: Missing a colon at end of the 'def' statement. </p>
<p>Error 2: The 'return isbn' statement is not indented; it is outside the function but should be inside.</p>
<p>Error 3: The line checking the length of lst[3] does not check the last element of the isbn string when there are more than four elements in ... | 0 | 2016-06-30T00:30:14Z | [
"python",
"isbn"
] |
Finding all combinations of paths from a graph with a given distance from the origin | 38,111,632 | <p><br />
I'm trying to find all combinations of paths from a graph with a given distance from the origin.</p>
<p>In fact, the new expansion of World of Warcraft (Legion) will introduce the Artifact system to the game.<br />
It's a feature that you can level up, each level give you 1 rank and you can spend 1 point for... | 2 | 2016-06-29T23:20:57Z | 38,112,362 | <p>If you intend to take just one path, then you can try <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm" rel="nofollow">Dijkstra's Algorithm</a> to get you the distance from the initial node to all other nodes. Then just iterate through them to return the ones with the distance you want.</p>
<p>If you w... | -1 | 2016-06-30T01:01:01Z | [
"python",
"algorithm",
"graph-algorithm"
] |
Finding all combinations of paths from a graph with a given distance from the origin | 38,111,632 | <p><br />
I'm trying to find all combinations of paths from a graph with a given distance from the origin.</p>
<p>In fact, the new expansion of World of Warcraft (Legion) will introduce the Artifact system to the game.<br />
It's a feature that you can level up, each level give you 1 rank and you can spend 1 point for... | 2 | 2016-06-29T23:20:57Z | 38,119,851 | <p>IIUC, you have an unweighted directed graph G, and you're looking for the set of all subgraphs H of G that have the following 2 properties:</p>
<ol>
<li>There is a path from the given origin vertex to every vertex in H (this implies that H itself is at least weakly connected)</li>
<li>The total number (or weight) o... | 0 | 2016-06-30T10:01:00Z | [
"python",
"algorithm",
"graph-algorithm"
] |
AttributeError: 'numpy.ndarray' object has no attribute 'plot' | 38,111,724 | <p>Why is this matplotlib code giving me a weird exception? I'm going for two rows of plots. The top row is supposed to show true vs. pred and the bottom row is supposed to show percent error.</p>
<pre><code>yy = func(*X)
fig, axes = plt.subplots(1, len(X))
for ax,_x in zip(axes,X):
ax.plot(_x, y, 'b.')
ax.pl... | 0 | 2016-06-29T23:32:41Z | 38,112,294 | <p>If <code>len(X)</code> is >1, <code>axes</code> will be a 2D array of <code>AxesSubplot</code> instances. So when you loop over <code>axes</code>, you actually get a slice along one dimension of the <code>axes</code> array.</p>
<p>To overcome this, you could use <code>axes.flat</code>:</p>
<pre><code>for ax,_x in ... | 2 | 2016-06-30T00:51:52Z | [
"python",
"matplotlib"
] |
How to implement the inverse of the integrated Chi^2 function? | 38,111,766 | <p>I am implementing some preprocessing of variables in the context of a paper called <a href="https://arxiv.org/abs/physics/0402093" rel="nofollow">A Neural Bayesian Estimator for Conditional Probability Densities</a>.</p>
<p>It states:
1.) Given a non-linear, a monotonous variable transformation F:t->s such that s ... | 0 | 2016-06-29T23:38:33Z | 38,133,366 | <p>If you mean X<sup>2</sup> distribution with PDF as described <a href="https://en.wikipedia.org/wiki/Chi-squared_distribution" rel="nofollow">here</a>, then what you're looking is X<sup>2</sup> CDF. It is expressed via incomplete Gamma function, see same reference, and you could use SciPy to compute it, <a href="http... | 1 | 2016-06-30T21:13:17Z | [
"python",
"statistics",
"distribution"
] |
Multiple "where clauses" in endpoint query string parameters | 38,111,789 | <p>Can I include multiple "where" clauses (or an AND operator) in an endpoint query string? I'd like to do something like this:</p>
<pre><code>http://localhost:5000/regions?where=name=="El Salvador"&where=lang=="es"
</code></pre>
<p>I've tried few different syntaxes, but I can't get it to work.</p>
<p>Is this po... | 3 | 2016-06-29T23:41:08Z | 38,111,870 | <p><a href="http://stackoverflow.com/questions/22974772/querystring-array-parameters-in-python-using-requests">Querystring Array Parameters in Python using Requests</a>
<br>Looks like what you are after. The where clause is not necessary if you are using the '&' syntax so your clause should look something like thi... | 1 | 2016-06-29T23:50:40Z | [
"python",
"eve"
] |
Multiple "where clauses" in endpoint query string parameters | 38,111,789 | <p>Can I include multiple "where" clauses (or an AND operator) in an endpoint query string? I'd like to do something like this:</p>
<pre><code>http://localhost:5000/regions?where=name=="El Salvador"&where=lang=="es"
</code></pre>
<p>I've tried few different syntaxes, but I can't get it to work.</p>
<p>Is this po... | 3 | 2016-06-29T23:41:08Z | 38,112,365 | <p>Have you tried <code>http://localhost:5000/regions?where=name=="El Salvador"%20and%20lang=="es"</code>?</p>
<p>You can replace <code>%20</code> for <code>space</code> in the <code>URL</code> if it doesn't work. In my postman environment works both ways.</p>
<p>Seems to work like the <code>AND</code> you want. The ... | 2 | 2016-06-30T01:01:41Z | [
"python",
"eve"
] |
How do I set the axis limits with wx.lib.plot in Python? | 38,111,819 | <p>The title really says it all. I currently have some Python code which generates a line graph using wx.lib.plot, and I would like to manually set the axis limits. How can I do so?</p>
| 0 | 2016-06-29T23:44:37Z | 38,125,229 | <p>You would set axis values while calling <a href="https://www.wxpython.org/docs/api/wx.lib.plot.PlotCanvas-class.html#Draw" rel="nofollow">PlotCanvas.Draw</a>.</p>
<pre><code>self.Draw(gc, xAxis=(0,xlimit), yAxis=(0,ylimit))
</code></pre>
<p>Where <code>self</code> is derived from <code>plot.PlotCanvas</code>.</p>
| 1 | 2016-06-30T13:54:02Z | [
"python",
"plot",
"wxpython"
] |
How can I convert a date/time string in local time into UTC in Python? | 38,111,921 | <p>I am trying to write a function that will convert a string date/time from local time to UTC in Python. </p>
<p>According to <a href="http://stackoverflow.com/questions/1111056/get-time-zone-information-of-the-system-in-python">this question</a>, you can use <code>time.tzname</code> to get some forms of the local ti... | 1 | 2016-06-29T23:56:24Z | 38,112,241 | <p>If I understand your question correctly you want this :</p>
<pre><code>from time import strftime,gmtime,mktime,strptime
# you can pass any time you want
strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(strptime("Thu, 30 Jun 2016 03:12:40", "%a, %d %b %Y %H:%M:%S"))))
# and here for real time
strftime("%Y-%m-%d %H:%M:%... | 1 | 2016-06-30T00:44:31Z | [
"python",
"datetime",
"timezone",
"utc"
] |
Django - formatting json objects | 38,111,941 | <p>I am working on a backend web service using Django to consume JSON for later be displayed in a map using d3.js. The problem is that I am having trouble to parsing the json in the way I need. This is the format I get right now:</p>
<pre><code>{
"UT": [
{"score": "Republican"},
{"recurrence": 32}
... | 0 | 2016-06-29T23:58:41Z | 38,112,511 | <p>How about a little <code>replace</code> (assuming your JSON is a variable called <code>data</code>):</p>
<p><code>data.replace("[", "{").replace("]", "}")</code></p>
| -1 | 2016-06-30T01:22:41Z | [
"python",
"json",
"django",
"d3.js"
] |
Django - formatting json objects | 38,111,941 | <p>I am working on a backend web service using Django to consume JSON for later be displayed in a map using d3.js. The problem is that I am having trouble to parsing the json in the way I need. This is the format I get right now:</p>
<pre><code>{
"UT": [
{"score": "Republican"},
{"recurrence": 32}
... | 0 | 2016-06-29T23:58:41Z | 38,112,540 | <p>This should do it without calling replace: </p>
<pre><code>states_dict[state.state] = {"score": state.score, "recurrence": state.recurrence}
</code></pre>
| 1 | 2016-06-30T01:26:20Z | [
"python",
"json",
"django",
"d3.js"
] |
SWIG argument error when using "using std::vector" in python | 38,111,942 | <p>This is very related to <a href="http://stackoverflow.com/questions/22491921/how-to-use-a-python-list-to-assign-a-stdvector-in-c-using-swig">this</a> question</p>
<p>Regardless of whether or not this is coding practice, I have come across code that looks like this</p>
<p><strong>test.hh</strong></p>
<pre><code>#i... | 2 | 2016-06-29T23:58:42Z | 38,113,826 | <p>To me, this looks like SWIG does not support the <code>using std::vector;</code> statement correctly. I think it's a SWIG bug. I can think of the following workarounds:</p>
<ul>
<li>Add <code>using namespace std;</code> to the SWIG interface file (this will only affect the way wrappers are created; the <code>using<... | 1 | 2016-06-30T04:07:34Z | [
"python",
"c++",
"c++11",
"vector",
"swig"
] |
Docker-Compose HAProxy missing frontend | 38,111,953 | <p>I'm trying to use HAProxy as a loadbalancer for my python webapp which uses redis. I'm working on transitioning the docker run commands to docker-compose using the docker-compose.yml --but I'm running into issues</p>
<p><strong>Below is my current "docker run" commands, which works perfectly fine!</strong></p>
<pr... | 1 | 2016-06-30T00:00:29Z | 38,131,276 | <p>I figured out the issue...</p>
<p>The docker-compose.yml has issues with the links.. the format for links is <em>service name</em>:<em>alias</em></p>
<p>The issue with mine is that even though my service names were correct, <strong>the alias' were incorrect</strong>... causing the docker-compose to fail without an... | 0 | 2016-06-30T19:01:00Z | [
"python",
"docker",
"docker-compose",
"haproxy"
] |
How to parse function calls in loop? | 38,111,962 | <p>i am writing a simple language to describe sequences of function calls. </p>
<p><em>I am using a python, but only algorithm answers also be accepted.</em> </p>
<p>For example i have a code:</p>
<pre><code>for 2:
{
a
for 3:
{
b
c
}
}
</code></pre>
<p>How can i proceed it to a such sequence? ( for ... | 0 | 2016-06-30T00:01:26Z | 38,112,300 | <p>Note that I do not have any experience with parsing and very limited experience with regex. This was more a challenge for myself more than a solution but regardless it may be useful to you.</p>
<p>Your syntax isn't that far off from a python generator, a valid python generator that produces the values you want wou... | 0 | 2016-06-30T00:52:31Z | [
"python",
"translate"
] |
Python: initialising many lists, good style of writing code | 38,111,970 | <p>If I have in the <code>__init__</code> function of my class to initialise many lists to empty like this:</p>
<pre><code>self.a = []
self.b = []
self.c = []
self.d = []
self.e = []
</code></pre>
<p>what is a better style of writing it - every list separately or maybe as</p>
<pre><code>self.a,self.b,self.c,self.d,s... | 1 | 2016-06-30T00:02:39Z | 38,111,985 | <pre><code>a, b, c, d, e = ([] for _ in range(5))
</code></pre>
| 2 | 2016-06-30T00:05:19Z | [
"python",
"initialization",
"pep8"
] |
Python: initialising many lists, good style of writing code | 38,111,970 | <p>If I have in the <code>__init__</code> function of my class to initialise many lists to empty like this:</p>
<pre><code>self.a = []
self.b = []
self.c = []
self.d = []
self.e = []
</code></pre>
<p>what is a better style of writing it - every list separately or maybe as</p>
<pre><code>self.a,self.b,self.c,self.d,s... | 1 | 2016-06-30T00:02:39Z | 38,233,445 | <p>As an alternative I might use <a href="https://docs.python.org/3/library/functions.html#setattr" rel="nofollow"><code>setattr</code></a>:</p>
<pre><code>for ch in "abcde": # or a list of strings
setattr(self, ch, [])
</code></pre>
| 0 | 2016-07-06T20:42:57Z | [
"python",
"initialization",
"pep8"
] |
Python dict key + list removal | 38,111,975 | <p>Is there a way to make a list of keys of a dict excluding an specific one, in <em>one single command</em>?</p>
<p>Using two commands it can be done:</p>
<pre><code>aDict = {'a': 'cat', 'b': 'dog', 'c': 'cow'}
list1 = aDict.keys()
list1.remove('b')
</code></pre>
<p>I'm looking for sth like <code>list1 = aDict.keys... | 0 | 2016-06-30T00:03:58Z | 38,111,989 | <p>You can use a list comprehension to filter the results as you iterate across them. For example:</p>
<p><code>list1 = [key for key in aDict if key != 'b']</code></p>
<p>would do it.</p>
| 3 | 2016-06-30T00:05:53Z | [
"python",
"list",
"dictionary"
] |
Python dict key + list removal | 38,111,975 | <p>Is there a way to make a list of keys of a dict excluding an specific one, in <em>one single command</em>?</p>
<p>Using two commands it can be done:</p>
<pre><code>aDict = {'a': 'cat', 'b': 'dog', 'c': 'cow'}
list1 = aDict.keys()
list1.remove('b')
</code></pre>
<p>I'm looking for sth like <code>list1 = aDict.keys... | 0 | 2016-06-30T00:03:58Z | 38,112,018 | <p>What you're probably looking for is a list comprehension:
</p>
<pre><code>list1 = [key for key in aDict.keys() if key != 'b']
</code></pre>
<p>That said, the right answer might be to just use the example you provide. The Python style guide suggests writing your code to maximize the obviousness of what you are doi... | 1 | 2016-06-30T00:09:08Z | [
"python",
"list",
"dictionary"
] |
Sort stdout by IP address in Python | 38,112,005 | <p>I have several methods which are being executed in parallel by using multiprocessing module but do not show output in correct order. For example:</p>
<pre><code>Host:10.76.0.114 Running upon kernel reinstallation for GRUB
Host:10.76.0.114 Running: /sbin/new-kernel-pkg --package kernel --mkinitrd --dracut --depmod... | 0 | 2016-06-30T00:07:55Z | 38,112,099 | <p>Here I have modified some:</p>
<pre><code>import StringIO
import string, sys
stdout = sys.stdout
sys.stdout = file = StringIO.StringIO()
print """
10.76.0.114 Initiate Recovery images download
10.76.0.114 Running: wget -b -N -i /tools/recovery/recovery-templates-url.list -o /tools/recovery/recovery-templates-d... | 1 | 2016-06-30T00:22:39Z | [
"python",
"linux",
"sorting",
"python-multiprocessing"
] |
Optimizing index difference of equal values for time complexity | 38,112,016 | <p>I have this code that finds the smallest difference between the indices of equal values in a list. (It finds the smallest "distance" between equal values.) I want to optimize its time complexity. My code currently runs in O(N^2).</p>
<pre><code>def func(arr):
length = len(arr)
res = 0
for i and j in ran... | 0 | 2016-06-30T00:09:07Z | 38,112,184 | <p>Here's a simple solution that has <strong>O(n)</strong> time complexity. For every item in the array it will store the first index it's found from and then later retrieves it to calculate the difference:</p>
<pre><code>def func(arr):
d = {}
return max(i - d.setdefault(x, i) for i, x in enumerate(arr))
</cod... | 6 | 2016-06-30T00:34:23Z | [
"python",
"optimization"
] |
Optimizing index difference of equal values for time complexity | 38,112,016 | <p>I have this code that finds the smallest difference between the indices of equal values in a list. (It finds the smallest "distance" between equal values.) I want to optimize its time complexity. My code currently runs in O(N^2).</p>
<pre><code>def func(arr):
length = len(arr)
res = 0
for i and j in ran... | 0 | 2016-06-30T00:09:07Z | 38,112,198 | <p>You can get a bit of a speed up by bringing that max() out to the top and using list comprehensions (although you'll still need to tackle the O notation complexity):</p>
<pre><code>def func(arr):
return max([abs(i - j)
for i in range(len(arr))
for j in range(len(arr))
... | 0 | 2016-06-30T00:38:04Z | [
"python",
"optimization"
] |
Data saved to text file is inconsistent | 38,112,029 | <p>My controller is receiving data from a radio module through a serial port, it's recording temperature and humidity to two decimal places every 1 second, using 'a' as a signal to time stamp it. For example: </p>
<pre><code>a21.12 65.43
a21.13 65.40
</code></pre>
<p>Here is the code I'm using:</p>
<pre><code>import... | 0 | 2016-06-30T00:10:30Z | 38,112,053 | <p>You are calling <code>read()</code> twice and writing only the output of the second call. I don't imagine that is your intent.</p>
<p>You can change this section:</p>
<pre><code>with open('tempdata.txt', 'a') as text_file:
while 1:
content = ser.read()
if content is 'a':
text_file.w... | 1 | 2016-06-30T00:15:24Z | [
"python",
"pyserial"
] |
Python/Selenium - text property of WebElement truncates duplicating whitespaces | 38,112,137 | <p>I would like to share my observation related with <strong>text</strong> property of <em>WebElement</em>. I have a pdf link:
<a href="http://i.stack.imgur.com/1cbPj.png" rel="nofollow"><img src="http://i.stack.imgur.com/1cbPj.png" alt="enter image description here"></a></p>
<p>The file name has triple whitespace and... | 0 | 2016-06-30T00:27:25Z | 38,112,310 | <p>As @Eric commented, this is not a problem of selenium. It is an issue in your application.
However, if you really want to get that text, you have to get attribute innerHTML. See code below:</p>
<pre><code>text = driver.find_element_by_css_selector("a").get_attribute("innerHTML")
</code></pre>
| 0 | 2016-06-30T00:53:51Z | [
"python",
"html",
"selenium",
"dom",
"selenium-webdriver"
] |
What do I set my columns as in Connect Four (made with tkinter/Python)? | 38,112,388 | <p>I'm working on my final project for my intro to CS class, and decided to create Connect Four using tkinter from Python. I drew my board using tkinter's 'create_rectangle()' but now I'm stuck on how to label/call/refer my columns. My grid is 700x600 pixels, with 7 columns, and 6 rows. In order to keep track of the pi... | 0 | 2016-06-30T01:05:31Z | 38,159,672 | <p>What I suggest is something along the lines of</p>
<pre><code>import tkinter as tk
root = tk.Tk()
c = tk.Canvas(root, width = 700, height = 600)
c.pack()
board_state = []
for i in range(0, 700, 100):
column = []
for k in range(0, 700, 100):
column.append(c.create_oval(i, k, i+100, k+100, fill=""))... | 0 | 2016-07-02T11:33:22Z | [
"python",
"tkinter",
"grid"
] |
split a text file into words based on words and special characters in file | 38,112,451 | <pre><code>import os
import re
import shutil
import tempfile
import csv
from StringIO import StringIO
import sqlite3
### SQL lite
file="H:/query.txt"
file = open(file, 'r')
text = file.read().lower()
file.close()
text = re.split('\W+',text)
print text
</code></pre>
<p>I am using above script to split a file into... | 0 | 2016-06-30T01:14:52Z | 38,112,794 | <pre><code>re.split('[\x7b-\x7f \x20-\x22 \x24-\x40]',<string_here>)
</code></pre>
<p>Basically, I took the ranges of everything outside of the upper/lower case character range and also excluded the '#' range. <code>\x</code> allows you match a specific ascii/unicode character by using its corresponding hex numb... | 1 | 2016-06-30T02:01:12Z | [
"python",
"regex"
] |
split a text file into words based on words and special characters in file | 38,112,451 | <pre><code>import os
import re
import shutil
import tempfile
import csv
from StringIO import StringIO
import sqlite3
### SQL lite
file="H:/query.txt"
file = open(file, 'r')
text = file.read().lower()
file.close()
text = re.split('\W+',text)
print text
</code></pre>
<p>I am using above script to split a file into... | 0 | 2016-06-30T01:14:52Z | 38,113,414 | <p>Just create a regex that matches exactly what you're looking for and use the findall command.</p>
<p>This expression will match all words 1 character or longer that might have a <code>.</code>, <code>#</code>, or a <code>_</code> inside the word.</p>
<pre><code>[a-z](?:[a-z.#_]*[a-z])?
</code></pre>
<p><img src="... | 0 | 2016-06-30T03:18:00Z | [
"python",
"regex"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.