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 is int() implemented in Python?
38,542,263
<p>How does it convert binary numbers to base 10 as quickly as it does? bin() returns a string, how does it convert them to integers to do the math on them?</p>
0
2016-07-23T13:22:10Z
38,542,789
<p>you can use int plus extra parameter to convert it </p> <pre><code>int('1000', 2) output: 8 </code></pre> <p>int class:</p> <pre><code>class int(x, base=10) </code></pre> <blockquote> <p>Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, i...
0
2016-07-23T14:21:02Z
[ "python", "binary" ]
Python3 webserver communicate between threads for IRC bot
38,542,298
<p>I've read a lot of documentation about Threading, Queuing, Pooling etc. but still couldn't figure out how to solve my problem. Here's the situation : I built a python3 Django application that's served by cherrypy. The application is basically another IRC client. When I use the GUI to run my code the first time, an I...
0
2016-07-23T13:26:22Z
38,542,615
<p>The problem is, as you noticed, that you spawn a new thread/bot each time there is an upload. A possible solution would be to rewrite your code to do something like this:</p> <pre><code>event_queue = multiprocessing.Queue() # Events that will be sent to the IRC bot thread def irc_bot_thread(): bot = connect_to...
1
2016-07-23T14:01:27Z
[ "python", "django", "multithreading", "irc" ]
Could pandas use column as index?
38,542,419
<p>I have a spreadsheet like this:</p> <pre><code>Locality 2005 2006 2007 2008 2009 ABBOTSFORD 427000 448000 602500 600000 638500 ABERFELDIE 534000 600000 735000 710000 775000 AIREYS INLET459000 440000 430000 517500 512500 </code></pre> <p>I don't want to manually swap the column with th...
0
2016-07-23T13:39:10Z
38,542,447
<p>Yes, with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow">set_index</a> you can make Locality your row index. <em>If you want to swap all row and column labels/indices, transpose is the way to go as <a href="http://stackoverflow.com/a/38542453/6525140">P...
1
2016-07-23T13:42:12Z
[ "python", "excel", "pandas" ]
Palindrome recursive function
38,542,526
<p>I tried to write a <strong>recursive</strong> function that says if a string is a palindrome, but all I get is an infinite loop and I don't know what the problem is</p> <pre><code>def isPalindrome(S): listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a'] length=len(listush) #length=6 if length==0 or l...
-1
2016-07-23T13:52:06Z
38,542,595
<p>First of all, indent your code properly.</p> <p>Secondly, you are calling the function again with the same argument. Call with 'listush' list from which you are deleting or delete from 'S' and recurse with S argument.</p>
1
2016-07-23T14:00:04Z
[ "python", "list", "function", "recursion", "palindrome" ]
Palindrome recursive function
38,542,526
<p>I tried to write a <strong>recursive</strong> function that says if a string is a palindrome, but all I get is an infinite loop and I don't know what the problem is</p> <pre><code>def isPalindrome(S): listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a'] length=len(listush) #length=6 if length==0 or l...
-1
2016-07-23T13:52:06Z
38,542,598
<p>If you do an <code>print(listush)</code> you can see, that your list never changes. The following modification of your code works:</p> <pre><code>def isPalindrome(testStr, orig=None): if orig is None: orig = testStr length = len(testStr) #length=6 print(testStr) if length == 0 or length == 1...
0
2016-07-23T14:00:43Z
[ "python", "list", "function", "recursion", "palindrome" ]
Palindrome recursive function
38,542,526
<p>I tried to write a <strong>recursive</strong> function that says if a string is a palindrome, but all I get is an infinite loop and I don't know what the problem is</p> <pre><code>def isPalindrome(S): listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a'] length=len(listush) #length=6 if length==0 or l...
-1
2016-07-23T13:52:06Z
38,542,623
<p>There's no need for creating a list. A python string is already an indexable sequence. </p> <p>Even better, we can employ slicing and let the function return <code>True</code> and <code>False</code> instead of a tuple with text, With all of this, <code>isPalindrome()</code> becomes a one-liner:</p> <pre><code>def ...
1
2016-07-23T14:02:39Z
[ "python", "list", "function", "recursion", "palindrome" ]
Palindrome recursive function
38,542,526
<p>I tried to write a <strong>recursive</strong> function that says if a string is a palindrome, but all I get is an infinite loop and I don't know what the problem is</p> <pre><code>def isPalindrome(S): listush=list(S) #listush=['a', 'b', 'n', 'n', 'b', 'a'] length=len(listush) #length=6 if length==0 or l...
-1
2016-07-23T13:52:06Z
38,542,637
<p>There are some things I would like to say about your code</p> <ul> <li>You can send a slice of the list, saving you the trouble of deleting elements.</li> <li>You don't need to convert it to a list, all the operations you need in finding palindrome are supported by strings.</li> <li>You are returning S in the recur...
0
2016-07-23T14:03:43Z
[ "python", "list", "function", "recursion", "palindrome" ]
Functionality of Python `in` vs. `__contains__`
38,542,543
<p>I implemented the <code>__contains__</code> method on a class for the first time the other day, and the behavior wasn't what I expected. I suspect there's some subtlety to the <a href="https://docs.python.org/2/library/operator.html" rel="nofollow"><code>in</code></a> operator that I don't understand and I was hopin...
7
2016-07-23T13:54:30Z
38,542,655
<p>In <a href="https://docs.python.org/3/reference/datamodel.html#object.__contains__" rel="nofollow">Python reference for <code>__contains__</code></a> it's written that <code>__contains__</code> should return <code>True</code> or <code>False</code>.</p> <p>If the return value is not boolean it's converted to boolean...
3
2016-07-23T14:05:52Z
[ "python", "contains" ]
Functionality of Python `in` vs. `__contains__`
38,542,543
<p>I implemented the <code>__contains__</code> method on a class for the first time the other day, and the behavior wasn't what I expected. I suspect there's some subtlety to the <a href="https://docs.python.org/2/library/operator.html" rel="nofollow"><code>in</code></a> operator that I don't understand and I was hopin...
7
2016-07-23T13:54:30Z
38,542,777
<p>Use the source, Luke!</p> <p>Let's trace down the <code>in</code> operator implementation</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; class test(object): ... def __contains__(self, other): ... return True &gt;&gt;&gt; def in_(): ... return 1 in test() &gt;&gt;&gt; dis.dis(in_) 2 ...
7
2016-07-23T14:19:30Z
[ "python", "contains" ]
Numpy mean of nonzero values
38,542,548
<p>I have a matrix of size N*M and I want to find the mean value for each row. The values are from 1 to 5 and entries that do not have any value are set to 0. However, when I want to find the mean using the following method, it gives me the wrong mean as it also counts the entries that have value of 0.</p> <pre><code>...
1
2016-07-23T13:54:49Z
38,542,569
<p>Get the count of non-zeros in each row and use that for averaging the summation along each row. Thus, the implementation would look something like this -</p> <pre><code>np.true_divide(matrix.sum(1),(matrix!=0).sum(1)) </code></pre> <p>If you are on an older version of NumPy, you can use float conversion of the cou...
2
2016-07-23T13:57:10Z
[ "python", "numpy" ]
print(sys.argv) doesn't take arguments
38,542,581
<p>that's probably a pretty dumb question, but I'm a beginner programmer and i can't get this.</p> <p>basically, i think im using sys.argv wrong because it just doesn't take arguments as much as i can tell. the first code i've written with sys.argv looks like this:</p> <pre><code>import sys import pyperclip dict = {...
0
2016-07-23T13:58:44Z
38,542,630
<p>Use ' python pw.py email ' for the first script and for the second 'python pw.py any_args'</p>
1
2016-07-23T14:03:18Z
[ "python", "windows", "sys" ]
Getting openCV error: Assertion Failed
38,542,599
<p>I'm using opencv 3.1 in RaspberryPi 3. I,m trying to run the following Hough Circle detection algorithm </p> <pre><code>#! /usr/bin/python import numpy as np import cv2 from cv2 import cv VInstance = cv2.VideoCapture(0) key = True """ params = dict(dp, minDist, circles, ...
1
2016-07-23T14:00:44Z
38,543,384
<p>Error code "Assertion failed (scn == 3 || scn == 4) in cvtColor" means that the input (source) image in your <code>cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)</code> method does not have 3 or 4 channels, which are necessary for this type of conversion. Probably your input image is already grayscale format. Try just not to ...
0
2016-07-23T15:27:11Z
[ "python", "opencv", "raspberry-pi", "assertions" ]
Getting openCV error: Assertion Failed
38,542,599
<p>I'm using opencv 3.1 in RaspberryPi 3. I,m trying to run the following Hough Circle detection algorithm </p> <pre><code>#! /usr/bin/python import numpy as np import cv2 from cv2 import cv VInstance = cv2.VideoCapture(0) key = True """ params = dict(dp, minDist, circles, ...
1
2016-07-23T14:00:44Z
39,885,029
<p>This means the input image is invalid, which is why you need to check the <code>ret</code> value in your loop!</p> <p>The error and question title doesn't have anything to do with your Hough circles, so I'll condense my answer to address the assertion failure (add back in your stuff later!):</p> <pre><code>#!/usr/...
0
2016-10-05T23:07:11Z
[ "python", "opencv", "raspberry-pi", "assertions" ]
Compare pandas dataframes for common rows in two dataframes
38,542,645
<p>I have two data frames df-1 and df-2 like this,</p> <pre><code>import pandas as pd raw_data = {'company': ['comp1', 'comp1', 'comp1', 'comp1', 'comp2', 'comp2', 'comp2', 'comp2', 'comp3', 'comp3', 'comp3', 'comp3'], 'region': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2n...
3
2016-07-23T14:04:46Z
38,542,786
<p>It depends what you mean by </p> <blockquote> <p>rows in df-1 which is same as df-2.</p> </blockquote> <p>since the columns are not identical. </p> <p>If you mean rows that have the same value for the intersection of columns, you can perform an <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pand...
2
2016-07-23T14:20:30Z
[ "python", "pandas" ]
Compare pandas dataframes for common rows in two dataframes
38,542,645
<p>I have two data frames df-1 and df-2 like this,</p> <pre><code>import pandas as pd raw_data = {'company': ['comp1', 'comp1', 'comp1', 'comp1', 'comp2', 'comp2', 'comp2', 'comp2', 'comp3', 'comp3', 'comp3', 'comp3'], 'region': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2n...
3
2016-07-23T14:04:46Z
38,542,932
<p>result = pd.merge(df1,df2, on=['company','region','region'],how="left")</p>
0
2016-07-23T14:37:03Z
[ "python", "pandas" ]
GAE Python Blobstore doesn't save filename containing unicode literals in Firefox only
38,542,758
<p>I am developing an app which prompts the user to upload a file which is then available for download. Here is the download handler:</p> <pre><code>class ViewPrezentacje(blobstore_handlers.BlobstoreDownloadHandler, BaseHandler): def get(self,blob_key): blob_key = str(urllib.unquote(blob_key)) blob...
0
2016-07-23T14:17:20Z
38,552,379
<p>Sending filenames with non-ASCII characters in attachments is fraught with difficulty, as the original specification was broken and browser behaviours have varied.</p> <p>You shouldn't be %-encoding (<code>urllib.quote</code>) the filename; Firefox is right to offer it as literal % sequences as a result. IE's behav...
1
2016-07-24T13:07:48Z
[ "python", "python-2.7", "google-app-engine", "firefox", "unicode" ]
Theano/Lasagne basic neural network with regression won't overfit dataset of size one
38,542,760
<p>I'm using a basic neural network in Theano/Lasagne to try to identify facial keypoints in images, and am currently trying to get it to learn a single image (I've just taken the first image from my training set). The images are 96x96 pixels, and there are 30 key points (outputs) that it needs to learn, but it fails t...
0
2016-07-23T14:17:35Z
38,551,407
<p>It turns out that I'd forgotten to change the output node functions from:</p> <pre><code>lasagne.nonlinearities.softmax </code></pre> <p>to:</p> <pre><code>lasagne.nonlinearities.linear </code></pre> <p>The code I was using as a base was for a classification problem (e.g. working out which digit the picture show...
1
2016-07-24T11:12:25Z
[ "python", "neural-network", "theano", "lasagne" ]
Can't create user site-packages directory for usercustomize.py file
38,542,834
<p>I need to add the win_unicode_console module to my <code>usercustomize.py</code> file, as described by the documentation.</p> <p>I've discovered my user site packages directory with:</p> <pre><code>&gt;&gt;&gt; import site &gt;&gt;&gt; site.getusersitepackages() 'C:\\Users\\my name\\AppData\\Roaming\\Python\\Pytho...
0
2016-07-23T14:25:26Z
38,606,990
<p>DOS style backslashes don't need to be escaped within the Windows console (else they may have used forward slashes way back when!).</p> <p>Follow these steps to manually create <code>usercustomize.py</code>:</p> <ol> <li>Start->Run:<code>cmd</code></li> <li><p>Make sure you're on the C: drive</p> <pre><code>c: </...
0
2016-07-27T07:52:34Z
[ "python", "windows", "unicode", "module", "python-unicode" ]
Clicking "button" in Selenium
38,542,882
<p>[Using Python 2.7 and Selenium Web-driver]</p> <p>So there's this HTML code, which is kind of a button. How do I click it in Selenium?</p> <pre><code>&lt;div class="PermalinkProfile-dismiss"&gt; &lt;span class="Icon Icon--close Icon--large"&gt;&lt;/span&gt; &lt;/div&gt; </code></pre> <p>I've tried:</p> <pre><cod...
-1
2016-07-23T14:30:17Z
38,543,215
<p><code>click()</code> is a function that doesn't return value, you can't assign it to variable. You can do</p> <pre><code>driver.find_element_by_xpath('//*[@id="permalink-overlay-body"]/div/div[1]/span').click() </code></pre> <p>Or</p> <pre><code>elem = driver.find_element_by_xpath('//*[@id="permalink-overlay-body...
0
2016-07-23T15:07:23Z
[ "python", "selenium" ]
Clicking "button" in Selenium
38,542,882
<p>[Using Python 2.7 and Selenium Web-driver]</p> <p>So there's this HTML code, which is kind of a button. How do I click it in Selenium?</p> <pre><code>&lt;div class="PermalinkProfile-dismiss"&gt; &lt;span class="Icon Icon--close Icon--large"&gt;&lt;/span&gt; &lt;/div&gt; </code></pre> <p>I've tried:</p> <pre><cod...
-1
2016-07-23T14:30:17Z
38,543,380
<p>It's possible that your selector is wrong. You can try other selection methods, for example <code>find_element_by_css_selector()</code>. </p> <p>First find the element and see if it returns anything. Modify which <code>find_*</code> method you use and experiment with your selector patterns untill it matches - retur...
0
2016-07-23T15:26:39Z
[ "python", "selenium" ]
Restart a function in python
38,542,917
<p>My code is in a while True loop. It basically tries something like captcha.</p> <p>So what I want is something like this</p> <pre><code>def loop(): toplam = 0 global sayilar x = br.open(something) html = x.read() sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa...
-5
2016-07-23T14:34:57Z
38,542,988
<p>Ok found a good way to restart it.</p> <pre><code>class CustomError(Exception): def __init__(self, arg): # Set some exception infomation self.msg = arg def loop(): toplam = 0 global sayilar x = br.open(something) html = x.read() sayilar = map(str.strip,''.join(kod.findall(ht...
0
2016-07-23T14:43:23Z
[ "python", "loops", "if-statement", "while-loop", "break" ]
Restart a function in python
38,542,917
<p>My code is in a while True loop. It basically tries something like captcha.</p> <p>So what I want is something like this</p> <pre><code>def loop(): toplam = 0 global sayilar x = br.open(something) html = x.read() sayilar = map(str.strip,''.join(kod.findall(html)).split("\xc4\x84\xc5\x95\xc5\xa...
-5
2016-07-23T14:34:57Z
38,543,064
<p>You can literally use <code>break</code>. By using <code>break</code>, you can stop the loop immediately. You will see the use of the <code>return</code> later.</p> <pre><code>for i in sayilar: if i in diction: toplam += diction[i] else: return None break return True ...
0
2016-07-23T14:52:16Z
[ "python", "loops", "if-statement", "while-loop", "break" ]
Stack two columns in a DataFrame, repeat others
38,543,026
<p>I have a pandas DataFrame with a structure like this:</p> <pre><code>df = pd.DataFrame( [ [ 'foo1', 'a', 'z', 'bar1', 1, 4 ], [ 'foo2', 'b', 'y', 'bar2', 2, 5 ], [ 'foo3', 'c', 'x', 'bar3', 3, 6 ] ] ) df.columns = [ 'foo', 'let1', 'let2', 'bar', 'num1', 'num2' ] print( df...
3
2016-07-23T14:47:49Z
38,543,214
<p>Here is my attempt to combine <a href="http://stackoverflow.com/questions/38543026/stack-two-columns-in-a-dataframe-repeat-others/38543214#comment64478268_38543026">@ayhan</a>'s solution with the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="nofollow">pd.melt()</a> method:</p>...
4
2016-07-23T15:07:20Z
[ "python", "pandas", "dataframe" ]
Stack two columns in a DataFrame, repeat others
38,543,026
<p>I have a pandas DataFrame with a structure like this:</p> <pre><code>df = pd.DataFrame( [ [ 'foo1', 'a', 'z', 'bar1', 1, 4 ], [ 'foo2', 'b', 'y', 'bar2', 2, 5 ], [ 'foo3', 'c', 'x', 'bar3', 3, 6 ] ] ) df.columns = [ 'foo', 'let1', 'let2', 'bar', 'num1', 'num2' ] print( df...
3
2016-07-23T14:47:49Z
38,545,243
<p>In the meantime, I came out with an answer as well. </p> <p>Far more modest than <a href="http://stackoverflow.com/a/38543214/776515">@MaxU</a>'s, and based on <a href="http://stackoverflow.com/questions/38543026/stack-two-columns-in-a-dataframe-repeat-others/38543214#comment64478268_38543026">@ayhan</a>'s comment ...
2
2016-07-23T18:38:52Z
[ "python", "pandas", "dataframe" ]
Stack two columns in a DataFrame, repeat others
38,543,026
<p>I have a pandas DataFrame with a structure like this:</p> <pre><code>df = pd.DataFrame( [ [ 'foo1', 'a', 'z', 'bar1', 1, 4 ], [ 'foo2', 'b', 'y', 'bar2', 2, 5 ], [ 'foo3', 'c', 'x', 'bar3', 3, 6 ] ] ) df.columns = [ 'foo', 'let1', 'let2', 'bar', 'num1', 'num2' ] print( df...
3
2016-07-23T14:47:49Z
38,545,269
<p>Try this: </p> <pre><code>dfm = pd.melt(df.drop(['num1','num2'], 1), id_vars=['foo','bar'], var_name=('let'), value_name=('letval')) dfm[['num', 'numvals']] = pd.melt(df.drop(['let1','let2'], 1), id_vars=['foo','bar'], var_name=('num'), value_name=('numvals'))[['num', 'numvals']] dfm: foo bar let letval ...
1
2016-07-23T18:41:58Z
[ "python", "pandas", "dataframe" ]
i am trying to code a quiz with python but its not working
38,543,125
<p>i am coding a quiz in python. everything seems to work until i try to input the answer. i am very new to this. also can somebody explain what an indentation block is and an example of it. this is the code:</p> <pre><code>&gt;&gt;&gt; print('physics quiz') physics quiz &gt;&gt;&gt; print('round 1') round 1 &gt;&gt;&...
-4
2016-07-23T14:58:18Z
38,543,165
<p>in this line </p> <pre><code>answer=int(input('you have 5 seconds')) </code></pre> <p>you are converting input to int, therefore it will fail once int() can't convert input</p>
0
2016-07-23T15:02:32Z
[ "python" ]
i am trying to code a quiz with python but its not working
38,543,125
<p>i am coding a quiz in python. everything seems to work until i try to input the answer. i am very new to this. also can somebody explain what an indentation block is and an example of it. this is the code:</p> <pre><code>&gt;&gt;&gt; print('physics quiz') physics quiz &gt;&gt;&gt; print('round 1') round 1 &gt;&gt;&...
-4
2016-07-23T14:58:18Z
38,545,624
<p>You are trying to get input from the user and change it to an integer in this line:</p> <p><code>answer=int(input('you have 5 seconds'))</code></p> <p>However, an integer can only be a number without a period (if that wasn't clear yet), and Python doesn't know what to do. And it gives you an error. Change this lin...
0
2016-07-23T19:20:49Z
[ "python" ]
Detecting Dash button ARP requests
38,543,131
<p>I am having some trouble finding working code to find ARP requests sent out by an Amazon dash button. I tried <a href="https://medium.com/@edwardbenson/how-i-hacked-amazon-s-5-wifi-button-to-track-baby-data-794214b0bdd8#.utodl94ug" rel="nofollow">Ted Benson's code</a>, and also <a href="https://gist.github.com/ibrah...
0
2016-07-23T14:59:04Z
39,907,430
<p>For the first example, you are probably missing the <code>libdnet</code> dependency, as discussed in <a href="http://stackoverflow.com/a/26247500/1772214">this SO answer</a>.</p> <p>Also, note that a different approach is required to detect newer model Dash buttons (listening for DHCP requests rather than ARP reque...
0
2016-10-07T00:04:54Z
[ "python", "arp" ]
How to read MLComp dataset using python?
38,543,156
<p>MLComp dataset have special type of file format what I don't know about. I want to read using python but can't. </p>
-1
2016-07-23T15:00:52Z
38,552,967
<p>First thing to note is that <code>sklearn</code> (v0.17.1, as of 24th July 2016), only supports the <code>DocumentClassification</code> domain of <code>mlcomp</code>.</p> <p>Supposing you've downloaded the e.g. <a href="http://mlcomp.org/datasets/523" rel="nofollow">WebKB dataset</a>, which has <code>id=523</code>,...
0
2016-07-24T14:14:34Z
[ "python", "machine-learning", "dataset", "scikit-learn" ]
Python Agglomerative Clustering : finding the closest points in clusters
38,543,185
<p>The linkage matrix for clustering provides the cluster index, and distance for each step of the clustering hierarchy. When two clusters are merged, I would like to know which two points were the closest in the clusters. I am using the metric "single" i.e. closest distance</p> <p>I know I can do this trivially by a...
0
2016-07-23T15:04:32Z
38,547,221
<p>To answer your questions:</p> <ul> <li><p>No, this information is not available after linkage, at least according to the official Python documentation.</p></li> <li><p>The <strong>closest pair of points problem</strong> is a problem of computational geometry, and can be solved in logarithmic time by a recursive <em...
0
2016-07-23T23:12:35Z
[ "python", "hierarchical-clustering" ]
How to make gif at pygame?
38,543,187
<p>I have 6 photos that I wanna make gif from them and show it on Pygame. I get that I can't preview it so simply, so what I can do to show the animation like a gif?</p> <p>Python 2.7</p>
0
2016-07-23T15:04:35Z
38,558,336
<p>You can create a class that switch between your images based on a time interval.</p> <pre><code>class Animation(pygame.sprite.Sprite): def __init__(self, images, time_interval): super(Animation, self).__init__() self.images = images self.image = self.images[0] self.time_interval...
0
2016-07-25T00:54:05Z
[ "python", "python-2.7", "pygame" ]
pandas, multiply all the numeric values in the data frame by a constant
38,543,263
<p>How to multiply all the numeric values in the data frame by a constant without having to specify column names explicitly? Example:</p> <pre><code>In [13]: df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]}) In [14]: df Out[14]: col1 col2 col3 0 A 1 30 1 B 2 10 2...
4
2016-07-23T15:13:01Z
38,543,323
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.select_dtypes.html" rel="nofollow">select_dtypes()</a> including <code>number</code> dtype or excluding all columns of <code>object</code> and <code>datetime64</code> dtypes:</p> <p>Demo:</p> <pre><code>In [162]: df Out[16...
3
2016-07-23T15:20:35Z
[ "python", "pandas", "dataframe" ]
pandas, multiply all the numeric values in the data frame by a constant
38,543,263
<p>How to multiply all the numeric values in the data frame by a constant without having to specify column names explicitly? Example:</p> <pre><code>In [13]: df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]}) In [14]: df Out[14]: col1 col2 col3 0 A 1 30 1 B 2 10 2...
4
2016-07-23T15:13:01Z
38,543,397
<p>The other answer specifies how to multiply only numeric columns. Here's how to update it:</p> <pre><code>df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]}) s = df.select_dtypes(include=[np.number])*3 df[s.columns] = s print (df) col1 col2 col3 0 A 3 90 1 B 6 ...
1
2016-07-23T15:28:54Z
[ "python", "pandas", "dataframe" ]
pandas, multiply all the numeric values in the data frame by a constant
38,543,263
<p>How to multiply all the numeric values in the data frame by a constant without having to specify column names explicitly? Example:</p> <pre><code>In [13]: df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]}) In [14]: df Out[14]: col1 col2 col3 0 A 1 30 1 B 2 10 2...
4
2016-07-23T15:13:01Z
38,543,403
<p>One way would be to get the <code>dtypes</code>, match them against <code>object</code> and <code>datetime</code> dtypes and exclude them with a mask, like so -</p> <pre><code>df.ix[:,~np.in1d(df.dtypes,['object','datetime'])] *= 3 </code></pre> <p>Sample run -</p> <pre><code>In [273]: df Out[273]: col1 col2 ...
4
2016-07-23T15:29:49Z
[ "python", "pandas", "dataframe" ]
pandas, multiply all the numeric values in the data frame by a constant
38,543,263
<p>How to multiply all the numeric values in the data frame by a constant without having to specify column names explicitly? Example:</p> <pre><code>In [13]: df = pd.DataFrame({'col1': ['A','B','C'], 'col2':[1,2,3], 'col3': [30, 10,20]}) In [14]: df Out[14]: col1 col2 col3 0 A 1 30 1 B 2 10 2...
4
2016-07-23T15:13:01Z
38,543,416
<p>This should work even over mixed types within columns but is likely slow over large dataframes. </p> <pre><code>def mul(x, y): try: return pd.to_numeric(x) * y except: return x df.applymap(lambda x: mul(x, 3)) </code></pre>
2
2016-07-23T15:31:10Z
[ "python", "pandas", "dataframe" ]
How to write server for chat program in php by using socket
38,543,264
<p>I use php as server on localhost. I use python as client.</p> <p>I want that: Client will send message to server. Server will send the same message to clients. And all of clients will show the message which is sent. But when I open 2 clients, the clients can't get answer from server when they send message.</p> <p>...
0
2016-07-23T15:13:04Z
38,782,141
<p>The server has to wait simultaneously for connections and data from clients; this is easy with <code>socket_select()</code>. Replace your <code>while (true){…}</code> loop with</p> <pre><code> $s = array($socket); // initially wait for connections while ($r = $s and socket_select($r, $n=NULL, $n=NULL, N...
0
2016-08-05T06:01:54Z
[ "php", "python", "sockets" ]
How to activate conda env with space in its name
38,543,266
<p><code>conda env list</code> or <code>conda info -e</code> shows</p> <p><code>py35 python=3.5</code> as one of the environment.</p> <p>How to activate conda env which has space in its name?</p>
1
2016-07-23T15:13:20Z
38,897,486
<p>tl;dr <strong>Surround the environment name with quotes.</strong></p> <p>@centau you can most definitely create environments with spaces in the name.</p> <p>Duplicating the problem:</p> <pre><code>conda create -n "foo bar" python=3.5 </code></pre> <p>Then inspecting the environments:</p> <pre><code>conda info -...
0
2016-08-11T13:16:05Z
[ "python", "anaconda", "conda" ]
Caffe always gives the same prediction in Python, but training accuracy is good
38,543,440
<p>I have a trained model with caffe (through the command line) where I get an <strong>accuracy of 63%</strong> (according to the log files). However, when I try to run a script in Python to test the accuracy, I get all the predictions in the same class, with very similar prediction values, but not quite identical. My ...
0
2016-07-23T15:34:33Z
39,570,767
<p>I figured it out, the deploy.prototxt had some input_param mismatch. </p> <p>Strange behavior. </p>
0
2016-09-19T10:20:42Z
[ "python", "caffe", "pycaffe" ]
How do I print a 2d array in python
38,543,484
<p>I'm having problems printing this 2d array for my Battleship game. </p> <pre><code>class Battleship: def __init__(self): self.__init__() def board(self, locate): locate = [] for i in range(10): locate.append([]) for j in range(10): locate[i].a...
1
2016-07-23T15:39:04Z
38,543,548
<pre><code>for i in range(10): for j in range(10): print(locate[i][j])` </code></pre> <p>This should make it work. </p>
0
2016-07-23T15:45:39Z
[ "python", "arrays", "multidimensional-array" ]
How do I print a 2d array in python
38,543,484
<p>I'm having problems printing this 2d array for my Battleship game. </p> <pre><code>class Battleship: def __init__(self): self.__init__() def board(self, locate): locate = [] for i in range(10): locate.append([]) for j in range(10): locate[i].a...
1
2016-07-23T15:39:04Z
38,543,590
<p>how do you want to print it? Please be more informative regarding the output format.</p> <p>Assuming you want <em>that</em> format, i.e. xOy coordinates (x,y):</p> <p>In this for-loop:</p> <pre><code>for i in range(10): locate.append([]) for j in range(10): locate[i].append(0) </code><...
0
2016-07-23T15:49:29Z
[ "python", "arrays", "multidimensional-array" ]
How do I print a 2d array in python
38,543,484
<p>I'm having problems printing this 2d array for my Battleship game. </p> <pre><code>class Battleship: def __init__(self): self.__init__() def board(self, locate): locate = [] for i in range(10): locate.append([]) for j in range(10): locate[i].a...
1
2016-07-23T15:39:04Z
38,543,605
<p>here is some code i wrote to generate the multiplication board, in order to demonstrate how to print a 2d array of unknowen size </p> <pre><code>l = [] # empty list a,b = 10,10 # size of board aXb for i in range(1,a+1): # generate board temp = [] for j in range(1,b+1): temp.append(i*j) l.appen...
0
2016-07-23T15:50:38Z
[ "python", "arrays", "multidimensional-array" ]
How do I print a 2d array in python
38,543,484
<p>I'm having problems printing this 2d array for my Battleship game. </p> <pre><code>class Battleship: def __init__(self): self.__init__() def board(self, locate): locate = [] for i in range(10): locate.append([]) for j in range(10): locate[i].a...
1
2016-07-23T15:39:04Z
38,543,772
<p>You have many forms of printing</p> <p>Using numpy</p> <pre><code>import numpy as np print(np.matrix(matrix)) </code></pre> <p>Using pprint</p> <pre><code>import pprint pprint.pprint(matrix) </code></pre>
0
2016-07-23T16:08:30Z
[ "python", "arrays", "multidimensional-array" ]
How do I print a 2d array in python
38,543,484
<p>I'm having problems printing this 2d array for my Battleship game. </p> <pre><code>class Battleship: def __init__(self): self.__init__() def board(self, locate): locate = [] for i in range(10): locate.append([]) for j in range(10): locate[i].a...
1
2016-07-23T15:39:04Z
38,544,008
<p>First, let's clean up the creation of the 2D-list :</p> <pre><code>locate = [[str(i)+","+str(j) for j in range(10)] for i in range(10)] </code></pre> <p>Then, to iterate over the array and print the values stored in each case :</p> <pre><code>for locate_i in locate: for locate_i_j in locate_i: print l...
0
2016-07-23T16:33:16Z
[ "python", "arrays", "multidimensional-array" ]
Change logging "print" function to "tqdm.write" so logging doesn't interfere with progress bars
38,543,506
<p>I have a simple question: How do I change the built-in Python logger's <code>print</code> function to <code>tqdm.write</code> such that logging messages do not interfere with tqdm's progress bars? Thanks!</p>
3
2016-07-23T15:40:48Z
38,543,578
<p>Not sure about what you are trying to do but if you use:</p> <pre><code>import tqdm </code></pre> <p>instead of</p> <pre><code>from tqdm import tqdm </code></pre> <p>when you (or some of your modules) put </p> <pre><code>print </code></pre> <p>in your program it won't make reference to </p> <pre><code>tqdm...
-2
2016-07-23T15:48:22Z
[ "python", "logging", "tqdm" ]
Change logging "print" function to "tqdm.write" so logging doesn't interfere with progress bars
38,543,506
<p>I have a simple question: How do I change the built-in Python logger's <code>print</code> function to <code>tqdm.write</code> such that logging messages do not interfere with tqdm's progress bars? Thanks!</p>
3
2016-07-23T15:40:48Z
38,739,634
<p>You need a custom logging handler:</p> <pre><code>import logging import tqdm class TqdmLoggingHandler (logging.Handler): def __init__ (self, level = logging.NOTSET): super (self.__class__, self).__init__ (level) def emit (self, record): try: msg = self.format (record) ...
3
2016-08-03T09:28:06Z
[ "python", "logging", "tqdm" ]
Django 1.9 + Celery unregistered tasks
38,543,513
<blockquote> <p>This configuration is <strong>correct</strong>. I was starting celery the wrong way :(, without specifying the project name. (celery worker -A hockey_manager -l info</p> </blockquote> <p>I did upgrade to Django 1.9 from 1.6.5 and I can't make the celery configuration work again.</p> <p>After alm...
1
2016-07-23T15:41:33Z
38,564,457
<p>use <code>django-celery</code> module.</p> <p>here is <a href="https://github.com/hirenalken/django-awesome-example/blob/master/django-celery-setup-steps.txt" rel="nofollow">link</a> to example how to use <code>django-celery</code> with django 1.9.1+</p>
2
2016-07-25T09:45:45Z
[ "python", "django", "celery", "django-celery" ]
Python if/elif syntax error... WHY
38,543,524
<p>I'm absolutely pulling my hair out over this. The if/elif statement in this function throws a syntax error on the elif line. To me there are no obvious syntax problems.</p> <pre><code>"elif n == cs_index:" ^ SyntaxError: invalid syntax </code></pre> <p>I tried switching it to a bear "else:" just to see if that...
0
2016-07-23T15:43:28Z
38,543,579
<p>After pasting my code into my Spyder IDE and running it, I exhibit no errors (apart from the parentheses missing in the <code>print</code> statements - you should really upgrade to Python 3.5.2!)</p> <p>Try re-indenting that line by resetting the indentation and adding three tabs. I get similar errors when I copy a...
1
2016-07-23T15:48:23Z
[ "python", "syntax-error" ]
Python if/elif syntax error... WHY
38,543,524
<p>I'm absolutely pulling my hair out over this. The if/elif statement in this function throws a syntax error on the elif line. To me there are no obvious syntax problems.</p> <pre><code>"elif n == cs_index:" ^ SyntaxError: invalid syntax </code></pre> <p>I tried switching it to a bear "else:" just to see if that...
0
2016-07-23T15:43:28Z
38,543,673
<p>You are mixing tabs and spaces in your code; taking the source of your initial post and pasting it into Sublime Text, then selecting all lines I see this:</p> <p><a href="http://i.stack.imgur.com/yYweS.png" rel="nofollow"><img src="http://i.stack.imgur.com/yYweS.png" alt="source code with spaces and tabs"></a></p> ...
1
2016-07-23T15:57:47Z
[ "python", "syntax-error" ]
slicing numpy array to get nth column
38,543,660
<p>Having the example array below, how do you slice by column to get the following (e.g. 3rd column) <code>[0, 0, ..., 1338, 1312, 1502, 0, ...]</code> Looking for the most efficient way, thanks!</p> <pre><code>&gt;&gt;&gt; r array([[[ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0], [...
1
2016-07-23T15:55:36Z
38,543,690
<p>For a generic ndarray of any dimensions, one way would be -</p> <pre><code>arr[...,n] </code></pre> <p>To get a flattened version, use <code>.ravel()</code> method -</p> <pre><code>arr[...,n].ravel() </code></pre> <p>Sample run -</p> <pre><code>In [317]: arr Out[317]: array([[[[2, 1, 2], [0, 2, 3], ...
7
2016-07-23T15:59:54Z
[ "python", "numpy" ]
slicing numpy array to get nth column
38,543,660
<p>Having the example array below, how do you slice by column to get the following (e.g. 3rd column) <code>[0, 0, ..., 1338, 1312, 1502, 0, ...]</code> Looking for the most efficient way, thanks!</p> <pre><code>&gt;&gt;&gt; r array([[[ 0, 0, 0], [ 0, 0, 0], [ 0, 0, 0], [...
1
2016-07-23T15:55:36Z
38,543,734
<p>Numpy supports the "semicolon notation" like matlab. In your case you should be able to take the third column by doing:<br> <code>x = r[:,:,2]</code> <br> and then <br> <code>a = numpy.concatenate([x[0],x[1],x[2]])</code></p>
3
2016-07-23T16:04:48Z
[ "python", "numpy" ]
List comprehension: Multiply each string to a single list
38,543,703
<p>I have a list of strings and want to get a new list consisting on each element a number of times.</p> <pre><code>lst = ['abc', '123'] n = 3 </code></pre> <p>I can do that with a for loop:</p> <pre><code>res = [] for i in lst: res = res + [i]*n print( res ) ['abc', 'abc', 'abc', '123', '123', '123'] </code></...
0
2016-07-23T16:01:25Z
38,543,715
<p>Use a <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions">nested list comprehension</a></p> <pre><code>&gt;&gt;&gt; lst = ['abc', '123'] &gt;&gt;&gt; n = 3 &gt;&gt;&gt; [i for i in lst for j in range(n)] ['abc', 'abc', 'abc', '123', '123', '123'] </code></pre> <p>The idea behind th...
6
2016-07-23T16:03:05Z
[ "python", "list", "python-3.x", "list-comprehension" ]
List comprehension: Multiply each string to a single list
38,543,703
<p>I have a list of strings and want to get a new list consisting on each element a number of times.</p> <pre><code>lst = ['abc', '123'] n = 3 </code></pre> <p>I can do that with a for loop:</p> <pre><code>res = [] for i in lst: res = res + [i]*n print( res ) ['abc', 'abc', 'abc', '123', '123', '123'] </code></...
0
2016-07-23T16:01:25Z
38,544,066
<p>It can also be done as:</p> <pre><code>&gt;&gt;&gt; lst = ['abc', '123'] &gt;&gt;&gt; n=3 &gt;&gt;&gt; [j for i in lst for j in (i,)*n] ['abc', 'abc', 'abc', '123', '123', '123'] </code></pre>
1
2016-07-23T16:37:56Z
[ "python", "list", "python-3.x", "list-comprehension" ]
Count lines of code in directory using Python
38,543,709
<p>I have a project whose lines of code I want to count. Is it possible to count all the lines of code in the file directory containing the project by using Python?</p>
0
2016-07-23T16:02:40Z
38,543,710
<pre><code>from os import listdir from os.path import isfile, join def countLinesInPath(path,directory): count=0 for line in open(join(directory,path), encoding="utf8"): count+=1 return count def countLines(paths,directory): count=0 for path in paths: count=count+countLinesInPath(pat...
1
2016-07-23T16:02:40Z
[ "python", "lines-of-code" ]
wxpython: closing application does not close the progress bar
38,543,721
<p>I have an app that retrieves data from a SQL server. I include a progress bar to show the progress. </p> <p>However, the problem is that when I try to close the application by clicking the "x" at the top right corner of the application window, the application's main window will close, but the progress bar will cont...
0
2016-07-23T16:03:31Z
38,543,960
<p>Yes, bind the close event.</p> <pre><code>self.Bind(wx.EVT_CLOSE, self.OnExit) </code></pre> <p>Also, I don't see you closing the database connection or a <code>self.Destroy()</code></p>
0
2016-07-23T16:28:53Z
[ "python", "wxpython", "progress-bar" ]
Django: duplicate key value violates unique constraint
38,543,752
<p>I have a Joke model:</p> <pre><code>class Joke(models.Model): ... date_created = models.DateTimeField(default=datetime.now, blank=True) date_modified = models.DateTimeField(default=datetime.now, blank=True) creator = models.OneToOneField(User, default=1) </code></pre> <p>Now, when I try to migrate the ...
0
2016-07-23T16:06:58Z
38,543,873
<p>OneToOne field enforces, as it's name says, an one-to-one relationship, which in your case means that one user can be creator of one and only one joke - definitely not what you want. Use <a href="https://docs.djangoproject.com/en/1.9/ref/models/fields/#foreignkey" rel="nofollow">ForeignKey</a> instead:</p> <pre><co...
2
2016-07-23T16:18:57Z
[ "python", "django", "postgresql", "one-to-one" ]
How to use PowerShell to set some primitive files?
38,543,786
<p>I've been doing "learn python the hard way" ex46 to make a skeleton of project, and I am confused about how to set the primitive files using Windows PowerShell. These are the instructions:</p> <pre><code>new-item -type file NAME/_init_.py </code></pre> <p>I typed that into PowerShell but I get an error.</p>
-1
2016-07-23T16:09:52Z
38,543,950
<p>You didn't follow the instructions. You need to create the directory <code>NAME</code> first before you can create a file inside it.</p> <p>Quoting from the <a href="http://learnpythonthehardway.org/book/ex46.html" rel="nofollow">exercise in question</a> (emphasis mine):</p> <blockquote> <p>First, create the str...
1
2016-07-23T16:27:33Z
[ "python", "powershell" ]
Pandas join dataframes by multiple key
38,543,800
<p>I have 3 different dataframes that I want to join, using label and window as keys.</p> <p>DataFrame1</p> <pre><code>Window Label FeatA 123 1 h 123 2 f </code></pre> <p>DataFrame2</p> <pre><code>Window Label FeatB 123 1 d 123 2 s </code></pre> <p>DataFrame3</p> <...
3
2016-07-23T16:11:26Z
38,544,019
<p>You need to use the <code>merge</code> function for joining tables, for your case, since you have multiple data frames to join, you can put them into a list and then use the <code>reduce</code> from <code>functools</code> to merge them one by one: </p> <pre><code>import pandas as pd from functools import reduce red...
3
2016-07-23T16:33:47Z
[ "python", "pandas" ]
Pandas join dataframes by multiple key
38,543,800
<p>I have 3 different dataframes that I want to join, using label and window as keys.</p> <p>DataFrame1</p> <pre><code>Window Label FeatA 123 1 h 123 2 f </code></pre> <p>DataFrame2</p> <pre><code>Window Label FeatB 123 1 d 123 2 s </code></pre> <p>DataFrame3</p> <...
3
2016-07-23T16:11:26Z
38,548,114
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow">combine_first</a>:</p> <pre><code>In[44]:df.combine_first(df1).combine_first(df2)[['Window','Label','FeatA','FeatB','FeatC']] Out[44]: Window Label FeatA FeatB FeatC 0 123 1 ...
1
2016-07-24T02:10:32Z
[ "python", "pandas" ]
Pandas join dataframes by multiple key
38,543,800
<p>I have 3 different dataframes that I want to join, using label and window as keys.</p> <p>DataFrame1</p> <pre><code>Window Label FeatA 123 1 h 123 2 f </code></pre> <p>DataFrame2</p> <pre><code>Window Label FeatB 123 1 d 123 2 s </code></pre> <p>DataFrame3</p> <...
3
2016-07-23T16:11:26Z
38,548,213
<p>A pure pandas answer using <code>pd.concat</code></p> <pre><code>pd.concat([df.set_index(['Window', 'Label']) for df in [df1_, df2_, df3_]], axis=1).reset_index() </code></pre> <p><a href="http://i.stack.imgur.com/C0WOv.png" rel="nofollow"><img src="http://i.stack.imgur.com/C0WOv.png" alt="enter image de...
3
2016-07-24T02:31:20Z
[ "python", "pandas" ]
Efficiency of using subprocess in conjunction with threads, in Python
38,543,836
<p>I am using Python 2.7. I have a multi-threaded program where the threads launch commands using the <code>subprocess</code> module. The processes run on the system and report data occasionally to the threads. The majority of the work is done in the processes - the threads just take information from the processes a...
0
2016-07-23T16:14:44Z
38,543,963
<p>Why not have the subprocesses just handle the data processing themselves? Passing stuff back to the process requires extra <a href="https://en.wikipedia.org/wiki/Context_switch" rel="nofollow">context switches</a> and the overhead of serialisation and deserialisation, which can become significant if you have a lot o...
0
2016-07-23T16:29:18Z
[ "python", "multithreading", "subprocess" ]
Tensorflow: How to Display Custom Images in Tensorboard (e.g. Matplotlib Plots)
38,543,850
<p>The <a href="https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tensorboard/README.md#image-dashboard" rel="nofollow">Image Dashboard</a> section of the Tensorboard ReadMe says:</p> <blockquote> <p>Since the image dashboard supports arbitrary pngs, you can use this to embed custom visualizations (e.g...
3
2016-07-23T16:15:43Z
38,676,842
<p>It is quite easy to do if you have the image in a memory buffer. Below, I show an example, where a pyplot is saved to a buffer and then converted to a TF image representation which is then sent to an image summary.</p> <pre><code>import io import matplotlib.pyplot as plt import tensorflow as tf def gen_plot(): ...
3
2016-07-30T17:51:10Z
[ "python", "matplotlib", "tensorflow", "tensorboard" ]
how to generate different color images according to one image in java or python?
38,543,898
<p>I want to generate some images in different color according to one image.But I couldn't find some resources about this.Could you recommand some useful reference material about how to implement by using java or python.</p> <p>for example,the images below is generated from one image. <a href="http://i.stack.imgur.com...
1
2016-07-23T16:20:54Z
38,544,018
<p>In Python, you can take the help of the Image module to do this stuff.</p> <p>For example - </p> <pre><code>import Image picture = Image.open("/path/to/my/picture.jpg") r,g,b = picture.getpixel( (0,0) ) print("Red: {0}, Green: {1}, Blue: {2}".format(r,g,b)) </code></pre> <p>This above code will give you informati...
0
2016-07-23T16:33:44Z
[ "java", "python", "image", "image-processing" ]
how to create and append multiple rows using two loops in python
38,543,952
<p>i need to create a dataframe such that i have the output as follows</p> <pre><code>day hour cal_hr 1 6 106 1 7 107 1 8 108 .. .. 1 24 124 .. 7 1 701 7 2 702 .. .. 7 24 724 </code></pre> <p>i want to loop through day and then hour and then do a concat of day and hour. With preceding...
1
2016-07-23T16:27:42Z
38,544,005
<p>Append to a list then convert to a dataframe. It would be much more efficient.</p> <pre><code>df = pd.DataFrame([(i, j, 100*i+j) for i in range(1, 8) for j in range(6, 25)], columns=['day', 'hour', 'cal_hr']) df.head() Out[143]: day hour cal_hr 0...
4
2016-07-23T16:33:09Z
[ "python", "python-3.x", "pandas" ]
how to create and append multiple rows using two loops in python
38,543,952
<p>i need to create a dataframe such that i have the output as follows</p> <pre><code>day hour cal_hr 1 6 106 1 7 107 1 8 108 .. .. 1 24 124 .. 7 1 701 7 2 702 .. .. 7 24 724 </code></pre> <p>i want to loop through day and then hour and then do a concat of day and hour. With preceding...
1
2016-07-23T16:27:42Z
38,548,159
<p>This isn't as fast or as intuitive as @ayhan's answer, but I think it's an interesting way to think about it.</p> <pre><code>day = pd.Series(np.arange(1, 8), name='day') hour = pd.Series(np.arange(6, 25), name='hour') df = pd.DataFrame(np.add.outer(day * 100, hour), day, hour) df = df.stack().rename('cal_hr').reset...
2
2016-07-24T02:19:13Z
[ "python", "python-3.x", "pandas" ]
I have a list of strings (html codes) and I want to extract all the emails in each of the string of my list
38,543,989
<p>I have a list of strings:</p> <pre><code>urls = ["url1","url2","url3"] </code></pre> <p>in order to generate another list of strings:</p> <pre><code>for i in range (0,2): htmlist = [urllib.urlopen(url[i]).read() for i in range(0,2) ] </code></pre> <p>When I try to extract the emails from the texts htmlist[i]...
0
2016-07-23T16:31:40Z
38,544,039
<p>That's because <code>emails</code> takes the value of the last iteration (at <code>htmlist[2]</code>). Move the print statement into the <code>for</code> loop to see <code>emails</code> at each iteration:</p> <pre><code>for i in range (0, 3) : emails = re.findall(r'[\w\.-]+@[\w\.-]+', htmlist[i]) print emai...
0
2016-07-23T16:35:03Z
[ "python", "string", "text" ]
How to position a borderless window in Kivy
38,544,254
<p>I was making an app with Kivy in python, and to make things a tad more stylish, I thought I could remove the border on the window and create by own:</p> <pre><code>from kivy.config import Config from kivy.core.window import Window Window.size = (900,550) Window.borderless = True Config.set('graphics','resizable',0)...
0
2016-07-23T16:54:38Z
38,669,304
<p>Borderless:</p> <pre><code>from kivy.config import Config Config.set('graphics','borderless',1) Config.set('graphics','resizable',0) </code></pre> <p><em>at the top</em> of your file before anything else. Just the core(Window) will remain.</p> <p>Position:</p> <pre><code>Config.set('graphics','position','custom'...
0
2016-07-30T00:45:28Z
[ "python", "python-3.x", "window", "kivy", "borderless" ]
python remove elements of list from another list WITH MULTIPLE OCCURRENCES of items in both
38,544,296
<p>Related to: <a href="http://stackoverflow.com/questions/4211209/remove-all-the-elements-that-occur-in-one-list-from-another">Remove all the elements that occur in one list from another</a></p> <p>I have listA <code>[1, 1, 3, 5, 5, 5, 7]</code> and listB <code>[1, 2, 5, 5, 7]</code> and I want to subtract <em>occurr...
1
2016-07-23T16:58:17Z
38,544,362
<p>In cases like these a list comprehension should always be used:</p> <pre><code>listA = [1, 1, 3, 5, 5, 5, 7] listB = [1, 2, 5, 5, 7] newList = [i for i in listA if i not in listB or listB.remove(i)] print (newList) </code></pre> <p>Here are the results:</p> <p><code>[1, 3, 5]</code></p>
1
2016-07-23T17:04:14Z
[ "python", "list" ]
python remove elements of list from another list WITH MULTIPLE OCCURRENCES of items in both
38,544,296
<p>Related to: <a href="http://stackoverflow.com/questions/4211209/remove-all-the-elements-that-occur-in-one-list-from-another">Remove all the elements that occur in one list from another</a></p> <p>I have listA <code>[1, 1, 3, 5, 5, 5, 7]</code> and listB <code>[1, 2, 5, 5, 7]</code> and I want to subtract <em>occurr...
1
2016-07-23T16:58:17Z
38,544,430
<p>Here is a non list comprehension version for those new to Python</p> <pre><code>listA = [1, 1, 3, 5, 5, 5, 7] listB = [1, 2, 5, 5, 7] for i in listB: if i in listA: listA.remove(i) print listA </code></pre>
3
2016-07-23T17:09:55Z
[ "python", "list" ]
Filter data with groupby in pandas
38,544,301
<p>I have a DataFrame where I have the following data. Here each row represents a word appearing in each episode of a TV series. Now if a word appears 3 times in an episode, the padas dataframe ahs 3 rows. Now I need to filter a list of words such that I should only get only words which appear more than or equal tp 2 t...
3
2016-07-23T16:59:13Z
38,544,486
<p><strong>Answer for the updated question:</strong></p> <pre><code>In [208]: df.groupby('dialogue')['episode'].transform('size') &gt;= 3 Out[208]: 0 True 1 False 2 False 3 False 4 False 5 False 6 False 7 True 8 False 9 True 10 False dtype: bool In [209]: df[df.groupby('d...
4
2016-07-23T17:16:27Z
[ "python", "pandas", "dataframe" ]
Filter data with groupby in pandas
38,544,301
<p>I have a DataFrame where I have the following data. Here each row represents a word appearing in each episode of a TV series. Now if a word appears 3 times in an episode, the padas dataframe ahs 3 rows. Now I need to filter a list of words such that I should only get only words which appear more than or equal tp 2 t...
3
2016-07-23T16:59:13Z
38,544,851
<p>You can use groupby's <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration"><code>filter</code></a>:</p> <pre><code>In [11]: df.groupby("dialogue").filter(lambda x: len(x) &gt; 1) Out[11]: dialogue episode 0 music 1 6 wind 2 7 music 1 9 music ...
5
2016-07-23T17:52:52Z
[ "python", "pandas", "dataframe" ]
Filter data with groupby in pandas
38,544,301
<p>I have a DataFrame where I have the following data. Here each row represents a word appearing in each episode of a TV series. Now if a word appears 3 times in an episode, the padas dataframe ahs 3 rows. Now I need to filter a list of words such that I should only get only words which appear more than or equal tp 2 t...
3
2016-07-23T16:59:13Z
38,547,975
<p>I'd use <code>value_counts</code></p> <pre><code>vc = df.dialogue.value_counts() &gt;= 2 vc = vc[vc] df[df.dialogue.isin(vc.index)] </code></pre> <p><a href="http://i.stack.imgur.com/0EwfW.png" rel="nofollow"><img src="http://i.stack.imgur.com/0EwfW.png" alt="enter image description here"></a></p> <hr> <h3>Timin...
2
2016-07-24T01:39:59Z
[ "python", "pandas", "dataframe" ]
conditionally print out lines in python
38,544,476
<p>I have a list of strings. I hope to print out the strings in the list that meet a condition. The list is as below:</p> <pre><code>In [5]: L = ["John and Mary", "Leslie", "Iva and Mark Li"] </code></pre> <p>I hope to print out each of the strings in L that has an <code>and</code> in it --</p> <pre><code>'John and ...
0
2016-07-23T17:14:48Z
38,544,508
<p>Should be straight-forward:</p> <pre><code>&gt;&gt;&gt; L = ["John and Mary", "Leslie", "Iva and Mark Li"] &gt;&gt;&gt; for s in L: if ' and ' in s: print(s) John and Mary Iva and Mark Li </code></pre> <p>If you want to capture the strings in a list, use a comprehension:</p> <pre><code>&gt;&gt;&gt; [s for s...
5
2016-07-23T17:18:39Z
[ "python", "string", "generator" ]
conditionally print out lines in python
38,544,476
<p>I have a list of strings. I hope to print out the strings in the list that meet a condition. The list is as below:</p> <pre><code>In [5]: L = ["John and Mary", "Leslie", "Iva and Mark Li"] </code></pre> <p>I hope to print out each of the strings in L that has an <code>and</code> in it --</p> <pre><code>'John and ...
0
2016-07-23T17:14:48Z
38,544,538
<p>Because your function does not have a return statement, it always returns <code>None</code>. You need to replace <code>print</code> with <code>return</code>.</p>
5
2016-07-23T17:21:11Z
[ "python", "string", "generator" ]
Python socket programming - exception handling
38,544,493
<p>I'm working on a basic socket client program in python and I'm not totally sure how to handle exceptions. This is what I did up to now:</p> <pre><code>TCP_IP = '..............' TCP_PORT = 4950 MESSAGE = "o3" BUFFER_SIZE = 2048 data = "" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.se...
0
2016-07-23T17:17:04Z
38,545,213
<p>Since you're doing exactly the same actions in all the exception blocks and catching the same <code>socket.error</code> exception, you could put <code>s.connect</code>, <code>s.sendall</code> and <code>s.recv</code> in the same <code>try:</code> block. Like so:</p> <pre><code>try: s.connect((TCP_IP, TCP_PORT)) ...
1
2016-07-23T18:34:12Z
[ "python", "sockets", "tcp", "client" ]
Python data persistent object for communication between threads
38,544,559
<p>As shown <a href="http://stackoverflow.com/questions/38542298/python3-webserver-communicate-between-threads-for-irc-bot/38542615#38542615">here</a>, I set up a python Django application served by cherrypy wsgi server. The app is basically another IRC client. Here's the deal : it is very likely that I have to create ...
1
2016-07-23T17:23:00Z
38,615,661
<p>So, turns out I just mixed up variables and objects. Variables cannot be defined in one module and imported to another one (a = foo, then modify a from another module and import a from third module). This is possible with lists, dicts and stuff. Solution : at each bot launch (and attempt to connect to a given server...
0
2016-07-27T14:20:43Z
[ "python", "django", "multithreading", "data-structures", "queue" ]
Removing period from number in python
38,544,578
<p>Given a real number between 0 and 1 (for example 0.2836) I want to return only the number without the dot (for example in this case from 0.2836 -> 2836 or 02836). I was trying to use python to do this but I just started and I need some help.</p>
-2
2016-07-23T17:24:58Z
38,544,608
<p>As long as you have a number, the following should do:</p> <pre><code>&gt;&gt;&gt; number = 0.2836 &gt;&gt;&gt; int(str(number).replace('.', '')) 2836 </code></pre> <p>If a <code>.</code> is not found in the string, <a href="https://docs.python.org/2/library/stdtypes.html#str.replace" rel="nofollow"><code>str.repl...
4
2016-07-23T17:27:35Z
[ "python" ]
Removing period from number in python
38,544,578
<p>Given a real number between 0 and 1 (for example 0.2836) I want to return only the number without the dot (for example in this case from 0.2836 -> 2836 or 02836). I was trying to use python to do this but I just started and I need some help.</p>
-2
2016-07-23T17:24:58Z
38,544,653
<p>The simplest way to remove an unwanted character from a strip is to call its <code>.replace</code> method with an empty string as the second argument:</p> <pre><code>x = str(123.45) x = x.replace('.','') print(x) # Prints 12345 </code></pre> <p>Note, this would leave any leading zeros (i.e. <code>0...
0
2016-07-23T17:31:01Z
[ "python" ]
%USERPROFILE% env variable for python
38,544,618
<p>I am writing a script in Python 2.7.</p> <p>It needs to be able to go whoever the current users profile in Windows. </p> <p>This is the variable and function I currently have: </p> <pre><code>import os desired_paths = os.path.expanduser('HOME'\"My Documents") </code></pre> <p>I do have doubts that this <code>exp...
0
2016-07-23T17:28:14Z
38,544,703
<p>Going by <a href="https://docs.python.org/2/library/os.path.html#os.path.expanduser" rel="nofollow"><code>os.path.expanduser</code></a> , using a <code>~</code> would seem more reliable than using <code>'HOME'</code>.</p>
0
2016-07-23T17:36:57Z
[ "python", "python-2.7", "windows-7-x64", "environment", "os.path" ]
%USERPROFILE% env variable for python
38,544,618
<p>I am writing a script in Python 2.7.</p> <p>It needs to be able to go whoever the current users profile in Windows. </p> <p>This is the variable and function I currently have: </p> <pre><code>import os desired_paths = os.path.expanduser('HOME'\"My Documents") </code></pre> <p>I do have doubts that this <code>exp...
0
2016-07-23T17:28:14Z
38,544,715
<p>You can access environment variables via the <a href="https://docs.python.org/2/library/os.html#os.environ" rel="nofollow"><code>os.environ</code> mapping</a>:</p> <pre><code>import os; print(os.environ['USERPROFILE']) </code></pre> <p>This will work in Windows. For another OS, you'd need the appropriate environ...
0
2016-07-23T17:37:56Z
[ "python", "python-2.7", "windows-7-x64", "environment", "os.path" ]
Can a class handle AttributeError by itself using some meta magic?
38,544,643
<p>So I have this example code, where Foo is very dynamic data structure. </p> <pre><code>def fetch(): # simulate api request return {'param1':1, 'param2':{'description':'param2', 'value':2}} class Foo(object): def __init__(self): self._rawdata = fetch() #set attributes accordingly t...
0
2016-07-23T17:30:09Z
38,544,660
<p>Implement the <a href="https://docs.python.org/2/reference/datamodel.html#object.__getattr__" rel="nofollow"><code>__getattr__</code> method</a>; it'll be called for all <em>nonexistent</em> attributes:</p> <pre><code>def __getattr__(self, name): # all non-existing attributes produce None return None </code...
3
2016-07-23T17:31:19Z
[ "python" ]
Django: DRY principle and UserPassesTestMixin
38,544,692
<p>I have a model named <code>Post</code> and have a field there called <code>owner</code> (foreign key to <code>User</code>). Of course, only owners can <code>update</code> or <code>delete</code> their own posts.</p> <p>That being said, I use <code>login_required</code> decorator in the views to make sure the user is...
0
2016-07-23T17:35:21Z
38,545,039
<p>The order of the classes you inherit from matters. For your access control to work, it must be enforced before UpdateView is executed:</p> <pre><code>class EditPost(TestUserOwnerOfPost, UpdateView): </code></pre>
2
2016-07-23T18:13:21Z
[ "python", "django", "generics" ]
Django: DRY principle and UserPassesTestMixin
38,544,692
<p>I have a model named <code>Post</code> and have a field there called <code>owner</code> (foreign key to <code>User</code>). Of course, only owners can <code>update</code> or <code>delete</code> their own posts.</p> <p>That being said, I use <code>login_required</code> decorator in the views to make sure the user is...
0
2016-07-23T17:35:21Z
38,545,128
<p>The first problem is that the order of the classes you inherit is incorrect, as @rafalmp says.</p> <p>However, fixing that doesn't solve the problem, because the <code>UserPassesTest</code> mixin performs the test <em>before</em> running the view. This means that it's not really suitable to check the owner of <code...
2
2016-07-23T18:24:21Z
[ "python", "django", "generics" ]
How to resolve the django import from view function?
38,545,126
<p>developers.I am learning the django following this <a href="http://gsl.mit.edu/media/programs/south-africa-summer-2015/materials/djangobook.pdf" rel="nofollow">book</a> and making changes for django 1.8</p> <p>The error showing is </p> <pre><code>name 'addPublisher' is not defined Request Method: GET Request ...
0
2016-07-23T18:24:02Z
38,547,290
<p>Your urls.py file is probably not in the same app (folder) than your views.py. You are getting this error saying that addPublisher <strong>is not defined</strong> because it's literally not <em>there</em>, by <em>there</em> I mean the app where urls.py is located.</p> <p>If that particular views.py above is locate...
1
2016-07-23T23:25:31Z
[ "python", "django", "django-1.8" ]
Remove additional quotes from python list
38,545,143
<p>I have a list with below pattern and i want to get rid of <code>"</code> which is present at the beginning and end of each sub list. I tried replace, strip but they are not the attribute of list and therefore gives <code>AttributeError</code>.</p> <pre><code>lst = [["'123', 'Name1', 'Status1'"], ["'234', 'Name2', '...
0
2016-07-23T18:25:40Z
38,545,153
<p>This should do the trick:</p> <pre><code>result = [[element.strip("'") for element in sub_list[0].split(', ')] for sub_list in lst] </code></pre> <p>I'm assuming that the format for the string is "strings wrapped in single quotes separated by commas and spaces." Note that my code will probably not do the expected ...
1
2016-07-23T18:26:34Z
[ "python" ]
Remove additional quotes from python list
38,545,143
<p>I have a list with below pattern and i want to get rid of <code>"</code> which is present at the beginning and end of each sub list. I tried replace, strip but they are not the attribute of list and therefore gives <code>AttributeError</code>.</p> <pre><code>lst = [["'123', 'Name1', 'Status1'"], ["'234', 'Name2', '...
0
2016-07-23T18:25:40Z
38,545,181
<p>You can use <a href="https://docs.python.org/2/library/shlex.html#shlex.split" rel="nofollow"><code>shlex.split</code></a> after <em>removing</em> commas with <code>replace</code>:</p> <pre><code>import shlex lst = [["'123', 'Name1', 'Status1'"], ["'234', 'Name2', 'Status2'"]] r = [shlex.split(x[0].replace(',', ''...
3
2016-07-23T18:29:47Z
[ "python" ]
access jupyter notebook running on vm
38,545,198
<p>I want to run jupyter notebook running on my ubuntu vm which i fired using vagrant. </p> <pre> $ jupyter notebook --no-browser --port 8004 [I 18:26:10.152 NotebookApp] Serving notebooks from local directory: /home/vagrant/path/to/jupyter/notebook/directory [I 18:26:10.153 NotebookApp] 0 active kernels [I 18:26:10.1...
0
2016-07-23T18:32:02Z
38,545,410
<p>how to run jupyter notebook as a server gives the answer</p> <p>first generaTE jupyter_notebook_config.py file</p> <pre><code>$ jupyter notebook --generate-config </code></pre> <p>jupyter_notebook_config.py would have everything commented. Find <code>c.NotebookApp.ip = 'localhost'</code> and edit it to <code>c.No...
0
2016-07-23T18:57:38Z
[ "python", "vagrant", "jupyter-notebook" ]
Run-length encoding program
38,545,225
<p>i have a string say "AAABBCCCDAAT" so output for the following should be A3B2C3D1A2T1.</p> <pre><code>data = input("enter data ") count =1 for steps in range(0,len(data)-1): if (str(data[steps])==str(data[steps+1])): count = count+1 else: str(data[steps])=str(data[steps+1]) count=1 p...
-4
2016-07-23T18:35:44Z
38,547,108
<p>Here's one way, using <a href="https://docs.python.org/3.1/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a>:</p> <pre><code>In [62]: from itertools import groupby In [63]: data Out[63]: 'AAABBCCCDAAT' In [64]: ''.join(char + str(len(list(grp))) for char, grp in groupby(d...
2
2016-07-23T22:55:42Z
[ "python", "python-3.x" ]
Run-length encoding program
38,545,225
<p>i have a string say "AAABBCCCDAAT" so output for the following should be A3B2C3D1A2T1.</p> <pre><code>data = input("enter data ") count =1 for steps in range(0,len(data)-1): if (str(data[steps])==str(data[steps+1])): count = count+1 else: str(data[steps])=str(data[steps+1]) count=1 p...
-4
2016-07-23T18:35:44Z
38,547,146
<p>I have a few approaches to share, but I think @Warren Weckesser's answer is better. :-)</p> <pre><code># Regular expression approach: import re def run_length_encode(text): # When the match is for AAA: # match.group(1) == 'A' # match.group(0) == 'AAA' # len(match.group(0)) == 3 def encode_sing...
0
2016-07-23T23:01:40Z
[ "python", "python-3.x" ]
How to read out *new* OS environment variables in Python?
38,545,262
<p>Reading out OS environment variables in Python is a piece of cake. Try out the following three code lines to read out the <code>'PATH'</code> variable in Windows:</p> <pre><code> ################# # PYTHON 3.5 # ################# &gt;&gt; import os &gt;&gt; pathVar = os.getenv('Path') &gt;...
1
2016-07-23T18:41:15Z
38,546,615
<p>On Windows, the initial environment variables are stored in the registry: <code>HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment</code> for system variables and <code>HKEY_CURRENT_USER\Environment</code> for user variables.</p> <p>Using the <code>winreg</code> module in Python, you ca...
3
2016-07-23T21:32:34Z
[ "python", "python-3.x", "environment-variables" ]
Time.sleep() function placement
38,545,275
<p>The problem I've encountered is while I am attempting to keep the first functions(StartUpScr) widgets on screen for 3 seconds using time.sleep(3) before deleting all it's widgets placed on screen and then continuing to place the next functions(MenuScr) widgets. I've managed to successfully use destroy() to delete th...
2
2016-07-23T18:42:40Z
38,545,456
<p>time.sleep() won't work here as it stops the execution of the program, you'll have to use after...and its also a bad practice to use sleep in GUI programming.</p> <pre><code>root.after(time_delay, function_to_run, args_of_fun_to_run) </code></pre> <p>So in your case it'll like</p> <pre><code>def destroy(): #d...
2
2016-07-23T19:02:23Z
[ "python", "time", "tkinter" ]
Time.sleep() function placement
38,545,275
<p>The problem I've encountered is while I am attempting to keep the first functions(StartUpScr) widgets on screen for 3 seconds using time.sleep(3) before deleting all it's widgets placed on screen and then continuing to place the next functions(MenuScr) widgets. I've managed to successfully use destroy() to delete th...
2
2016-07-23T18:42:40Z
38,547,052
<p>So we are defining three functions: <code>firstScreen</code>, <code>secondScreen</code>, and <code>changeScreen</code>. The idea is running <code>firstScreen</code> and after 3 seconds, running <code>changeScreen</code> which will destroy the current parent window (<code>master</code>) and create the next brand new ...
1
2016-07-23T22:45:38Z
[ "python", "time", "tkinter" ]
Volume Yahoo Finance
38,545,299
<p>What is the meaning of Volume in Yahoo Finance (web.DataReader(stock, 'yahoo', start, end))? Is it average daily trading volume or average dollar volume? Is it a number of shares or number of dollars?</p>
0
2016-07-23T18:45:13Z
38,547,342
<p>According to:</p> <p><a href="https://biz.yahoo.com/charts/guide20.html" rel="nofollow">https://biz.yahoo.com/charts/guide20.html</a></p> <p>Volume on Yahoo Finance's charts are the physical number of shares traded of that stock (not dollar amount) for your given period of time. This is typically what volume is re...
0
2016-07-23T23:35:13Z
[ "python", "volume", "datareader", "yahoo-finance" ]
Visual Studio code and virtualenv
38,545,326
<p>I am trying to use Visual Studio Code with virtual environment. In the Launch JSON I specify the nosetests launch like this:</p> <pre><code>{ "name": "nosetests", "type": "python", "request": "launch", "stopOnEntry": true, "program": "${workspaceRoot}/env/dev/bin/nosetests", "args": [ ...
1
2016-07-23T18:48:21Z
38,607,114
<p>@mikebz you need to configure the path to the python executable as follows:<br> <code> "pythonPath":"${workspaceRoot}/env/dev/bin/python" </code></p> <p>The path may not be 100% accurate (please double check it), but that's how you need to configure it in launch.json.<br> With the next version of VS Code you wi...
2
2016-07-27T07:58:47Z
[ "python", "vscode", "nose" ]
How to free memory of python deleted object?
38,545,463
<p>It seems python3.5 does not completely free memory of any deleted object, this may because of python internally maintaining some kind of memroy pool for reusing purpose, however, I don't want to reuse them, and I want to free them to make memory available for other programs running on linux. </p> <pre><code>&gt;&gt...
10
2016-07-23T19:02:45Z
38,545,526
<p>Once you delete an object it is available to garbage collected rather than deleted immediately - so just give it some time and it will free up or trigger a <code>gc.collect()</code> to speed things up.</p> <pre><code>python.exe Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on...
5
2016-07-23T19:10:39Z
[ "python", "python-3.x", "memory", "memory-management", "memory-leaks" ]
Merge DataFrames on two columns
38,545,544
<p>This is a follow-up from <a href="http://stackoverflow.com/questions/38543026/stack-two-columns-in-a-dataframe-repeat-others/38543214">this question</a></p> <p>I have two pandas DataFrames, as follows:</p> <pre><code>print( a ) foo bar let letval 9 foo1 bar1 let1 a 8 foo2 bar2 let1 b 7 fo...
3
2016-07-23T19:12:29Z
38,545,661
<p>you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow">combine_first</a>:</p> <pre><code>In[21]:a.combine_first(b) Out[21]: bar foo let letval num numval 0 bar1 foo1 let1 a num1 1 1 bar2 foo2 let1 b num1 ...
1
2016-07-23T19:24:48Z
[ "python", "pandas", "merge" ]
Merge DataFrames on two columns
38,545,544
<p>This is a follow-up from <a href="http://stackoverflow.com/questions/38543026/stack-two-columns-in-a-dataframe-repeat-others/38543214">this question</a></p> <p>I have two pandas DataFrames, as follows:</p> <pre><code>print( a ) foo bar let letval 9 foo1 bar1 let1 a 8 foo2 bar2 let1 b 7 fo...
3
2016-07-23T19:12:29Z
38,547,935
<p>The reason you are getting that is because the columns you are merging on do not constitute unique combinations. For example, The first (index 0) row of <code>a</code> has <code>foo1</code> and <code>bar1</code>, but so does the fourth row (index 3). Ok, that's fine, but <code>b</code> has the same issue. So, whe...
3
2016-07-24T01:31:01Z
[ "python", "pandas", "merge" ]
python urlopen error [Errno 10060]
38,545,603
<p>I am trying to run the following code, </p> <pre><code>for parname in parss: data = {'action': 'listp', 'parish': parname} data = urllib.urlencode(data) req = urllib2.Request('http://www.irishancestors.ie/search/townlands/ded_index.php', data) response = urllib2.urlopen(req) </code></pre> <p>but i ...
0
2016-07-23T19:18:30Z
38,552,666
<p>As discussed in the comments, executing large numbers of requests in very short time can lead to the server, especially web-servers, to block your connection attempts.</p> <p>This is a common counter measure to automated attacks on the web. Depending on the server, waiting very short amounts of time between request...
1
2016-07-24T13:42:54Z
[ "python", "urlopen" ]
What is the most efficient way to collect HoG descriptors (ndarrays) together for processing by Kmeans
38,545,611
<p>In scikit image there is a feature descriptor called <a href="http://scikit-image.org/docs/0.12.x/api/skimage.feature.html#hog" rel="nofollow">HoG</a></p> <p>The code below will calculate the descriptor for a single frame "greyVideoFrame"</p> <pre><code>HoGDescriptor = hog(greyVideoFrame, orientations=8, pixels_pe...
-1
2016-07-23T19:19:35Z
39,087,705
<p>Decided to go with h5py to store the data in a format that wasn't limited to the size of RAM available</p>
0
2016-08-22T19:57:00Z
[ "python", "computer-vision", "scikit-image" ]
How to convert an IP address to something 32 bit you can use as a dict key
38,545,718
<p>If I have an IP address I can use it as a key in a dict as follows:</p> <pre><code>dict = {} IP = "172.23.1.99" dict[IP] = "pear" </code></pre> <p>However, if I have a lot of them this is very memory inefficient. </p> <blockquote> <p>How can I convert the IP to a 32 bit representation which I can still use a ...
4
2016-07-23T19:32:27Z
38,545,780
<p>Yes you can use the <a href="https://docs.python.org/3/library/ipaddress.html#module-ipaddress" rel="nofollow"><code>ipaddress</code></a> module:</p> <pre><code>from ipaddress import ip_address int(ip_address('172.23.1.99')) </code></pre> <p>output:</p> <pre><code>2887188835 </code></pre> <p>and back:</p> <pre...
0
2016-07-23T19:40:23Z
[ "python" ]
How to convert an IP address to something 32 bit you can use as a dict key
38,545,718
<p>If I have an IP address I can use it as a key in a dict as follows:</p> <pre><code>dict = {} IP = "172.23.1.99" dict[IP] = "pear" </code></pre> <p>However, if I have a lot of them this is very memory inefficient. </p> <blockquote> <p>How can I convert the IP to a 32 bit representation which I can still use a ...
4
2016-07-23T19:32:27Z
38,546,641
<p>Given the number of entries you intend to store, I suggest you use SQLite. It's both easy and probably efficient enough. In fact, it has the nice property that for every record it uses only as much space as necessary. For an IP address that is between 1 and 5 bytes depending on the IP address (so on average, 3 bytes...
2
2016-07-23T21:36:42Z
[ "python" ]