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 improve the run time of a python code
39,583,361
<p>I am trying to solve the below problem from an online coding site.</p> <p><strong>QUESTION:</strong> Fredo is pretty good at dealing large numbers. So, once his friend Zeus gave him an array of N numbers , followed by Q queries which he has to answer. In each query , he defines the type of the query and the number ...
0
2016-09-19T23:04:43Z
39,584,617
<p>Some suggestions: get the <code>int()</code> conversion of <code>tokenizedInput</code> done and out of the way rather than repeatedly calling <code>int()</code> over and over in the loop; a dictionary like <code>collection</code> is very efficient, don't second guess it by extracting the keys and values, use it as ...
0
2016-09-20T02:01:30Z
[ "python", "performance", "for-loop", "runtime" ]
Pandas Dataframe return index with inaccurate decimals
39,583,363
<p>I have a Pandas Dataframe like this:</p> <pre><code> 0 1 2 3 4 5 \ event_at 0.00 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 0.01 0.975381 0.959061 0....
2
2016-09-19T23:04:51Z
39,583,454
<p>you can do it this way (assuming we want to get a row with a <code>0.96</code> index, which is internally represented as <code>0.95999999999</code>):</p> <pre><code>In [466]: df.index Out[466]: Float64Index([0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06, 0.95999999999, 0.97, 0.98, 0.99, 1.0], dtype='float64') In [467]: ...
2
2016-09-19T23:15:34Z
[ "python", "pandas", "numpy", "dataframe" ]
Binding callbacks to minimize and maximize events in Toplevel windows
39,583,495
<p>I've read through related answers and it seems that the accepted way to do this is by binding callbacks to <code>&lt;Map&gt;</code> and <code>&lt;Unmap&gt;</code> events in the Toplevel widget. I've tried the following but to no effect:</p> <pre><code>from Tkinter import * tk = Tk() def visible(event): print ...
1
2016-09-19T23:21:34Z
39,585,436
<p>For me, on Win10, your code works perfectly, with the caveat that the middle frame button produces 'visible' whether it means 'maximize' or 'restore'. So maximize followed by restore results in 2 new 'visibles' becoming visible.</p> <p>I did not particularly expect this because <a href="http://infohost.nmt.edu/tcc...
0
2016-09-20T03:54:40Z
[ "python", "linux", "tkinter" ]
Binding callbacks to minimize and maximize events in Toplevel windows
39,583,495
<p>I've read through related answers and it seems that the accepted way to do this is by binding callbacks to <code>&lt;Map&gt;</code> and <code>&lt;Unmap&gt;</code> events in the Toplevel widget. I've tried the following but to no effect:</p> <pre><code>from Tkinter import * tk = Tk() def visible(event): print ...
1
2016-09-19T23:21:34Z
39,586,786
<h3>Unmapping on Linux</h3> <p>The term <code>Unmap</code> has a quite different meaning on Linux than it has on Windows. On Linux, <em>Unmapping</em> a window means making it (nearly) untraceable; It does not appear in the application's icon, nor is it listed anymore in the output of <code>wmctrl -l</code>. We can un...
1
2016-09-20T06:05:25Z
[ "python", "linux", "tkinter" ]
Binding callbacks to minimize and maximize events in Toplevel windows
39,583,495
<p>I've read through related answers and it seems that the accepted way to do this is by binding callbacks to <code>&lt;Map&gt;</code> and <code>&lt;Unmap&gt;</code> events in the Toplevel widget. I've tried the following but to no effect:</p> <pre><code>from Tkinter import * tk = Tk() def visible(event): print ...
1
2016-09-19T23:21:34Z
39,590,204
<p>My own implementation of the <a href="http://stackoverflow.com/a/39586786/2592879">hack</a> suggested by Jacob.</p> <pre><code>from Tkinter import Tk, Toplevel import subprocess class CustomWindow(Toplevel): class State(object): NORMAL = 'normal' MINIMIZED = 'minimized' def __init__(self...
0
2016-09-20T09:18:40Z
[ "python", "linux", "tkinter" ]
Converting a dictionary of tuple arrays to a CSV
39,583,508
<p>I'm trying to convert a dictionary structured like this:</p> <pre><code>{ 'AAA': [ ('col1', 1), ('col2', 2), ('col3', 3) ], 'BBB': [ ('col2', 1), ('col3', 4) ], 'CCC': [ ('col4', 7) ] } </code></pre> <p>...into a csv structured like this:</p> <pre><code>key col1, col2, col3, col4 AAA 1 2 3 B...
1
2016-09-19T23:23:01Z
39,583,796
<p>There isn't a simple way to do what you're asking for without processing your dictionary first.</p> <p>Python has a csv library: <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">https://docs.python.org/2/library/csv.html</a> but you have to have your data in the right format before using it. You...
1
2016-09-20T00:04:39Z
[ "python", "csv", "dictionary" ]
Python Multiprocessing and Queue
39,583,557
<p>I am new to amazing world of python, was developing a test system consist of continuous sense and test run. i have three or more while loops of which one is producer and rest two are consumers. did not understand multiprocessing very well, here are a sample code, first loop will create a data and second loop will ge...
2
2016-09-19T23:30:06Z
39,583,700
<pre><code>def send(): cnt = -1 while True: cnt += 1 yield cnt def rcv(value): ... # logic consumers = [rcv] * NUM_CONSUMERS idx = 0 for val in send(): consumers[idx](val) idx += 1 idx %= NUM_CONSUMERS - 1 </code></pre>
-1
2016-09-19T23:49:56Z
[ "python" ]
Python Multiprocessing and Queue
39,583,557
<p>I am new to amazing world of python, was developing a test system consist of continuous sense and test run. i have three or more while loops of which one is producer and rest two are consumers. did not understand multiprocessing very well, here are a sample code, first loop will create a data and second loop will ge...
2
2016-09-19T23:30:06Z
39,586,063
<p>I would suggest you to dive in to the <a href="https://docs.python.org/2/library/multiprocessing.html#exchanging-objects-between-processes" rel="nofollow">documentation</a> of the multiprocessing-library you are using.</p> <p>Basically, you have two options. Queue and Pipe. Now you are using Queue, </p> <pre><code...
2
2016-09-20T05:05:56Z
[ "python" ]
Python dictionary: number of keys with specific number of values
39,583,568
<p>I have a huge dictionary that looks like this: </p> <pre><code>data = {'this': [{'DT': 100}], 'run': [{'NN': 215}, {'VB': 2}], 'the': [{'NNP': 6}, {'JJ': 7}, {'DT': 39517}]} </code></pre> <p>What I would like to to do is to run enquires that would return ,for example, the number of keys with exactly two values, in...
0
2016-09-19T23:31:36Z
39,583,732
<p>This will do the job:</p> <pre><code>print len( filter( lambda x: len( x ) == 2, data.values() ) ) </code></pre> <p>The lambda returns true when the length of an item is 2. <code>filter()</code> selects only those items where the lambda returns true, and then we count the length of the sequence returned by <code>f...
2
2016-09-19T23:55:06Z
[ "python", "dictionary" ]
Python dictionary: number of keys with specific number of values
39,583,568
<p>I have a huge dictionary that looks like this: </p> <pre><code>data = {'this': [{'DT': 100}], 'run': [{'NN': 215}, {'VB': 2}], 'the': [{'NNP': 6}, {'JJ': 7}, {'DT': 39517}]} </code></pre> <p>What I would like to to do is to run enquires that would return ,for example, the number of keys with exactly two values, in...
0
2016-09-19T23:31:36Z
39,583,757
<p>You do not need <code>regex</code> to achieve this. Regex are for parsing the strings. Better way is to create a new list to store the <code>key</code> with value as list of <code>len() == 2</code>:</p> <pre><code>data = {'this': [{'DT': 100}], 'run': [{'NN': 215}, {'VB': 2}], 'the': [{'NNP': 6}, {'JJ': 7}, {'DT': ...
0
2016-09-20T00:00:08Z
[ "python", "dictionary" ]
Python dictionary: number of keys with specific number of values
39,583,568
<p>I have a huge dictionary that looks like this: </p> <pre><code>data = {'this': [{'DT': 100}], 'run': [{'NN': 215}, {'VB': 2}], 'the': [{'NNP': 6}, {'JJ': 7}, {'DT': 39517}]} </code></pre> <p>What I would like to to do is to run enquires that would return ,for example, the number of keys with exactly two values, in...
0
2016-09-19T23:31:36Z
39,583,934
<p>Just get the lengths and count the desired length.</p> <pre><code>&gt;&gt;&gt; map(len, data.values()).count(2) 1 </code></pre>
0
2016-09-20T00:22:59Z
[ "python", "dictionary" ]
Box Plot of grouped data in Pandas
39,583,581
<p>I am trying to plot a boxplot of a grouped dataset.</p> <p>Imagine my data set looks like this</p> <pre><code>Gender | Age ------ | ------ Male | 20 ------ | ------ Female | 40 ------ | ------ Female | 45 ------ | ------ Unknown| 5 ------ | ------ Male | 80 ------ | ------ Female | 30 ------ | ------ Unknown| ...
1
2016-09-19T23:32:38Z
39,584,062
<p>I was able to figure it out on my own.</p> <p>Using the seaborn package, one can simply do this</p> <pre><code>sns.boxplot(data["Age"], groupby=data["Gender"]) </code></pre> <p>and it renders a beautiful boxplot grouped</p>
0
2016-09-20T00:41:45Z
[ "python", "matplotlib", "plot" ]
Spark Logistic Regression Error Dimension Mismatch
39,583,623
<p>I just started using spark and am trying to run a logistic regression. I keep getting this error: </p> <pre><code>Caused by: java.lang.IllegalArgumentException: requirement failed: Dimensions mismatch when adding new sample. Expecting 21 but got 17. </code></pre> <p>The number of features that I have is 21 , but...
0
2016-09-19T23:38:51Z
39,585,121
<p>Looks like some problem with the raw data. I guess some of the values are not passing through the <strong><code>isFloat</code></strong> validation. Can you just try printing the values on console, It will help you in identifying the error lines.</p>
0
2016-09-20T03:09:53Z
[ "python", "apache-spark", "pyspark", "logistic-regression" ]
Spark Logistic Regression Error Dimension Mismatch
39,583,623
<p>I just started using spark and am trying to run a logistic regression. I keep getting this error: </p> <pre><code>Caused by: java.lang.IllegalArgumentException: requirement failed: Dimensions mismatch when adding new sample. Expecting 21 but got 17. </code></pre> <p>The number of features that I have is 21 , but...
0
2016-09-19T23:38:51Z
39,585,625
<p>The error comes from the matrix multiplication where dimensions are not matching. array is not getting all 21 values. I suggest you to set variables to 0 in case they are not float, as that (seemingly) you want</p>
0
2016-09-20T04:22:21Z
[ "python", "apache-spark", "pyspark", "logistic-regression" ]
Pandas group by, filter & plot
39,583,634
<p>I have a dataframe </p> <pre><code>Date rule_name Jan 1 2016 A Feb 4 2016 B Jun 6 2016 C Feb 5 2016 B Feb 9 2016 D Jun 5 2016 A </code></pre> <p>And so on ...</p> <p>I am hoping to get a dataframe for each rule similar to below: E.g. Dataframe for rule_name A:</p> <pre><code>date counts...
2
2016-09-19T23:39:29Z
39,583,669
<p><strong><em>Solution</em></strong><br> Use <code>df.Date.str.split().str[0]</code> to get months</p> <pre><code>df.groupby([df.Date.str.split().str[0]]).rule_name.value_counts(True) \ .unstack(fill_value=0).mul(100).round(1) </code></pre> <p><a href="http://i.stack.imgur.com/YI8TV.png" rel="nofollow"><img src="h...
3
2016-09-19T23:45:02Z
[ "python", "pandas", "plot", "group-by", "filtering" ]
Not sure solution is correct for python classes
39,583,721
<p>Here is the question; create a car class with the following data attributes</p> <pre><code>__year_model __make __speed </code></pre> <p>The class should have an <code>__init__</code> method that accepts the car's year model and make as argument. The value should be assigned to the objects <code>__year_model</code>...
1
2016-09-19T23:53:46Z
39,583,749
<p>Yes, <code>test</code> is an object, i.e. an instance of a class <em>is</em> an object.</p> <p>Your class needs some work. According to the spec, <code>speed</code> is not supposed to be passed to <code>__init__()</code>. Remove that and initialise <code>self.__speed</code> to <code>0</code> in <code>__init__()</co...
2
2016-09-19T23:58:15Z
[ "python", "class", "object" ]
Simple Sorting Python Objects - Indexing Error
39,583,729
<p>I thought this would be a super simple sorting exercise but I'm not understanding the errors I'm getting.</p> <p>I'm creating a simple <code>Book</code> class and then adding two entries. I am then sorting via <code>sorted</code> and using a <code>lambda</code> so that I sort by the <code>isbn</code> attribute.</p>...
0
2016-09-19T23:54:44Z
39,583,741
<p>No, you need to use:</p> <pre><code>sorted_books = sorted(books, key=lambda book: book.isbn) </code></pre> <p>The result:</p> <pre><code>In [2]: sorted_books = sorted(books, key=lambda book: book.isbn) In [3]: sorted_books Out[3]: [('English for All', 'Zöd', '229'), ('Russian for All', 'Chompsky', '334')] </cod...
1
2016-09-19T23:57:24Z
[ "python", "sorting" ]
Iterating through multiple text files and comparing
39,583,740
<p>I'm trying to write a function that puts text files into a list and then iterates through the files to find exact and partial copies to weed out people who may have cheated by plagarising their work. I start by using my class roster and adding .txt to their name to find their assignments and whether they've even com...
1
2016-09-19T23:57:08Z
39,584,310
<p>Try this. You may need to modify it for your file structure, but it should be close.</p> <pre><code>import re from itertools import product def hash_sentences(document): # remove all characters except those below, replace with a space # split into a list cleaned_text = re.sub(r'[^A-z0-9,;:\.\?! ]', ' ...
0
2016-09-20T01:18:42Z
[ "python", "list", "file", "iteration" ]
NaN from sparse_softmax_cross_entropy_with_logits in Tensorflow
39,583,752
<p>I am getting NaN when I attempt to use the sparse_softmax_cross_entropy_with_logits loss function in tensorflow. I have a simple network, something like:</p> <pre><code>layer = tf.nn.relu(tf.matmul(inputs, W1) + b1) layer = tf.nn.relu(tf.matmul(inputs, W2) + b2) logits = tf.matmul(inputs, W3) + b3 loss = tf.sparse_...
0
2016-09-19T23:58:44Z
39,588,018
<p><code>tf.sparse_softmax_cross_entropy_with_logits</code> handles the case of <code>log(0)</code> for you, you don't have to worry about it.</p> <p>Usually a <code>NaN</code> is due to a high learning rate of your optimization algorithm. Try to lower it until <code>NaN</code> errors disappear and the loss starts to ...
1
2016-09-20T07:21:53Z
[ "python", "tensorflow" ]
NaN from sparse_softmax_cross_entropy_with_logits in Tensorflow
39,583,752
<p>I am getting NaN when I attempt to use the sparse_softmax_cross_entropy_with_logits loss function in tensorflow. I have a simple network, something like:</p> <pre><code>layer = tf.nn.relu(tf.matmul(inputs, W1) + b1) layer = tf.nn.relu(tf.matmul(inputs, W2) + b2) logits = tf.matmul(inputs, W3) + b3 loss = tf.sparse_...
0
2016-09-19T23:58:44Z
39,588,174
<p>The <code>NaN</code> error probably occurs when one of the softmaxed logits gets truncated to 0, as you have said, and then it performs log(0) to compute the cross-entropy error.</p> <p>To avoid this, as it is suggested in <a href="http://stackoverflow.com/questions/33712178/tensorflow-nan-bug/33713196#33713196">th...
1
2016-09-20T07:29:42Z
[ "python", "tensorflow" ]
NaN from sparse_softmax_cross_entropy_with_logits in Tensorflow
39,583,752
<p>I am getting NaN when I attempt to use the sparse_softmax_cross_entropy_with_logits loss function in tensorflow. I have a simple network, something like:</p> <pre><code>layer = tf.nn.relu(tf.matmul(inputs, W1) + b1) layer = tf.nn.relu(tf.matmul(inputs, W2) + b2) logits = tf.matmul(inputs, W3) + b3 loss = tf.sparse_...
0
2016-09-19T23:58:44Z
39,602,346
<p>It actually turns out that some of my labels were out of range (e.g. a label of 14000, when my logits matrix is just 150 x 10000). It turns out this results in a NaN rather than an error.</p>
0
2016-09-20T19:29:12Z
[ "python", "tensorflow" ]
Pyspark DataFrame - How to use variables to make join?
39,583,773
<p>I'm having a bit of trouble to make a join on two Data Frames using Spark Data Frames on python. I have two data frames that I had to change the name of the columns in order to make them unique for each data frame, so later I could tell which column is which. I did this to rename the columns (firstDf and secondDf ar...
2
2016-09-20T00:02:43Z
39,583,831
<p>Generally speaking don't use dots in names. These have special meaning (can be used either to determine the table or to access <code>struct</code> fields) and require some additional work to be correctly recognized.</p> <p>For equi joins all you need is a column name:</p> <pre><code>from pyspark.sql.functions impo...
0
2016-09-20T00:10:02Z
[ "python", "apache-spark", "pyspark", "spark-dataframe", "pyspark-sql" ]
Python: how would I write a keyevent?
39,583,782
<p>So simply put I want my code to call a event like OnKeyPress("Keyname") or something, each time I press a key. I don't want to use tkinter.</p> <p>I have a Update method that gets called 20 times a second that's in a parent class I have several child classes that have that function called. On some of them I want to...
0
2016-09-20T00:03:28Z
39,583,899
<p>This should work <pre> class _GetchUnix: def <strong>init</strong>(self): import tty, sys def <strong>call</strong>(self): import sys, tty, termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try: tty.setraw(sys.stdin.fileno()) ...
0
2016-09-20T00:18:26Z
[ "python", "events", "keypress" ]
Python: how would I write a keyevent?
39,583,782
<p>So simply put I want my code to call a event like OnKeyPress("Keyname") or something, each time I press a key. I don't want to use tkinter.</p> <p>I have a Update method that gets called 20 times a second that's in a parent class I have several child classes that have that function called. On some of them I want to...
0
2016-09-20T00:03:28Z
39,584,910
<p>I urge you to reconsider not using tkinter. Ignoring the GUI stuff, it has a tested, cross-platform, <em>asynchonous</em> event loop system that handles both scheduled (timed) events and key press and release events. And it is written in C and updated as platforms change. (See the comments for the recipe @Ty quot...
1
2016-09-20T02:42:41Z
[ "python", "events", "keypress" ]
unicode for arrow keys?
39,583,798
<p>I am trying to make a game where you can instantly have the user's input be transmitted to the computer instead of having to press <code>enter</code> every time. I know how to do that, but I cannot seem to find the unicode number for the arrow keys. Is there unicode for that, or am I just going to be stuck with wasd...
0
2016-09-20T00:04:55Z
39,584,425
<p>Start by reading the relevant doc for msvcrt.</p> <blockquote> <p>msvcrt.kbhit()</p> <p>Return true if a keypress is waiting to be read.</p> <p>msvcrt.getch()</p> <p>Read a keypress and return the resulting character as a byte string. Nothing is echoed to the console. This call will block if a keyp...
0
2016-09-20T01:36:08Z
[ "python", "python-2.7", "unicode", "python-unicode" ]
Matplotlib squishes axis labels when setting labels on twiny() axis
39,583,802
<p>I'm trying to add a second set of tic marks to my plot. I'm getting the original tic marks with <code>get_xticks()</code>, converting them to what I want (in this example simply adding 100) and calling <code>set_xticks()</code> on an axis I got from <code>ax.twiny()</code>.</p> <p>When I do this, my twin axis label...
0
2016-09-20T00:05:07Z
39,583,986
<p>Try this (incomplete code; needs to be merged with OPs):</p> <pre><code>from matplotlib.ticker import FuncFormatter def shift(x, pos): return x+100 formatter = FuncFormatter(shift) ax2 = ax1.twiny() ax2.xaxis.set_major_formatter(formatter) ax2.set_xlim(ax1.get_xlim()) </code></pre> <p>Read also <a href="http:...
0
2016-09-20T00:30:05Z
[ "python", "matplotlib", "plot" ]
Static files not being served on Django
39,583,896
<p>I am trying to serve static files in Django in development (<code>DEBUG=True</code>) mode. I have a directory structure like this:</p> <pre><code>my_project/ ... static/ img.png </code></pre> <p>In my <code>settings.py</code> I have this:</p> <pre><code>STATIC_ROOT = os.path.join(BASE_DIR, "static") STATI...
1
2016-09-20T00:17:59Z
39,585,592
<p>You can debug this in many different ways. Here's my approach.</p> <p>main settings.py:</p> <pre><code>DEBUG = False TDEBUG = True </code></pre> <p>urls.py:</p> <pre><code>from django.conf import settings import os if settings.TDEBUG: urlpatterns += patterns('', (r'^static/(?P&lt;path&gt;.*)$', 'dja...
0
2016-09-20T04:17:16Z
[ "python", "django" ]
Multiple Levels of Sorting without module
39,583,953
<p><a href="https://wiki.python.org/moin/HowTo/Sorting" rel="nofollow">This article</a> states that you can use multiple levels of sorting with the <code>operator</code> module.</p> <blockquote> <p>The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age: </p> </block...
0
2016-09-20T00:26:08Z
39,583,964
<p>Do what the function in <code>operator</code> does and return a tuple:</p> <pre><code>key=lambda student: (student.grade, student.age) </code></pre>
2
2016-09-20T00:27:27Z
[ "python", "sorting" ]
Why is 'é' and 'é' encoding to different bytes?
39,583,993
<h1>Question</h1> <p>Why is the same character encoding to different bytes in different parts of my code base?</p> <h1>Context</h1> <p>I have a unit test that generates a temporary file tree and then checks to make sure my scan actually finds the file in question.</p> <pre><code>def test_unicode_file_name(): te...
2
2016-09-20T00:31:04Z
39,585,206
<p>Your operating system (MacOS, at a guess) has converted the filename <code>'é'</code> to <a href="https://en.wikipedia.org/wiki/Unicode_equivalence#Normal_forms" rel="nofollow">Unicode Normal Form D</a>, decomposing it into an unaccented <code>'e'</code> and a combining acute accent. You can see this clearly with a...
3
2016-09-20T03:20:59Z
[ "python", "python-3.x", "unicode", "normalization" ]
Reading .obj file and split lines
39,584,021
<p>I made a simple code to read a .obj file that looks like this</p> <pre><code>g cube v 0.0 0.0 0.0 v 0.0 0.0 1.0 v 0.0 1.0 0.0 v 0.0 1.0 1.0 v 1.0 0.0 0.0 v 1.0 0.0 1.0 v 1.0 1.0 0.0 v 1.0 1.0 1.0 f 1//2 7//2 5//2 f 1//2 3//2 7//2 f 1//6 4//6 3//6 f 1//6 2//6 4//6 f 3//3 8/...
0
2016-09-20T00:35:11Z
39,584,038
<p>The error message is pretty clear: you are passing <code>int</code> a list (the result of calling <code>split</code>); maybe you only meant to call it with one of the elements of that list.</p>
0
2016-09-20T00:38:05Z
[ "python", "python-3.x" ]
Reading .obj file and split lines
39,584,021
<p>I made a simple code to read a .obj file that looks like this</p> <pre><code>g cube v 0.0 0.0 0.0 v 0.0 0.0 1.0 v 0.0 1.0 0.0 v 0.0 1.0 1.0 v 1.0 0.0 0.0 v 1.0 0.0 1.0 v 1.0 1.0 0.0 v 1.0 1.0 1.0 f 1//2 7//2 5//2 f 1//2 3//2 7//2 f 1//6 4//6 3//6 f 1//6 2//6 4//6 f 3//3 8/...
0
2016-09-20T00:35:11Z
39,584,318
<p>Recreate your case with one line:</p> <pre><code>In [435]: line='f 1//2 7//2 5//2' In [436]: elem = line.split() In [437]: elem Out[437]: ['f', '1//2', '7//2', '5//2'] In [438]: elem[0] Out[438]: 'f' </code></pre> <p>split on <code>/</code> behaves as I expect:</p> <pre><code>In [439]: for i in range(1,len(ele...
1
2016-09-20T01:20:00Z
[ "python", "python-3.x" ]
Folder creation with timestamp in python
39,584,028
<p>Hi I am a beginner in python and not well versed with file operations.I am writing a python script for logging. Below is my code snippet:</p> <pre><code>infile = open('/home/nitish/profiles/Site_info','r') lines = infile.readlines() folder_output = '/home/nitish/profiles/output/%s'%datetime.now().strftime('%Y-...
0
2016-09-20T00:36:43Z
39,584,131
<p>You have trailing newlines on all the urls so that would not work, you won't get past <code>folder = open(folder_output,"w")</code> as you are trying to create a file not a folder, there is also no need for a subprocess. You can do it all using standard lib functions:</p> <pre><code>from os import mkdir import urll...
0
2016-09-20T00:51:27Z
[ "python", "timestamp", "folder" ]
unsupported operand type(s) for ** or pow(): 'method' and 'int'
39,584,033
<pre><code>from tkinter import * import math import sys def quit(): root.destroy() def a_b_c(): print_a() print_b() print_c() calculation() return def print_a(): get_a = a.get() printing_a = Label(root, text=get_a).grid(row=8, column=1) return def print_b(): get_b = b.get() printing_b =Label(r...
0
2016-09-20T00:37:47Z
39,584,143
<p>You are assigning a few values:</p> <pre><code>two_a = a.get two_b = b.get two_c = c.get </code></pre> <p>And then doing calculations:</p> <pre><code>d = two_b**2-... </code></pre> <p>However, <code>a.get</code> is a method that retrieves the value of that <code>StringVar</code>. To actually call it and retrieve...
2
2016-09-20T00:52:31Z
[ "python", "python-3.x", "math" ]
unsupported operand type(s) for ** or pow(): 'method' and 'int'
39,584,033
<pre><code>from tkinter import * import math import sys def quit(): root.destroy() def a_b_c(): print_a() print_b() print_c() calculation() return def print_a(): get_a = a.get() printing_a = Label(root, text=get_a).grid(row=8, column=1) return def print_b(): get_b = b.get() printing_b =Label(r...
0
2016-09-20T00:37:47Z
39,584,166
<p>Please read and study this SO help page about <a href="https://stackoverflow.com/help/mcve">mcves</a>. Here is an mcve based on the code you posted. It produces the exact same error message on the last line.</p> <pre><code>import tkinter as tk root = tk.Tk() b = tk.StringVar(root) two_b = b.get d = two_b**2 </code...
0
2016-09-20T00:56:21Z
[ "python", "python-3.x", "math" ]
How do I delete duplicate lines and create a new file without duplicates?
39,584,043
<p>I searched on here an found many postings, however none that I can implement into the following code</p> <pre><code>with open('TEST.txt') as f: seen = set() for line in f: line_lower = line.lower() if line_lower in seen and line_lower.strip(): print(line.strip()) else: ...
1
2016-09-20T00:38:32Z
39,584,745
<p>this is something you could use:</p> <pre><code>import linecache with open('pizza11.txt') as f: for i, l in enumerate(f): pass x=i+1 k=0 i=2 j=1 initial=linecache.getline('pizza11.txt', 1) clean= open ('clean.txt','a') clean.write(initial) while i&lt;(x+1): a...
0
2016-09-20T02:17:48Z
[ "python", "hyperlink", "duplicates" ]
How do I delete duplicate lines and create a new file without duplicates?
39,584,043
<p>I searched on here an found many postings, however none that I can implement into the following code</p> <pre><code>with open('TEST.txt') as f: seen = set() for line in f: line_lower = line.lower() if line_lower in seen and line_lower.strip(): print(line.strip()) else: ...
1
2016-09-20T00:38:32Z
39,598,759
<p>Sounds simple enough, but what you did looks overcomplicated. I think the following should be enough:</p> <pre><code>with open('TEST.txt', 'r') as f: unique_lines = set(f.readlines()) with open('TEST_no_dups.txt', 'w') as f: f.writelines(unique_lines) </code></pre> <p>A couple things to note:</p> <ul> <li...
1
2016-09-20T15:57:46Z
[ "python", "hyperlink", "duplicates" ]
dask dataframe how to convert column to to_datetime
39,584,118
<p>I am trying to convert one column of my dataframe to datetime. Following the discussion here <a href="https://github.com/dask/dask/issues/863" rel="nofollow">https://github.com/dask/dask/issues/863</a> I tried the following code:</p> <pre><code>import dask.dataframe as dd df['time'].map_partitions(pd.to_datetime, c...
1
2016-09-20T00:50:15Z
39,593,279
<h3>Use <code>astype</code></h3> <p>You can use the <code>astype</code> method to convert the dtype of a series to a NumPy dtype</p> <pre><code>df.time.astype('M8[us]') </code></pre> <p>There is probably a way to specify a Pandas style dtype as well (edits welcome)</p> <h3>Use map_partitions and meta</h3> <p>When ...
1
2016-09-20T11:49:19Z
[ "python", "pandas", "dask" ]
How to convert for loops to while loops in Python?
39,584,119
<p>I need to change all the for to while. How to do it for the below code? I have commented about what each for block does.</p> <pre><code>def createClusters(k, centroids, datadict, repeats): for apass in range(repeats): print("****PASS",apass,"****") clusters = [] for i in range(...
-5
2016-09-20T00:50:15Z
39,584,219
<p>Why on earth would you want to convert all the <code>for</code> loops to <code>while</code> loops.<br> Just to show how ugly this would be, consider a canonical <code>for</code> loop:</p> <pre><code>for i in iterable: ... </code></pre> <p>Would turn into:</p> <pre><code>it = iter(iterable) while True: try...
0
2016-09-20T01:03:39Z
[ "python" ]
Removing extra characters from a string with a specific pattern PHP
39,584,160
<p>I am moving data from the output of a python function to php and then converting it to JSON and sending it to a javascript function that calls it with AJAX. </p> <p>The format should look like this:</p> <pre><code>{"data_name" : [1.02, 3.013, -24.12, 39], "data_name_2" : [-0.32151], "data_name_3" : [0.321, -21.424...
0
2016-09-20T00:55:49Z
39,584,830
<p>I agree with Sammitch. </p> <p>The quick fix for 2. is <a href="http://php.net/manual/en/function.stripslashes.php" rel="nofollow">stripslashes</a></p> <p>For the rest, you may be able to create patterns with <a href="http://php.net/manual/en/function.preg-replace.php" rel="nofollow">preg_replace</a> that can filt...
0
2016-09-20T02:31:06Z
[ "javascript", "php", "python", "json" ]
Why is my list not getting reset on every loop in Python
39,584,181
<p>I have a function that needs to take in a list called edges. I need to preform many loops and on each loop I change properties values of edges. At the beginning of the next loop I need edges to take on its original value. To try and deal with this I have cast my list as a tuple so it wouldn't be mutable and assigned...
0
2016-09-20T00:58:49Z
39,584,226
<p><code>permEdges</code> may be a tuple, but its contents are not; remember that both <code>permEdges</code> and <code>trialEdges</code> are storing pointers to four two-element lists. When you set <code>trialEdges[0][0] = 100</code>, you're <em>modifying</em> but not <em>replacing</em> the first element of <code>tria...
4
2016-09-20T01:04:48Z
[ "python", "list", "tuples" ]
pandas.Series.get fails with: object has no attribute 'values'
39,584,228
<p>I don't seem to be able to call Series.get on a Series object. </p> <pre><code>&gt;&gt; print col 0 1 1 1 2 0 Name: a, dtype: float64 &gt;&gt;&gt; counts = col.value_counts() &gt;&gt;&gt; print counts 1 2 0 1 dtype: int64 </code></pre> <p>... makes sense. 2 ones. 1 zero</p> <pre><code>&gt;&gt;&gt; ...
0
2016-09-20T01:04:57Z
39,584,660
<p>Seems to be bug in pandas 15</p> <p>Upgrading to pandas 18 resolves this.</p>
0
2016-09-20T02:06:51Z
[ "python", "pandas" ]
Loaded pickle data is much larger in memory than on disk and seems to leak. (Python 2.7)
39,584,233
<p>I'm having a memory issue. I have a pickle file that I wrote with the Python 2.7 cPickle module. This file is 2.2GB on disk. It contains a dictionary of various nestings of dictionaries, lists, and numpy arrays. </p> <p>When I load this file (again using cPickle on Python 2.7) the python process ends up using 5.13G...
1
2016-09-20T01:05:34Z
39,584,495
<p>One possible culprit here is that Python, by design, overallocates data structures like lists and dictionaries to make appending to them faster, because memory allocations are slow. For example, on a 32-bit Python, an empty dictionary has a <code>sys.getsizeof()</code> of 36 bytes. Add one element and it becomes 52 ...
3
2016-09-20T01:44:56Z
[ "python", "python-2.7", "numpy", "pickle" ]
PCA in sklearn vs numpy is diferent.
39,584,263
<p>Am i misunderstanding something. This is my code </p> <p><strong>using sklearn</strong></p> <pre><code>import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import decomposition from sklearn import datasets from sklearn.preprocessing import StandardScaler pca = de...
0
2016-09-20T01:09:34Z
39,586,059
<p>Don't use <code>StandardScaler</code>. Instead, just subtract the mean of each column from <code>x</code>:</p> <pre><code>In [92]: xm = x - x.mean(axis=0) In [93]: cov = np.cov(xm.T) In [94]: evals, evecs = np.linalg.eig(cov) In [95]: xm.dot(evecs) Out[95]: array([[ -4.2532e+03, -8.3786e-03, -8.4129e-01], ...
2
2016-09-20T05:05:38Z
[ "python", "numpy", "scikit-learn" ]
Python Crash Course 8-15, Not Defined Error
39,584,329
<p>I'm reading the book 'Python Crash Course' by Eric Matthes and I seem to be having issues with exercise 8-15.</p> <p>8-15 says: "Put the functions for the example print_models.py in a separate file called printing_functions.py. Write an import statement at the top of print_models.py, and modify the file to use the ...
0
2016-09-20T01:22:04Z
39,584,403
<p>You've mostly done the correct thing, but variables need to be assigned before you can use them. </p> <p>Also, since you've separated / moved the functions to a module, you have to use those imported ones while the variables remain in this module </p> <pre><code>import printing_functions as pf unprinted_designs ...
1
2016-09-20T01:32:17Z
[ "python" ]
Loop through all pixels of 2 images and replace the black pixels with white
39,584,343
<p>I have 2 co-located images, both created in a similar way and both have the size of 7,221 x 119 pixels.</p> <p>I want to loop through all the pixels of both images. If the pixels are black on the first image and also black on the second image then turn it into white, otherwise, no change.</p> <p>How can I do it wi...
0
2016-09-20T01:24:41Z
39,584,624
<p>I suggest the use of the Pillow library (<a href="https://python-pillow.org/" rel="nofollow">https://python-pillow.org/</a>) which is a fork of the PIL library.</p> <p>Here's something from the Pillow docs: <a href="http://pillow.readthedocs.io/en/3.1.x/reference/PixelAccess.html" rel="nofollow">http://pillow.readt...
0
2016-09-20T02:03:06Z
[ "python", "image" ]
Loop through all pixels of 2 images and replace the black pixels with white
39,584,343
<p>I have 2 co-located images, both created in a similar way and both have the size of 7,221 x 119 pixels.</p> <p>I want to loop through all the pixels of both images. If the pixels are black on the first image and also black on the second image then turn it into white, otherwise, no change.</p> <p>How can I do it wi...
0
2016-09-20T01:24:41Z
39,584,922
<p>This should hopefully be pretty close to what you're looking for.</p> <pre><code>from PIL import Image from PIL import ImageFilter im = Image.open('a.png') imb = Image.open('b.png') pix = im.load() width, height = im.size for w in xrange(width): for h in xrange(height): r...
0
2016-09-20T02:44:15Z
[ "python", "image" ]
Crawling Links from JSON file
39,584,415
<p>So, I am new to the world of web crawlers and I'm having a little difficulty crawling a simple JSON file and retrieving links from it. I am using scrapy framework to try and accomplish this. </p> <p>My JSON example file: </p> <pre><code>{ "pages": [ { "address":"http://foo.bar.com/p1", "links": ["http://fo...
0
2016-09-20T01:33:36Z
39,584,790
<p>So first thing is you need to have a way to parse the json file, <code>json</code> lib should do nicely. Then the next bit would be to run your crawler with the url.</p> <pre><code>import json with open("myExample.json", 'r') as infile: contents = json.load(infile) #contents is now a dictionary of your json ...
-1
2016-09-20T02:25:06Z
[ "python", "scrapy", "web-crawler" ]
python script to check if module is present else install module
39,584,442
<p>I have this simple Python script. I want to include some sort of condition that checks for the Python module (in my example below <code>subprocess</code>) before running it. If the module is not present, install the module then run the script. If the module is present, skip the installation of the module and run the...
1
2016-09-20T01:37:38Z
39,584,932
<p>Here is how you can check if pycurl is installed:</p> <pre><code># if you want to now install pycurl and run it, it is much trickier # technically, you might want to check if pip is installed as well import sys import pip def install(package): pip.main(['install', package]) try: import pycurl except Impo...
1
2016-09-20T02:45:16Z
[ "python", "python-2.7" ]
Pandas Percent Change on Non-Descending Cells
39,584,544
<p>I'm new to Pandas and Stack Overflow, so please bear with me. I'm trying to calculate the percent change on two times (e.g., for a race, not time of day). So suppose I have five athletes. I've formatted the .csv to give me something like the following:</p> <pre><code>In [3]: df Out [3]: Athlete Time ...
1
2016-09-20T01:50:57Z
39,585,018
<pre><code>df1['pct_diff'] = df['seconds'] / df.loc['Chris', 'seconds'] - 1 </code></pre>
1
2016-09-20T02:58:44Z
[ "python", "pandas" ]
Plotting an array of vectors in Python (pyplot)
39,584,547
<p>I'm trying to plot a large array of vectors using pyplot. Right now I've got</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import operator t = np.arange(0, np.pi, .01) def pos1(t): x1 = .72 * np.cos(13*t) y1 = .72 * np.sin(13*t) return x1, y1 def pos2(t): x2 = np.cos(8*t) ...
1
2016-09-20T01:51:41Z
39,612,879
<p><code>quiver</code> handles length of arrows. It seems <code>quiver</code> is not what you need.</p> <p><strong>Using regular <code>plot</code>:</strong></p> <pre><code>import numpy as np import matplotlib.pyplot as plt t = np.arange(0, 2 * np.pi, 0.01) x0 = np.sin(8 * t) y0 = np.cos(8 * t) x1 = 0.72 * np.sin(13...
1
2016-09-21T09:40:17Z
[ "python", "arrays", "numpy" ]
Process command using python
39,584,565
<p>I want to pick up the command and its arguments in Python.</p> <p>I can use </p> <pre><code>process=os.popen('ps -elf').read().split("\n") </code></pre> <p>and then use regular expression to extract the command but its ugly.</p> <p>psutils returns a process name but not the actual commands and arguments</p> <p>...
0
2016-09-20T01:54:21Z
39,585,228
<p><code>psutil</code> can get the command line arguments:</p> <pre><code>import psutil for p in psutil.process_iter(): cmd_line = p.cmdline() if cmd_line: print(cmd_line) </code></pre> <p>EDIT: updated to fix the issue found by @Keir</p>
0
2016-09-20T03:23:53Z
[ "python", "process", "command" ]
Process command using python
39,584,565
<p>I want to pick up the command and its arguments in Python.</p> <p>I can use </p> <pre><code>process=os.popen('ps -elf').read().split("\n") </code></pre> <p>and then use regular expression to extract the command but its ugly.</p> <p>psutils returns a process name but not the actual commands and arguments</p> <p>...
0
2016-09-20T01:54:21Z
39,606,006
<p>The last suggestion is almost correct. It should be</p> <pre><code>for p in psutil.process_iter(): cline = p.cmdline if cline: print(cline) </code></pre>
0
2016-09-21T01:05:50Z
[ "python", "process", "command" ]
How to get request object in scrapy pipeline
39,584,817
<p>I know that when the pipelines are called, it means the request have been stopped, generally we should do some validation,persist job based on the extracted item, it seems there is no sense to get request in the pipeline.</p> <p>However I found it may useful in certain situation,in my application I use two pipeline...
0
2016-09-20T02:29:43Z
39,585,287
<p>Here are two approaches:</p> <ol> <li><p>Add a dummy field to the item to store whatever you want in the spider code. And later retrieve the value (and pop out the field) in the item pipeline.</p></li> <li><p>Instead of using an item pipeline, use a <a href="http://doc.scrapy.org/en/latest/topics/spider-middleware....
2
2016-09-20T03:32:15Z
[ "python", "scrapy" ]
Loop through a finite language described by regex in python
39,584,908
<p>The given input is a regex that describe a finite language. Is there a simple way to enumerate the language in python (or in other programming language)?</p> <p>The following is what I expect:</p> <p>Psuedocode:</p> <pre><code>for x in r'[a-c]': print(x) </code></pre> <p>Output:</p> <pre><code>a b c </code>...
2
2016-09-20T02:42:25Z
39,630,865
<p>There's no way to do this with the built-in <code>re</code> module.</p> <p>Instead, what you need to do is build your own regular expression parser and use that to generate your language.</p> <p>Just to see if I could do it, I made a <em>basic</em> regular expression parser and generator. The code is 410 lines lo...
0
2016-09-22T05:25:28Z
[ "python", "regex" ]
Python Pandas Data sampling/aggregation
39,584,916
<p>I have a huge comma separated datetime, <code>unique_id</code> dataset which looks as below.</p> <pre><code>datetime, unique_id 2016-09-01 19:50:01, bca8ca1c91d283212faaade44c6185956265cc09 2016-09-01 19:50:02, ddd20611d47597435412739db48b0cb04599e340 2016-09-01 19:50:10, 5b8776d7dc0b83f9bd9ad70a403a5f605e37d4d4 ...
1
2016-09-20T02:43:18Z
39,584,979
<p>You can set the datetime as index and use the <code>pandas.TimeGrouper</code> to create the group variable, which can group your data frame with specified frequency in time, and then count the number of unique ids:</p> <pre><code>import pandas as pd df.set_index(pd.to_datetime(df.datetime)).groupby(pd.TimeGrouper(f...
2
2016-09-20T02:53:55Z
[ "python", "python-2.7", "pandas", "group", "aggregate" ]
Python Pandas Data sampling/aggregation
39,584,916
<p>I have a huge comma separated datetime, <code>unique_id</code> dataset which looks as below.</p> <pre><code>datetime, unique_id 2016-09-01 19:50:01, bca8ca1c91d283212faaade44c6185956265cc09 2016-09-01 19:50:02, ddd20611d47597435412739db48b0cb04599e340 2016-09-01 19:50:10, 5b8776d7dc0b83f9bd9ad70a403a5f605e37d4d4 ...
1
2016-09-20T02:43:18Z
39,586,252
<p>I think you need specify <code>Series</code> - <code>['unique_id']</code> and add <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.tseries.resample.Resampler.nunique.html" rel="nofollow"><code>Resampler.nunique</code></a>:</p> <pre><code>resampled_data = raw_df.set_index(pd.DatetimeIndex(raw_d...
2
2016-09-20T05:23:33Z
[ "python", "python-2.7", "pandas", "group", "aggregate" ]
How to make a function that replaces the exponent feature?
39,584,924
<p>Before hand yes this is a homework question. Well there are two I'd like to ask for help with. The first one is a function that needs to take two numbers (base, exp) and then multiply base by itself by the amount of times that exponent represents. eg. base = 2, exp = 3. it would be 2*2*2. So far this is what I have:...
0
2016-09-20T02:44:21Z
39,585,063
<p>You probably just want:</p> <pre><code>ans = 1 for i in range(exp): ans *= base return ans </code></pre> <p>As your last condition.<br> You also don't need the middle condition.</p>
1
2016-09-20T03:03:54Z
[ "python", "python-3.x" ]
How to make a function that replaces the exponent feature?
39,584,924
<p>Before hand yes this is a homework question. Well there are two I'd like to ask for help with. The first one is a function that needs to take two numbers (base, exp) and then multiply base by itself by the amount of times that exponent represents. eg. base = 2, exp = 3. it would be 2*2*2. So far this is what I have:...
0
2016-09-20T02:44:21Z
39,585,085
<p>It should work.</p> <pre><code>def iterPower(base, exp): if base &lt; 0: return 0 ans = 1 for i in range(exp): ans *= base return ans </code></pre> <p>First, check how the conditionals work in Python, <code>base and exp &lt;= 0</code> is different than <code>base &lt;= 0 and exp &lt...
0
2016-09-20T03:06:05Z
[ "python", "python-3.x" ]
How to make a function that replaces the exponent feature?
39,584,924
<p>Before hand yes this is a homework question. Well there are two I'd like to ask for help with. The first one is a function that needs to take two numbers (base, exp) and then multiply base by itself by the amount of times that exponent represents. eg. base = 2, exp = 3. it would be 2*2*2. So far this is what I have:...
0
2016-09-20T02:44:21Z
39,585,105
<p>Can also use a while loop to shorten your code.</p> <pre><code>def iterPower(base, exp): answer = 1 while exp &gt; 0: answer *= base exp -= 1 return answer </code></pre>
0
2016-09-20T03:08:03Z
[ "python", "python-3.x" ]
How to make a function that replaces the exponent feature?
39,584,924
<p>Before hand yes this is a homework question. Well there are two I'd like to ask for help with. The first one is a function that needs to take two numbers (base, exp) and then multiply base by itself by the amount of times that exponent represents. eg. base = 2, exp = 3. it would be 2*2*2. So far this is what I have:...
0
2016-09-20T02:44:21Z
39,585,112
<p>There are a couple of issues with your code.</p> <ol> <li><p>The statement <code>if base and exp &lt;= 0</code> basically translates to <code>if (base) and (exp &lt;= 0)</code>. Here the conditions are evaluated separately. You may want to use <code>if base &lt;= 0 and exp &lt;= 0:</code> (or something similar).</p...
0
2016-09-20T03:08:50Z
[ "python", "python-3.x" ]
How to make a function that replaces the exponent feature?
39,584,924
<p>Before hand yes this is a homework question. Well there are two I'd like to ask for help with. The first one is a function that needs to take two numbers (base, exp) and then multiply base by itself by the amount of times that exponent represents. eg. base = 2, exp = 3. it would be 2*2*2. So far this is what I have:...
0
2016-09-20T02:44:21Z
39,585,114
<p>1I think the code you want is:</p> <pre><code>def iterPower( base, exp ): if base and exp &lt; 0: return 0 elif base and exp == 0: return 1 elif base and exp == 1: return base else: ans = base for i in range( 1, exp ): ans *= base return a...
0
2016-09-20T03:09:10Z
[ "python", "python-3.x" ]
How to install virtualenv on Centos6?
39,584,981
<p>I want to apply my Flask project on my workplace Centos6. So I followed guide from google to install pip, virtualenv, and flask, but I cannot successfully install either pip or virtualenv.</p> <p>What I have done is this:</p> <p>1) <a href="http://sharadchhetri.com/2014/05/30/install-pip-centos-rhel-ubuntu-debian/...
-3
2016-09-20T02:54:10Z
39,605,794
<p>Thankyou for the advices</p> <p>what I have done is to not use pip, instead I just download python module packages.</p> <p>I went to the link <a href="http://pypi.python.org/simple/" rel="nofollow">http://pypi.python.org/simple/</a> which I got from error message from above (my 3 trial)</p> <p>and download [packa...
0
2016-09-21T00:39:14Z
[ "python", "flask", "pip", "virtualenv", "centos6" ]
Run time call within pprint
39,585,003
<p>How to pass value inside pprint at run time?</p> <pre><code>import nltk, sys from pprint import pprint from nltk.corpus import framenet as fn #Word = raw_input("enter a word: ") pprint(fn.frames(r'(?i)Medical_specialties')) f = fn.frame(256) f.ID f.name f.definition print f print '\b' pprint(sorted([x for x in f.FE...
0
2016-09-20T02:56:45Z
39,594,091
<p>Although you happen to be working with the <code>nltk</code>, your question has nothing to do with it (or with <code>pprint</code>, for that matter): You need to input a string from the user, then stick <code>"(?i)"</code> in front to construct your desired regexp. </p> <p>Since that's all you need to do, the simpl...
1
2016-09-20T12:27:53Z
[ "python", "python-2.7", "function", "pprint" ]
Quickest way to find smallest Hamming distance in a list of fixed-length hexes
39,585,069
<p>I'm using <a href="https://github.com/JohannesBuchner/imagehash" rel="nofollow">Imagehash</a> in Python to generate 48-digit hexadecimal hashes of around 30,000 images, which I'm storing in a list of dictionaries (the phashes as well as some other image properties). For example:</p> <pre><code>[{"name":"name1", "ph...
0
2016-09-20T03:04:36Z
39,585,339
<p><a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.spatial.distance.pdist.html" rel="nofollow">Scipy's pairwise distance function </a> supports Hamming distances. I'd try that.</p>
-1
2016-09-20T03:39:29Z
[ "python", "hamming-distance" ]
Quickest way to find smallest Hamming distance in a list of fixed-length hexes
39,585,069
<p>I'm using <a href="https://github.com/JohannesBuchner/imagehash" rel="nofollow">Imagehash</a> in Python to generate 48-digit hexadecimal hashes of around 30,000 images, which I'm storing in a list of dictionaries (the phashes as well as some other image properties). For example:</p> <pre><code>[{"name":"name1", "ph...
0
2016-09-20T03:04:36Z
39,671,900
<p>I got an answer from the guy behind ImageHash, <a href="https://github.com/JohannesBuchner" rel="nofollow">Johannes Buchner</a>.</p> <p>I can store the DB as a 2d matrix:</p> <pre><code>arr = [] for dbHash in db: arr.append(dbHash.hash.flatten()) arr = numpy.array(arr) </code></pre> <p>Then I can do the compa...
0
2016-09-24T02:25:03Z
[ "python", "hamming-distance" ]
Number refuses to divide
39,585,070
<p>I have made a simple function called "Approx" which multiplies two numbers together then divides them by two. When I use the function by itself it works great but it seems in the hunk of code I have it doesn't divide the number in half and I have no idea why. This is my code where is the error and how can I fix it?<...
0
2016-09-20T03:04:43Z
39,605,552
<p>Your function works the way you describe it, however I don't understand how you use it in the rest of the code.</p> <p>It seems like you are trying to approximate square roots using a variant of Newton's method, but it's hard to understand how you implement it. Some variables in your code are not used (what is <cod...
1
2016-09-21T00:05:31Z
[ "python", "python-3.x" ]
Number refuses to divide
39,585,070
<p>I have made a simple function called "Approx" which multiplies two numbers together then divides them by two. When I use the function by itself it works great but it seems in the hunk of code I have it doesn't divide the number in half and I have no idea why. This is my code where is the error and how can I fix it?<...
0
2016-09-20T03:04:43Z
39,605,809
<p>It looks to me that it definitely <strong>does</strong> divide by two, it is just that dividing by two doesn't undo multiplying two large numbers together. For example, say you wanted to find the square root of <code>10</code>. <code>trunk</code> is set to <code>11</code>. <code>Approx(root, trunk)</code> is <code>1...
1
2016-09-21T00:41:33Z
[ "python", "python-3.x" ]
How to increment training Theano saved models?
39,585,131
<p>I have a trained model by <a href="http://www.deeplearning.net/software/theano/" rel="nofollow">Theano</a>, and there are new training data I want to increase the mode, How could I do this?</p>
0
2016-09-20T03:11:21Z
39,589,279
<p>Initialize the model with the pre-trained weights and perform gradient updates for the new examples, but you do have to take care of the learning rate and other parameters (depending on your optimizer). You may also try storing optimizer's parameter as well, initializing the optimizer with those values of parameters...
1
2016-09-20T08:34:20Z
[ "python", "numpy", "machine-learning", "neural-network", "theano" ]
Python: print the dictionary elements which has multiple values assigned for each key
39,585,179
<p>I've got a dictionary like the one, below:</p> <pre><code>{ "amplifier": ["t_audio"], "airbag": ["t_trigger"], "trigger": ["t_sensor1", "t_sensor2"], "hu": ["t_fused"], "cam": ["t_front", "t_ldw", "t_left", "t_nivi", "t_rear_camera", "t_right"], "video_screen": ["t_video"] } </co...
1
2016-09-20T03:17:57Z
39,585,212
<pre><code>for k, v in mydict.iteritems(): for vv in v: print "group(%s,%s)" % (k,vv) #or print "group(",k,",",vv,")" #or the python 3 format syntax </code></pre>
0
2016-09-20T03:22:08Z
[ "python", "list", "dictionary" ]
Python: print the dictionary elements which has multiple values assigned for each key
39,585,179
<p>I've got a dictionary like the one, below:</p> <pre><code>{ "amplifier": ["t_audio"], "airbag": ["t_trigger"], "trigger": ["t_sensor1", "t_sensor2"], "hu": ["t_fused"], "cam": ["t_front", "t_ldw", "t_left", "t_nivi", "t_rear_camera", "t_right"], "video_screen": ["t_video"] } </co...
1
2016-09-20T03:17:57Z
39,585,231
<pre><code>for key in dict: for value in dict[key]: print value </code></pre>
0
2016-09-20T03:24:07Z
[ "python", "list", "dictionary" ]
Python: print the dictionary elements which has multiple values assigned for each key
39,585,179
<p>I've got a dictionary like the one, below:</p> <pre><code>{ "amplifier": ["t_audio"], "airbag": ["t_trigger"], "trigger": ["t_sensor1", "t_sensor2"], "hu": ["t_fused"], "cam": ["t_front", "t_ldw", "t_left", "t_nivi", "t_rear_camera", "t_right"], "video_screen": ["t_video"] } </co...
1
2016-09-20T03:17:57Z
39,585,280
<p>Very simple: loop through each key in the dictionary. Since each value is going to be a list with one or more elements, just loop through those and print the string you need:</p> <pre><code>d = {'amplifier': ['t_audio'], 'hu': ['t_fused'], 'trigger': ['t_sensor1', 't_sensor2'], 'cam': ['t_front', 't_ldw', 't_left',...
1
2016-09-20T03:31:11Z
[ "python", "list", "dictionary" ]
BeautifulSoup - How do I get all <div> from a class in html?
39,585,184
<p>I am trying to get a list of all NFL teams from a website and I am very close. I am able to get some data, but I can't drill down far enough to get what I want.</p> <p>My code:</p> <pre><code>from bs4 import BeautifulSoup import requests f = open('C:\Users\Josh\Documents\Python\outFileRoto.txt', 'w') errorFile = ...
0
2016-09-20T03:18:41Z
39,585,457
<p>To drill down further, get beautifulsoup to return the div that has the class "rgt-col", and the style "display: block;".</p> <p>Once you have that, drill down further by finding all the divs within that div, but ignoring the first result. Or you can also get all the divs that do not have a class.</p> <p>EDIT 1: T...
1
2016-09-20T03:58:22Z
[ "python", "python-2.7", "beautifulsoup", "python-requests" ]
BeautifulSoup - How do I get all <div> from a class in html?
39,585,184
<p>I am trying to get a list of all NFL teams from a website and I am very close. I am able to get some data, but I can't drill down far enough to get what I want.</p> <p>My code:</p> <pre><code>from bs4 import BeautifulSoup import requests f = open('C:\Users\Josh\Documents\Python\outFileRoto.txt', 'w') errorFile = ...
0
2016-09-20T03:18:41Z
39,586,338
<p>It looks like your main problem is that the table you're interested in is dynamically built by JS. See this answer for info on scraping dynamically loaded content. <a href="http://stackoverflow.com/questions/17597424/how-to-retrieve-the-values-of-dynamic-html-content-using-python">How to retrieve the values of dyn...
0
2016-09-20T05:29:54Z
[ "python", "python-2.7", "beautifulsoup", "python-requests" ]
BeautifulSoup - How do I get all <div> from a class in html?
39,585,184
<p>I am trying to get a list of all NFL teams from a website and I am very close. I am able to get some data, but I can't drill down far enough to get what I want.</p> <p>My code:</p> <pre><code>from bs4 import BeautifulSoup import requests f = open('C:\Users\Josh\Documents\Python\outFileRoto.txt', 'w') errorFile = ...
0
2016-09-20T03:18:41Z
39,589,610
<p>The data is in <em>json</em> format in the page source inside the <code>$(document).ready(function()</code> call which is what loads the data you see in your browser. You just need to find the correct <em>script</em> tag with <em>bs4</em> and parse it using a regex then use <em>json.loads</em> the result to get a li...
1
2016-09-20T08:50:01Z
[ "python", "python-2.7", "beautifulsoup", "python-requests" ]
mac two version python conflict
39,585,238
<p>I installed python3.5 on my mac, its installation was automatically. but these days i found there was already python2 on my mac and every module i installed through pip went to <code>/Library/Python/2.7/site-packages</code>.</p> <p>I find python3 installed location is <code>/Library/Frameworks/Python.framework/Vers...
0
2016-09-20T03:25:42Z
39,585,904
<p>for mysql-connector installation problem, i found the solution:</p> <p>Try go to python3 bin directory and find pip method. this pip method can be override by the system python2 pip command, so if you want to install MySQL-python module to python3.x site-packages, you should cd to such bin directory and <code>./pip...
0
2016-09-20T04:50:11Z
[ "python", "osx" ]
How to add a class instance from user input in python?
39,585,258
<pre><code>class Student(object): def __init__(self, name, chinese = 0, math = 0, english = 0): self.name = name self.chinese = chinese self.math = math self.english = english self.total = self.chinese + self.math + self.english Student.list.append(name)' </code></pre...
0
2016-09-20T03:27:54Z
39,585,294
<pre><code>import pprint class Student(): #blah blah blah if __name__ == "__main__": list_of_students = [] while True: if raw_input("Add student? (y/n)") == "n": break # ask your questions here list_of_students.append( Student( # student data ) ) for student in list_of_s...
0
2016-09-20T03:33:29Z
[ "python" ]
How to add a class instance from user input in python?
39,585,258
<pre><code>class Student(object): def __init__(self, name, chinese = 0, math = 0, english = 0): self.name = name self.chinese = chinese self.math = math self.english = english self.total = self.chinese + self.math + self.english Student.list.append(name)' </code></pre...
0
2016-09-20T03:27:54Z
39,585,551
<p>Try doing it the following way. :</p> <pre><code>from collections import defaultdict class Student: def __init__(self, name=None, chinese=None, math=None, english=None): self.student_info = defaultdict(list) if name is not None: self.student_info['name'].append(name) sel...
0
2016-09-20T04:09:56Z
[ "python" ]
Get unique intersection values of two sets
39,585,328
<p>I'd like to get the indexes of unique vectors using hash (for matrices it is efficient) but np.intersect1d does not give indices, it gives values. np.in1d on the other hand does give indices but not unique ones. I zipped a dict to make it work but it doesn't seem like the most efficient. I am new to python so trying...
3
2016-09-20T03:38:37Z
39,587,314
<p>The <a href="https://github.com/EelcoHoogendoorn/Numpy_arraysetops_EP" rel="nofollow">numpy_indexed</a> package (disclaimer: I am its author) has efficient functionality for doing things like this (and related functionality):</p> <pre><code>import numpy_indexed as npi uniques = npi.intersection(x, y) </code></pre> ...
0
2016-09-20T06:40:42Z
[ "python", "numpy", "hash", "intersection" ]
Get unique intersection values of two sets
39,585,328
<p>I'd like to get the indexes of unique vectors using hash (for matrices it is efficient) but np.intersect1d does not give indices, it gives values. np.in1d on the other hand does give indices but not unique ones. I zipped a dict to make it work but it doesn't seem like the most efficient. I am new to python so trying...
3
2016-09-20T03:38:37Z
39,592,711
<p>Use np.unique's return_index property to return flags for the unique values given by in1d</p> <p>code:</p> <pre><code>import numpy as np import hashlib x=np.array([[1, 2, 3],[1, 2, 3], [4, 5, 6], [7, 8, 9]]) y=np.array([[1, 2, 3], [7, 8, 9]]) xhash=[hashlib.sha1(row).digest() for row in x] yhash=[hashlib.sha1(row)...
0
2016-09-20T11:19:40Z
[ "python", "numpy", "hash", "intersection" ]
Python current time comparison with other time
39,585,338
<p>I am looking for a comparison of two times in Python. One time is the real time from computer and the other time is stored in a string formatted like <code>"01:23:00"</code>.</p> <pre><code>import time ctime = time.strptime("%H:%M:%S") # this always takes system time time2 = "08:00:00" if (ctime &gt; time2): ...
2
2016-09-20T03:39:20Z
39,585,471
<p><a href="https://docs.python.org/2/library/datetime.html" rel="nofollow">https://docs.python.org/2/library/datetime.html</a></p> <p>The <code>datetime</code> module will parse dates, times, or combined date-time values into objects that can be compared.</p>
0
2016-09-20T03:59:39Z
[ "python", "python-2.7", "datetime" ]
Python current time comparison with other time
39,585,338
<p>I am looking for a comparison of two times in Python. One time is the real time from computer and the other time is stored in a string formatted like <code>"01:23:00"</code>.</p> <pre><code>import time ctime = time.strptime("%H:%M:%S") # this always takes system time time2 = "08:00:00" if (ctime &gt; time2): ...
2
2016-09-20T03:39:20Z
39,585,673
<pre><code>import datetime now = datetime.datetime.now() my_time_string = "01:20:33" my_datetime = datetime.datetime.strptime(my_time_string, "%H:%M:%S") # I am supposing that the date must be the same as now my_datetime = now.replace(hour=my_datetime.time().hour, minute=my_datetime.time().minute, second=my_datetime...
2
2016-09-20T04:27:01Z
[ "python", "python-2.7", "datetime" ]
Python current time comparison with other time
39,585,338
<p>I am looking for a comparison of two times in Python. One time is the real time from computer and the other time is stored in a string formatted like <code>"01:23:00"</code>.</p> <pre><code>import time ctime = time.strptime("%H:%M:%S") # this always takes system time time2 = "08:00:00" if (ctime &gt; time2): ...
2
2016-09-20T03:39:20Z
39,586,091
<pre><code>from datetime import datetime current_time = datetime.strftime(datetime.utcnow(),"%H:%M:%S") #output: 11:12:12 mytime = "10:12:34" if current_time &gt; mytime: print "Time has passed." </code></pre>
0
2016-09-20T05:08:39Z
[ "python", "python-2.7", "datetime" ]
Show how a projectile (turtle) travels over time
39,585,354
<p>I am new to Python, and currently having a rough time with turtle graphics. This is what I am trying to solve</p> <blockquote> <p>On Turtellini (the planet where Python turtles live) the transportation system propels turtles with a giant slingshot. A particular turtle's original location (x0, y0) is (-180, -1...
0
2016-09-20T03:41:55Z
39,736,969
<p>You seem to have most of the parts and pieces. The biggest issue I see is you didn't put your x,y calculation in the loop. The loop iteration variable <code>i</code> is really <code>t</code> in your motion equations. Each time you calculate a new x,y you simply move the turtle to that position:</p> <pre><code>im...
0
2016-09-28T02:12:30Z
[ "python", "turtle-graphics" ]
Deskew Text with OpenCV and Python (RotatedRect, minAreaRect)
39,585,407
<p>I'm new with OpenCV and I want to deskew an image that have a skewed text. First I read the image in GrayScale and Binarize it, then I try to do <a href="http://opencvpython.blogspot.com.ar/2012/06/contours-2-brotherhood.html" rel="nofollow">this</a>:</p> <pre><code>import cv2 import numpy as np img = cv2.imread('...
0
2016-09-20T03:50:58Z
39,585,700
<p>Maybe you can check this out: <a href="http://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/" rel="nofollow">http://www.pyimagesearch.com/2014/08/25/4-point-opencv-getperspective-transform-example/</a></p> <p>In that link, the author deskews or transforms the entire document (and ...
0
2016-09-20T04:30:13Z
[ "python", "c++", "opencv", "vertices", "skew" ]
Python USB Serial works in IDLE but not when run as a file
39,585,435
<p>I'm currently attempting to write over USB serial to an Arduino Nano of mine using Python. However, what I've discovered is that (using the <em>exact</em> same code), the code works perfectly when I type it into IDLE, but when I save it to a file and attempt to run from there, for some reason the Arduino is never re...
0
2016-09-20T03:54:34Z
39,585,773
<p>I somehow missed this answer on SO before (<a href="http://stackoverflow.com/questions/28192190/pyserial-write-works-fine-in-python-interpreter-but-not-python-script?rq=1">pySerial write() works fine in Python interpreter, but not Python script</a>), but it turns out that I needed to add a time.sleep(2) after openin...
0
2016-09-20T04:37:35Z
[ "python", "arduino", "raspberry-pi", "pyserial" ]
Is there a way to return a dictionary value without quotations?
39,585,570
<p>Sorry if this is somewhere out there but I just couldn't find a solution to what I was looking for. I want to return the value of my dictionary without the quotations and can't figure out what I'm doing wrong.</p> <pre><code>def read_wiktionary(): answer = dict() f = open('wiktionary.txt', 'r') for line in f: ...
-2
2016-09-20T04:12:55Z
39,585,608
<p>The quotation is just used as a separator between different keys and values so it cannot be removed.The quotation doesn't affect your values in the dictionary.</p>
0
2016-09-20T04:20:10Z
[ "python", "dictionary", "return" ]
Is there a way to return a dictionary value without quotations?
39,585,570
<p>Sorry if this is somewhere out there but I just couldn't find a solution to what I was looking for. I want to return the value of my dictionary without the quotations and can't figure out what I'm doing wrong.</p> <pre><code>def read_wiktionary(): answer = dict() f = open('wiktionary.txt', 'r') for line in f: ...
-2
2016-09-20T04:12:55Z
39,585,676
<p>When you read a file, everything is read as a string. To get a float value, you'll need to cast it to a float.</p> <pre><code>def read_wiktionary(): answer = dict() f = open('wiktionary.txt', 'r') for line in f: word, value = line.rstrip('\n').split(' ') answer[word] = float(value) r...
0
2016-09-20T04:27:20Z
[ "python", "dictionary", "return" ]
Python UDP communication using Socket, check data received
39,585,724
<p>I'm pretty new to the Python, trying to write a code to receive string from UDP connection, the problem I have now is that I need to receive data from 2 sources, I want the program continue looping if there is no data from either or both of them, but now if there is no data from source 2, it will stop there and wait...
0
2016-09-20T04:32:50Z
39,585,988
<p>If <a href="https://docs.python.org/2/library/select.html" rel="nofollow">select</a> doesn't work out for you you can always throw them into a thread. You'll just have to be careful about the shared data and place good mutex around them. See <a href="https://docs.python.org/2/library/threading.html#threading.Lock" ...
1
2016-09-20T04:59:48Z
[ "python", "sockets", "udp" ]
Global list is appending nothing
39,585,833
<pre><code>answers = [] def search(visit_order, nodes_to_visit, distance): if len(nodes_to_visit) == 0: print visit_order answers.append(visit_order) return else: for node in nodes_to_visit: nodes_to_visit.remove(node) visit_order.append(node) ...
0
2016-09-20T04:43:42Z
39,586,364
<p>So the problem is you are appending <em>the same object</em> to <code>answers</code> which you then empty. Check the output of <code>[id(e) for e in answers]</code> and you should see the same object ids. A quick fix is to append <em>a copy</em> by using <code>answers.append(list(visit_order))</code> or <code>answer...
0
2016-09-20T05:31:55Z
[ "python", "list", "global" ]
Swagger Integration in Django
39,585,869
<p>I need to integrate Swagger in Django. So, can anyone discuss the steps to integrate Swagger in Django. I need the full description.</p> <p>Thanks in advance.</p>
0
2016-09-20T04:46:59Z
39,586,908
<p>If you're trying to use Swagger, then I'm sure you're building an API (REST). So answering to your wide range question about Swagger integration with Django, you can use Django Rest Framework + Swagger (which I recommend) or Swagger only. What you need to do in this case:</p> <h2>Django Rest Framework + Swagger</h2...
1
2016-09-20T06:14:12Z
[ "python", "django", "python-2.7", "swagger", "swagger-ui" ]
what's wrong with my code? countconsonant
39,585,895
<pre><code>def countConsonant (s): """Count consonants. 'y' and 'Y' are not consonants. Params: s (string) Returns: (int) #consonants in s (either case) """ # do not use a brute force solution: # think of a short elegant solution (mine is 5 lines long); # do not use lines longer than...
-7
2016-09-20T04:49:40Z
39,585,918
<p><code>==</code> checks for equality, and that's probably not what you want. You have to use the <code>in</code> operator to check membership, and in this case membership of a character in a string. It follows this general syntax:</p> <pre><code>if x in y: </code></pre> <p>Where <code>x</code> is the operand or the...
3
2016-09-20T04:51:24Z
[ "python" ]
what's wrong with my code? countconsonant
39,585,895
<pre><code>def countConsonant (s): """Count consonants. 'y' and 'Y' are not consonants. Params: s (string) Returns: (int) #consonants in s (either case) """ # do not use a brute force solution: # think of a short elegant solution (mine is 5 lines long); # do not use lines longer than...
-7
2016-09-20T04:49:40Z
39,587,592
<p>With the statement </p> <p><code>for index in s:</code> </p> <p>you are iterating over all the characters in s. So the condition </p> <p><code>if index == 'bcdfghjklmnpqrstvwxyz':</code></p> <p>ever evaluates to<code>False</code> and the function returns 0 in every cases.</p> <p>To check the membership of a cha...
0
2016-09-20T06:57:43Z
[ "python" ]
tkinter tag_config does not work
39,585,905
<p>I am building a notepad like application in tkinter-python. There is an option to change the font of the text writen in the text field of the application.</p> <p>I have created a Font Chooser popup screen to be called from main window on clicking 'font' menu, which basically creates a FontChooser class object and p...
0
2016-09-20T04:50:14Z
39,607,923
<p>IDLE uses tag_config to syntax color python code and it works on all Python versions and major OSes for the last 15 years.</p> <p>To have some idea of why it seems to fail for you, you need to find an <a href="https://stackoverflow.com/help/mcve">MCVE</a> that fails. Start without tix and scrollbars. (Tix is depr...
0
2016-09-21T05:02:32Z
[ "python", "tkinter" ]
Python- obtain maximum value in an interval
39,586,287
<p>I have a .CSV file (a list) that contains 43142 rows and 2 columns.</p> <p>When plotting the list's values x vs y:</p> <pre><code> import numpy as np import matplotlib.pyplot as plt filename=np.genfromtxt(list.CSV,delimiter=',') plt.plot(filename[:,0],filename[:,1]) </code></pre> <p>I get a graph ...
1
2016-09-20T05:26:32Z
39,586,753
<p>If you have a range <code>xmin &lt; x &lt; xmax</code> then this should work (taking <code>x=filename[:,0]</code> and <code>y=filename[:,1]</code>) :</p> <pre><code>idx = np.where(y==np.max(y[(x&gt;xmin)&amp;(x&lt;xmax)]))[0][0] </code></pre> <p>This will return a single index corresponding to the maximum y value ...
0
2016-09-20T06:02:36Z
[ "python", "python-2.7", "numpy", "argmax" ]
(Scrapy) How to get the CSS rule for a HTML element?
39,586,331
<p>I am building a crawler using Scrapy. I need to get the font-family assigned to a particular HTML element.</p> <p>Let's say there is a css file, styles.css, which contains the following:</p> <pre><code>p { font-family: "Times New Roman", Georgia, Serif; } </code></pre> <p>And in the HTML page there is text as...
0
2016-09-20T05:29:14Z
39,589,441
<p>You need to download and parse css seperately. For css parsing you can use <a href="https://pythonhosted.org/tinycss/" rel="nofollow">tinycss</a> or even regex:</p> <pre><code>import tinycss class MySpider(Spider): name='myspider' start_urls = [ 'http://some.url.com' ] css_rules = {} def pa...
1
2016-09-20T08:42:24Z
[ "python", "xpath", "scrapy" ]
Kivy scatter region is limited to window size
39,586,388
<p>I'm basically running into issues with the only "grabbable" scatter regions being entirely defined by the size of the window I am viewing the program in, and not the size of the scatter.</p> <p>Here's a working example of the bug:</p> <pre><code>from kivy.app import App from kivy.uix.widget import Widget from kivy...
0
2016-09-20T05:34:31Z
39,605,397
<p>Ok. I couldn't figure out a way to do it with the vanilla scatter object itself, but I made a workaround that seems to work well enough.</p> <p>Basically, scatter controls what's grabbable through the <code>collide_point</code> method in its class. This class references its own width/height (which are irritatingly...
0
2016-09-20T23:45:32Z
[ "python", "kivy" ]
How to compare decimal numbers available in columns of pandas dataframe?
39,586,398
<p>I want to compare decimal values which are available in two columns of pandas dataframe.</p> <p>I have a dataframe:</p> <pre><code>data = {'AA' :{0:'-14.35',1:'632.0',2:'619.5',3:'352.35',4:'347.7',5:'100'}, 'BB' :{0:'-14.3500',1:'632.0000',2:'619.5000',3:'352.3500',4:'347.7000',5:'200'} } df1 = pd....
3
2016-09-20T05:35:18Z
39,586,425
<p>You need cast column to <code>float</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="nofollow"><code>astype</code></a> and then compare columns, because <code>type</code> of values in columns is <code>string</code>. Then use <a href="http://pandas.pydata.org/pa...
2
2016-09-20T05:37:14Z
[ "python", "pandas", "indexing", "dataframe", "condition" ]
Python tracing, doesnt show the indexes
39,586,439
<p>Hey people i just got a quick question, for some of you it might be very simple but please help out. lets say we got:</p> <pre><code>--- modulename: test, funcname: &lt;module&gt; test.py(1): nums = [3, 1, 2, 10] test.py(3): where = 0 test.py(5): for number in range(1, len(nums)): test.py(7): if nums[number] &lt;...
0
2016-09-20T05:38:46Z
39,586,540
<p>Add print statement where you want to see output.</p> <p><strong>Version:</strong></p> <pre><code>[root@dsp-centos ~]# python -V Python 2.7.5 [root@dsp-centos ~]# [root@dsp-centos ~]# python -m trace --version trace 2.0 [root@dsp-centos ~]# </code></pre> <p><strong>Code :</strong></p> <pre><code>nums = [33, 21, ...
0
2016-09-20T05:45:56Z
[ "python", "tracing" ]
Python tracing, doesnt show the indexes
39,586,439
<p>Hey people i just got a quick question, for some of you it might be very simple but please help out. lets say we got:</p> <pre><code>--- modulename: test, funcname: &lt;module&gt; test.py(1): nums = [3, 1, 2, 10] test.py(3): where = 0 test.py(5): for number in range(1, len(nums)): test.py(7): if nums[number] &lt;...
0
2016-09-20T05:38:46Z
39,586,770
<p>You need to format it accordingly to see what goes inside at each step</p> <pre><code>nums = [33, 21, 4, 8] where = 0 for number in range(1, len(nums)): print number if nums[number] &lt; nums[where]: print where where = number answer = nums[where] print answer </code></pre>
0
2016-09-20T06:04:06Z
[ "python", "tracing" ]
Referencing an object of a model with all foreign keys in Django admin UI
39,586,476
<p>I am developing my Djnago app for processing data into DB from admin frontend. I have a table with both foreign keys in it.</p> <p><code>class exam_questions(models.Model): exam_id=models.ForeignKey(exams, on_delete=models.CASCADE) question_id=models.ForeignKey(questions, on_delete=models.CASCADE) def ...
0
2016-09-20T05:41:42Z
39,586,618
<p>You need to provide the <code>__str__</code> or <code>__unicode__</code> functions, with regard to your python version, in a model for Django admin to be able to list items with their proper intended information.</p> <pre><code>@python_2_unicode_compatible class exam_questions(models.Model): exam_id=models.Fore...
2
2016-09-20T05:51:52Z
[ "python", "mysql", "django" ]