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
How to remove an item from a list if its in one or two (or N) other lists
37,867,126
<p>I have a parent list called <code>parent_list</code>, and two subsets via which I'm to filter the <code>parent_list</code>. These subsets are also python lists, and they're called <code>filter1</code> and <code>filter2</code>.</p> <p>Can I do:</p> <pre><code>final_list = [object for object in parent_list if object...
3
2016-06-16T18:46:48Z
37,867,236
<p>You can also use:</p> <pre><code>final_list = [object for object in parent_list if object.pk not in filter1+filter2] </code></pre>
1
2016-06-16T18:53:10Z
[ "python", "list-comprehension" ]
How to remove an item from a list if its in one or two (or N) other lists
37,867,126
<p>I have a parent list called <code>parent_list</code>, and two subsets via which I'm to filter the <code>parent_list</code>. These subsets are also python lists, and they're called <code>filter1</code> and <code>filter2</code>.</p> <p>Can I do:</p> <pre><code>final_list = [object for object in parent_list if object...
3
2016-06-16T18:46:48Z
37,867,390
<p>Use sets for fast look up of the items:</p> <pre><code>final_list = [object for object in parent_list if object.pk not in set(filter1 + filter2)] # ^ </code></pre> <p>The size of the entire search space is also reduced as duplicate items are remove...
5
2016-06-16T19:00:28Z
[ "python", "list-comprehension" ]
In numpy, what does selection by [:,None] do?
37,867,354
<p>I'm taking the Udacity course on deep learning and I came across the following code:</p> <pre><code>def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == label...
2
2016-06-16T18:58:33Z
37,867,542
<p><a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html">http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html</a></p> <blockquote> <p>numpy.newaxis</p> <p>The newaxis object can be used in all slicing operations to create an axis of length one. :const: newaxis is an alias for ‘Non...
5
2016-06-16T19:10:16Z
[ "python", "numpy" ]
In numpy, what does selection by [:,None] do?
37,867,354
<p>I'm taking the Udacity course on deep learning and I came across the following code:</p> <pre><code>def reformat(dataset, labels): dataset = dataset.reshape((-1, image_size * image_size)).astype(np.float32) # Map 0 to [1.0, 0.0, 0.0 ...], 1 to [0.0, 1.0, 0.0 ...] labels = (np.arange(num_labels) == label...
2
2016-06-16T18:58:33Z
37,867,583
<p><code>None</code> is an alias for <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis" rel="nofollow">NP.newaxis</a>. It creates an axis with length 1. This can be useful for matrix multiplcation etc.</p> <pre><code>&gt;&gt;&gt;&gt; import numpy as NP &gt;&gt;&gt;&gt; a = NP.arang...
3
2016-06-16T19:12:18Z
[ "python", "numpy" ]
PyQt - trigger an event when nothing is selected in a QListWidget?
37,867,392
<p>I have an object of type QListWidget where the user can select 0 or more items. </p> <p>If nothing is selected, how can i trigger an event that would call a function? I know that you can detect clicking on a specific item by using:</p> <pre><code>QListWidget.itemClicked.connect(self.item_click) </code></pre> <p>I...
0
2016-06-16T19:00:32Z
37,868,608
<p>Generally, you would connect to the <code>itemSelectionChanged</code> signal and then check whether anything is selected. </p> <pre><code>self.listwidget.itemSelectionChanged.connect(self.on_selection_changed) def on_selection_changed(self): if not self.listwidget.selectedItems(): # Do Stuff Here ...
1
2016-06-16T20:14:45Z
[ "python", "pyqt" ]
how to search a number using binary search algorithm (without implementing any function) in python
37,867,530
<p>Below is my complete code for binary search written in python3 version. I was able to:-i) create a list, ii) sorted the list using bubble sort algorithm, iii)wrote code snippet for searching a number using binary search, But while searching for any number (which is present/not present in the list), my code goes int...
0
2016-06-16T19:09:26Z
37,867,695
<p>The infinite loop is from the line</p> <pre><code>low=mid+1 </code></pre> <p>I think what you meant was</p> <pre><code>last=mid+1 </code></pre> <p>The error was that the case <code>list[mid]&lt;target</code> would happen, but since <code>low</code> is being changed not <code>last</code>, <code>mid</code> never c...
1
2016-06-16T19:19:36Z
[ "python", "algorithm", "search", "binary" ]
How to read data only between two lines in python using numpy or pandas?
37,867,657
<p>I have a datafile like this: </p> <pre><code># column 1 is the angle of incidence (degrees) # column 2 is the wavelength (microns) # column 3 is the transmission probability # column 4 is the reflection probability 14.2000 0.300000 0.01 0.999920 14.2000 0.301000 0.02 0.999960 14...
3
2016-06-16T19:16:12Z
37,868,044
<p>If your goal is to maintain the appearance of the written file (i.e., the line spacing is the same), then you'll likely need to keep the original file's contents.</p> <pre><code>from io import StringIO contents = open(infile).read() df = pd.read_csv(StringIO(contents), sep='\s+', header = None,skiprows = 0, ...
3
2016-06-16T19:39:42Z
[ "python", "numpy", "pandas" ]
How to read data only between two lines in python using numpy or pandas?
37,867,657
<p>I have a datafile like this: </p> <pre><code># column 1 is the angle of incidence (degrees) # column 2 is the wavelength (microns) # column 3 is the transmission probability # column 4 is the reflection probability 14.2000 0.300000 0.01 0.999920 14.2000 0.301000 0.02 0.999960 14...
3
2016-06-16T19:16:12Z
37,868,088
<p>I'd skip pandas or numpy altogether</p> <pre><code>fo = open('filter_3.txt', 'w') with open('filter_2.txt', 'r') as fi: line = fi.readline() while line: split = line.split() if (split[0] == '#') or (float(split[2]) &gt;= 0.027): print line, fo.write(line) lin...
3
2016-06-16T19:42:30Z
[ "python", "numpy", "pandas" ]
How to read data only between two lines in python using numpy or pandas?
37,867,657
<p>I have a datafile like this: </p> <pre><code># column 1 is the angle of incidence (degrees) # column 2 is the wavelength (microns) # column 3 is the transmission probability # column 4 is the reflection probability 14.2000 0.300000 0.01 0.999920 14.2000 0.301000 0.02 0.999960 14...
3
2016-06-16T19:16:12Z
37,868,337
<p>IIUC, you can do it this way:</p> <pre><code>In [51]: df[df.ix[df.trans &gt;= 0.05, 'trans'].index.min() : df.ix[df.trans &gt;= 0.05, 'trans'].index.max() + 1] Out[51]: angle wave trans refl 4 14.2 0.304 0.06 0.99998 5 14.2 0.305 0.08 0.99997 6 14.2 0.306 0.20 0.99995 7 14.2 0.30...
3
2016-06-16T19:57:14Z
[ "python", "numpy", "pandas" ]
Docker / Celery: Can't get celery to run
37,867,722
<p>I can't get my celery workers to constantly listen to the default queue. Celery constantly exits.</p> <pre><code>$: docker-compose up Starting tasker_rabbitmq_1 Starting tasker_celery_1 Attaching to tasker_rabbitmq_1, tasker_celery_1 tasker_celery_1 exited with code 1 rabbitmq_1 | rabbitmq_1 | Rabb...
4
2016-06-16T19:20:49Z
39,708,243
<p>1) install celery to python Docker image or use <code>https://hub.docker.com/r/library/celery/</code></p> <p>2) add full adress to rabbitmq with password in row:</p> <p><code>celery = Celery('tasks', broker='amqp://guest:mypass@rabbit//')</code></p>
1
2016-09-26T16:50:01Z
[ "python", "docker", "celery" ]
Appending to a file, then reading from it into a list, then re-appending to it and overwriting certain parts
37,867,747
<p>I want to be able to have a program whereby the user can input a paragraph/sentence/word/character whatever and have that stored in a list e.g. in list[0]. Then I want them to be able to write another bit of text and have that stored in e.g. list[1]. Then at any time I want the user to be able to read that from the ...
0
2016-06-16T19:22:12Z
37,869,739
<p>A quick point of correction:</p> <p><code>global</code> is only required if you're defining a global variable inside a non-global context. In other words, anything defined at the default indentation level, will be accessible by everything else defined below it. For example:</p> <pre><code>def set_global(): x =...
1
2016-06-16T21:37:11Z
[ "python" ]
Can the values from hashlib.sha1 library change between versions of Python?
37,867,766
<p>I am using the hashlib.sha1 library to store file names in Python. e.g.:</p> <pre><code> file_name = hashlib.sha1(url.encode()).hexdigest() </code></pre> <p>Is this library fixed, so that the same term entered would yield the same hash in different versions of Python?</p>
1
2016-06-16T19:23:32Z
37,867,839
<p>As long as there are no bugs that's how a hash function has to work. If the hash would be different you couldn't log in anymore on many webpages since the only store a hash of your password.</p> <p>That being said it could always be possible that there was a bug producing wrong results. On the other hand I guess th...
0
2016-06-16T19:28:06Z
[ "python", "hash", "hashlib" ]
Quick sort not working after the first partition
37,867,825
<p>I am trying to write my first quick sort algorithm for hours, but still not getting it right. The goal is to write a quick sort code for sorting an array. I want to use two functions: recursive function quick_sort, and partition function. </p> <p>I found the partition function seems work correctly on each sub-array...
0
2016-06-16T19:27:07Z
37,867,937
<p>Replace this</p> <pre><code>quicksort(a[:j]) quicksort(a[j+1:]) </code></pre> <p>For </p> <pre><code>quick_sort(a,first,j-1) quick_sort(a,j+1,last) </code></pre> <p>Since you are calling <code>quicksort(a)</code> this willl do again only the first iteration, bc you set the low and high as the first iteration all...
2
2016-06-16T19:33:38Z
[ "python", "quicksort" ]
Suggest a better counting process using Python | Pandas?
37,867,880
<p>I'm using Python and Pandas to pull metrics (inbound calls, abandoned calls, etc.) from our call switch (csv format). The code works well but how I'm calculating the metrics feels kludige and I'm hoping someone can suggest a better way.</p> <p>Data looks like:</p> <pre><code>Date/Time VPSNumber Duration Cal...
0
2016-06-16T19:30:22Z
37,868,339
<p>First filter for inbound calls using a boolean mask <code>df[df.Direction == "» In"]</code>. You can then is <code>loc</code> with <code>isin(...)</code> to located all those inbound calls with an extension in your desired group (e.g. 3, 717 and 726).</p> <pre><code>df = (phone_df.loc['2016-01-01':'2016-05-31']) a...
0
2016-06-16T19:57:18Z
[ "python", "pandas" ]
How do I capture multiple characters with (\s|\S) (i.e. p OR not p)?
37,868,003
<p>I'm trying to parse an email that is being passed to the function looking like this:</p> <pre class="lang-none prettyprint-override"><code>From: Bob Sent: Thursday To: Jack Cc: Mary, Zaphod, Janice, Trillian Subject: Restaurant at the End of the Universe I can't seem to find this on the map, any help? ...
0
2016-06-16T19:37:23Z
37,868,187
<p>You can use non-greedy match to match everything until <code>Subject</code>:</p> <pre class="lang-none prettyprint-override"><code>From:(?:\s){0,}(.*)(?:\s){1,}Sent:(.*)(?:\s){1,}To:(.*)(?:\s){1,}Cc:([\s\S]*?)Subject:(.*)(\s){1,}([\s\S]*) </code></pre> <p><a href="https://regex101.com/r/sQ5nN0/1" rel="nofollow">...
1
2016-06-16T19:47:43Z
[ "python", "regex" ]
How do I capture multiple characters with (\s|\S) (i.e. p OR not p)?
37,868,003
<p>I'm trying to parse an email that is being passed to the function looking like this:</p> <pre class="lang-none prettyprint-override"><code>From: Bob Sent: Thursday To: Jack Cc: Mary, Zaphod, Janice, Trillian Subject: Restaurant at the End of the Universe I can't seem to find this on the map, any help? ...
0
2016-06-16T19:37:23Z
37,869,185
<p>You could probably generalize it a bit more and do some trimming all at once.<br> I added named groups, but you could remove them, or change to the <code>(?P&lt;&gt;)</code> Python form. </p> <pre><code>From:\s*\s*(?&lt;From&gt;.*?)\s+Sent:\s*(?&lt;Sent&gt;.*?)\s+To:\s*(?&lt;To&gt;[\S\s]*?)\s+Cc:\s*(?&lt;Cc&gt;[\S...
1
2016-06-16T20:54:47Z
[ "python", "regex" ]
How do I add an option in django model choice through template
37,868,084
<p>I am Learning Django and i need to allow users of the app to be able to add more options to the item_name field through the template but i don't have an idea on how to achieve that. Thanks for the help. </p> <p><strong>Here is my model</strong></p> <pre><code>class ItStore(models.Model): type_choice = ( ...
1
2016-06-16T19:42:11Z
37,869,417
<p>You could not define <code>choices=</code> on your model. But instead define a list of default choices outside of the model. </p> <pre><code>my_choices = ( "foo", "bar", "pop", ) class MyModel(models.Model): my_field = models.CharField(max_length=100) </code></pre> <p>Then in your view you'd want t...
1
2016-06-16T21:11:50Z
[ "python", "django", "django-models", "django-templates" ]
overlapping dates between two date ranges in python
37,868,117
<p>I'm looking to find overlapping dates between two dates ranges as the following:</p> <pre><code>range1 = start(2016-06-01) end (2016-06-20) range2 = start(2016-06-10) end (2016-06-13) </code></pre> <p>result here is 4 dates <code>(2016-06-10,2016-06-11,2016-06-12,2016-06-13)</code>. another example:</p> <pre><cod...
5
2016-06-16T19:44:27Z
37,868,598
<p>When you're not working with Python3 yet and thus cannot make use of the memory efficient <code>range</code> objects, you could make a namedtuple as shown in <a href="https://stackoverflow.com/a/9044111/2476444">the answer you link to</a> (otherwise you could just as well use the new <code>range</code> objects). Fro...
1
2016-06-16T20:14:06Z
[ "python", "date", "date-range" ]
overlapping dates between two date ranges in python
37,868,117
<p>I'm looking to find overlapping dates between two dates ranges as the following:</p> <pre><code>range1 = start(2016-06-01) end (2016-06-20) range2 = start(2016-06-10) end (2016-06-13) </code></pre> <p>result here is 4 dates <code>(2016-06-10,2016-06-11,2016-06-12,2016-06-13)</code>. another example:</p> <pre><cod...
5
2016-06-16T19:44:27Z
37,869,871
<p>I would suggest generating the dates in each of both ranges, then selecting the intersection between the two set. A snipped doing so may look like this:</p> <pre><code>from datetime import date, timedelta def f(d1, d2): delta = d2 - d1 return set([d1 + timedelta(days=i) for i in range(delta.days + 1)]) r...
1
2016-06-16T21:47:18Z
[ "python", "date", "date-range" ]
reference functions to array slices in python
37,868,129
<p>Is the following was possible in python?</p> <p>(I am pretty new to python, not sure what the appropriate search term would be)</p> <p>I have a class that stores and manipulates a large numpy array. Now I would like to access parts of this array via an alias 'reference function'</p> <p>Here is a dummy example for...
0
2016-06-16T19:45:02Z
37,868,375
<blockquote> <p>is there a simpler way to use just one function to refer to the parts of the array M that would work for both getting and setting values?</p> </blockquote> <p>Yes, and you've written it. It is your <code>get</code> function:</p> <pre><code>initialData=t.get_second_row() t.get_second_row()[:] = np.ra...
0
2016-06-16T19:59:49Z
[ "python", "arrays", "numpy" ]
Python - print link.get href - print output url only separated by commas
37,868,130
<p>I want to separate the url with commas,</p> <p>code :</p> <pre><code>for link in v.find_all('a'): print (link.get('href')) </code></pre> <p>output :</p> <pre><code>xxxx@xxxx-K43U:~/Desktop$ python p.py https://ecs7.tokopedia.net/img/product-1/2016/1/28/22599505/22599505_ab305ff4-e19f-489e-bcdc-113aeb7581ea.j...
1
2016-06-16T19:45:02Z
37,868,215
<p>Use <a href="https://docs.python.org/2/library/stdtypes.html#str.join" rel="nofollow"><code>str.join()</code></a>:</p> <pre><code>print(','.join([link.get('href') for link in v.find_all('a')]) </code></pre> <p>Note that if you want to dump the URLs into a file, you should better use the <a href="https://docs.pytho...
2
2016-06-16T19:49:52Z
[ "python", "beautifulsoup" ]
Converting a scapy packet to string produces an E?
37,868,201
<p>I'm currently working on using scapy for sending data packets, and I've run into a weird issue. When I create a packet as such:</p> <pre><code>pack = IP(dst="127.0.0.1", id=local_ID)/UDP()/chunk </code></pre> <p>and then convert that packet to a string (so I can send it via a socket)</p> <pre><code>sendPack = str...
0
2016-06-16T19:49:03Z
37,876,322
<p>First, you are printing a packet, not the content of your UDP datagram. The first two fields of an IPv4 packet are version and IHL which values are respectively 4 (for IP version 4) and 5 (5 words of 32 bits) by default in Scapy. This gives 45 if you put it on one byte in hexadecimal which is letter "E" in ascii. Th...
0
2016-06-17T08:07:34Z
[ "python", "string", "sockets", "scapy" ]
Converting a scapy packet to string produces an E?
37,868,201
<p>I'm currently working on using scapy for sending data packets, and I've run into a weird issue. When I create a packet as such:</p> <pre><code>pack = IP(dst="127.0.0.1", id=local_ID)/UDP()/chunk </code></pre> <p>and then convert that packet to a string (so I can send it via a socket)</p> <pre><code>sendPack = str...
0
2016-06-16T19:49:03Z
37,884,787
<p>To those interested, I fixed the issue by doing the following:</p> <p>As pointed out above, the E was a result of me printing the packet, not it's contents. In order to access the contents I wanted, I had to do the following:</p> <pre><code>sendPack = pack[UDP].load #Get the packet's load at the UDP layer id...
0
2016-06-17T15:01:30Z
[ "python", "string", "sockets", "scapy" ]
Z3 Optimization, strict inqualities
37,868,251
<p>I'm having a problem which was referred to before where I do not quite get the solution (combining substitute with simplify). In my encoding, I have strict inequalities and I would need to set the epsilon either to 0 or to a very small value. For instance, I have the following simplified Python code:</p> <pre><code...
2
2016-06-16T19:52:03Z
37,945,788
<p><strong>Premise</strong>:</p> <ol> <li><p>I assume that you simply want a model in which <code>p</code> <em>approaches 1</em> with <em>a fixed precision</em>.</p></li> <li><p>In <a href="https://stackoverflow.com/questions/26061619/z3-maximization-api-possible-bug">this answer</a> N.B. states <strong>(emphasis is m...
0
2016-06-21T13:26:46Z
[ "python", "z3", "z3py" ]
How to get a left and right frame to fill in TKinter?
37,868,371
<p>I'm trying to make a window that has two half-window frames on either side, but I can't get them to fill. I need the two frames to take up half of the width and all of the height of the window, no matter the size of their contents. I've set up a grid layout, but the two frames aren't expanding to fill their size. He...
-1
2016-06-16T19:59:28Z
37,869,759
<p>You need to use the <code>sticky</code> attribute so that the frames stick to the sides of the space allocated to them.</p> <pre><code>... viewerPane.grid(row=0,column=0, sticky="nsew") actionPane.grid(row=0,column=1, sticky="nsew") ... </code></pre>
0
2016-06-16T21:38:42Z
[ "python", "tkinter", "grid-layout" ]
python pandas - simultaneously map and insert column to specific index
37,868,379
<p>In pandas, is it possible to simultaneously map and insert a new column to a specific index/place in a dataframe?</p> <p>I can get the mapping to work (from a multi key dictionary), successfully creating a new column at the end of my dataframe.</p> <pre><code>#using multi_key_dict https://pypi.python.org/pypi/mult...
1
2016-06-16T20:00:03Z
37,886,147
<p>I did the reorder/sort after the mapping and insert, using...</p> <p>Original column order: <code>['col1', 'col2', 'col3']</code></p> <p>Reordered using: <code>df = df[['col3', 'col2', 'col1']]</code></p>
0
2016-06-17T16:19:44Z
[ "python", "pandas", "ipython" ]
In python argparse, is there a use case for nargs=1?
37,868,384
<p>It seems as though it would always make more sense to use the default action of <code>store</code> without specifying <code>nargs</code> so the output is always as expected, instead of sometimes being a <code>list</code> and sometimes not. I'm just curious if I missed something..</p> <p>example</p> <pre><code>&gt;...
2
2016-06-16T20:00:14Z
37,868,918
<p>Both the default <code>nargs=None</code> and <code>nargs=1</code> expect one value, but <code>nargs=1</code> will put it in a list, e.g.</p> <pre><code>Namespace(foo='test') Namespace(foo=['test']) </code></pre> <p><code>nargs=3</code> will require 3 values, and put them in a list as well. <code>*</code> and <cod...
3
2016-06-16T20:37:27Z
[ "python", "argparse" ]
In python argparse, is there a use case for nargs=1?
37,868,384
<p>It seems as though it would always make more sense to use the default action of <code>store</code> without specifying <code>nargs</code> so the output is always as expected, instead of sometimes being a <code>list</code> and sometimes not. I'm just curious if I missed something..</p> <p>example</p> <pre><code>&gt;...
2
2016-06-16T20:00:14Z
37,937,919
<p>The case for nargs=1 for me is that I can use it with the "append" action, then if I want to use the option once, I get a list of one item, if I use it twice, I get a list of two items, etc.</p>
0
2016-06-21T07:19:57Z
[ "python", "argparse" ]
BMI Calculator Not letting a converter pick one or the other
37,868,391
<p>I am making a BMI calculator and I am trying to add a converter into the code for people who don't know their SI proportions. The problem is the way I want to write this is if you know your SI you just press enter and it will ask you for the SI preferences.</p> <pre><code>print("\n") print(" -------------------...
-3
2016-06-16T20:00:56Z
37,873,907
<p>You could declare w1 and h1 as globals, and check user input for empty string with the != (not equal) comparison. Take a look at <a href="https://docs.python.org/release/2.5.2/lib/comparisons.html" rel="nofollow">comparison operators</a>. </p> <p><code>if c1 != '': global w1, h1 f1=float(c1) w1=f1*.4565...
0
2016-06-17T05:39:40Z
[ "python", "loops", "python-3.x" ]
Python (Excel, dictionary) how to write it shorter
37,868,413
<p>I wrote a program that is too long and I'm sure that I can write it shorter.</p> <p>This is a function that export values from Excel:</p> <pre><code>#"place" is a place where I have Excel file "book1.xlsx" place=os.path.join(DATA_DIR,'book1.xlsx') Excel=win32com.client.Dispatch('Excel.Application') wb=Excel.Workb...
0
2016-06-16T20:02:14Z
37,871,119
<p>Since I have no Excel installed, I've converted your file to <a href="https://www.dropbox.com/s/vmcvhc5a5ciiqmv/sheet1.csv?dl=1" rel="nofollow">csv</a>, and wrote a simple parser, which returns table headers and a dictionary with every header and it's values. I hope, this is a good starting point, since you can do w...
1
2016-06-16T23:51:44Z
[ "python", "excel", "dictionary", "compact" ]
accept ssl cert with marionette firefox webdrive python splinter
37,868,425
<p>when using python splinter firefox 47 marionette new webdriver, it gives certificate error when access the website i want, i tried to accept ssl certs with </p> <p>browser = Browser('firefox', capabilities = {'marionette': True, 'acceptSslCerts': True})</p> <p>or using trustAllSSLCertificates instead of acceptSsl...
0
2016-06-16T20:02:52Z
37,974,837
<p>I am also facing this issue. </p> <p>This has been acknowledged as a bug. <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1103196" rel="nofollow">https://bugzilla.mozilla.org/show_bug.cgi?id=1103196</a></p> <p>There may be a workaround I havent tried it yet. <a href="http://stackoverflow.com/questions/143500...
0
2016-06-22T17:38:50Z
[ "python", "selenium", "firefox", "webdriver", "splinter" ]
Time-Efficient Wide to Long Conversion Pandas
37,868,453
<p>I have an dataset of around 54 million rows that I need to read from a tab-delimited text file, convert from wide to long format, and write to a new text file. The data is too large to fit in memory, so I've been using iterators. There are three separate variables that I want to move from wide to long, so I have b...
1
2016-06-16T20:05:02Z
37,870,124
<p><code>pandas</code> csv parser is really fast, but you might try a pure python solution, because pandas is doing a bunch of things you don't really care about (type inference &amp; conversion, all the join alignment, indexing, etc).</p> <p>This is a just a start, but here's a very simple wide-to-long example. You'...
2
2016-06-16T22:05:55Z
[ "python", "performance", "numpy", "pandas", "bigdata" ]
Shell Code executes directly, but not in PythonScript
37,868,508
<p>I wrote a little <strong>Python</strong> function that uses the <strong>BeatifulSoup</strong> libary. The function should return a list of symbols from a <strong>Wikipedia</strong> article.</p> <p>In the Shell, I execute the function like this: </p> <pre><code>pythonScript.my_function() </code></pre> <p>...it th...
1
2016-06-16T20:08:26Z
37,870,204
<p>You have passed a link with a <code>htttp</code>, i.e you have three t when there should be just two, that code would error wherever you run it. The correct url is:</p> <pre><code>http://en.wikipedia.org/wiki/list_of_S%26P_500_companies </code></pre> <p>Once you fix the url the request works fine:</p> <pre><code>...
0
2016-06-16T22:12:27Z
[ "python", "function", "shell", "beautifulsoup", "bs4" ]
Heroku node.js and Flask application working locally but not in server
37,868,711
<p>I have a web application which uses node.js and communicates with a Flask application to retrieve some configurations and send jobs to the back-end. The Flask returns a JSON with the information </p> <p>Flask file (REST.PY):</p> <pre><code>from flask import Flask, jsonify, request, redirect, url_for import subproc...
0
2016-06-16T20:22:36Z
37,932,969
<p>You dont know the heroku server port used that's a problem. It won't be 9000. You need to be able to get the heroku app port if it exists and take this in consideration or use a default port.</p> <p>Sorry for posting as an answer I missclicked...</p>
0
2016-06-20T22:42:30Z
[ "javascript", "python", "node.js", "heroku", "flask" ]
Heroku node.js and Flask application working locally but not in server
37,868,711
<p>I have a web application which uses node.js and communicates with a Flask application to retrieve some configurations and send jobs to the back-end. The Flask returns a JSON with the information </p> <p>Flask file (REST.PY):</p> <pre><code>from flask import Flask, jsonify, request, redirect, url_for import subproc...
0
2016-06-16T20:22:36Z
37,937,363
<p>If you are running a web dyno then heroku needs to be able to connect to it within 60s or it assumes that it isn't working and shuts down the dyno. The port heroku uses isn't set so you need to grab the port from the dynos environment I had the same error when starting out as you have no control over what port herok...
0
2016-06-21T06:51:15Z
[ "javascript", "python", "node.js", "heroku", "flask" ]
Converting RSA encryption code from php to python
37,868,717
<p>I'm trying to connect to a api in my python app . so the api documentations comes with php and asp sample code but no python </p> <p>I'm pretty good with php but have no experience with encryption ... I'm trying to re-write python code for the api using php sample .</p> <p>They use this class for RSA</p> <pre><co...
0
2016-06-16T20:22:59Z
37,882,229
<blockquote> <p>They use this class for RSA</p> <pre><code>https://github.com/AlaFalaki/Pclass/blob/master/libraries/rsa.class.php </code></pre> </blockquote> <p>My advice: Run away screaming.</p> <p>RSA is a mine field of security issues. There are a lot of things that you can screw up. So when someone <em>implem...
1
2016-06-17T13:00:52Z
[ "php", "python", "django", "encryption", "rsa" ]
Animation problems persist
37,868,724
<h1>The code</h1> <pre><code>#Importing files/modules import pygame import random #Colors BLACK = ( 0, 0, 0) WHITE = ( 255, 255, 255) GREEN = ( 0, 255, 0) RED = ( 255, 0, 0) ORANGe = (255, 115, 0) YELLOW = (242, 255, 0) BROWN = (115, 87, 39) PURPLE = ( 298, 0, 246) GRAY = ( 168, 168, 168) BLUE = ( 0, 0, 255) GROUND ...
0
2016-06-16T20:23:24Z
37,872,507
<p>Ok I solved it. Turns out due to the amount of events, I had to increment the last image by 2000 not 1000. So c and d need to be added by 2000 not 1000.</p>
0
2016-06-17T03:13:40Z
[ "python", "animation", "pygame" ]
List of dicts: Getting list of matching dictionary based on id
37,868,733
<p>I'm trying to get the matching IDs and store the data into one list. I have a list of dictionaries:</p> <pre><code>list = [ {'id':'123','name':'Jason','location': 'McHale'}, {'id':'432','name':'Tom','location': 'Sydney'}, {'id':'123','name':'Jason','location':'Tompson Hall'} ...
0
2016-06-16T20:24:26Z
37,868,826
<p>Given this input</p> <pre><code>mylist = [ {'id':'123','name':'Jason','location': 'McHale'}, {'id':'432','name':'Tom','location': 'Sydney'}, {'id':'123','name':'Jason','location':'Tompson Hall'} ] </code></pre> <p>You can just extract it with a comprehension</p> <pre><co...
1
2016-06-16T20:31:24Z
[ "python", "dictionary" ]
List of dicts: Getting list of matching dictionary based on id
37,868,733
<p>I'm trying to get the matching IDs and store the data into one list. I have a list of dictionaries:</p> <pre><code>list = [ {'id':'123','name':'Jason','location': 'McHale'}, {'id':'432','name':'Tom','location': 'Sydney'}, {'id':'123','name':'Jason','location':'Tompson Hall'} ...
0
2016-06-16T20:24:26Z
37,868,978
<p>First, you're iterating through the list of dictionaries in your for loop, but never referencing the dictionaries, which you're storing in <code>item</code>. I think when you wrote <code>list[id]</code> you mean <code>item[id]</code>.</p> <p>Second, <code>any()</code> returns a boolean (true or false), which isn't ...
1
2016-06-16T20:41:55Z
[ "python", "dictionary" ]
List of dicts: Getting list of matching dictionary based on id
37,868,733
<p>I'm trying to get the matching IDs and store the data into one list. I have a list of dictionaries:</p> <pre><code>list = [ {'id':'123','name':'Jason','location': 'McHale'}, {'id':'432','name':'Tom','location': 'Sydney'}, {'id':'123','name':'Jason','location':'Tompson Hall'} ...
0
2016-06-16T20:24:26Z
37,869,461
<p>I would use kdopen's approach along with a merging method after converting the dictionary entries I expect to become lists into lists. Of course if you want to avoid redundancy then make them sets.</p> <pre><code>mylist = [ {'id':'123','name':['Jason'],'location': ['McHale']}, {'id':'432','...
1
2016-06-16T21:15:26Z
[ "python", "dictionary" ]
Retrieve Django ManyToMany results outside of the current model
37,868,817
<p>Hi I'm brand new to Django.</p> <ul> <li>I have a list of <strong>stores</strong>. Each of those stores carry <strong>brands</strong> of products.</li> <li>For a store, I can list the brands that they carry. </li> <li><strong>For a brand, I want to list the stores that carry that brand.</strong></li> </ul> <p>Here...
1
2016-06-16T20:30:52Z
37,869,014
<p>Many-to-Many relationships are mutual. So stores can be seen from brands and vice-versa.</p> <p>You can use <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#prefetch-related" rel="nofollow"><code>prefetch_related</code></a> to minimize the number of DB queries that will be required to do this:</...
3
2016-06-16T20:44:31Z
[ "python", "django" ]
Retrieve Django ManyToMany results outside of the current model
37,868,817
<p>Hi I'm brand new to Django.</p> <ul> <li>I have a list of <strong>stores</strong>. Each of those stores carry <strong>brands</strong> of products.</li> <li>For a store, I can list the brands that they carry. </li> <li><strong>For a brand, I want to list the stores that carry that brand.</strong></li> </ul> <p>Here...
1
2016-06-16T20:30:52Z
37,869,333
<p>I think I've found a solution online, not sure if it's perfect but it's working for me:</p> <pre><code>class Store(models.Model): brands = models.ManyToManyField('Brand', blank=True) class Brand(models.Model): stores = models.ManyToManyField('Store', through=Store.brands.through, blank=True) </code></pre>
-1
2016-06-16T21:05:00Z
[ "python", "django" ]
How to search and replace text in an XML file using Python?
37,868,881
<p>How do I search an entire <strong>xml</strong> file for a specific text pattern and then replace each occurrence of that text with new text pattern in Python 3.5? </p> <p>Everything else (format, attributes, comments, etc.) needs to remain as it is in the original xml file.</p> <p>I am running Python 3.5.1 on Win...
1
2016-06-16T20:34:47Z
37,881,638
<p>Caveats:</p> <ul> <li>I have never worked with the <code>xml.etree.ElementTree</code> library</li> <li>I have never worked with it because I never find myself manipulating XML</li> <li>I don't know if this is the "best" way compared to someone that knows the library in and out</li> <li>Commentors seem set on judgin...
1
2016-06-17T12:29:48Z
[ "python", "xml", "search", "replace" ]
Tensorflow reshape tensor
37,868,935
<p>I have a prediction tensor (the actual network) </p> <pre><code>(Pdb) pred &lt;tf.Tensor 'transpose_1:0' shape=(?, 200, 200) dtype=float32&gt; </code></pre> <p>and a y tensor</p> <pre><code>y = tf.placeholder("float", [None, n_steps, n_classes]) (Pdb) y &lt;tf.Tensor 'Placeholder_1:0' shape=(?, 200, 200) dtype=f...
2
2016-06-16T20:38:37Z
37,873,120
<p>I'm the author of one of the answers of the other question in Yaroslav's comment. You can use -1 for the None dimension.</p> <hr> <p>You can do it easily with tf.reshape() without knowing the batch size.</p> <pre><code>x = tf.placeholder(tf.float32, shape=[None, 9,2]) shape = x.get_shape().as_list() # a li...
2
2016-06-17T04:25:38Z
[ "python", "machine-learning", "neural-network", "artificial-intelligence", "tensorflow" ]
What is the pythonic way to to resume a loop within a loop
37,868,942
<p>I have an python 2.7 application that I am occasionally interrupting.</p> <p>I am processing a very large data file. To deal with memory constraints, I have divided up the data file into grids that are identified by an x and y components. Each grid is processed independently.</p> <p>It takes a very long time to ...
2
2016-06-16T20:39:12Z
37,869,048
<p>I'm not sure about a more pythonic way, but you could rewrite it like this (in any language really):</p> <pre><code>y_ranges_resume = zip(np.arange(y_start,y_size,y_step),np.arange(y_start+y_step,y_size+y_step,y_step) for x_min,x_max in x_ranges: y_ranges_used = y_ranges if x_min == x_start: y...
3
2016-06-16T20:46:03Z
[ "python", "python-2.7", "for-loop", "resume" ]
What is the pythonic way to to resume a loop within a loop
37,868,942
<p>I have an python 2.7 application that I am occasionally interrupting.</p> <p>I am processing a very large data file. To deal with memory constraints, I have divided up the data file into grids that are identified by an x and y components. Each grid is processed independently.</p> <p>It takes a very long time to ...
2
2016-06-16T20:39:12Z
37,869,151
<p>You could try list comprehension:</p> <pre><code>[[doAction() for y_min,y_max in y_ranges_resume] if x_min == x_start else [doAction() for y_min,y_max in y_ranges] for x_min,xmax in x_ranges] </code></pre> <p>Or you could use a lambda function to simplify the condition</p> <pre><code>correct_y_range = lambda x : ...
2
2016-06-16T20:52:28Z
[ "python", "python-2.7", "for-loop", "resume" ]
How to programmatically define properties in python
37,869,030
<p>I have an object that describes a dataset with multiple required pieces of data and metadata. The different data and metadata elements are themselves objects of the same type with a number of different attributes, including a name and a value attribute. Most of the interactions with these data elements are with the ...
2
2016-06-16T20:45:21Z
37,869,076
<p>In python, there are functions <code>getattr</code> and <code>setattr</code> that can get and set properties of objects. It's used like this:</p> <pre><code>setattr(obj, "prop", value) # set the value getattr(obj, "prop") # get the value </code></pre>
0
2016-06-16T20:47:38Z
[ "python" ]
How to programmatically define properties in python
37,869,030
<p>I have an object that describes a dataset with multiple required pieces of data and metadata. The different data and metadata elements are themselves objects of the same type with a number of different attributes, including a name and a value attribute. Most of the interactions with these data elements are with the ...
2
2016-06-16T20:45:21Z
37,869,096
<p>After trying a lot of things that didn't work, this did:</p> <pre><code>class my_par(object): def __init__(self, name, value): self.name = name self.value = value class my_obj(object): def __init__(self, xval, yval, zval): self.xval = my_par('x', xval) self.yval = my_par...
0
2016-06-16T20:48:45Z
[ "python" ]
How to programmatically define properties in python
37,869,030
<p>I have an object that describes a dataset with multiple required pieces of data and metadata. The different data and metadata elements are themselves objects of the same type with a number of different attributes, including a name and a value attribute. Most of the interactions with these data elements are with the ...
2
2016-06-16T20:45:21Z
37,896,886
<p>Try <a href="https://docs.python.org/3.5/library/collections.html#collections.namedtuple" rel="nofollow">namedtuple</a></p> <pre><code>from collections import namedtuple my_par = namedtuple('par', 'name value') par = my_par('par_name', 'par_value') print(par[0]) #outputs: par_name print(par.value) #outputs: par_va...
0
2016-06-18T12:22:57Z
[ "python" ]
How to replace all the occurences but one in Python
37,869,089
<p>I have a list of integers of length <code>K</code>.</p> <pre><code>a = [0, 0, 0, 1, 1, 5] # length here is 6 </code></pre> <p>I would like to replace all the occurrences of each distinct value in the list by <code>len(a)</code>, except for keeping the last value intact. I have three <code>0</code>, two <code>1</c...
0
2016-06-16T20:48:16Z
37,869,228
<p>Here's one way to do it. Use a dict <code>prev</code> to keep track of the index of the previous seen value. If we've seen it, then change it to 6:</p> <pre><code>a = [0, 0, 0, 1, 1, 5] prev = {} for i in range(len(a)): if a[i] in prev: a[prev[a[i]]] = len(a) prev[a[i]] = i print a </code></pre>
4
2016-06-16T20:58:01Z
[ "python" ]
How to replace all the occurences but one in Python
37,869,089
<p>I have a list of integers of length <code>K</code>.</p> <pre><code>a = [0, 0, 0, 1, 1, 5] # length here is 6 </code></pre> <p>I would like to replace all the occurrences of each distinct value in the list by <code>len(a)</code>, except for keeping the last value intact. I have three <code>0</code>, two <code>1</c...
0
2016-06-16T20:48:16Z
37,869,247
<p>If it doesn't have to be the first element, that you keep, I'd do:</p> <pre><code>seen = [] for i, elm in enumerate(a): if elm in seen: a[i] = len(a) else: seen.append(elm) del seen </code></pre> <p>This yields</p> <pre><code>[0, 6, 6, 1, 6, 5] </code></pre>
1
2016-06-16T20:59:29Z
[ "python" ]
How to replace all the occurences but one in Python
37,869,089
<p>I have a list of integers of length <code>K</code>.</p> <pre><code>a = [0, 0, 0, 1, 1, 5] # length here is 6 </code></pre> <p>I would like to replace all the occurrences of each distinct value in the list by <code>len(a)</code>, except for keeping the last value intact. I have three <code>0</code>, two <code>1</c...
0
2016-06-16T20:48:16Z
37,869,386
<p>Well, if you'd like it in a one-liner:</p> <pre><code>a = [len(a) if val==a[i+1] else val \ for i, val in enumerate(a[:-1])] + [a[-1]] </code></pre> <p>For each element, check to see whether it equals the one after (assumes that <strong>a</strong> has all equal values contiguous in the list). If so, c...
2
2016-06-16T21:09:32Z
[ "python" ]
Raising a FileNotFoundError
37,869,146
<p>I have a function that takes a source file containing times (a csv file), reads it, then sorts the lines in order and writes them in a destination file. However, if the source csv file does not exist, I need to raise a FileNotFoundError. I've raised exceptions before, for example, if a parameter wasn't an integer I ...
1
2016-06-16T20:52:18Z
37,869,195
<p>If the specified file is not found, the <code>FileNotFoundError</code> will be raised automatically by the <code>open</code> call when trying to open the file.</p>
3
2016-06-16T20:55:32Z
[ "python", "csv", "exception", "filenotfoundexception" ]
Raising a FileNotFoundError
37,869,146
<p>I have a function that takes a source file containing times (a csv file), reads it, then sorts the lines in order and writes them in a destination file. However, if the source csv file does not exist, I need to raise a FileNotFoundError. I've raised exceptions before, for example, if a parameter wasn't an integer I ...
1
2016-06-16T20:52:18Z
37,869,216
<p>The exception is automatically <em>raised</em> by python. But you may need to wrap your <code>open</code> with a <code>try-except</code> to <em>catch</em> the exception without breaking your code:</p> <pre><code>try: s = open(src,'r') except FileNotFoundError: print('file not found') </code></pre>
1
2016-06-16T20:57:25Z
[ "python", "csv", "exception", "filenotfoundexception" ]
BeautifulSoup Scrapping Span Class HTML
37,869,268
<p>I am trying to scrap from the <code>&lt;span class= ''&gt;</code>. The code looks like this on the pages I am scrapping:</p> <pre><code> &lt; span class = "catnum"&gt; Disc Number &lt; / span&gt; "1" &lt; br &gt; &lt; span class = "catnum"&gt; Track Number &lt; / span&gt; "1" &lt; br&gt; ...
-1
2016-06-16T21:01:17Z
37,869,347
<p>as said in the error message, you should use <code>tag.has_attr("class")</code> in place of the deprecated <code>tag.has_key("class")</code> method.</p> <p>Hope it helps.</p> <p>Simone</p>
-1
2016-06-16T21:06:52Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
BeautifulSoup Scrapping Span Class HTML
37,869,268
<p>I am trying to scrap from the <code>&lt;span class= ''&gt;</code>. The code looks like this on the pages I am scrapping:</p> <pre><code> &lt; span class = "catnum"&gt; Disc Number &lt; / span&gt; "1" &lt; br &gt; &lt; span class = "catnum"&gt; Track Number &lt; / span&gt; "1" &lt; br&gt; ...
-1
2016-06-16T21:01:17Z
37,869,448
<p>You can constrain your search by attribute <code>{'class': 'catnum'}</code> and the text inside <code>text=re.compile('Disc Number')</code>. Then use <code>.next_sibling</code> to find the text:</p> <pre><code>from bs4 import BeautifulSoup import re s = ''' &lt;span class = "catnum"&gt; Disc Number &lt;/span&gt...
0
2016-06-16T21:14:20Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
What is the "rtol" parameter for the root finding function scipy.optimize.brentq?
37,869,299
<p>I'm having trouble understanding what the "rtol" parameter for brentq does. The help information is located here :</p> <p><a href="http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.optimize.brentq.html#scipy.optimize.brentq" rel="nofollow">http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/sc...
1
2016-06-16T21:02:56Z
37,869,435
<p>For a number <code>x</code>, if the root finder can guarantee that there is a root <code>x'</code> such that <code>|x - x'| &lt;= x*rtol</code>, <code>x</code> is deemed close enough to report it as the root.</p>
4
2016-06-16T21:13:22Z
[ "python", "optimization", "scipy" ]
when using pip install with git urls, is possible to skip checkout and use an existing local repository?
37,869,587
<p>I have a project with requirments.txt file that contains entries of the form:</p> <pre><code>-e git+http://repo/my_project.git#egg=SomeProject </code></pre> <p>which checks out the repository and performs and installs the library - which is the required behaviour in most cases.</p> <p>however, sometimes I want to...
0
2016-06-16T21:25:30Z
37,870,997
<p>I'm hopefully not out of scope, but you can do this using bash:</p> <pre><code>cat requirements.txt |grep -v project|xargs pip install -e path/to/project </code></pre> <p>This will leave out your project package from the <code>requirements.txt</code>, then replaces it with the path to the local version.</p>
2
2016-06-16T23:32:47Z
[ "python", "git", "pip" ]
when using pip install with git urls, is possible to skip checkout and use an existing local repository?
37,869,587
<p>I have a project with requirments.txt file that contains entries of the form:</p> <pre><code>-e git+http://repo/my_project.git#egg=SomeProject </code></pre> <p>which checks out the repository and performs and installs the library - which is the required behaviour in most cases.</p> <p>however, sometimes I want to...
0
2016-06-16T21:25:30Z
37,871,078
<p>if you don't want to make any changes to requirements.txt, you can setup a http server and make <code>repo</code> an alias for localhost in your <code>hosts</code> file </p>
0
2016-06-16T23:45:57Z
[ "python", "git", "pip" ]
PyQt4: Difference between QtCore.QCoreApplication.instance().quit and self.close?
37,869,599
<p>I've been doing a lot of research and have been unable to come up with anything describing this particular line of code in PyQt4. Like many others learning PyQt, I've been following zetcode's <a href="http://zetcode.com/gui/pyqt4/" rel="nofollow">PyQt4 tutorial</a>. I'm still somewhat of a beginner in Python, but I'...
1
2016-06-16T21:26:36Z
37,874,234
<p><code>qbtn.clicked</code> is the signal emitted by the button. <code>QCoreApplication.instance()</code> is the main application object. So it's connecting the button signal to the quit slot of the application.</p> <p>In your second example the button will just close the window that owns the button. If the applicat...
0
2016-06-17T06:05:38Z
[ "python", "pyqt4" ]
Python argparse: Too few arguments
37,869,616
<p>I'm trying to use the argparse library in Python. I want to have the user do something like:</p> <pre><code>python my_script.py csv_name.csv [--dryrun] </code></pre> <p>where <code>--dryrun</code> is an optional parameter.</p> <p>I then have the user enter an API key and secret key. When I run my code, I get pa...
2
2016-06-16T21:27:26Z
37,869,660
<p>When you use the following syntax:</p> <pre><code>parser.add_argument("csv") parser.add_argument("dryrun") </code></pre> <p>You're adding these as positional -- <em>required</em> -- arguments. Only arguments with a leading dash or two are optional.</p> <p>See <a href="https://docs.python.org/3/library/argparse.ht...
3
2016-06-16T21:31:06Z
[ "python", "argparse" ]
Python argparse: Too few arguments
37,869,616
<p>I'm trying to use the argparse library in Python. I want to have the user do something like:</p> <pre><code>python my_script.py csv_name.csv [--dryrun] </code></pre> <p>where <code>--dryrun</code> is an optional parameter.</p> <p>I then have the user enter an API key and secret key. When I run my code, I get pa...
2
2016-06-16T21:27:26Z
37,870,157
<p>To add an optional <code>--dry-run</code> argument, you may use the following snippet:</p> <pre><code>parser.add_argument('--dry-run', action='store_true') </code></pre> <p>Calling your script using <code>python my_script.py csv_name.csv --dry-run</code> will result to <code>args.dry_run</code> being <code>True</c...
2
2016-06-16T22:08:25Z
[ "python", "argparse" ]
pyopencl.cffi_cl.RuntimeError: clenqueuendrangekernel failed: OUT_OF_RESOURCES
37,869,622
<p>I'm new to pyopencl and opencl generally, so it's not surprising I've gotten to a point with this project where I'm officially stuck. Why am I getting the title error when I run this code?</p> <p>Code:</p> <pre><code>from __future__ import division import numpy as np import pyopencl as cl from time import time i...
0
2016-06-16T21:27:48Z
37,869,822
<p>Figured it out: The correct call is <code>prg.rmse(queue, (512,), (1,),</code>, setting the global workgroup size to 512 makes 512 workgroups, not 512 threads, which overwhelms the device.</p>
1
2016-06-16T21:42:47Z
[ "python", "opencl", "pyopencl" ]
Disable Shockwave Flash plugin using Selenium with Python
37,869,703
<p>In a crawling project, the Shockwave Flash plugin keeps crashing. Is there a simple way to disable it to begin with? </p> <p>Many thanks in advance!</p>
0
2016-06-16T21:34:21Z
38,861,370
<p>This worked for me pretty well.</p> <pre><code>from selenium.webdriver.chrome.options import Options options= webdriver.ChromeOptions() profile = {"plugins.plugins_disabled": ["Shockwave Flash"]} options.add_experimental_option("prefs", profile) # Make sure to add chrome_options=options browser = webdriver.Chrom...
1
2016-08-09T22:21:58Z
[ "python", "python-3.x", "selenium", "selenium-chromedriver" ]
Why is not a good idea to keep a sorted list in a extremely simple restaurant simulator
37,869,718
<p>I just begin to study python 3. There is a project about doing a simple restaurant simulator to see which four given approaches (1. Fist-in,fist-served, 2. last-in, first-served, 3. serve the most expensive order first, 4. serve the one with least preparation time first) yield the best results(profit and number of c...
0
2016-06-16T21:35:11Z
37,869,959
<p>The first one asks you to implement a QUEUE , the second one asks you to implement a STACK, and the third and fourth are variations of PRIORITY QUEUE data structures. </p>
0
2016-06-16T21:53:20Z
[ "python", "sorting" ]
Path Changed in Python Script Executed by Another Python Script
37,869,863
<p>A script at <code>/foo/bar.py</code> tries to run a second script <code>/main.py</code> using the <code>subprocess</code> module. Although <code>main.py</code> runs fine with <code>python main.py</code> in the Windows command prompt, running <code>bar.py</code> which calls <code>main.py</code> causes an error</p> <...
0
2016-06-16T21:46:19Z
37,870,226
<p>If <code>settings.ini</code> is presumed to be in the same directory as <code>main.py</code> you can deduce its full path from <code>__file__</code> and read the settings using the full path.</p> <p><strong>main.py</strong>:</p> <pre><code>import os ini_path = os.path.join(os.path.dirname(__file__), "settings.ini...
1
2016-06-16T22:13:49Z
[ "python", "python-2.7", "subprocess" ]
Path Changed in Python Script Executed by Another Python Script
37,869,863
<p>A script at <code>/foo/bar.py</code> tries to run a second script <code>/main.py</code> using the <code>subprocess</code> module. Although <code>main.py</code> runs fine with <code>python main.py</code> in the Windows command prompt, running <code>bar.py</code> which calls <code>main.py</code> causes an error</p> <...
0
2016-06-16T21:46:19Z
37,902,348
<p>Check that the <code>read()</code> method returns a non-empty list otherwise it means that <code>settings.ini</code> is not found. Relative paths are resolved relative to the current working directory (place where you've run <code>python</code>), not script's directory (where <code>bar.py</code> is stored).</p> <p...
0
2016-06-18T22:52:16Z
[ "python", "python-2.7", "subprocess" ]
How to parse this JSON data to list in Python?
37,869,866
<p>I have a json file which looks like this:</p> <pre><code>[{"lat":51.877743,"lng":-0.4116338,"acc":0,"time":0},`{"lat":51.877743,"lng":-0.4116338,"acc":20,"time":1465386382293},{"lat":51.877743,"lng":-0.4116338,"acc":20,"time":1465386412347}, ...` </code></pre> <p>I read them using the following code:</p> <pre><co...
-1
2016-06-16T21:46:41Z
37,869,898
<p>You can try something along these lines:</p> <pre><code>what_you_want = [[e['lat'], e['lng']] for e in data] </code></pre> <p>This can further be converted to array, or better yet, to a <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.ndarray.html" rel="nofollow"><code>numpy.array</code></...
1
2016-06-16T21:49:00Z
[ "python", "json" ]
How to parse this JSON data to list in Python?
37,869,866
<p>I have a json file which looks like this:</p> <pre><code>[{"lat":51.877743,"lng":-0.4116338,"acc":0,"time":0},`{"lat":51.877743,"lng":-0.4116338,"acc":20,"time":1465386382293},{"lat":51.877743,"lng":-0.4116338,"acc":20,"time":1465386412347}, ...` </code></pre> <p>I read them using the following code:</p> <pre><co...
-1
2016-06-16T21:46:41Z
37,869,976
<p>You could simply use a list comprehension:</p> <pre><code>&gt;&gt;&gt; [[i['lat'], i['lng']] for i in data] [[51.877743, -0.4116338], [51.877743, -0.4116338], [51.877743, -0.4116338]] </code></pre> <p>To get your stylized array, use <code>numpy</code></p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np...
1
2016-06-16T21:54:36Z
[ "python", "json" ]
How to parse this JSON data to list in Python?
37,869,866
<p>I have a json file which looks like this:</p> <pre><code>[{"lat":51.877743,"lng":-0.4116338,"acc":0,"time":0},`{"lat":51.877743,"lng":-0.4116338,"acc":20,"time":1465386382293},{"lat":51.877743,"lng":-0.4116338,"acc":20,"time":1465386412347}, ...` </code></pre> <p>I read them using the following code:</p> <pre><co...
-1
2016-06-16T21:46:41Z
37,870,218
<p>pandas approach:</p> <pre><code>import pandas as pd In [109]: df = pd.DataFrame(data) In [110]: df Out[110]: acc lat lng time 0 0 51.877743 -0.411634 0 1 20 51.877743 -0.411634 1465386382293 2 20 51.877743 -0.411634 1465386412347 In [111]: df[['lat','lng']] Out[...
2
2016-06-16T22:13:34Z
[ "python", "json" ]
Compare string to bytes that works in both Python 2 and 3
37,869,917
<p>What is the best way to compare a string object to a bytes object that works in both Python 2 and Python 3? Assume both are <code>utf8</code>. More generally, how does one write a Python 2 and Python 3 compatible comparison of two objects that may each be a string, bytes, or unicode object?</p> <p>The problem is ...
3
2016-06-16T21:49:55Z
37,869,996
<p>In both Python 2 and Python 3, anything that is an instance of <code>bytes</code> has a decode method. Thus, you can do the following:</p> <pre><code>def compare(a, b, encoding="utf8"): if isinstance(a, bytes): a = a.decode(encoding) if isinstance(b, bytes): b = b.decode(encoding) retur...
4
2016-06-16T21:56:04Z
[ "python", "string", "python-3.x", "bytearray", "python-2.x" ]
Compare string to bytes that works in both Python 2 and 3
37,869,917
<p>What is the best way to compare a string object to a bytes object that works in both Python 2 and Python 3? Assume both are <code>utf8</code>. More generally, how does one write a Python 2 and Python 3 compatible comparison of two objects that may each be a string, bytes, or unicode object?</p> <p>The problem is ...
3
2016-06-16T21:49:55Z
37,870,009
<p>You can check whether you're using Python 2 or 3 and act accordingly:</p> <pre><code>import sys if sys.version_info[0] &lt; 3: text_type = unicode else: text_type = str if isinstance(obj, text_type): result = obj.encode('utf-8') else: result = obj </code></pre>
3
2016-06-16T21:56:43Z
[ "python", "string", "python-3.x", "bytearray", "python-2.x" ]
Set correctly timeout when connection fails on Python socket
37,870,127
<p>I'm starting to learn python socket and the TCP/IP model, so I'm at very beginning. I have this simple piece of code that works correctly as expected:</p> <pre><code>import socket from datetime import datetime s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) start = datetime.now() try: s.connect(("www.sta...
1
2016-06-16T22:06:03Z
37,870,183
<p>Use <code>socket.settimeout()</code></p> <pre><code>s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(1.0) </code></pre> <p>This sets the timeout to 1 second.</p> <blockquote> <p>socket.settimeout(value)</p> <p>Set a timeout on blocking socket operations. The ...
1
2016-06-16T22:10:32Z
[ "python", "python-2.7", "sockets", "connection", "timeout" ]
Django MultiChoiceField with extra field
37,870,141
<p>Basically I need to create a multichoicefield, witch additionally has quantity field.</p> <p>So for each choice I need to add this extra positiveinteger field but i don't know how to add it.</p> <p>EDIT:</p> <p>I need to make orders, so you need to check what elements you want to add to the order, and how many of...
-2
2016-06-16T22:07:37Z
37,875,490
<p>You need two different fields. First one, with the element, and another one with the quantity. Then, when you recover them (from a form normally) you can handle them as you want (in the view), and you could store them in the db (by model).</p> <p>Could be:</p> <pre><code>class Order(forms.Form): quantity = forms...
0
2016-06-17T07:22:37Z
[ "python", "django", "forms", "multichoiceitems" ]
Multiplying matrices by block
37,870,148
<p>I need to multiply matrices of different shapes, M and N with a finite size of MxN.</p> <p>I think an example will make it more clear:</p> <p>A (shape: 4x4) =</p> <pre><code>0 3 0 0 0 0 4 0 0 0 0 3 0 0 0 0 </code></pre> <p>B (shape: 7x7) = </p> <pre><code>3 0 0 0 0 0 0 0 2 0 0 0 0 ...
2
2016-06-16T22:07:53Z
37,870,269
<p>You're looking for the Kronecker product, <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.kron.html">np.kron</a>, which is convenient to make block matrices like this:</p> <pre><code>&gt;&gt;&gt; A = np.array([[1, 2], [0, 1]]) &gt;&gt;&gt; B = np.array([[1, 2, 3], [0, 1, 3], [0,0,0]]) &gt;&gt;&g...
5
2016-06-16T22:17:47Z
[ "python", "python-2.7", "numpy", "matrix" ]
Python and Pyglet input
37,870,186
<p>Total python beginner here.</p> <p>I'm trying to make a game with the Python library Pyglet. It's been working great until I got to the part where I need the input.</p> <p>I've followed the examples and docs and my code looks something like this. I will only focus on the mouse input for now as the keyboard input s...
0
2016-06-16T22:10:43Z
37,999,814
<p>This is a basic skeleton of a good Pyglet class.<br> Modify it to your liking, the important thing here is that you handle mouse and keyboard I/O seperately.</p> <pre><code>import pyglet from pyglet.gl import * # Optional audio outputs (Linux examples): # pyglet.options['audio'] = ('alsa', 'openal', 'silent') key ...
0
2016-06-23T19:05:05Z
[ "python", "input", "pyglet" ]
Use value from select2:opening call as input to ajax autocomplete data parameter
37,870,210
<p>I'm generating a table of results dynamically and one cell in each row contains an autocomplete. I'm using Select2 to display the autocomplete options and am populating the drop-down from ajax data and custom data unique for each row. My ajax data is coming from my Python app method and I'm using POST to send a vari...
0
2016-06-16T22:13:00Z
37,887,119
<p>I was able to pass back data to the autocomplete method for the select element the user clicked on as follows:</p> <pre><code>$(".js-example-tokenizer-ajax-data").select2({ tags: true, //Allows for free text input of tag values createTag: function (params) { return { ...
0
2016-06-17T17:25:55Z
[ "python", "ajax", "python-2.7", "jquery-select2" ]
What's the best way to rename files with the same modified date and time?
37,870,371
<p>Path a/b/c/d where folder d has a bunch of files and folders, something like this.</p> <ul> <li>Folder E which has abc.txt, def.jpg, and ghi.pst</li> <li>Folder D also has loose files like jkl.pst, mno.jpg, pqr.txt</li> </ul> <p>Path w/x/y/z where folder z has a bunch of folders named like</p> <ul> <li>a3cj85zbla...
0
2016-06-16T22:26:01Z
37,871,733
<p>In pseudocode:</p> <ol> <li>Find all files in locations Source and Target.</li> <li>For each file in Source, calculate (checksum, size), and use this as a key in a dict, where the value is the filename. </li> <li>For each file in Target, calculate (checksum, size), and look it up in the dict created previously. If...
0
2016-06-17T01:26:20Z
[ "python", "windows", "file", "rename" ]
Call a python function from one class in another
37,870,407
<p>I am new to Python and I have difficulties in the basics of functions</p> <p><strong>a.py</strong></p> <pre><code>import b from ConfigParser import SafeConfigParser class A: def method1(): config = SafeConfigParser() b = B() b.method2(config) </code></pre> <p><strong>b.py</strong></p> <pre><code>c...
-1
2016-06-16T22:29:33Z
37,870,463
<p>There are two possible reasons:</p> <ol> <li><p>The hint doesn't show up because this code has typos and will not run anyway. You're missing <code>()</code> after <code>method1</code> and a colon after <code>method2(config)</code>. Also your <code>B</code> class will not be automatically visible, you should refer t...
0
2016-06-16T22:35:11Z
[ "python" ]
Call a python function from one class in another
37,870,407
<p>I am new to Python and I have difficulties in the basics of functions</p> <p><strong>a.py</strong></p> <pre><code>import b from ConfigParser import SafeConfigParser class A: def method1(): config = SafeConfigParser() b = B() b.method2(config) </code></pre> <p><strong>b.py</strong></p> <pre><code>c...
-1
2016-06-16T22:29:33Z
37,870,466
<p>You can something similar to what you're looking for with the <code>dir()</code> <a href="https://docs.python.org/3/library/functions.html#dir" rel="nofollow">function in python3</a>. This will print everything that's in the scope of the variable. Just change your <code>b.py</code> file to this:</p> <pre><code>clas...
0
2016-06-16T22:35:20Z
[ "python" ]
Call a python function from one class in another
37,870,407
<p>I am new to Python and I have difficulties in the basics of functions</p> <p><strong>a.py</strong></p> <pre><code>import b from ConfigParser import SafeConfigParser class A: def method1(): config = SafeConfigParser() b = B() b.method2(config) </code></pre> <p><strong>b.py</strong></p> <pre><code>c...
-1
2016-06-16T22:29:33Z
37,870,472
<p><code>import</code> is not <code>#include</code>. It automatically namespaces everything to the imported name. Your first example should look like this</p> <pre><code>import b from ConfigParser import SafeConfigParser class A: def method1: config = SafeConfigParser() c = b.B() c.method2(config) </c...
1
2016-06-16T22:36:10Z
[ "python" ]
Python Regex: How to append string if found and append "Not Found" otherwise?
37,870,495
<p>I am trying to append a result to a list if found, and append the string "N/A" to the list if no match is found. show_version_lists is a list of logs from various network devices.</p> <pre><code>import re for result in show_version_list: for matchedtext in re.findall(r'(?&lt;=Version).*?(?=-)',result)[:1]: ...
1
2016-06-16T22:38:30Z
37,870,749
<p>The problem is in your code logic. Your code is essentially saying the following:</p> <p>For all the times you find regex result in matchedtext *if you find the same regex result do x *if not (which you always will) do y (so y never happens)</p> <p>As an example, change the logic to something like: For all the dat...
1
2016-06-16T23:02:35Z
[ "python", "regex" ]
Python Regex: How to append string if found and append "Not Found" otherwise?
37,870,495
<p>I am trying to append a result to a list if found, and append the string "N/A" to the list if no match is found. show_version_lists is a list of logs from various network devices.</p> <pre><code>import re for result in show_version_list: for matchedtext in re.findall(r'(?&lt;=Version).*?(?=-)',result)[:1]: ...
1
2016-06-16T22:38:30Z
37,870,951
<p>Use <a href="https://docs.python.org/2/library/re.html#re.finditer" rel="nofollow">re.finditer</a>.</p> <p>finditer returns a match object, and we can use the re.group to append the version information from the match object. It's as simple as this.</p> <pre><code>import re version_numbers_xe = [] for result in s...
1
2016-06-16T23:26:26Z
[ "python", "regex" ]
How to assert ValueError in pytest
37,870,587
<p>I am writing pytest unit tests for the following function</p> <pre><code>from datetime import datetime def validate_timestamp(timestamp): """Confirm that the passed in string is in the proper format %Y%m%d_%H""" try: ts = datetime.strptime(str(timestamp),'%Y%m%d_%H') except: raise ValueError("{0} must be...
0
2016-06-16T22:47:31Z
37,870,714
<p>Run the code that is expected to raise an exception in a <code>with</code> block like:</p> <pre><code>with pytest.raises(ValueError): # code </code></pre> <p>For details and option please read <a href="https://pytest.org/latest/assert.html" rel="nofollow">https://pytest.org/latest/assert.html</a> .</p>
1
2016-06-16T22:59:25Z
[ "python", "unit-testing", "py.test" ]
Numpy array rounding
37,870,615
<p>Recently I've been following some methods from a prior question <a href="http://stackoverflow.com/questions/37780057/explanation-on-numpy-broadcasting-answer">here</a>. </p> <p>I've created a script to use it, and added some visualization to help show the issue I am having. </p> <pre><code>#Python 2.7, import futu...
0
2016-06-16T22:49:58Z
37,891,170
<p>It does seem to be an issue with the mod operation.</p> <p>I solved it by adding:</p> <pre><code> latva = round(latva,3) latva = list(str(latva)) if (int(latva[-1]) - 1) != -1: latva[-1] = str(int(latva[-1]) - 1) latva = float("".join(latva)) latvb = round(latvb,3) latvb = list(str(...
0
2016-06-17T22:21:04Z
[ "python", "arrays", "numpy" ]
Matplotlib color surface ellipsoid distance from centre
37,870,623
<p>I am trying to plot an error ellipsoid in 3D. This is ofcourse not that hard, but I found troubles with the collors. The colormap that I used use the Z values for the color. I would like that the describes the relationship of the distance between a point on the ellipsoid and another (for simple use the centre) point...
0
2016-06-16T22:50:49Z
37,876,518
<p>Well i have the answer found. The following code generates the ellispoid and its distances:</p> <pre><code>from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np from matplotlib import cm fig = plt.figure() ax = fig.add_subplot(111, projection='3d') u = np.linspace(0, 2 * np.pi...
0
2016-06-17T08:19:22Z
[ "python", "matplotlib", "mplot3d" ]
Basic algebra with sympy: keep coefficients and variables together
37,870,629
<p>I'm trying to use sympy for some basic algebra and physics. When defining an equation such as</p> <pre><code>import sympy as sy g,h = sy.Symbols("g h") v = sy.sqrt(2 * g * h) </code></pre> <p>the equation v gets expanded to</p> <pre><code>v = sqrt(2) * sqrt(g * h) </code></pre> <p>there a way to specify that the...
3
2016-06-16T22:51:15Z
37,876,063
<blockquote> <p>is there a way to specify that the coefficient "2" should not be factored out from under the square root and the term under the sqare root is kept as "2 * g * h"?</p> </blockquote> <p>Yes, just create a <code>Pow</code> object (power raise) with the optional parameter <code>evaluate=False</code>:...
2
2016-06-17T07:53:10Z
[ "python", "sympy" ]
Why can't I store the text from a Tk text widget into a variable
37,870,641
<p>I am trying to get the user input from the text widget and store it in a variable for use later in my code </p> <pre><code>self.dataset = Text(master) self.dataset.pack() self.data = self.dataset.get('1.0', 'end') ttk.Button(master, text="print dataset", command=lambda: print(self.data).pack() </code></pre> <p>...
0
2016-06-16T22:53:09Z
37,890,250
<p>Bryan's comment is correct, you're getting the data very, very quickly and then never updating it from then. To solve it, since you need to reference it later, you need to use something you can <code>set</code>, like a tkinter <code>StringVar</code>; then your button command can become </p> <pre><code>lambda: self....
1
2016-06-17T20:55:22Z
[ "python", "python-3.x", "user-interface", "tkinter", "tk" ]
Load JSON file in current distribution of a python package using pkg_resources
37,870,647
<p>I am building a package that has the following directory structure - </p> <pre><code>terraai_preprocessing |setup.py ||MANIFEST.in |terraai_preprocessing |__init__.py |combinatorics |preprocessing |__init__.py |config.json |pp_main.py |pp_helpers.py </code></pre> <p>I am trying to load config...
0
2016-06-16T22:53:46Z
37,870,767
<p>It has to be like:</p> <pre><code>with open('data.json', encoding='utf-8') as data_file: data = json.loads(data_file.read()) </code></pre> <p>so in your case </p> <pre><code> config = json.loads(f.read()) </code></pre>
1
2016-06-16T23:04:04Z
[ "python", "json", "packages" ]
Load JSON file in current distribution of a python package using pkg_resources
37,870,647
<p>I am building a package that has the following directory structure - </p> <pre><code>terraai_preprocessing |setup.py ||MANIFEST.in |terraai_preprocessing |__init__.py |combinatorics |preprocessing |__init__.py |config.json |pp_main.py |pp_helpers.py </code></pre> <p>I am trying to load config...
0
2016-06-16T22:53:46Z
38,420,093
<p>Python could not find the file as the function <code>resource_filename()</code> returns the address with <code>\\</code> as separators. By replacing <code>\\</code> with <code>/</code> it was able to locate the file.</p> <p>So I used the following code - </p> <pre><code>&gt;&gt; file_location = resource_filename('...
0
2016-07-17T10:08:23Z
[ "python", "json", "packages" ]
Tweepy to not store duplicate tweets into database
37,870,732
<p>I'm using Tweepy to get tweets and store all the tweets into database. but the problem I'm facing right now is Tweepy also store duplicate tweets into database.</p> <p>here's the code I use below:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true"> <div class="snippet-code"> <pre cl...
0
2016-06-16T23:01:15Z
37,871,106
<p>Since the program is automatically storing incoming tweets from the twitter user straight into your database you have a few options. You could:</p> <ol> <li><p>First store all of the tweets into a set (which is an 'unordered collection of <em>unique</em> values'), then save the elements of the set into your databas...
0
2016-06-16T23:49:22Z
[ "python", "mysql", "database", "api", "tweepy" ]
Should I commit /bin directory when working with virtualenv?
37,870,808
<p>I am starting my first actual python project. I follow "Learn Python the Hard Way" to make an initial <a href="http://learnpythonthehardway.org/book/ex46.html" rel="nofollow">Python skeleton</a> and I am using virtualenv too.</p> <p>Now I want to use git to do the version control. According to some previous questio...
0
2016-06-16T23:08:59Z
37,872,783
<p><code>yourproject/bin</code> is distinct from <code>yourproject/env/bin</code>, where <code>yourproject/env</code> is the virtual environment's directory (and neither of them is <code>/bin</code> in the root directory). You should ignore everything in <code>env</code>, and indeed, your project should work for someon...
1
2016-06-17T03:43:54Z
[ "python", "git", "project", "virtualenv", "setuptools" ]
How to aggregate intraday time stamps and create a new column in pandas dataframe Python
37,870,809
<p>I've tried this problem for hours and has no solution..</p> <p>Below is intraday 5 min forex data - df. It is recorded every 5 mins every day. I have excluded weekends data since market is close on weekends.Here a weekend is defined as from Friday 5:00 pm - Sunday 5:00 pm. </p> <pre><code> Time ...
2
2016-06-16T23:08:59Z
37,871,130
<p>I use pandas offsets.</p> <pre><code>import pandas as pd times = pd.date_range('2016-01-01 11:00:00', '2016-01-15 11:00:00', freq='H') pd.to_datetime((times - pd.offsets.Hour(11) + pd.offsets.BDay()).date) </code></pre> <p><code>times</code> gets every hour between <code>'2016-01-01 11:00:00'</code> and <code>'20...
1
2016-06-16T23:53:37Z
[ "python", "pandas", "dataframe" ]
Having trouble installing Python bindings of jq on ubuntu linux
37,870,814
<p>I have been trying to install the Python bindings of jq on ubuntu using pip.</p> <p>However, when I run the following command, it fails.</p> <p><code>sudo pip install jq</code></p> <p>This is the error message it get.</p> <pre><code>Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-b...
0
2016-06-16T23:09:41Z
37,999,780
<p>This gets compiled, you need to install the build dependencies.</p> <p><code>apt-get install autoconf automake build-essential libtool python-dev</code></p> <p>See the Pypi page for more info ... <a href="https://pypi.python.org/pypi/jq/0.1.6" rel="nofollow">https://pypi.python.org/pypi/jq/0.1.6</a></p>
0
2016-06-23T19:03:18Z
[ "python", "linux", "ubuntu", "jq" ]
How can you find the most common sets using python?
37,870,929
<p>I have a pandas dataframe where one column is a list of all courses taken by a student. The index is the student's ID.</p> <p>I'd like to find the most common set of courses across all students. For instance, if the dataframe looks like this:</p> <pre><code>ID | Courses 1 [A, C] 2 [A, C...
1
2016-06-16T23:23:35Z
37,870,977
<p>You can first convert <code>list</code> to <code>tuples</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html"><code>value_counts</code></a>. Last use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.to_dict.html"><code>to_dict</cod...
5
2016-06-16T23:29:56Z
[ "python", "pandas", "set" ]
How can you find the most common sets using python?
37,870,929
<p>I have a pandas dataframe where one column is a list of all courses taken by a student. The index is the student's ID.</p> <p>I'd like to find the most common set of courses across all students. For instance, if the dataframe looks like this:</p> <pre><code>ID | Courses 1 [A, C] 2 [A, C...
1
2016-06-16T23:23:35Z
37,871,051
<pre><code>import pandas as pd # create example data a = range(6) b = [['A', 'C'], ['A', 'C'], ['A', 'C'], ['B', 'C'], ['B', 'C'], ['K', 'D']] df = pd.DataFrame({'ID': a, 'Courses': b}) # convert lists in Courses-column to tuples (which some parts of pandas need) df['Courses'] = df['Courses'].apply(lambda x: tuple(x)...
2
2016-06-16T23:42:02Z
[ "python", "pandas", "set" ]
Resetting imported Python module variables
37,870,959
<p>I'm trying to understand why instantiated module variables will not reset after they have been modified once after they are imported. I've been working with <code>minimalmodbus</code>, and I am trying to reset the Baud rate if the default does not match the connected device's. Setting my own default, I cannot get th...
0
2016-06-16T23:27:50Z
37,871,040
<p>The first time you use a given serial port, <code>minimalmodbus</code> <a href="https://github.com/pyhys/minimalmodbus/blob/master/minimalmodbus.py#L101" rel="nofollow">creates a <code>serial.Serial</code> instance using the current value of <code>BAUDRATE</code> and saves it</a>:</p> <pre><code>def __init__(self, ...
1
2016-06-16T23:40:14Z
[ "python" ]
Why is TKinter OptionMenu changing the size of it's parent?
37,870,982
<p>I have this GUI program, and one of the Frames has an OptionMenu in it. Whenever I select something in the OptionMenu, it resizes the parent frame, even though it has more than enough room to fit in the current panel. It's hard to describe in words, so here's an image of what I mean:</p> <p><a href="http://i.stack....
1
2016-06-16T23:30:26Z
37,871,855
<p>The root of the problem lies in the fact you don't give any widgets a size, and all the frames are empty. The following description may sound confusing, but it's actually pretty logical, deterministic, and consistent with the documented behavior.</p> <h2>The natural size of the widgets and columns</h2> <p>Because ...
2
2016-06-17T01:42:31Z
[ "python", "tkinter", "grid-layout", "optionmenu" ]
Python 2 change the way to start a new process
37,871,087
<p>Can I change the way Python 2 creates a new process, like what <code>set_start_method</code> does in Python 3 on UNIX based OSes? </p>
1
2016-06-16T23:46:46Z
37,871,128
<p>You can write your own <code>Process</code> class that mocks original attributes but internally uses <code>subprocess</code> for starting another Python interpretator with required arguments: <a href="https://docs.python.org/2/library/subprocess.html#replacing-the-os-spawn-family" rel="nofollow">https://docs.python....
0
2016-06-16T23:53:31Z
[ "python", "python-2.7", "multiprocessing" ]
object has no attributes. New to classes in python
37,871,095
<pre><code>import praw import time class getPms(): r = praw.Reddit(user_agent="Test Bot By /u/TheC4T") r.login(username='*************', password='***************') cache = [] inboxMessage = [] file = 'cache.txt' def __init__(self): cache = self.cacheRead(self, self.file) sel...
0
2016-06-16T23:48:17Z
37,871,140
<p>Your <code>cacheRead</code> function (as well as <code>bot_run</code> and <code>cacheSave</code>) is indented too far, so it's defined in the body of your other function <code>getPms</code>. Thus it is only accessible inside of <code>getPms</code>. But you're trying to call it from <code>__init__</code>.</p> <p>I'm...
3
2016-06-16T23:54:53Z
[ "python", "class" ]