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 |
|---|---|---|---|---|---|---|---|---|---|
Randomly parsing files in Python from the command line | 38,751,610 | <p>When I was programming in C I had figured out a way in order to parse command line arguments for my program in any order, but I just would have to specify what the file was.
So my input was something like this: <code>./exe.out -i <inputfile> -o <outputfile> -a <someotherfile> etc...</code> And this... | -2 | 2016-08-03T18:57:21Z | 38,751,654 | <p>You are looking for <code>optparse</code> (before Python 2.7) or <code>argparse</code> (Python 2.7 or above).</p>
| 3 | 2016-08-03T19:00:08Z | [
"python",
"parsing",
"command",
"arguments"
] |
How do I convert Tensorflow variables to Matlab structures? | 38,751,664 | <p>I am trying to pass the model parameters (W & b) from tensorflow to matlab as a dictionary. But when I convert it to a structure in matlab the fields are still tensor variables and I cant do the desired operations on them. Is there any way to fix that and convert them to double or matrix?</p>
<p>In tensor flow:... | 0 | 2016-08-03T19:00:35Z | 38,752,950 | <p>Assuming in your TensorFlow program you have a <code>tf.Session</code> object called <code>sess</code>, you should modify your code to return the following:</p>
<pre><code>def myModelOutput(...):
# ...
sess = tf.Session()
# ...
# Convert the `tf.Variable` objects `W` and `b` to NumPy arrays.
W_val, ... | 0 | 2016-08-03T20:22:27Z | [
"python",
"matlab",
"data-structures",
"tensorflow",
"data-type-conversion"
] |
Python 2.7 on OS X: TypeError: 'frozenset' object is not callable on each command | 38,751,800 | <p>I have this error on each my command with Python:</p>
<pre>
â /tmp sudo easy_install pip
Traceback (most recent call last):
File "/usr/bin/easy_install-2.7", line 11, in
load_entry_point('setuptools==1.1.6', 'console_scripts', 'easy_install')()
File "/System/Library/Frameworks/Python.framework/Versions/... | 0 | 2016-08-03T19:08:29Z | 38,767,427 | <p>Removal of this package have helped me:</p>
<pre>
sudo rm -rf /Library/Python/2.7/site-packages/hashlib-20081119-py2.7-macosx-10.11-intel.egg
</pre>
| 1 | 2016-08-04T12:31:23Z | [
"python"
] |
Python 3.5: PIL Image.fromarray producing nonsense image | 38,751,865 | <p>I have an RGB image. When I import this image, I convert it to HSV using <code>matplotlib.color</code> and save the resulting array in a dict. When I want to display this image, I use <code>Image.fromarray</code> with <code>mode = 'HSV'</code>. I'm not sure what I am doing wrong but when the image is displayed, I ge... | 1 | 2016-08-03T19:12:33Z | 38,878,046 | <p>As per user sascha's comment (see below question), I decided to normalize the libraries I'm using for HSV conversion. Once I did that, I got normal images no problem. It turns out that depending on what library you use for image conversion, you will get different HSV value ranges. Some libraries will produce a range... | 0 | 2016-08-10T15:43:22Z | [
"python",
"image",
"matplotlib",
"python-imaging-library"
] |
How to prevent airflow from backfilling dag runs? | 38,751,872 | <p>Say you have an airflow DAG that doesn't make sense to backfill, meaning that, after it's run once, running it subsequent times quickly would be completely pointless.</p>
<p>For example, if you're loading data from some source that is only updated hourly into your database, backfilling, which occurs in rapid succes... | 3 | 2016-08-03T19:12:56Z | 38,885,573 | <p>This appears to be an unsolved Airflow problem. I know I would really like to have exactly the same feature. Here is as far as I've gotten; it may be useful to others.</p>
<p>The are UI features (at least in 1.7.1.3) which can help with this problem. If you go to the Tree view and click on a specific task (squar... | 1 | 2016-08-11T00:34:10Z | [
"python",
"scheduled-tasks",
"airflow"
] |
mapping URL arguments in Python Requests redirect | 38,751,932 | <p>While using the <a href="http://routes.readthedocs.io/en/latest/" rel="nofollow">Routes</a> library I want to <a href="http://routes.readthedocs.io/en/latest/uni_redirect_rest.html#redirect-routes" rel="nofollow">redirect</a> certain URLs. The documentation says it can be achieved like this:</p>
<pre><code>map.redi... | 0 | 2016-08-03T19:16:26Z | 38,773,565 | <p>I ended up implementing it as follows:</p>
<pre><code>def _map_redirects( app ):
"""
Add redirect to the Routes mapper and forward the received query string.
Subsequently when the redirect is triggered in Routes middleware the request
will not even reach the webapp.
"""
def forward_qs(enviro... | 0 | 2016-08-04T17:11:36Z | [
"python",
"routes",
"url-routing",
"url-redirection"
] |
Color numbers in pandas dataframe | 38,752,010 | <p>Is there a way to print some numbers in a dataframe in a different color?
So for instance if I wanted to have the 1 in the following table in red. How can I do that?</p>
<pre><code>import pandas as pd
A=pd.DataFrame({'A':[1,2], 'B':[3,4]})
</code></pre>
<p>I found libraries like termcolor. But there I can only pri... | 1 | 2016-08-03T19:21:18Z | 38,752,335 | <p>In addition to the answer @piRSquared provided which gives great ability for granular control, it appears <code>pandas</code> has added a <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">style</a> feature as of <code>0.17.1</code> for addressing this exact issue. Here is a slightly mod... | 2 | 2016-08-03T19:42:14Z | [
"python",
"python-2.7",
"pandas"
] |
Overwrite yaml config file in GUI (python) | 38,752,011 | <p>I have implemented a GUI interface using PyQt4. In my GUI interface I have a configuration tab where users can make changes to the config file (with line edits). I am able to overwrite the yaml config file in the GUI with these inputted values (I have buttons for load, save, and overwrite), but when these variables ... | 0 | 2016-08-03T19:21:20Z | 38,766,629 | <p>You probably do not update the values <code>MIN_VOLTAGE</code>. <code>MAX_VOLTAGE</code> and <code>MAX_CURR</code> after writing the YAML file, but you do not show enough code to identify the problem.</p>
<p>You code loads the YAML file once (probably at application startup), and the values are populated thereafter... | 0 | 2016-08-04T11:53:45Z | [
"python",
"file",
"pyqt4",
"yaml",
"config"
] |
django deploy- ImproperlyConfigured: The SECRET_KEY setting must not be empty | 38,752,015 | <p>The project worked fine on windows pycharm.</p>
<p>Now i am putting it on ubuntu14.04 and apache2.</p>
<p>When i run <code>python manage.py runserver 8000</code></p>
<pre><code>Traceback (most recent call last): File "manage.py", line 14, in <module>
execute_from_command_line(sys.argv) File "/usr/lo... | 1 | 2016-08-03T19:21:44Z | 38,755,630 | <p>This error is common when your <a href="http://stackoverflow.com/a/20646241/2532070"><code>DJANGO_SETTINGS_MODULE</code> path is incorrect</a>.</p>
<p>When you run <code>python manage.py runserver 8000</code> you are using <code>manage.py</code> which is settings your <code>DJANGO_SETTINGS_MODULE</code> to <code>se... | 0 | 2016-08-04T00:17:59Z | [
"python",
"django",
"ubuntu",
"deployment"
] |
django deploy- ImproperlyConfigured: The SECRET_KEY setting must not be empty | 38,752,015 | <p>The project worked fine on windows pycharm.</p>
<p>Now i am putting it on ubuntu14.04 and apache2.</p>
<p>When i run <code>python manage.py runserver 8000</code></p>
<pre><code>Traceback (most recent call last): File "manage.py", line 14, in <module>
execute_from_command_line(sys.argv) File "/usr/lo... | 1 | 2016-08-03T19:21:44Z | 38,755,646 | <p>Maybe in your settings file, you are setting the <code>SECRET_KEY</code> using a <code>ENV</code> variable, open a shell and just:</p>
<pre><code> export SECRET_KEY='test_key'
</code></pre>
<p>Then, try to run your server again. </p>
| 0 | 2016-08-04T00:20:32Z | [
"python",
"django",
"ubuntu",
"deployment"
] |
Communication from Python to Arduino over USB | 38,752,081 | <p>I am trying to communicate with an Arduino. I use python and pyserial for communication over USB. As you can see in the source code below, I am trying to send a bytearray, which contains some information for two ledstrips, to the Arduino. But the Arduino does not receive the right information. It looks like the byte... | 1 | 2016-08-03T19:26:26Z | 38,763,286 | <p>Changing the baudrate to 9600 has fixed the communication</p>
| 0 | 2016-08-04T09:17:55Z | [
"python",
"arduino",
"pyserial"
] |
PUT dictionary in dictionary in Python requests | 38,752,091 | <p>I want to send a PUT request with the following data structure:</p>
<pre><code>{ body : { version: integer, file_id: string }}
</code></pre>
<p>Here is the client code:</p>
<pre><code>def check_id():
id = request.form['id']
res = logic.is_id_valid(id)
file_uuid = request.form['file_id']
url = 'ht... | -1 | 2016-08-03T19:27:03Z | 38,752,460 | <p>In official doc you found a topic called <a href="http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests" rel="nofollow">More complicated POST requests</a></p>
<blockquote>
<p>There are many times that you want to send data that is not form-encoded. If you pass in a string inste... | 0 | 2016-08-03T19:51:39Z | [
"python",
"dictionary",
"python-requests"
] |
PUT dictionary in dictionary in Python requests | 38,752,091 | <p>I want to send a PUT request with the following data structure:</p>
<pre><code>{ body : { version: integer, file_id: string }}
</code></pre>
<p>Here is the client code:</p>
<pre><code>def check_id():
id = request.form['id']
res = logic.is_id_valid(id)
file_uuid = request.form['file_id']
url = 'ht... | -1 | 2016-08-03T19:27:03Z | 39,598,206 | <p>Use <code>json=</code> instead of <code>data=</code> when doing <code>requests.put</code> and <code>headers = {'content-type':'application/json'}</code>:</p>
<pre><code> r = requests.put(url = url,
json = {'body' : {'version': id, 'file_id': str(file_uuid)}},
headers = {'content-... | 0 | 2016-09-20T15:32:11Z | [
"python",
"dictionary",
"python-requests"
] |
Finding specific Bigram using NLTK Python 3 | 38,752,101 | <p>I have a Problem that should actually be very easy solve with NLTK. I found a solution to my problem, but there they don't use NLTK:</p>
<p><a href="http://stackoverflow.com/questions/36707617/how-can-i-count-the-specific-bigram-words">how can I count the specific bigram words?</a></p>
<p>Is it possible to do that... | 0 | 2016-08-03T19:27:46Z | 38,760,578 | <p>You could try to count unigram and bigram without NLTK and using regular expressions (<code>re</code>). Now you do not need two separate calculations, but you can do it in one go with <code>re.findall()</code>:</p>
<pre><code>import re
import codecs
# List of words and a sentence
l = ['cow', 'dog', 'hot dog', 'pet... | 0 | 2016-08-04T07:04:42Z | [
"python",
"count",
"nltk"
] |
How to run python file from django | 38,752,121 | <p>How I can run python file, or django file from django view.
I'm trying to make like ipython notebook, but use just text editor.</p>
<p>I have create view, in this view I'm simply add python(django) text.</p>
<p>Then when smb requests some view, wich process this python(django) file, I should send response with res... | -3 | 2016-08-03T19:29:03Z | 38,753,719 | <p>If I understand well you want to run some function inside of your view that is stored in and external file. If so just put the file in your app root directory and import it in your views.py</p>
<pre><code>from your_app.your_file import your_method
</code></pre>
| 1 | 2016-08-03T21:12:02Z | [
"python",
"django"
] |
Python2.7: How to split a column into multiple column based on special strings like this? | 38,752,135 | <p>I'm a newbie for programming and python, so I would appreciate your advice!</p>
<p>I have a dataframe like this.
<a href="http://i.stack.imgur.com/33lcM.png" rel="nofollow"><img src="http://i.stack.imgur.com/33lcM.png" alt="enter image description here"></a>
In 'info' column, there are 7 different categories: activ... | -2 | 2016-08-03T19:29:42Z | 38,752,306 | <p>It looks like the content of the <code>info</code> column is JSON-formatted, so you can parse that into a dict object easily:</p>
<pre><code>>>> import json
>>> s = '''{"activities": ["Tour"], "locations": ["Tokyo"], "groups": []}'''
>>> j = json.loads(s)
>>> j
{u'activities': [u... | 0 | 2016-08-03T19:40:45Z | [
"python",
"python-2.7",
"pandas",
"split",
"multiple-columns"
] |
Python2.7: How to split a column into multiple column based on special strings like this? | 38,752,135 | <p>I'm a newbie for programming and python, so I would appreciate your advice!</p>
<p>I have a dataframe like this.
<a href="http://i.stack.imgur.com/33lcM.png" rel="nofollow"><img src="http://i.stack.imgur.com/33lcM.png" alt="enter image description here"></a>
In 'info' column, there are 7 different categories: activ... | -2 | 2016-08-03T19:29:42Z | 38,752,523 | <p>Ok, here is how to do it :</p>
<pre><code>import pandas as pd
import ast
#Initial Dataframe is df
mylist = list(df['info'])
mynewlist = []
for l in mylist:
mynewlist.append(ast.literal_eval(l))
df_info = pd.DataFrame(mynewlist)
#Add columns of decoded info to the initial dataset
df_new = pd.concat([df,df_in... | 0 | 2016-08-03T19:55:51Z | [
"python",
"python-2.7",
"pandas",
"split",
"multiple-columns"
] |
What does self[identifier] = some_value do in this code? | 38,752,193 | <p>I was just trying to learn K-ary tree implementation in Python and came across this link:
<a href="http://www.quesucede.com/page/show/id/python-3-tree-implementation">http://www.quesucede.com/page/show/id/python-3-tree-implementation</a></p>
<p>In the tree.py file, there is a section of code like this:</p>
<pre><c... | 6 | 2016-08-03T19:33:22Z | 38,752,271 | <p>In the full example code, this is the important bit:</p>
<pre><code>def __getitem__(self, key):
return self.__nodes[key]
def __setitem__(self, key, item):
self.__nodes[key] = item
</code></pre>
<p>These two 'magic methods', <code>__getitem__</code> and <code>__setitem__</code>, allow the class to be acces... | 3 | 2016-08-03T19:38:24Z | [
"python"
] |
What does self[identifier] = some_value do in this code? | 38,752,193 | <p>I was just trying to learn K-ary tree implementation in Python and came across this link:
<a href="http://www.quesucede.com/page/show/id/python-3-tree-implementation">http://www.quesucede.com/page/show/id/python-3-tree-implementation</a></p>
<p>In the tree.py file, there is a section of code like this:</p>
<pre><c... | 6 | 2016-08-03T19:33:22Z | 38,752,558 | <p>They are using the <code>__getitem__</code> magic method. This method is used in a class to allow its instances to use [] (indexer) operators for list indexing, dictionary lookups, or accessing ranges of values.</p>
<p>In the fallowing sample, we have a list with some extra functionality like head and tail. Example... | 1 | 2016-08-03T19:58:20Z | [
"python"
] |
In DRF(django-rest-framework), If model has two foreignkeyfield, is it possible to serialize? | 38,752,198 | <p>I made django project through DRF.</p>
<p>On my struggling with DRF, I getting wonder that it is possible to serializing these models.</p>
<p><strong>models.py</strong></p>
<pre><code>class Post(models.Model):
author = models.ForeignKey(User, related_name='related_postwriter')
title = models.CharField(max... | 0 | 2016-08-03T19:33:42Z | 38,752,275 | <p>There is nothing wrong, you are just accessing the wrong attributes. If you look at your models, you define a related name to posts:</p>
<p><code>post = models.ForeignKey('blog.Post', related_name='related_comments')</code></p>
<p>So, when you write your serializer, the "field" you should be accessing should be th... | 2 | 2016-08-03T19:38:36Z | [
"python",
"django",
"django-rest-framework"
] |
In DRF(django-rest-framework), If model has two foreignkeyfield, is it possible to serialize? | 38,752,198 | <p>I made django project through DRF.</p>
<p>On my struggling with DRF, I getting wonder that it is possible to serializing these models.</p>
<p><strong>models.py</strong></p>
<pre><code>class Post(models.Model):
author = models.ForeignKey(User, related_name='related_postwriter')
title = models.CharField(max... | 0 | 2016-08-03T19:33:42Z | 38,752,835 | <p>You can use <a href="http://www.django-rest-framework.org/api-guide/relations/#nested-relationships" rel="nofollow">Nested relationships</a></p>
| 1 | 2016-08-03T20:15:31Z | [
"python",
"django",
"django-rest-framework"
] |
remove extra newline when writing to a file | 38,752,220 | <p>This little script writes keywords to a file, but adds an extra newline between each keyword. How do I make it stop? I.e. instead of</p>
<pre><code>Apple
Banana
Crayon
</code></pre>
<p>I want </p>
<pre><code>Apple
Banana
Crayon
</code></pre>
<p>I tried Googling "listwrite" but didn't help.</p>
<p>I am sure t... | -2 | 2016-08-03T19:35:10Z | 38,752,272 | <pre><code>def listwrite(output_file,thelist):
for item in thelist:
item.encode('utf-8')
output_file.write("%s\n\n" % item)
</code></pre>
<p>In the code, listwrite is defined as a function. For every <code>item</code> in <code>thelist</code>, it writes the <code>item</code>, followed by two newline... | 2 | 2016-08-03T19:38:25Z | [
"python",
"newline"
] |
Dynamicly add a new subplot2grid to a figure | 38,752,242 | <p>I have an application that have 3 figures, and dynamicaly change them. For now it's been working fine by using <code>add_subplot()</code> to the figure. But now I have to make my graphs more complex, and need to use <code>subplot2grid()</code></p>
<pre><code>self.figure1 = plt.figure()
self.canvas1 = FigureCanvas(s... | 0 | 2016-08-03T19:36:56Z | 38,752,824 | <p>Looking into the source code of <code>matplotlib</code>, the <code>subplot2grid</code>-function is defined in the following way:</p>
<pre><code>def subplot2grid(shape, loc, rowspan=1, colspan=1, **kwargs):
"""
Create a subplot in a grid. The grid is specified by *shape*, at
location of *loc*, spanning ... | 1 | 2016-08-03T20:14:48Z | [
"python",
"matplotlib"
] |
How do I set a global variable via function call? | 38,752,431 | <p>I am trying to change the value of global variable <code>edl_loading</code> to <code>True</code> in function <code>edl_flashing</code> ,somehow it doesn't work?can anyone help understand why does <code>print edl_loading</code> prints <code>False</code> after call to <code>edl_flashing</code> in which I change the va... | 1 | 2016-08-03T19:49:10Z | 38,752,484 | <p>You need to use the <code>global</code> in both of your functions - <code>main</code> and <code>edl_flashing</code></p>
<pre><code>def edl_flashing():
global edl_loading
edl_loading = True
print edl_loading
</code></pre>
<p>Without the global declaration in the function, the variable name is local to t... | 1 | 2016-08-03T19:53:31Z | [
"python"
] |
get mean for all columns in a dataframe and create a new dataframe | 38,752,444 | <p>I have a dataframe with only numeric values and I want to calculate the mean for every column and create a new dataframe.<br>
The original dataframe is indexed by a datetimefield. The new dataframe should be indexed by the same field as original dataframe with a value equal to last row index of original dataframe.<... | 0 | 2016-08-03T19:50:23Z | 38,752,851 | <p>Your question implies that you want a new DataFrame with a single row.</p>
<pre><code>In [10]: df.head(10)
Out[10]:
0 1 2 3
2011-01-01 00:00:00 0.182481 0.523784 0.718124 0.063792
2011-01-01 01:00:00 0.321362 0.404686 0.481889 0.524521
2011-01-01 02:00:00... | 2 | 2016-08-03T20:16:09Z | [
"python",
"dataframe",
"series"
] |
CSRF token cookie vulnerabilities during security scan | 38,752,546 | <p>I am making a simple website for my employer using Django, and I had to run the code through a security scan to test for vulnerabilities. One of the issues is cookie vulnerabilities that I can find documentation to find for.</p>
<p>The cookie vulnerabilities are raised when logging in to my website.</p>
<p>Here is... | 2 | 2016-08-03T19:57:16Z | 38,752,679 | <p>It sounds like you want to change the <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#csrf-cookie-age"><code>CSRF_COOKIE_AGE</code></a> setting to <code>None</code>:</p>
<blockquote>
<p>Default: <strong>31449600</strong> (approximately 1 year, in seconds)</p>
<p>The age of CSRF cookies, in secon... | 5 | 2016-08-03T20:05:28Z | [
"python",
"django",
"security",
"cookies"
] |
output file with names from groupby results pandas python | 38,752,592 | <p>i have a sample dataset:</p>
<pre><code>import pandas as pd
df = {'READID': [1,1,1 ,1,1 ,5,5 ,5,5],
'VG': ['LV5-F*01','LV5-F*01' ,'LV5-F*01','LV5-F*01','LV5-F*01','LV5-A*01','LV5-A*01','LV5-A*01','LV5-A*01'],
'Pro': [1,1,1,1,1,2,2,2,2]}
df = pd.DataFrame(df)
</code></pre>
<p>it looks like :</p>
<pr... | 1 | 2016-08-03T20:00:19Z | 38,752,660 | <p>You don't need groupby, you can just select the rows you need and convert them to text file.</p>
<pre><code>import pandas as pd
df = {'READID': [1,1,1 ,1,1 ,5,5 ,5,5],
'VG': ['LV5-F*01','LV5-F*01' ,'LV5-F*01','LV5-F*01','LV5-F*01','LV5-A*01','LV5-A*01','LV5-A*01','LV5-A*01'],
'Pro': [1,1,1,1,1,2,2,2,2]}... | 0 | 2016-08-03T20:04:23Z | [
"python",
"pandas"
] |
output file with names from groupby results pandas python | 38,752,592 | <p>i have a sample dataset:</p>
<pre><code>import pandas as pd
df = {'READID': [1,1,1 ,1,1 ,5,5 ,5,5],
'VG': ['LV5-F*01','LV5-F*01' ,'LV5-F*01','LV5-F*01','LV5-F*01','LV5-A*01','LV5-A*01','LV5-A*01','LV5-A*01'],
'Pro': [1,1,1,1,1,2,2,2,2]}
df = pd.DataFrame(df)
</code></pre>
<p>it looks like :</p>
<pr... | 1 | 2016-08-03T20:00:19Z | 38,752,953 | <pre><code>g = df.groupby(['READID','VG','Pro'])
for group in g:
group[1].to_csv('{}.txt'.format(group[0][1]), sep='\t', index=False)
</code></pre>
<p>You might want to strip <code>*</code> character if it causes problems.</p>
<p>Also note that you group on three keys but using only one key as the file name. It m... | 0 | 2016-08-03T20:22:41Z | [
"python",
"pandas"
] |
Merge Dataframe by regular expression or fuzzy match | 38,752,653 | <p>I have d1 and d2 and I want to merge the two by ID column.
However, the ID and ID2 are not exactly match. Instead, ID is the first 8 digit of ID2 (sometimes it can be the first 6 digit, or sometimes it can be one or two digit different).</p>
<p>I understand that I can pre-process ID2 to keep only the first 8 digit.... | 2 | 2016-08-03T20:03:45Z | 38,752,724 | <p>dude,</p>
<p>I have had the same problem and the only solution is to use other python packages. Have a look at <code>fuzzywuzzy</code> for instance. Its very good.</p>
<p>The general idea is that, for every row in d1, you will look for the row in d2 that has the highest fuzzy matching score.</p>
| 1 | 2016-08-03T20:08:17Z | [
"python",
"regex",
"pandas",
"merge",
"fuzzy"
] |
Python Tkinter GUI Calculator | 38,752,665 | <p>So I am currently in the process of making a GUI Calculator, but am unsure on how to write code that will perform the operations of the calculator. Right now I currently have setup the window, entry box, and calculator buttons, but none of them actually do anything at the moment. </p>
<p>I am just confused on how t... | -1 | 2016-08-03T20:04:34Z | 38,753,030 | <p>What you could do is <em>bind</em> all buttons to a method that identifies the button and append a string to a list or evaluate the expression. This list could then be displayed in the label.</p>
<pre><code>def button_press(self, event):
widget = event.widget
text = widget["text"]
if text != "AC" and te... | 0 | 2016-08-03T20:27:27Z | [
"python",
"user-interface",
"tkinter",
"calculator",
"operator-keyword"
] |
How to flatten a nested "homogeneous" list | 38,752,696 | <p>I have read <a href="http://stackoverflow.com/q/10823877/3001761">What is the fastest way to flatten arbitrarily nested lists in Python?</a>, which provides good answers on how to flatten arbitrarily nested lists in Python. However, a lot of the time, lists are nested to an arbitrary depth but homogeneous. A homogen... | -3 | 2016-08-03T20:06:26Z | 38,752,697 | <p>Here is my solution:</p>
<pre><code>def homo_flat( seq ):
first = 0
while True:
if type( seq[ first ] ) not in [ list, tuple ]:
return seq
else:
seq = [ inner for outer in seq for inner in outer ]
</code></pre>
| -5 | 2016-08-03T20:06:26Z | [
"python",
"list"
] |
Convert spreadsheet to nested dictionary form for D3 | 38,752,756 | <p>Having trouble with this one. Feel as though I've whipped through similar transformations of data, but this one is throwing me for a <em>loop</em>.</p>
<p>Looking to convert a spreadsheet data into a nested JSON that will be used for a D3 visualization, seen it referred to as "<a href="https://gist.github.com/mbos... | 0 | 2016-08-03T20:10:45Z | 38,753,169 | <p>This should do it:</p>
<pre><code>def convert_data(data):
out = {'name': 'root', 'children': []}
for row in data:
out['children'].append({})
current = out['children']
... | 1 | 2016-08-03T20:36:38Z | [
"python",
"d3.js",
"nested-loops"
] |
Return True every other weekend, return False any other day | 38,752,837 | <p>I'm trying to make a script that will run every other weekend, I've tried using datetime for that (a solution I found on the internet, likewise), but it always prints the entire week.</p>
<pre><code>from datetime import date, timedelta
reference_monday = date(2016, 1, 8) # any monday of a "week one"
schedul... | 1 | 2016-08-03T20:15:38Z | 38,752,960 | <p>As stated in the comments, there are better alternatives to scheduling tasks. </p>
<p>Is this what you want?</p>
<pre><code>def check_date(d):
return not schedule[abs(d - reference_monday).days / 7 % 2][d.weekday()]
</code></pre>
<p>Output</p>
<pre><code>week of 2012-06-04 : False,False,False,False,False,Fal... | 0 | 2016-08-03T20:22:58Z | [
"python"
] |
y axis of heat map not inverting in Python | 38,752,844 | <p>I'm generating 4 heat maps using subplots and want the y-axis inverted. I'm using <code>ax[i].invert_yaxis()</code> but it doesn't seem to be working. An example of the code is below:</p>
<pre><code>everything = [data_y_axis, data_length, data_roundness, data_y_SDev]
legend = ['title1', 'title2', 'title3', 'title4'... | 1 | 2016-08-03T20:15:56Z | 38,753,354 | <p>Aha. I have solved it. I removed <code>ax[i].invert_yaxis()</code> from within the <code>for</code> loop and stuck it at the end. It now works:</p>
<pre><code>for i, v in enumerate(everything):
heatmap = ax[i].pcolor(v, cmap=plt.cm.Blues)
ax[i].xaxis.tick_top()
ax[i].set_xticks(np.arange(v.shape[1])+0... | 0 | 2016-08-03T20:48:56Z | [
"python",
"matplotlib",
"heatmap"
] |
Pandas Date Conditional Calculation | 38,753,047 | <p>I am trying to create a column in pandas based off of a conditional statement that calculates time between two events. I was able to work out the day calculation but when plugged into my conditional statement:</p>
<pre><code>def defect_age(df):
if df['Status'] == 'R':
return (pd.to_datetime(df['resolve... | 1 | 2016-08-03T20:28:30Z | 38,753,381 | <p>Do it like this :</p>
<pre><code>group_df['Age'] = group_df.apply(lambda row:defect_age(row), axis=1)
</code></pre>
<p>This is because you want to apply the function to each row not to the whole dataframe at once.</p>
<p><code>df['Status'] == 'R'</code> will give a list of booleans if applied on a dataframe and u... | 1 | 2016-08-03T20:50:50Z | [
"python",
"datetime",
"pandas",
"conditional"
] |
Pandas Date Conditional Calculation | 38,753,047 | <p>I am trying to create a column in pandas based off of a conditional statement that calculates time between two events. I was able to work out the day calculation but when plugged into my conditional statement:</p>
<pre><code>def defect_age(df):
if df['Status'] == 'R':
return (pd.to_datetime(df['resolve... | 1 | 2016-08-03T20:28:30Z | 38,753,438 | <p>Try using this definition of <code>defect_age</code></p>
<pre><code>def defect_age(df):
resolved = pd.to_datetime(df.resolved_on, errors='coerce')
submitted = pd.to_datetime(df.submitted_on)
r = (resolved - submitted) / np.timedelta64(1, 'D')
return np.where(df.Status == 'R', r, np.nan)
</code></pre... | 1 | 2016-08-03T20:54:13Z | [
"python",
"datetime",
"pandas",
"conditional"
] |
alternative to numpy.gradient | 38,753,066 | <p>I have been struggling to find a robust function to compute gradient for a 3D array. numpy.gradient supports up to 2nd order accuracy. Is there any alternative way to compute the gradient with a better accuracy? thanks.</p>
| 2 | 2016-08-03T20:30:06Z | 38,753,582 | <p>I would suggest using the symbolic library called <em>Theano</em> (<a href="http://deeplearning.net/software/theano/" rel="nofollow">http://deeplearning.net/software/theano/</a>). It is primarily designed for neural networks and deep learning stuff, yet quite nicely fits what you want. </p>
<p>After installing thea... | 1 | 2016-08-03T21:02:55Z | [
"python",
"gradient",
"numerical-methods"
] |
alternative to numpy.gradient | 38,753,066 | <p>I have been struggling to find a robust function to compute gradient for a 3D array. numpy.gradient supports up to 2nd order accuracy. Is there any alternative way to compute the gradient with a better accuracy? thanks.</p>
| 2 | 2016-08-03T20:30:06Z | 38,766,576 | <p>Finally I found this: 4th order gradient.
Wish numpy would integrate this, too...</p>
<p><a href="https://gist.github.com/deeplycloudy/1b9fa46d5290314d9be02a5156b48741" rel="nofollow">https://gist.github.com/deeplycloudy/1b9fa46d5290314d9be02a5156b48741</a></p>
<pre><code>def gradientO4(f, *varargs):
"""Calculate... | 0 | 2016-08-04T11:50:40Z | [
"python",
"gradient",
"numerical-methods"
] |
PyQt - Animations without redrawing everything? | 38,753,131 | <p>So I'm trying to learn animations in PyQt and throughout all the examples I can find online, they all seem to use the <code>self.update()</code> or <code>self.repaint()</code> methods to increment the animations. This means basically the code has to erase then redraw the entire widget for every frame, even though mu... | 0 | 2016-08-03T20:34:20Z | 38,765,868 | <p>The Qt's documentation about QWidget repaint slot says:</p>
<p><em>Repaints the widget directly by calling paintEvent() immediately, unless updates are disabled or the widget is hidden.
We suggest only using repaint() if you need an immediate repaint, for example during animation. In almost all circumstances update... | 0 | 2016-08-04T11:16:41Z | [
"python",
"qt",
"user-interface",
"animation",
"pyqt"
] |
How to search for text in Beautiful Soup | 38,753,155 | <p>Im trying to create a script that checks the stock of items on a website, im trying to locate every line that has "ATS" in it including the number after the colon. I then want to print all the values of "ATS" (one value for each size) Here is the script that I have so far:</p>
<pre><code>import requests
from bs4 im... | 1 | 2016-08-03T20:35:35Z | 38,753,299 | <p>I think BeautifulSoup is not the optimal way to go. It looks more like json-formated data. BeautifulSoup is mainly a parser for HTML/XML.
So my suggestion is to go for</p>
<pre><code>import requests
import json
prodpage=requests.get('http://www.adidas.com/on/demandware.store/Sites-adidas-US-Site/en_US/Product-GetV... | 0 | 2016-08-03T20:45:44Z | [
"python",
"beautifulsoup",
"bs4"
] |
selenium webdriver importing Options giving me an ImportError | 38,753,173 | <p>Link to the original code I'm trying to implement into my code.</p>
<p><a href="http://stackoverflow.com/questions/16800689/running-selenium-webdriver-using-python-with-extensions-crx-files">Running Selenium WebDriver using Python with extensions (.crx files)</a></p>
<pre><code>from selenium import webdriver
from ... | 1 | 2016-08-03T20:36:54Z | 38,753,490 | <p>Seems like there is an issue with below statement:-</p>
<pre><code>chop = webdriver.ChromeOptions()
</code></pre>
<p>Try:-</p>
<pre><code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chop = Options()
chop.add_extension('Adblock-Plus_v1.4.1.crx')
driver = webdriver.Chrome(ch... | 0 | 2016-08-03T20:57:04Z | [
"python",
"selenium",
"selenium-webdriver",
"google-chrome-extension",
"selenium-chromedriver"
] |
selenium webdriver importing Options giving me an ImportError | 38,753,173 | <p>Link to the original code I'm trying to implement into my code.</p>
<p><a href="http://stackoverflow.com/questions/16800689/running-selenium-webdriver-using-python-with-extensions-crx-files">Running Selenium WebDriver using Python with extensions (.crx files)</a></p>
<pre><code>from selenium import webdriver
from ... | 1 | 2016-08-03T20:36:54Z | 38,755,825 | <p>I fixed the problem, there was no options.py in the selenium2.7 version for some unusual reason.</p>
<p>All I did was update using terminal for mac osx, but you can't just update it, you have to delete all the pre existing paths first. So go find where your selenium is installed using</p>
<pre><code>import sys
pri... | 1 | 2016-08-04T00:47:30Z | [
"python",
"selenium",
"selenium-webdriver",
"google-chrome-extension",
"selenium-chromedriver"
] |
Django: clearing sessions in django_session table | 38,753,183 | <p>I am working on sessions in Django.</p>
<p>By default django stores sessions in django_session, I found out there is no way to purge sessions.</p>
<p>though clearsession can be used to delete rows. It is also recommended to run this as a cron job.</p>
<p>But doing this means logging out all logged-in users..right... | 0 | 2016-08-03T20:37:54Z | 38,753,254 | <p>The Django <a href="https://docs.djangoproject.com/en/dev/topics/http/sessions/#clearing-the-session-store" rel="nofollow">documentation</a> states (emphasis from me):</p>
<blockquote>
<h1>Clearing the session store</h1>
<p>As users create new sessions on your website, session data can
accumulate in your s... | 1 | 2016-08-03T20:42:50Z | [
"python",
"django"
] |
How can I remove rows from a numpy array that have NaN as the first element? | 38,753,198 | <p>I have a numpy array that looks like this:</p>
<pre><code> [[nan 0 0 ..., 0.0 0.053526738 0.068421053]
[nan 0 0 ..., 0.0 0.059653990999999996 0.068421053]
[nan 0 0 ..., 1.0 0.912542592 0.068421053]
...,
[1 0 0 ..., 0.0 0.126523399 0.193548387]
[nan 0 0 ..., 0.0 0.034388807 0.068421053]
[4 0 0 ..., 0.0 0.0225... | 0 | 2016-08-03T20:39:09Z | 38,753,885 | <p>If x is the original array, the following puts the valid rows into y:</p>
<pre><code>y = x[~np.isnan(x[:, 0])]
</code></pre>
| 1 | 2016-08-03T21:23:39Z | [
"python",
"numpy"
] |
how to plot a list of byte data with matplotlib | 38,753,205 | <p>I've got a bunch of data that I read in from a telnet machine...It's x, y data, but it's just comma separated like <code>x1,y1,x2,y2,x3,y3,...</code></p>
<p>Here's a sample:</p>
<pre><code>In[28] data[1:500]
Out[28] b'3.00000000E+007,-5.26880000E+001,+3.09700000E+007,-5.75940000E+001,+3.19400000E+007,-5.56250000E... | 1 | 2016-08-03T20:39:46Z | 38,753,409 | <p>to read your items, two at a time (x1, y1), try this: <a href="http://stackoverflow.com/questions/16789776/iterating-over-two-values-of-a-list-at-a-time-in-python">iterating over two values of a list at a time in python</a></p>
<p>and then (divide and conquer style), deal with the scientific notation separately.</p... | 1 | 2016-08-03T20:52:39Z | [
"python",
"list",
"numpy",
"matplotlib",
"bytearray"
] |
how to plot a list of byte data with matplotlib | 38,753,205 | <p>I've got a bunch of data that I read in from a telnet machine...It's x, y data, but it's just comma separated like <code>x1,y1,x2,y2,x3,y3,...</code></p>
<p>Here's a sample:</p>
<pre><code>In[28] data[1:500]
Out[28] b'3.00000000E+007,-5.26880000E+001,+3.09700000E+007,-5.75940000E+001,+3.19400000E+007,-5.56250000E... | 1 | 2016-08-03T20:39:46Z | 38,753,491 | <p>First convert your data to numbers with for example:</p>
<pre><code>data = b'3.00000000E+007,-5.26880000E+001,+3.09700000E+007,-5.75940000E+001'
numbers = map(float, data.split(','))
</code></pre>
<p>Now slice the array to get x and y-data seperately and plot it with matplotlib</p>
<pre><code>x = numbers[::2]
y =... | 4 | 2016-08-03T20:57:08Z | [
"python",
"list",
"numpy",
"matplotlib",
"bytearray"
] |
Beautifulsoup HTML table parsing--only able to get the last row? | 38,753,246 | <p>I have a simple HTML table to parse but somehow Beautifulsoup is only able to get me results from the last row. I'm wondering if anyone would take a look at that and see what's wrong. So I already created the rows object from the HTML table:</p>
<pre><code> <table class='participants-table'>
<thead>... | 2 | 2016-08-03T20:42:11Z | 38,753,740 | <p>You need to extend if you want all the th tags in a single list, you just keep reassigning <code>cells = row.find_all('th')</code> so when your print cells outside the loop you will only see what it was last assigned to i.e the last th in the last tr:</p>
<pre><code>cells = []
for row in rows:
cells.extend(row.fin... | 1 | 2016-08-03T21:13:32Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] |
await asyncio.wait(coroutines) invalid syntax | 38,753,312 | <p>I have a python program that uses <code>asyncio</code> and <code>await</code> modules. This is an example program that I have taken from
<a href="http://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/" rel="nofollow">here</a>. </p>
<pre><code>import asyncio
import os
import urllib.request
impor... | 1 | 2016-08-03T20:46:31Z | 38,753,417 | <p>Your article says:</p>
<blockquote>
<p>The async and await keywords were added in Python 3.5 to define a native coroutine and make them a distinct type when compared with a generator based coroutine. If youâd like an in-depth description of async and await, you will want to check out PEP 492.</p>
</blockquote>
... | 1 | 2016-08-03T20:53:10Z | [
"python",
"coroutine",
"python-asyncio"
] |
await asyncio.wait(coroutines) invalid syntax | 38,753,312 | <p>I have a python program that uses <code>asyncio</code> and <code>await</code> modules. This is an example program that I have taken from
<a href="http://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/" rel="nofollow">here</a>. </p>
<pre><code>import asyncio
import os
import urllib.request
impor... | 1 | 2016-08-03T20:46:31Z | 38,755,741 | <p><code>await</code> will raise a <code>SyntaxError</code> when used anywhere other than inside of a function defined using the <code>async</code> keyword, regardless of whether or not it has been made a coroutine using the <code>@asyncio.coroutine</code> decorator.</p>
<pre><code>import asyncio
async def test():
... | 1 | 2016-08-04T00:35:11Z | [
"python",
"coroutine",
"python-asyncio"
] |
await asyncio.wait(coroutines) invalid syntax | 38,753,312 | <p>I have a python program that uses <code>asyncio</code> and <code>await</code> modules. This is an example program that I have taken from
<a href="http://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/" rel="nofollow">here</a>. </p>
<pre><code>import asyncio
import os
import urllib.request
impor... | 1 | 2016-08-03T20:46:31Z | 39,302,678 | <p>You have two different issues here. </p>
<ol>
<li><p>As mentioned by <a href="http://stackoverflow.com/users/978961/dirn">dirn</a> in his comment, you should not be importing <code>await</code>. <code>await</code> is a built in keyword in Python 3.5. So, remove <code>import await</code>.</p></li>
<li><p>You've mixe... | 1 | 2016-09-03T02:23:13Z | [
"python",
"coroutine",
"python-asyncio"
] |
Why is my Django form template removing all data after a space? | 38,753,345 | <p>I am using a Django Form to validate a specific sign up page. The Form is set up as so:</p>
<pre><code>class MemberForm(forms.Form):
email = forms.EmailField(label='Email', required=True)
password = forms.RegexField(label='Password', widget=forms.PasswordInput, required=True, regex=r'^(?=.*[A-Za-z])(?=.*\d)... | 0 | 2016-08-03T20:48:36Z | 38,754,218 | <p>Django is not doing this, your browser is. You need to put the value variable in quotes:</p>
<pre><code>value="{{ field.data|default_if_none:"" }}"
</code></pre>
<p>But really, your shouldn't output fields like this: use Django to do it properly, with just <code>{{ field }}</code>.</p>
| 0 | 2016-08-03T21:50:20Z | [
"python",
"html",
"django",
"django-forms",
"django-templates"
] |
Django and read-only database connections | 38,753,431 | <p>Assume a Django application which is supposed to use two MySQL databases:</p>
<ul>
<li><code>default</code> - for storing data represented by models <code>A</code> and <code>B</code> (read-write access)</li>
<li><code>support</code> - for importing data represented by models <code>C</code> and <code>D</code> (read-... | 1 | 2016-08-03T20:54:03Z | 39,598,235 | <p>Had the same problem.
Django is trying to create the 'django_migrations' table in all DBs.
This happens even if there are no models associated with the read-only DB
and all routers are pointing a different DB.</p>
<p>I also ended up using peewee.</p>
| 0 | 2016-09-20T15:33:34Z | [
"python",
"mysql",
"django",
"database"
] |
How do you negate an annotated field in django? | 38,753,458 | <p>I have an annotated queryset in which I am annotating the sum of numbers. However, I want the result to be the negative of that sum. I can't seem to do it like this:</p>
<p><code>Model.objects.all().annotate(total=-Sum('qty'))</code></p>
| 1 | 2016-08-03T20:55:27Z | 38,753,749 | <p>F objects, of course!</p>
<p><code>Model.objects.all().annotate(total=Sum(F('qty')*-1))</code></p>
| 0 | 2016-08-03T21:14:01Z | [
"python",
"django"
] |
How do you negate an annotated field in django? | 38,753,458 | <p>I have an annotated queryset in which I am annotating the sum of numbers. However, I want the result to be the negative of that sum. I can't seem to do it like this:</p>
<p><code>Model.objects.all().annotate(total=-Sum('qty'))</code></p>
| 1 | 2016-08-03T20:55:27Z | 38,753,772 | <p>I know it sounds crazy, but try this:</p>
<pre><code>Model.objects.all().annotate(total=0-Sum('qty'))
</code></pre>
<p>The unary operator <code>-</code> seems unsupported, but the binary operator works. </p>
| 0 | 2016-08-03T21:15:48Z | [
"python",
"django"
] |
Pandas: drop rows based on duplicated values in a list | 38,753,515 | <p>I would like to drop rows within my dataframe based on if a piece of a string is duplicated within that string. For example, if the string is jkl-ghi-jkl, I would drop this row because jkl is repeated twice. I figured that creating a list and checking the list for duplicates would be the ideal approach.</p>
<p>My... | 6 | 2016-08-03T20:59:07Z | 38,753,716 | <p>You can combine <code>str.split</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow"><code>duplicated</code></a> to get a Boolean indexer:</p>
<pre><code># Get a Boolean indexer for duplicates.
dupe_rows = df1['Col1'].str.split('-', expand=True)... | 4 | 2016-08-03T21:11:56Z | [
"python",
"pandas"
] |
Pandas: drop rows based on duplicated values in a list | 38,753,515 | <p>I would like to drop rows within my dataframe based on if a piece of a string is duplicated within that string. For example, if the string is jkl-ghi-jkl, I would drop this row because jkl is repeated twice. I figured that creating a list and checking the list for duplicates would be the ideal approach.</p>
<p>My... | 6 | 2016-08-03T20:59:07Z | 38,753,754 | <p><code>split</code> <code>'Col1'</code> and apply a repeat checker using an efficient <code>numpy</code> algorithm.</p>
<pre><code>def nerpt(lst):
ti = np.triu_indices(len(lst), 1)
a = np.array(lst)
return (a[ti[0]] == a[ti[1]]).any()
df1[~df1.Col1.str.split('-').apply(nerpt)]
</code></pre>
<p><a href=... | 4 | 2016-08-03T21:15:02Z | [
"python",
"pandas"
] |
Pandas: drop rows based on duplicated values in a list | 38,753,515 | <p>I would like to drop rows within my dataframe based on if a piece of a string is duplicated within that string. For example, if the string is jkl-ghi-jkl, I would drop this row because jkl is repeated twice. I figured that creating a list and checking the list for duplicates would be the ideal approach.</p>
<p>My... | 6 | 2016-08-03T20:59:07Z | 38,753,833 | <p>Here is another option, using <code>set</code> and <code>len</code>:</p>
<pre><code>df1 = pd.DataFrame({'Col1' : ['abc-def-ghi-jkl', 'jkl-ghi-jkl-mno'],})
df1['length'] = df1['Col1'].str.split('-').apply(set).apply(len)
print( df1 )
Col1 length
0 abc-def-ghi-jkl 4
1 jkl-ghi-jkl-mno 3... | 4 | 2016-08-03T21:19:38Z | [
"python",
"pandas"
] |
Pandas: drop rows based on duplicated values in a list | 38,753,515 | <p>I would like to drop rows within my dataframe based on if a piece of a string is duplicated within that string. For example, if the string is jkl-ghi-jkl, I would drop this row because jkl is repeated twice. I figured that creating a list and checking the list for duplicates would be the ideal approach.</p>
<p>My... | 6 | 2016-08-03T20:59:07Z | 38,754,134 | <p>I went the same route you did, but instead kept everything in one dataframe; used <code>apply()</code> and indexed to get what I needed:</p>
<pre><code>[in]:
gf1 = df1
gf1['Col2'] = gf1['Col1'].str.split('-') #keep lists in same DF
gf1['Col3'] = gf1['Col2'].apply(set).apply(len) == gf1['Col2'].apply(len)
df1 = gf... | 1 | 2016-08-03T21:44:03Z | [
"python",
"pandas"
] |
double read calls in python fuse leading to EINVAL | 38,753,522 | <p>I am having trouble with python-fuse. Here is a standalone example of the issue: <a href="https://gist.github.com/ensonic/87e4108a7be64412d1c5a553b7e01f88" rel="nofollow">https://gist.github.com/ensonic/87e4108a7be64412d1c5a553b7e01f88</a></p>
<p>When mounting the fake-in-memory file system, I can list the contents... | 1 | 2016-08-03T20:59:17Z | 38,762,579 | <p>Turns out it is related to the tricky handling of encoding in python 2 (there is no python-fuse for py3).</p>
<p>Returning bytes(buf) in read() fixes it. The fuse code uses EINVAL also when things look wrong it received from the python side.</p>
| 0 | 2016-08-04T08:46:09Z | [
"python",
"fuse"
] |
Using os.system() in Python is open a program, can't see window of launched program | 38,753,553 | <p>I am trying to launch a program/GUI from within a python code.</p>
<p>From the terminal, I can get the program to launch by simply typing the program name. A few lines get outputted to the terminal, and then a separate window opens with the GUI. </p>
<p>I tried to emulate this in python by running</p>
<pre><code>... | 1 | 2016-08-03T21:01:07Z | 38,753,764 | <p>Here is a solution using <code>subprocess</code></p>
<pre><code>import subprocess
subprocess.Popen("notepad.exe")
</code></pre>
<p>Or if you want to run a python program with a specific interpreter:</p>
<pre><code>subprocess.Popen('{0} {1}'.format(PythonInterpreterPath,PythonFilePath.py))
</code></pre>
| 0 | 2016-08-03T21:15:29Z | [
"python",
"os.system"
] |
Using os.system() in Python is open a program, can't see window of launched program | 38,753,553 | <p>I am trying to launch a program/GUI from within a python code.</p>
<p>From the terminal, I can get the program to launch by simply typing the program name. A few lines get outputted to the terminal, and then a separate window opens with the GUI. </p>
<p>I tried to emulate this in python by running</p>
<pre><code>... | 1 | 2016-08-03T21:01:07Z | 38,753,886 | <p>From the <a href="https://docs.python.org/3/library/os.html#os.system" rel="nofollow">Python manual</a>:</p>
<blockquote>
<p>[<a href="https://docs.python.org/3/library/os.html#os.system" rel="nofollow"><code>os.system</code></a>] is implemented by calling the Standard C function
<a href="http://linux.die.net/m... | 1 | 2016-08-03T21:23:40Z | [
"python",
"os.system"
] |
What does "TypeError : (1,2,3) is not JSON serializable" mean? | 38,753,599 | <p>I'm trying to pull an array from Objective-C into my Python code, and when I do, I get the following error:</p>
<pre><code>TypeError: (
5850,
5500,
5170,
2500,
2400,
2400,
2400,
2500,
5170,
5500,
5850
) is not JSON serializable
</code></pre>
<p>I've tried to put a dict() method around my Objective-C wrapper call t... | -1 | 2016-08-03T21:03:43Z | 38,753,654 | <p>A <code>dict()</code> object or in this case, a JSON object requires a key followed by a value.</p>
<p>Thus, you are getting a <code>TypeError</code> as you are trying to convert an array to JSON.
Adding some keys to this array will fix the error.</p>
<p>Sample Code:</p>
<pre><code>json_payload = {
'0': 5850,
'1'... | -1 | 2016-08-03T21:07:58Z | [
"python",
"objective-c",
"arrays",
"json"
] |
What does "TypeError : (1,2,3) is not JSON serializable" mean? | 38,753,599 | <p>I'm trying to pull an array from Objective-C into my Python code, and when I do, I get the following error:</p>
<pre><code>TypeError: (
5850,
5500,
5170,
2500,
2400,
2400,
2400,
2500,
5170,
5500,
5850
) is not JSON serializable
</code></pre>
<p>I've tried to put a dict() method around my Objective-C wrapper call t... | -1 | 2016-08-03T21:03:43Z | 38,753,776 | <p>You want a Python array object, i.e. a <code>list()</code> object. There's no sense in using a <code>dict()</code>, unless you want a dictionary.</p>
<p>Use <code>list(1,2,3..,n)</code> or <code>[1, 2, 3..., n ]</code>to make a Python list object. You'll then access elements by their respective indices.</p>
<p>A P... | 2 | 2016-08-03T21:15:57Z | [
"python",
"objective-c",
"arrays",
"json"
] |
How to Modify the Dataframe so Each Row Stores All the Data of its Duplicate Rows? | 38,753,631 | <p>I have this dataframe with three columns (<code>ID</code>,<code>key</code>, and <code>word</code>)</p>
<pre><code> ID key word
0 1 A Apple
1 1 B Bug
2 2 C Cat
3 3 D Dog
4 3 E Exogenous
5 3 E Egg
</code></pre>
<p>I want to create additional <code>key</code> and <code>word</c... | 1 | 2016-08-03T21:06:08Z | 38,753,767 | <p>You can use concat after using Alex's solution :</p>
<pre><code>df1 = df.groupby('ID')['key'].apply(
lambda s: pd.Series(s.values, index=['key_%s' % i for i in range(s.shape[0])])).unstack(-1)
df2 = df.groupby('ID')['word'].apply(
lambda s: pd.Series(s.values, index=['word_%s' % i for i in range(s.shape[0])])).uns... | 0 | 2016-08-03T21:15:39Z | [
"python",
"pandas",
"dataframe",
"format",
"series"
] |
How to Modify the Dataframe so Each Row Stores All the Data of its Duplicate Rows? | 38,753,631 | <p>I have this dataframe with three columns (<code>ID</code>,<code>key</code>, and <code>word</code>)</p>
<pre><code> ID key word
0 1 A Apple
1 1 B Bug
2 2 C Cat
3 3 D Dog
4 3 E Exogenous
5 3 E Egg
</code></pre>
<p>I want to create additional <code>key</code> and <code>word</c... | 1 | 2016-08-03T21:06:08Z | 38,754,244 | <pre><code>df2 = df.set_index('ID').groupby(level=0).apply(lambda df: df.reset_index(drop=True)).unstack()
df2.columns = df2.columns.set_levels((df2.columns.levels[1]).astype(str), level=1)
df2.columns = df2.columns.to_series().str.join('_')
df2
</code></pre>
<p><a href="http://i.stack.imgur.com/w3bvQ.png" rel="nofoll... | 1 | 2016-08-03T21:52:04Z | [
"python",
"pandas",
"dataframe",
"format",
"series"
] |
How to Modify the Dataframe so Each Row Stores All the Data of its Duplicate Rows? | 38,753,631 | <p>I have this dataframe with three columns (<code>ID</code>,<code>key</code>, and <code>word</code>)</p>
<pre><code> ID key word
0 1 A Apple
1 1 B Bug
2 2 C Cat
3 3 D Dog
4 3 E Exogenous
5 3 E Egg
</code></pre>
<p>I want to create additional <code>key</code> and <code>word</c... | 1 | 2016-08-03T21:06:08Z | 38,759,655 | <p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p>
<pre><code>df['cols'] = df.groupby('ID')['ID'].cumcount().astype(str)
df1 = df.pivot_table(index='ID', columns='cols', values=['key','word'], aggfunc=''.join... | 0 | 2016-08-04T06:09:39Z | [
"python",
"pandas",
"dataframe",
"format",
"series"
] |
inserting numpy integer types into sqlite with python3 | 38,753,737 | <p>What is the correct way to insert the values of numpy integer objects into databases in python 3? In python 2.7 numpy numeric datatypes insert cleanly into sqlite, but they don't in python 3</p>
<pre><code>import numpy as np
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE foo (id INTEG... | 4 | 2016-08-03T21:13:24Z | 39,106,289 | <p>According to sqlite3 docs:</p>
<blockquote>
<p>To use other Python types with SQLite, you must adapt them to one of the sqlite3 moduleâs supported types for SQLite: one of NoneType, int, float, str, bytes.</p>
</blockquote>
<p>So you can <strong>adapt</strong> <em>np.int64</em> type. You should do something li... | 1 | 2016-08-23T16:21:51Z | [
"python",
"sqlite",
"python-3.x",
"numpy",
"python-db-api"
] |
Scrapy merge subsite-item with site-item | 38,753,743 | <p>Im trying to <strong>scrape details from a subsite and merge with the details scraped with site</strong>. I've been researching through stackoverflow, as well as documentation. However, I still cant get my code to work. It seems that my function to extract additional details from the subsite does not work. If anyone... | 0 | 2016-08-03T21:13:43Z | 38,753,888 | <p>What you are looking here is called request chaining. Your problem is - yield one item from several requests. A solution to this is to chain requests while carrying your item in requests <code>meta</code> attribute.<br>
Example:</p>
<pre><code>def parse(self, response):
item = MyItem()
item['name'] = respon... | 1 | 2016-08-03T21:23:52Z | [
"python",
"function",
"merge",
"scrapy"
] |
Write to Excel File with Pandas Module | 38,753,750 | <p>How could I write a list of items <code>[1,2,3,4,5]</code> to an excel file in a specific tab starting at a specific row and column location using the <code>Pandas</code> module? Does it involve the <code>pandas.DataFrame.to_excel</code> function, and do I need to convert my <code>list</code> into a <code>dataframe... | 0 | 2016-08-03T21:14:17Z | 38,757,389 | <p>Yes you will need to use 'to_excel'. The one line code below creates a list, converts it to a series, then converts it to a dataframe and creates and excel file</p>
<pre><code>pd.Series([ i for i in range(10)]).to_frame().to_excel('test.xlsx')
</code></pre>
| 0 | 2016-08-04T02:07:49Z | [
"python",
"excel",
"pandas"
] |
python matplotlib plotting many subfigures with the same parameters | 38,753,766 | <p>My plot is like the following </p>
<pre><code>fig = plt.figure(figsize=(7,3))
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)
ax1.... | 2 | 2016-08-03T21:15:30Z | 38,753,925 | <p>You could do this:</p>
<pre><code>fig = plt.figure(figsize=(7,3))
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)
xs = [x11, x12,... | 3 | 2016-08-03T21:26:43Z | [
"python",
"matplotlib",
"plot"
] |
python matplotlib plotting many subfigures with the same parameters | 38,753,766 | <p>My plot is like the following </p>
<pre><code>fig = plt.figure(figsize=(7,3))
ax1 = fig.add_subplot(1,3,1)
ax2 = fig.add_subplot(1,3,2)
ax3 = fig.add_subplot(1,3,3)
ax1.... | 2 | 2016-08-03T21:15:30Z | 38,760,016 | <p>I like organizing the data and styles, and then using that to organize the plotting. Generating some random data to make a runnable example: </p>
<pre><code>import matplotlib.pyplot as plt
from numpy.random import random
fig, axs = plt.subplots(3, figsize=(7,3)) #axs is an array of axes ... | 1 | 2016-08-04T06:33:05Z | [
"python",
"matplotlib",
"plot"
] |
Mypy Python 2 insist on unicode value not string value | 38,753,817 | <p>Python 2 will implicitly convert <code>str</code> to <code>unicode</code> in some circumstances. This conversion will sometimes throw a <code>UnicodeError</code> depending on what you try to do with the resulting value. I don't know the exact semantics, but it's something I'd like to avoid.</p>
<p>Is it possible to... | 2 | 2016-08-03T21:18:24Z | 38,775,762 | <p>This is, unfortunately, an ongoing and currently unresolved issue -- see <a href="https://github.com/python/mypy/issues/1141" rel="nofollow">https://github.com/python/mypy/issues/1141</a> and <a href="https://github.com/python/typing/issues/208" rel="nofollow">https://github.com/python/typing/issues/208</a>.</p>
<p... | 1 | 2016-08-04T19:24:12Z | [
"python",
"python-2.7",
"mypy"
] |
How to identify consecutive dates | 38,753,823 | <p>I would like to identify dates in a dataframe which are consecutive, that is there exists either an immediate predecessor or successor. I would then like to mark which dates are and are not consecutive in a new column. Additionally I would like to do this operation within particular subsets of my data. </p>
<p>Firs... | 3 | 2016-08-03T21:18:51Z | 38,754,106 | <p>Once you have the ordinal numbers it's a trivial task, here I'm using numpy arrays to propose one alternative</p>
<pre><code>a=np.array([1,2,4,6,7,10,12,13,14,20])
d=a[1:]-a[:-1] # compute delta
ind=np.logical_or(np.insert(d,0,0)==1,np.append(d,0)==1) # at least one side ... | 1 | 2016-08-03T21:41:41Z | [
"python",
"datetime",
"pandas"
] |
How to identify consecutive dates | 38,753,823 | <p>I would like to identify dates in a dataframe which are consecutive, that is there exists either an immediate predecessor or successor. I would then like to mark which dates are and are not consecutive in a new column. Additionally I would like to do this operation within particular subsets of my data. </p>
<p>Firs... | 3 | 2016-08-03T21:18:51Z | 38,754,698 | <p>You can use .shift(-1) or .shift(1) to compare consecutive entries:</p>
<pre><code>df.loc[df['DATE_INT'].shift(-1) - df['DATE_INT'] == 1, 'CONSECUTIVE_DAY'] = True
</code></pre>
<p>Will set CONSECUTIVE_DAY to TRUE if the previous entry is the previous day</p>
<pre><code>df.loc[(df['DATE_INT'].shift(-1) - df['DATE... | 2 | 2016-08-03T22:29:45Z | [
"python",
"datetime",
"pandas"
] |
Sharing Global variables in python | 38,753,914 | <p>I have 2 files a.py and b.py as follows:</p>
<p>a.py</p>
<pre><code>import b.py
Test="abc"
def main(args):
global Test
if args.target=="this":
Test="klm"
b.fun()
#rest of the body which I intend to execute only once
#hence I cannot call main() again
if __name__ == "__main__":
#some arguments are p... | -1 | 2016-08-03T21:25:53Z | 38,754,017 | <pre><code>import a
a.main()
print a.Test
a.Test = "new Value"
print a.Text
</code></pre>
<p>You never invoke the main function. When you import a module, <code>__name__</code> is not <code>"__main__"</code>, so your main() never runs. When you run a.py directly it will run main()</p>
| 1 | 2016-08-03T21:34:20Z | [
"python",
"python-2.7",
"variables",
"global-variables",
"global"
] |
Sharing Global variables in python | 38,753,914 | <p>I have 2 files a.py and b.py as follows:</p>
<p>a.py</p>
<pre><code>import b.py
Test="abc"
def main(args):
global Test
if args.target=="this":
Test="klm"
b.fun()
#rest of the body which I intend to execute only once
#hence I cannot call main() again
if __name__ == "__main__":
#some arguments are p... | -1 | 2016-08-03T21:25:53Z | 38,754,246 | <h2>Added due to question edit:</h2>
<p>You need to consider the ordering of the imports execution. Consider these working files.</p>
<p>a.py</p>
<pre><code>print("Entering a")
import argparse
import b
Test="abc"
print("Id of Test: ", id(Test))
def main(args):
global Test
if args.target=="this":
Test="klm... | 0 | 2016-08-03T21:52:21Z | [
"python",
"python-2.7",
"variables",
"global-variables",
"global"
] |
Sharing Global variables in python | 38,753,914 | <p>I have 2 files a.py and b.py as follows:</p>
<p>a.py</p>
<pre><code>import b.py
Test="abc"
def main(args):
global Test
if args.target=="this":
Test="klm"
b.fun()
#rest of the body which I intend to execute only once
#hence I cannot call main() again
if __name__ == "__main__":
#some arguments are p... | -1 | 2016-08-03T21:25:53Z | 38,754,333 | <p>In a.py you run main in the if statement:</p>
<pre><code>if __name__ == "__main__":
main()
</code></pre>
<p>Only executes main() if that is the main script. When you import the module all the code in the if block is not run because it is not the main script. To have the main method be called remove the if sta... | 0 | 2016-08-03T21:58:53Z | [
"python",
"python-2.7",
"variables",
"global-variables",
"global"
] |
sliceplot for bound material in yt without showing unbound | 38,753,964 | <p>I am trying to mask out the bound density of a system with the masking field </p>
<pre><code>@derived_field(name = "bound_density", units = "g/cm**3")
def _get_ejected_density(field, data):
E = 0.5* data["cell_mass"]* (data["velx"]**2+data["vely"]**2+data["velz"]**2)+ data["gpot"]*data["cell_mass"]
... | 2 | 2016-08-03T21:29:50Z | 38,754,068 | <p>Here's an example that shows how to manipulate the colorbar so the background color matches the color at the bottom of the colorbar:</p>
<p><a href="https://gist.github.com/4d07fc6475becd18b793e15ae2f00dff" rel="nofollow">https://gist.github.com/4d07fc6475becd18b793e15ae2f00dff</a></p>
| 1 | 2016-08-03T21:38:57Z | [
"python",
"background-color",
"yt-project"
] |
python3.4 import visa fails, this worked under python3.5 | 38,754,007 | <p>OK, I loaded Python 3.5 PYVISA, and set up my path variables in Windows, and import visa worked! Yay!</p>
<p>Now I want to create an executable, using cx_Freeze. I try running it, and it says it wants to see Python 3.4.</p>
<p>OK, I load Python 3.4. I add python34 paths to Windows and start up idle, load my scri... | 0 | 2016-08-03T21:33:20Z | 38,754,231 | <p>If you have installed pyvisa by using below command:</p>
<pre><code>pip install pyvisa
</code></pre>
<p>Then it gets installed in site packages of python 3.5 (or) site packages of that specific python version (whichever python that is serving at that point of time)</p>
<p>If you want that to be available for all ... | 2 | 2016-08-03T21:51:17Z | [
"python",
"visa"
] |
python regex: escape illegal characters only if it's not escaped already | 38,754,038 | <p>Right now I'm taking in files as string and formatting them into json. The file contains \r, \n characters that I want to escape, but there are json objects in the files which already has those illegal characters escaped, like \\r and \\n. So right now I want to replace \r \n characters with \\r \\n only if it's not... | 0 | 2016-08-03T21:36:31Z | 38,754,114 | <p>You could do it like this using RegEx:</p>
<pre><code>import re
data = 'Hello\r\nWorld\\r\\n'
print(data)
print('-'*20)
data = re.sub(r'([^\\])\r', '\\1\\\\r', data)
data = re.sub(r'([^\\])\n', '... | 3 | 2016-08-03T21:42:30Z | [
"python",
"json",
"regex"
] |
Python Split Unless Next Character Is Something | 38,754,072 | <p>I am using Python 3.5, and I would like to split a string by the character <code>\n</code>, or new line. however if the line starts with a underscore, for example, it should put that line with the one above it. I need the solution to work for all characters, not just underscore. It should work like this:</p>
<pre><... | -3 | 2016-08-03T21:39:08Z | 38,754,167 | <p>You can repalce <code>\n_</code> with some characters and then split the string with delimiter <code>\n</code></p>
<pre><code>>>> a = '''red
... yellow
... green
... _surprise!
... blue'''
>>> a
'red\nyellow\ngreen\n_surprise!\nblue'
</code></pre>
<p>Either:</p>
<pre><code>>>> [x.replac... | 0 | 2016-08-03T21:47:02Z | [
"python",
"python-3.x",
"split"
] |
Python Split Unless Next Character Is Something | 38,754,072 | <p>I am using Python 3.5, and I would like to split a string by the character <code>\n</code>, or new line. however if the line starts with a underscore, for example, it should put that line with the one above it. I need the solution to work for all characters, not just underscore. It should work like this:</p>
<pre><... | -3 | 2016-08-03T21:39:08Z | 38,754,180 | <p>It's pretty easy using regular expressions:</p>
<pre><code>import re
re.split('\n(?!_)', a)
# ['red', 'yellow', 'green\n_surprise!', 'blue']
</code></pre>
<p>This regex litterally means <code>split by \n not followed by _</code>.</p>
| 2 | 2016-08-03T21:47:54Z | [
"python",
"python-3.x",
"split"
] |
How do I subset a 2D grid from another 2D grid in python? | 38,754,079 | <p>I have gridded data over the contiguous United States and I'm trying to select a chunk of it over a specific area.</p>
<pre><code>import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt
filename = '/Users/me/myfile.nc'
full_data = Dataset(filename,'r')
latitudes = full_data.variables['latitu... | 0 | 2016-08-03T21:39:28Z | 38,754,255 | <p>Edub,</p>
<p>I suggest looking on at numpy's matrix indexing documentation, specifically <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#other-indexing-options" rel="nofollow">http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#other-indexing-options</a> . Currently, you are ... | 0 | 2016-08-03T21:53:04Z | [
"python",
"arrays",
"indexing"
] |
IPython: How to show the same plot in different cells? | 38,754,107 | <p>I'm still new to IPython Notebooks, Jupyter, and Python in general.</p>
<p>I'm creating a scatter plot in a Jupyter notebook using the following code:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
plt.axes([0.025, 0.025, 0.95... | 3 | 2016-08-03T21:41:59Z | 38,768,002 | <p>Try the object-oriented interface of matplotlib - <a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure" rel="nofollow">matplotlib.figure</a>; you can use the reference of the Figure object created, as required. </p>
<ul>
<li>Create a figure object - <code>fig = plt.figure()</code></li>
<li>A... | 0 | 2016-08-04T12:57:11Z | [
"python",
"matplotlib",
"ipython-notebook",
"jupyter-notebook"
] |
Making .next() compatible with both python 2 and 3 | 38,754,118 | <p>I have written code in python 2.7 that I want to make it compatible with
Python 3.x. So far I have tried the <code>futurize</code> and <code>modernize</code> python packages as well as <code>2to3</code>, and everything seems fine.</p>
<p>But I'm stuck with python 2.7's <code>.next()</code> method. And I get warni... | 0 | 2016-08-03T21:42:55Z | 38,761,356 | <p>Don't call the <code>.next()</code> method directly. Use the <a href="https://docs.python.org/2/library/functions.html#next" rel="nofollow"><code>next()</code> <em>function</em></a> on an iterator instead:</p>
<pre><code>for u in up:
head = next(u)[1:].strip()
q = "".join(s.strip() for s in next(u))
</code>... | 2 | 2016-08-04T07:44:02Z | [
"python",
"python-2.7",
"iterator"
] |
Pandas Interpolate dataframe with new length | 38,754,132 | <p>I have a dataframe with columns of Datetime, lat, lon, z. I am reading the data in from a csv file so setting the period for the datetimes do not work. The times are in 6 hour intervals but I want to linearly interpolate the data to hourly intervals. </p>
<p>Go from</p>
<pre><code> 'A' 'B' 'C... | 3 | 2016-08-03T21:43:58Z | 38,755,716 | <pre><code>i = pd.DatetimeIndex(start=df.index.min(), end=df.index.max(), freq='H')
df = df.reindex(i).interpolate()
print(df)
</code></pre>
<p>outputs</p>
<pre><code>2010-09-13 18:00:00 16.300000 -78.500000
2010-09-13 19:00:00 16.350000 -78.716667
2010-09-13 20:00:00 16.400000 -78.933333
2010-09-13 21:00:00 16.4... | 1 | 2016-08-04T00:30:37Z | [
"python",
"pandas",
"linear-interpolation"
] |
Embedded Cython UCS2 UCS4 issue | 38,754,156 | <p>I have some python code I am trying to embed within c++ code using the cython api construct. For testing purposes I have been working off of:
<a href="https://stackoverflow.com/questions/34480973/example-program-of-cython-as-python-to-c-converter">Example program of Cython as Python to C Converter</a></p>
<p>With t... | 0 | 2016-08-03T21:45:55Z | 38,778,201 | <p>It turns out I had two different installations of python on my system and I was linking the wrong one.</p>
| 0 | 2016-08-04T22:08:33Z | [
"python",
"c++",
"cython",
"ucs2",
"ucs-4"
] |
Sort CSV data with Python | 38,754,163 | <p>I have a CSV that have this example format (there will be many rows like this format):</p>
<pre><code>1131,01/06/15,PROFI ROM FOOD SRL,290.7,,
1131,,,,,
3811861,01/12/15,CENTRUL TERITORIAL DE CALCUL,141.36,,
3811861,,ELECTRONIC SA,,,
49171,01/15/15,AUTOGLOBUS 2000 SRL,"1,138.10",,
49171,,,,,
2024194PJ,01/08/1... | -1 | 2016-08-03T21:46:31Z | 38,755,048 | <p>You should look at the built-in <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv module</a> to load the csv data, and then just loop through the lines and filter out the ones you want.</p>
| -1 | 2016-08-03T23:08:08Z | [
"python",
"csv"
] |
Python keyboard events without GUI (non-blocking) | 38,754,175 | <p>I am trying to find a way to get KeyDown and KeyUp events in Python. With Pygame, this is easily done with <code>pygame.KEYDOWN</code> and <code>pygame.KEYUP</code>, but I am trying to find a way to do it without using a GUI.</p>
<p>Ideally, I would like to be able to define a function <code>isKeyDown(key)</code>, ... | 0 | 2016-08-03T21:47:36Z | 38,754,863 | <p>It looks like what you want to do is get <a href="https://pypi.python.org/pypi/pyHook" rel="nofollow">pyhook</a>. I believe it depends on the <a href="https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/" rel="nofollow">pywin32</a> library.</p>
<p>Basically what you want to do is look for creating a ... | 0 | 2016-08-03T22:47:18Z | [
"python",
"windows",
"python-3.x"
] |
Changing Edges to match angles | 38,754,184 | <p>I'm scripting in python and I'm very new to this, and don't have a lot of experience with vector math, I can get dot product, length, and angle of two vectors, and I've managed to get the angle of difference between the two points (an edge), but I'm not sure about the math/process of actually modifying the second se... | 1 | 2016-08-03T21:48:09Z | 38,754,866 | <p>Define a new function called rotate:</p>
<pre><code>def rotate(v,ang):
result =[v[0]*math.cos(ang)-v[1]*math.sin(ang),v[0]*math.sin(ang)+v[1]*math.cos(ang)]
return result
# So to rotate a given vector,lets take your example
p1,p2 = (1,1),(-2,-2)
p3,p4 = (-1,1),(-3,3)
p1,p2 = (1,1),(-2,-2)
p3,p4 = (-1,1),(... | 0 | 2016-08-03T22:47:36Z | [
"python",
"math",
"rotation"
] |
drawing gaussian random variables using scipy erfinv | 38,754,423 | <p>I would like to draw <em>npts</em> random variables distributed as a gaussian with mean <em>mu</em> and dispersion <em>sigma</em>. I know how to do this in Numpy:</p>
<pre><code>x = np.random.normal(loc=mu, scale=sigma, size=npts)
print(np.std(x), np.mean(x))
0.1998, 0.3997
</code></pre>
<p>This should also be pos... | 0 | 2016-08-03T22:05:57Z | 38,754,558 | <p>The best approach would probably be an own implementation of highly-optimized gaussian-samplers like:</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/Marsaglia_polar_method" rel="nofollow">polar-method</a></li>
<li><a href="https://en.wikipedia.org/wiki/Ziggurat_algorithm" rel="nofollow">ziggurat</a></li>
<li><... | 2 | 2016-08-03T22:16:18Z | [
"python",
"numpy",
"random",
"scipy",
"scientific-computing"
] |
drawing gaussian random variables using scipy erfinv | 38,754,423 | <p>I would like to draw <em>npts</em> random variables distributed as a gaussian with mean <em>mu</em> and dispersion <em>sigma</em>. I know how to do this in Numpy:</p>
<pre><code>x = np.random.normal(loc=mu, scale=sigma, size=npts)
print(np.std(x), np.mean(x))
0.1998, 0.3997
</code></pre>
<p>This should also be pos... | 0 | 2016-08-03T22:05:57Z | 38,754,777 | <p>Try this:</p>
<pre><code>mean = 100
sigma = 7
x = mean + 2**0.5 * sigma * erfinv(np.random.uniform(size=10**5) * 2 - 1)
x.mean(), x.std()
Out: (99.965915366042381, 7.0062395839075107)
</code></pre>
<p><a href="http://i.stack.imgur.com/t3ow5.png" rel="nofollow"><img src="http://i.stack.imgur.com/t3ow5.png" alt="ent... | 4 | 2016-08-03T22:37:59Z | [
"python",
"numpy",
"random",
"scipy",
"scientific-computing"
] |
pip.main() resetting logging settings in python | 38,754,432 | <p>It seems that if I call <code>pip.main()</code> in my code my logging settings get reset.</p>
<p>Working example:</p>
<pre><code>import logging
import pip
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.debug("Test")
# prints 'DEBUG:root:Test'
pip.main(["install", "requests"])
# prints pip o... | 0 | 2016-08-03T22:06:31Z | 38,774,175 | <p>The <code>install</code> command of <code>pip</code> overwrites the logging configuration. You need to reset the configuration yourself afterwards, e.g. by doing</p>
<pre><code>logger.setLevel(logging.DEBUG)
</code></pre>
<p>again after the <code>pip.main()</code> call. Note that you may also have to add handlers,... | 0 | 2016-08-04T17:49:06Z | [
"python",
"logging",
"pip"
] |
pip.main() resetting logging settings in python | 38,754,432 | <p>It seems that if I call <code>pip.main()</code> in my code my logging settings get reset.</p>
<p>Working example:</p>
<pre><code>import logging
import pip
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logging.debug("Test")
# prints 'DEBUG:root:Test'
pip.main(["install", "requests"])
# prints pip o... | 0 | 2016-08-03T22:06:31Z | 38,777,502 | <p>It turns out that this is a <a href="https://github.com/pypa/pip/issues/3043#issuecomment-237476013" rel="nofollow">known issue</a> in the <a href="https://github.com/pypa/pip" rel="nofollow">pip module</a>. </p>
<p>This is because when pip was created it was not intended to be imported into other programs, therefo... | 0 | 2016-08-04T21:13:38Z | [
"python",
"logging",
"pip"
] |
Program output is not as expected - Searching for int values in a list of tuples | 38,754,478 | <p>I am coding a function which takes a search enquiry for a list of tuples (Employee records) and then outputs based on the enquiry parameters. For example, in my problem I am searching a salary range with a minimum of 30000 and a maximum of 100000, I would expect this to output the names of staff members within this ... | 0 | 2016-08-03T22:09:51Z | 38,754,582 | <p>I think your program exits after the first tuple is processed. Is the first tuple outside of the salary range? If so, it skips the if statement and goes to the elif. querFound is still false and x is still 0, so it prints and exits.</p>
<hr>
<p>My suggestion is to replace your entire while loop with this for loop:... | 1 | 2016-08-03T22:19:03Z | [
"python",
"list",
"python-3.x",
"indexing",
"tuples"
] |
Efficient data sampling with sparse timestamps on a pre-defined date range | 38,754,493 | <p>Consider a dataframe with sparse temporal data. The timestamps can be very old (e.g. years ago) or very recent.</p>
<p>As an example, let's take the following dataframe:</p>
<pre><code> tstamp item_id budget
2016-07-01 14:56:51.882649 0Szr8SuNbY 5000.00
2016-07-20 14:57:23.856878 0Szr8S... | 0 | 2016-08-03T22:10:33Z | 38,754,772 | <p>You can do a <code>groupby</code> on <code>'item_id'</code> and call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> on each group:</p>
<pre><code># Define the new time interval.
new_dates = pd.date_range('2016-07-15', '2016-07-31... | 1 | 2016-08-03T22:37:19Z | [
"python",
"pandas",
"numpy",
"resampling"
] |
AWS Unable to import module 'app' : no module named Pymysql | 38,754,595 | <p>I am using the AWS Console and trying to add data to a MySQL table using a Lambda function. Whenever I try to test the function, I get the following error: </p>
<blockquote>
<p>Unable to import module 'app' : no module named pymysql</p>
</blockquote>
<p>Its acting like pymysql is not in the path. I went into the... | 0 | 2016-08-03T22:19:56Z | 38,754,838 | <p>You must package all your project dependency in your deployment.</p>
<ol>
<li>Copy from your virtual environment the package PyMysql, to the
root of directory where your code lives. </li>
<li><p>Create a zip, and upload it to lambda function</p>
<p>See the <a href="http://docs.aws.amazon.com/es_es/lambda/latest/d... | 0 | 2016-08-03T22:44:39Z | [
"python",
"amazon-web-services",
"import",
"pymysql"
] |
Separating multiple query results | 38,754,667 | <p>I am running multiple (about 60) queries in impala using impala shell from a file and outputting to a file. I am using :</p>
<pre><code>impala-shell -q "query_here; query_here; etc;" -o output_path.csv -B --output_delimiter=','
</code></pre>
<p>The issue is that they are not separated between queries, so query 2 w... | 0 | 2016-08-03T22:26:42Z | 39,276,579 | <p>You could insert your own separators by issuing some extra queries, for example <code>select '-----';</code> between the real queries.</p>
<p>Writing results of individual queries to local files is not yet possible, but there is already a feature request for it (<a href="https://issues.cloudera.org/browse/IMPALA-20... | 0 | 2016-09-01T16:27:39Z | [
"python",
"sql",
"impala"
] |
Plane fitting in a 3d point cloud | 38,754,668 | <p>I am trying to find planes in a 3d point cloud, using the regression formula <a href="https://en.wikipedia.org/wiki/Plane_(geometry)" rel="nofollow">Z= a<em>X + b</em>Y +C</a> </p>
<p>I implemented least squares and ransac solutions,
but the 3 parameters equation limits the plane fitting to 2.5D- the formula can n... | 3 | 2016-08-03T22:26:59Z | 38,770,513 | <p>I think that you could easily use <a href="https://en.wikipedia.org/wiki/Principal_component_analysis" rel="nofollow">PCA</a> to fit the plane to the 3D points instead of regression.</p>
<p>Here is a simple PCA implementation:</p>
<pre><code>def PCA(data, correlation = False, sort = True):
""" Applies Principal Co... | 2 | 2016-08-04T14:42:05Z | [
"python",
"3d",
"geometry",
"computer-vision",
"point-clouds"
] |
SQLAlchemy : random Unique integer? | 38,754,816 | <p>I can do this to set column type to be unique string :</p>
<pre><code> uuid = Column(String, default=lambda: str(uuid.uuid4()), unique=True)
</code></pre>
<p>but I want to generate <strong>random-unique-integer</strong>, not random-unique-string.</p>
<p>any idea how to do that ?</p>
<hr>
<p>uuid.uuid4().int... | 1 | 2016-08-03T22:42:06Z | 38,755,193 | <pre><code>from random import randint
def random_integer():
min_ = 100
max_ = 1000000000
rand = randint(min_, max_)
# possibility of same random number is very low.
# but if you want to make sure, here you can check id exists in database.
from sqlalchemy.orm import sessionmaker
db_session... | 1 | 2016-08-03T23:26:33Z | [
"python",
"random",
"sqlalchemy",
"unique",
"identifier"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.