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
Using Requests Post to login to this site not working
38,733,204
<p>I know there are tons of threads and videos on how to do this, I've gone through them all and am in need of a little advanced guidance.</p> <p>I am trying to log into this webpage where I have an account so I can send a request to download a report.<br> First I send the <code>get</code> request to the login page, t...
0
2016-08-03T02:05:42Z
38,748,823
<p>There are a few more fields in the form data to post:</p> <pre><code>import requests data = {"redirect": "1", "XXX_login_name": "your_username", "XXX_login_password": "your_password", "XXX_actionSUBMITLOGIN": "Login", "XXX_login_php": "1"} with requests.Session() as s: s.headers...
1
2016-08-03T16:15:08Z
[ "python", "post", "login", "python-requests" ]
Using Requests Post to login to this site not working
38,733,204
<p>I know there are tons of threads and videos on how to do this, I've gone through them all and am in need of a little advanced guidance.</p> <p>I am trying to log into this webpage where I have an account so I can send a request to download a report.<br> First I send the <code>get</code> request to the login page, t...
0
2016-08-03T02:05:42Z
38,757,422
<p>So I figured out what my problem was, just in case anyone in the future has the same issue. I am sure different websites have different requirements but in this case the <code>Cookie:</code> I was sending in the request header was blocking it. What I did was grab my cookie in the headers AFTER I logged in. I upda...
0
2016-08-04T02:11:13Z
[ "python", "post", "login", "python-requests" ]
Simple table creation sql works for mysql and postgre, but reported errors in oracle
38,733,212
<p>I am using Python with cx_Oracle to work with Oracle 11g.</p> <p>I have following SQL work well with MySQL/PostgreSQL, </p> <pre><code>stock_info_create = 'CREATE TABLE STOCK_INFO(' + \ 'CODE VARCHAR2(255) NOT NULL,' + \ 'NAME VARCHAR2(255) NOT NULL,' + \ ...
0
2016-08-03T02:06:25Z
38,733,290
<p>Certain reserved words in Oracle are not allowed to be used as column names - data types are among those reserved words, e.g. <code>Date</code>, <code>Number</code>. You got an "ORA-00904: invalid identifier" error because of your <code>Date</code> column. For good practice, try and avoid using reserved words as col...
1
2016-08-03T02:15:10Z
[ "python", "mysql", "oracle", "postgresql" ]
Difference between scikit-learn and sklearn
38,733,220
<p>On OS X 10.11.6 and python 2.7.10 I need to import from sklearn manifold. I have numpy 1.8 Orc1, scipy .13 Ob1 and scikit-learn 0.17.1 installed.<br> I used pip to install sklearn(0.0), but when I try to import from sklearn manifold I get the following: </p> <blockquote> <p>Traceback (most recent call last): ...
0
2016-08-03T02:07:21Z
38,733,854
<p>You might need to reinstall numpy. It doesn't seem to have installed correctly.</p> <p><code>sklearn</code> is how you type the scikit-learn name in python.</p> <p>Also, try running the standard tests in scikit-learn and check the output. You will have detailed error information there.</p> <p>Do you have <code>no...
0
2016-08-03T03:25:22Z
[ "python", "python-2.7", "scikit-learn" ]
extract a string between 2 strings in python?
38,733,221
<p>I need to one give me the string between <code>~</code> and <code>^</code></p> <p>i have string like this</p> <p><code>:::ABC???,:::DEF???</code></p> <p>I need to get the string between them with python</p> <p>I want to do all this because i am trying to extract text from an html page. like this example</p> <pr...
1
2016-08-03T02:07:34Z
38,733,282
<p>You can use the <code>isalpha()</code> function in a generator expression. Then combine the characters as a single <code>string</code> using <code>join()</code>.</p> <pre><code>def extract_string(s): return ''.join(i for i in s if i.isalpha()) </code></pre> <p><strong>Sample output:</strong></p> <pre><code>pr...
2
2016-08-03T02:14:17Z
[ "python" ]
extract a string between 2 strings in python?
38,733,221
<p>I need to one give me the string between <code>~</code> and <code>^</code></p> <p>i have string like this</p> <p><code>:::ABC???,:::DEF???</code></p> <p>I need to get the string between them with python</p> <p>I want to do all this because i am trying to extract text from an html page. like this example</p> <pr...
1
2016-08-03T02:07:34Z
38,733,321
<p>It seems like you want ABC and DEF , so you need write re like this (.*?) </p> <pre><code>import re target = ' &lt;td class="cell-1"&gt;&lt;div&gt;&lt;span class="value-frame"&gt;&amp;nbsp;~ABC^,~DEF^&lt;/span&gt;&lt;/div&gt;&lt;/td&gt;' matchObj = re.findall(r'~(.*?)\^', target) print matchObj # ['ABC', 'DEF'] </...
1
2016-08-03T02:19:23Z
[ "python" ]
IBM Bluemix set_hadoop_config error
38,733,247
<p>Whenever I try the setup procedure for Apache spark data analytics, I get this error.</p> <p>In</p> <pre><code>def set_hadoop_config(credentials): prefix = "fs.swift.service." + credentials['name'] hconf = sc._jsc.hadoopConfiguration() hconf.set(prefix + ".auth.url", credentials['auth_url']+'/v3/auth/...
0
2016-08-03T02:10:12Z
38,733,588
<p>I think you are missing the credentials dictionary i.e you should pass the values for parameters of accessing Object Store service as follows: </p> <pre><code>credentials = { 'auth_uri':'', 'global_account_auth_uri':'', 'username':'admin_b055482b7febbd287d9020d65cdd55f5653d0ffb', 'password':"XXXXXX", 'au...
1
2016-08-03T02:49:25Z
[ "python", "hadoop", "apache-spark", "ibm-bluemix", "ibm" ]
Returning multiple elements of a list
38,733,287
<p>Just have a simple question I need to write a function that takes a list as a parameter and returns a new list containing all the elements of the parameter data but with the last item appearing twice.</p> <p>This is what I have:</p> <pre><code>def duplicate_last(data): return data[:], data[-1] </code></pre> <...
1
2016-08-03T02:14:55Z
38,733,317
<p>You want a list.</p> <p>You have:</p> <pre><code>def duplicate_last(data): return data[:], data[-1] </code></pre> <p>That creates a tuple with two elements, a copy of the list (<code>data[:]</code>) and the last element of the list.</p> <p>The error message is telling you exactly what the problem with <code>...
1
2016-08-03T02:18:51Z
[ "python", "python-3.x" ]
Returning multiple elements of a list
38,733,287
<p>Just have a simple question I need to write a function that takes a list as a parameter and returns a new list containing all the elements of the parameter data but with the last item appearing twice.</p> <p>This is what I have:</p> <pre><code>def duplicate_last(data): return data[:], data[-1] </code></pre> <...
1
2016-08-03T02:14:55Z
38,733,318
<p>You could make a slight amendment to your current code:</p> <pre><code>def duplicate_last(data): return data[:] + [data[-1]] </code></pre>
3
2016-08-03T02:18:56Z
[ "python", "python-3.x" ]
Categorical axis with a bokeh area chart
38,733,308
<h2>Question</h2> <p>Is it currently possible to use a categorical axis with a bokeh <code>Area</code> chart?</p> <h2>Details</h2> <p>I'm trying to plot an area chart with a categorical x-axis using the high-level <code>bokeh.charts</code> API.</p> <h2>Example</h2> <p>If set up bokeh and a dataframe like this:</p>...
2
2016-08-03T02:17:27Z
38,733,857
<p>One option would be to make custom tick labels for your axes. Modifying from the answer here - <a href="http://stackoverflow.com/questions/37173230/how-do-i-use-custom-labels-for-ticks-in-bokeh">How do I use custom labels for ticks in Bokeh?</a>:</p> <p>First up we do our imports and create a dictionary to store ou...
1
2016-08-03T03:25:36Z
[ "python", "bokeh" ]
Why am I unable to send HTTP Headers to Flask-RESTful reqparse module using add_argument()?
38,733,337
<p>I am trying to integrate the Flask-RESTful's request parsing interface, <a href="http://flask-restful-cn.readthedocs.io/en/0.3.4/reqparse.html" rel="nofollow">reqparse</a> in my backend to request HTTP headers from the client. Currently, I wish to use this for authentication of a user and wish to pass <code>'secret_...
2
2016-08-03T02:21:23Z
38,792,538
<p>I did some tests with the code you gave here and I found out that the problem doesn't come from you code but from the name of the variable:</p> <p>If you replace <code>secret_key</code> by <code>secretkey</code> (or something else without underscore) it will work !</p> <p>I found this <a href="http://stackoverflow...
1
2016-08-05T15:10:24Z
[ "python", "api", "curl", "http-headers", "flask-restful" ]
Python Unicode Handling
38,733,356
<p>I've looked through several questions and I can't seem to find the exact answer to what I need.</p> <p>I am trying to figure out how to take an emoji and use unicodedata.name() to return it's name. </p> <p>So for example, I have this emoji: 💩. I want to be able to get it's identifier and get the value of it'...
0
2016-08-03T02:24:12Z
38,733,401
<p>The solution is very simple:</p> <pre><code>import unicodedata unicodedata.name('💩') </code></pre> <p>which returns:</p> <pre><code>'PILE OF POO' </code></pre>
2
2016-08-03T02:28:05Z
[ "python", "unicode" ]
Iterate and replace words in lines of a tuple python
38,733,418
<p>I want to iterate through this tuple and for each line, iterate through the words to find and replace some words (internet addresses, precisely) using regex while leaving them as lines.</p> <pre><code>aList= [ "being broken changes people, \nand rn im missing the old me", "@SaifAlmazroui @troyboy621 @petr_hrub...
1
2016-08-03T02:30:33Z
38,733,960
<p>Your question is a little unclear, but I think I get what you're going for</p> <pre><code>newlist = [re.sub(r"{regex}", "", line) for line in alist] </code></pre> <p>Should iterate through a list of strings and replace any strings that match your regex pattern with an empty string using a python list comprehension...
1
2016-08-03T03:38:11Z
[ "python", "regex", "loops", "replace", "tuples" ]
Iterate and replace words in lines of a tuple python
38,733,418
<p>I want to iterate through this tuple and for each line, iterate through the words to find and replace some words (internet addresses, precisely) using regex while leaving them as lines.</p> <pre><code>aList= [ "being broken changes people, \nand rn im missing the old me", "@SaifAlmazroui @troyboy621 @petr_hrub...
1
2016-08-03T02:30:33Z
38,738,056
<p>From this:</p> <pre><code>re.sub(r"^[http](.*)\/(.*)$", "", line) </code></pre> <p>it looks to me as if you expect that all your URLs will be at the end of the line. In that case, try:</p> <pre><code>[re.sub('http://.*', '', s) for s in aList] </code></pre> <p>Here, <code>http://</code> matches anything that st...
1
2016-08-03T08:14:21Z
[ "python", "regex", "loops", "replace", "tuples" ]
Python dictionary throws invalid syntax
38,733,475
<p>Why does this code throw an invalid syntax error? I am pretty sure this ran fine about three months ago. Has something changed in the Python language in regards to dictionaries? The error is as follows:</p> <pre><code>File "code.py", line 4 'den'{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\...
2
2016-08-03T02:38:03Z
38,733,510
<p>You lost <code>,</code> before string <code>'den'</code>.</p>
2
2016-08-03T02:42:06Z
[ "python", "dictionary", "syntax" ]
Python dictionary throws invalid syntax
38,733,475
<p>Why does this code throw an invalid syntax error? I am pretty sure this ran fine about three months ago. Has something changed in the Python language in regards to dictionaries? The error is as follows:</p> <pre><code>File "code.py", line 4 'den'{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\...
2
2016-08-03T02:38:03Z
38,733,512
<p>You seem to be missing a comma after the close brace after <code>'cen':.9</code>. Try this fix:</p> <pre><code>... 'cen':.9} ,\ \ den:{... </code></pre> <p>I'm pretty sure that this file, in this condition, would not have run correctly three months ago.</p>
3
2016-08-03T02:42:12Z
[ "python", "dictionary", "syntax" ]
Python dictionary throws invalid syntax
38,733,475
<p>Why does this code throw an invalid syntax error? I am pretty sure this ran fine about three months ago. Has something changed in the Python language in regards to dictionaries? The error is as follows:</p> <pre><code>File "code.py", line 4 'den'{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\...
2
2016-08-03T02:38:03Z
38,733,576
<p>You missed a few commas, fixed:</p> <pre><code>milevalue = {'adm':{'adm':0,'den':2.4,'ear':3,'edi':3.2,'eug':2.6,'fra':2.1,'thu':1.2,'hor':3.4,'lon':1.5,'rid':7.7,'hig':1.8,'tho':5.5,'was':1.8,'aca':0.8,'cen':.9},'den':{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,'hor':1.6,'lon':1.4,'rid':7....
2
2016-08-03T02:48:42Z
[ "python", "dictionary", "syntax" ]
Python dictionary throws invalid syntax
38,733,475
<p>Why does this code throw an invalid syntax error? I am pretty sure this ran fine about three months ago. Has something changed in the Python language in regards to dictionaries? The error is as follows:</p> <pre><code>File "code.py", line 4 'den'{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\...
2
2016-08-03T02:38:03Z
38,734,337
<p>Such syntax errors are much easier to spot with judicious use of whitespace. At the very least, the error message will you give you a better idea of where to look.</p> <pre><code>milevalue = { 'adm': { 'adm': 0, 'den': 2.4, 'ear': 3, 'edi': 3.2, 'hug': 2.6, 'fra': 2.1, 'the': 1.2, ...
2
2016-08-03T04:19:46Z
[ "python", "dictionary", "syntax" ]
Python dictionary throws invalid syntax
38,733,475
<p>Why does this code throw an invalid syntax error? I am pretty sure this ran fine about three months ago. Has something changed in the Python language in regards to dictionaries? The error is as follows:</p> <pre><code>File "code.py", line 4 'den'{'adm':2.4,'den':0,'ear':3.5,'edi':3.6,'eug':1.6,'fra':3.0,'thu':3.1,\...
2
2016-08-03T02:38:03Z
38,736,383
<p>Code Fixed.</p> <p>Missing commas, "," please be careful with them or you should use dictionary notation to generate dictionaries.</p> <pre>milevalue = {'adm':{'adm':0,'den':2.4,'ear':3,'edi':3.2,'eug':2.6,'fra':2.1,'thu':1.2,\ 'hor':3.4,'lon':1.5,'rid':7.7,'hig':1.8,'tho':5.5,'was':1.8,'aca':0.8,'cen':.9}\ \ 'den...
1
2016-08-03T06:51:57Z
[ "python", "dictionary", "syntax" ]
What's the best way to sum all values in a Pandas dataframe?
38,733,477
<p>I figured out these two methods. Is there a better one?</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({'A': [5, 6, 7], 'B': [7, 8, 9]}) &gt;&gt;&gt; print df.sum().sum() 42 &gt;&gt;&gt; print df.values.sum() 42 </code></pre> <p>Just want to make sure I'm not missing something more...
2
2016-08-03T02:38:11Z
38,733,583
<pre><code>df.values </code></pre> <p>Is the underlying numpy array</p> <pre><code>df.values.sum() </code></pre> <p>Is the numpy sum method and is faster</p>
3
2016-08-03T02:49:04Z
[ "python", "pandas", "dataframe", "sum" ]
Publishing MQTT messages from a Python script on a Raspberry Pi
38,733,589
<p>I am trying to configure a Raspberry Pi (Raspbian, Jessie) to send temperature data from a DS18B20 sensor to my MQTT broker.</p> <p>I have installed mosquitto, mosquitto-clients, and python-mosquitto. I have also installed paho-mqtt.</p> <p>Mosquitto seems to be working fine; I can publish from the command line bu...
1
2016-08-03T02:49:25Z
38,738,316
<p>As mentioned in the comment, the code you posted does work, but for publishing a <a href="https://eclipse.org/paho/clients/python/docs/#single" rel="nofollow">single</a> message this form is better</p> <pre><code>#!/usr/bin/env python import paho.mqtt.publish as publish publish.single("test/test", "Hello world!", ...
2
2016-08-03T08:27:45Z
[ "python", "raspberry-pi", "mqtt" ]
Best way to perform calculations on a list/tuple in Python 3x
38,733,593
<p>I wrote this program that will tell you the two <s>multiples</s> factors of your input. Ex. if I were to input 35 (a semiprime), the program would print 5 and 7, which are the two prime numbers that multiply to 35.</p> <p>But I am wondering if there is a more concise or pythonic way to iterate through this tuple so...
4
2016-08-03T02:49:58Z
38,733,684
<p>I hinted at this in my comment, but realized just the link to the function docs may not be enough.</p> <p>Here's how you could write your code using <a href="https://docs.python.org/dev/library/itertools.html#itertools.combinations_with_replacement" rel="nofollow"><code>itertools.combinations_with_replacement</code...
3
2016-08-03T03:01:32Z
[ "python", "python-3.x", "tuples" ]
Best way to perform calculations on a list/tuple in Python 3x
38,733,593
<p>I wrote this program that will tell you the two <s>multiples</s> factors of your input. Ex. if I were to input 35 (a semiprime), the program would print 5 and 7, which are the two prime numbers that multiply to 35.</p> <p>But I am wondering if there is a more concise or pythonic way to iterate through this tuple so...
4
2016-08-03T02:49:58Z
38,733,835
<p>While jedwards demonstrates the most Pythonic approach - using the <code>itertools</code> library which you will come to know and love- here is the more "classic" approach using for-loops for the pattern you want. I bring it up because as a programming beginner, it is important to know this basic, imperative idiom:<...
1
2016-08-03T03:23:17Z
[ "python", "python-3.x", "tuples" ]
Best way to perform calculations on a list/tuple in Python 3x
38,733,593
<p>I wrote this program that will tell you the two <s>multiples</s> factors of your input. Ex. if I were to input 35 (a semiprime), the program would print 5 and 7, which are the two prime numbers that multiply to 35.</p> <p>But I am wondering if there is a more concise or pythonic way to iterate through this tuple so...
4
2016-08-03T02:49:58Z
38,733,966
<p>Even though @<strong>jedwards</strong> solution is great, (<em>as well as concise/pythonic</em>); one other possible solution:</p> <pre><code>def prime_multiples(l,t ): for i in l: # Iterate over our list. for j in t: # Iterate over the tuple of prime factors. # We check to see that we ...
1
2016-08-03T03:38:48Z
[ "python", "python-3.x", "tuples" ]
Can't install Pillow for Python 3.x in Windows - Zlib is required
38,733,647
<p>I am using PyCharm with Python 3.0 and I want to import Pillow Module.</p> <p>While installing the Pillow module from Project Interpreter, I got a message which says:</p> <pre><code>ValueError: zlib is required unless explicitly disabled using --disable-zlib, aborting. </code></pre> <p><a href="http://i.stack.img...
1
2016-08-03T02:56:35Z
39,305,161
<p>Go to the Virtualenv path cd path to virtualenv cd Script then run easy_install Pillow</p> <p>It works fine</p>
1
2016-09-03T09:04:15Z
[ "python", "windows", "python-3.x", "pycharm" ]
Can't install Pillow for Python 3.x in Windows - Zlib is required
38,733,647
<p>I am using PyCharm with Python 3.0 and I want to import Pillow Module.</p> <p>While installing the Pillow module from Project Interpreter, I got a message which says:</p> <pre><code>ValueError: zlib is required unless explicitly disabled using --disable-zlib, aborting. </code></pre> <p><a href="http://i.stack.img...
1
2016-08-03T02:56:35Z
39,894,227
<p>files > Settings > Project Test > Project Interpreter > ADD > Pillow-PIL</p>
-1
2016-10-06T11:00:49Z
[ "python", "windows", "python-3.x", "pycharm" ]
Efficient way to get the unique values from 2 or more columns in a Dataframe
38,733,719
<p>Given a matrix from an <code>SFrame</code>:</p> <pre><code>&gt;&gt;&gt; from sframe import SFrame &gt;&gt;&gt; sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]}) &gt;&gt;&gt; sf Columns: x int y int z int Rows: 5 Data: +---+---+---+ | x | y | z | +---+---+---+ | 1 | 2 | 2 | | 1 | 4 ...
12
2016-08-03T03:07:31Z
38,734,603
<p>I dont have SFrame but tested on pd.DataFrame: </p> <pre><code> sf[["x", "y"]].stack().value_counts().index.tolist() [2, 1, 8, 7, 6, 5, 4] </code></pre>
2
2016-08-03T04:46:54Z
[ "python", "csv", "pandas", "dataframe", "sframe" ]
Efficient way to get the unique values from 2 or more columns in a Dataframe
38,733,719
<p>Given a matrix from an <code>SFrame</code>:</p> <pre><code>&gt;&gt;&gt; from sframe import SFrame &gt;&gt;&gt; sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]}) &gt;&gt;&gt; sf Columns: x int y int z int Rows: 5 Data: +---+---+---+ | x | y | z | +---+---+---+ | 1 | 2 | 2 | | 1 | 4 ...
12
2016-08-03T03:07:31Z
38,735,070
<p>Although I don't know how to do it in SFrame, here's a longer explanation of @Merlin's answer:</p> <pre><code>&gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; df = pd.DataFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]}) &gt;&gt;&gt; df[['x', 'y']] x y 0 1 2 1 1 4 2 2 6 3 5 8 4 7 2 </code></pre>...
1
2016-08-03T05:27:10Z
[ "python", "csv", "pandas", "dataframe", "sframe" ]
Efficient way to get the unique values from 2 or more columns in a Dataframe
38,733,719
<p>Given a matrix from an <code>SFrame</code>:</p> <pre><code>&gt;&gt;&gt; from sframe import SFrame &gt;&gt;&gt; sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]}) &gt;&gt;&gt; sf Columns: x int y int z int Rows: 5 Data: +---+---+---+ | x | y | z | +---+---+---+ | 1 | 2 | 2 | | 1 | 4 ...
12
2016-08-03T03:07:31Z
39,044,499
<p>The easiest way I can think of is to convert to a numpy array then find unique values</p> <pre><code>np.unique(sf[['x', 'y']].to_numpy()) array([1, 2, 4, 5, 6, 7, 8]) </code></pre> <p>If you needed it in an sframe</p> <pre><code>SFrame({'xy_unique': np.unique(sf[['x', 'y']].to_numpy())}) </code></pre> <p><a hre...
2
2016-08-19T17:12:04Z
[ "python", "csv", "pandas", "dataframe", "sframe" ]
Efficient way to get the unique values from 2 or more columns in a Dataframe
38,733,719
<p>Given a matrix from an <code>SFrame</code>:</p> <pre><code>&gt;&gt;&gt; from sframe import SFrame &gt;&gt;&gt; sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]}) &gt;&gt;&gt; sf Columns: x int y int z int Rows: 5 Data: +---+---+---+ | x | y | z | +---+---+---+ | 1 | 2 | 2 | | 1 | 4 ...
12
2016-08-03T03:07:31Z
39,044,505
<p><strong>SFrame</strong></p> <p>I haven't used SFrame and don't know on which conditions it copies data. (Does selection <code>sf['x']</code> or <code>append</code> copy data to memory?). There are <code>pack_columns</code> and <code>stack</code> methods in SFrame and if they don't copy data, then this should work:<...
2
2016-08-19T17:12:47Z
[ "python", "csv", "pandas", "dataframe", "sframe" ]
Efficient way to get the unique values from 2 or more columns in a Dataframe
38,733,719
<p>Given a matrix from an <code>SFrame</code>:</p> <pre><code>&gt;&gt;&gt; from sframe import SFrame &gt;&gt;&gt; sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]}) &gt;&gt;&gt; sf Columns: x int y int z int Rows: 5 Data: +---+---+---+ | x | y | z | +---+---+---+ | 1 | 2 | 2 | | 1 | 4 ...
12
2016-08-03T03:07:31Z
39,071,903
<p>Take a look at <a href="http://stackoverflow.com/questions/26977076/pandas-unique-values-multiple-columns">this answer</a> to a similar question. Note that Pandas' <code>pd.unique</code> function is considerably faster than Numpy's.</p> <pre><code>&gt;&gt;&gt; pd.unique(sf[['x','y']].values.ravel()) array([2, 8, 5,...
2
2016-08-22T05:27:51Z
[ "python", "csv", "pandas", "dataframe", "sframe" ]
Efficient way to get the unique values from 2 or more columns in a Dataframe
38,733,719
<p>Given a matrix from an <code>SFrame</code>:</p> <pre><code>&gt;&gt;&gt; from sframe import SFrame &gt;&gt;&gt; sf =SFrame({'x':[1,1,2,5,7], 'y':[2,4,6,8,2], 'z':[2,5,8,6,2]}) &gt;&gt;&gt; sf Columns: x int y int z int Rows: 5 Data: +---+---+---+ | x | y | z | +---+---+---+ | 1 | 2 | 2 | | 1 | 4 ...
12
2016-08-03T03:07:31Z
39,154,077
<p>Here's a little benchmark between three possible methods:</p> <pre><code>from sframe import SFrame import numpy as np import pandas as pd import timeit sf = SFrame({'x': [1, 1, 2, 5, 7], 'y': [2, 4, 6, 8, 2], 'z': [2, 5, 8, 6, 2]}) def f1(sf): return sf['x'].unique().append(sf['y'].unique()).unique() def f...
1
2016-08-25T20:18:00Z
[ "python", "csv", "pandas", "dataframe", "sframe" ]
How to Create New Columns to Store the Data of the Duplicate ID Column?
38,733,732
<p>I have this dataframe:</p> <pre><code> ID key 0 1 A 1 1 B 2 2 C 3 3 D 4 3 E 5 3 E </code></pre> <p>I want to create additional <code>key</code> columns -as necessary- to store the data in the <code>key</code> column when there are duplicate <code>IDs</code></p> <p>This is a snippe...
0
2016-08-03T03:09:20Z
38,734,358
<p>Check out <code>groupby</code> and <code>apply</code>. Their respective docs are <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">here</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofoll...
1
2016-08-03T04:22:33Z
[ "python", "regex", "pandas", "dataframe", "format" ]
How to Create New Columns to Store the Data of the Duplicate ID Column?
38,733,732
<p>I have this dataframe:</p> <pre><code> ID key 0 1 A 1 1 B 2 2 C 3 3 D 4 3 E 5 3 E </code></pre> <p>I want to create additional <code>key</code> columns -as necessary- to store the data in the <code>key</code> column when there are duplicate <code>IDs</code></p> <p>This is a snippe...
0
2016-08-03T03:09:20Z
38,735,498
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p> <pre><code>df['...
1
2016-08-03T05:57:03Z
[ "python", "regex", "pandas", "dataframe", "format" ]
Loading django.apps module inside the url patterns file
38,733,763
<p>I have added a router property (an instance of DRF's SimpleRouter) to my AppConfig. I want to get a list of all installed apps in my urls.py file and add any app with the router property to my url patterns.</p> <p>This is my urls.py file:</p> <pre><code>from django.conf.urls import url, include from django.contrib...
0
2016-08-03T03:13:27Z
38,747,709
<p>The error wasn't being caused by the urls.py folder, it was being by the AppConfig. I had to import the auth_router inside the ready method</p> <pre><code>from django.apps import AppConfig class AuthConfig(AppConfig): name = "core.auth" # to avoid classing with the django auth label = "custom_auth" ...
1
2016-08-03T15:23:02Z
[ "python", "django", "django-rest-framework", "django-urls" ]
Can not enter characters in dictionary with python script
38,733,798
<p>I made a dictionary in python by retrieving data in json format.</p> <pre><code>[{"id":"1","kingdom":"Metazoa ","phylum":"Arthropoda ","class":"Insecta ","order":"Hemiptera ","family":"Belostomatidae ","genus":"Abedus"},&lt;br&gt; {"id":"2","kingdom":"Viridiplantae ","phylum":"Streptophyta ","class":"unclassified_S...
1
2016-08-03T03:17:54Z
38,733,827
<p>The error you are getting is because you are trying to convert a string containing non numeric values into an integer. To fix that, remove <code>get = int(str(title))</code></p> <hr> <p>The data you have is a list. Lists use numeric indexing to access elements at different locations in the list. To print <code>gen...
3
2016-08-03T03:21:37Z
[ "python", "json", "python-2.7" ]
Can not enter characters in dictionary with python script
38,733,798
<p>I made a dictionary in python by retrieving data in json format.</p> <pre><code>[{"id":"1","kingdom":"Metazoa ","phylum":"Arthropoda ","class":"Insecta ","order":"Hemiptera ","family":"Belostomatidae ","genus":"Abedus"},&lt;br&gt; {"id":"2","kingdom":"Viridiplantae ","phylum":"Streptophyta ","class":"unclassified_S...
1
2016-08-03T03:17:54Z
38,733,836
<p>This will find the first entry that matches:</p> <pre><code>print next(x for x in data if x["genus"] == title) </code></pre>
2
2016-08-03T03:23:28Z
[ "python", "json", "python-2.7" ]
how to avoid inserting duplicated rows working on pandas dataframe?
38,733,807
<p>I am working on pandas dataframe and mysql, my table is timeseries related like,</p> <pre><code>symbol_id date close 1 2016-6-1 123 1 2016-6-2 133 1 2016-6-3 143 2 2016-6-1 23 2 2016-6-2 33 2 2016-6-3 43 </code></pre> <p>When asserting a new dataframe into...
0
2016-08-03T03:18:53Z
38,735,282
<p>Assuming you want to remove duplicates, you can do something like this</p> <pre><code>df.drop_duplicates(subset='symbol_id') </code></pre> <p>If you do not specify any subset parameter, then it by default checks for row level duplicates. </p> <p>There are options to keep the first occurrence or last occurrence e...
0
2016-08-03T05:41:55Z
[ "python", "mysql", "pandas" ]
python pandas reattach column after aggregation
38,733,848
<p>My DataFrame looks like this</p> <pre><code>exams = pd.DataFrame({'id1':['1x', '1x','2x','3x','3x'], 'id2':['a','a','b','a','a'],'data':[1,2,3,4,5]}) id1 id2 data 0 1x a 1 1 1x a 2 2 2x b 3 3 3x a 4 4 3x a 5 </code></pre> <p>Then I aggrega...
1
2016-08-03T03:24:56Z
38,733,921
<p>If a unique <code>id1</code> always corresponds to the same <code>id2</code>, you can simply add <code>id2</code> in your <code>groupby</code> :</p> <pre><code>In [5]: df.groupby(['id1', 'id2']).agg('mean') Out[5]: data id1 id2 1x a 1.5 2x b 3.0 3x a 4.5 </code></pre>
2
2016-08-03T03:33:53Z
[ "python", "pandas", "merge", "aggregate" ]
List of objects affecting other object's list
38,733,882
<p>I'm trying to build a graph where a vertex has a string identifier and is connected to another vertex if the string identifiers of the 2 vertices differ by only a single character. For example, 'dog' and 'dot' can be connected by an edge. I'm maintaining the graph with an adjacency list. However, after I have valida...
1
2016-08-03T03:29:13Z
38,733,931
<p>I'm not completely sure but I think the problem is using the default value <code>[]</code> for <code>edges</code> which (I think) creates a unique object <code>[]</code> and then initialise by default to that unique object. So all your edges will essentially be the same object and when you append to one of them, you...
1
2016-08-03T03:35:12Z
[ "python", "list" ]
What is the order of operations for 'and' and 'or'?
38,733,885
<p>In Python is this:</p> <pre><code>def blackjack_check(hand): # hand is a tuple winning_cards = [10,'Jack','Queen','King'] if hand[0] in winning_cards and hand[1] == 'Ace': return True elif hand[0] == 'Ace' and hand[1] in winning_cards: return True else: return False </code></...
1
2016-08-03T03:29:27Z
38,733,911
<p>The usual advice is if you don't know, then your readers might not know either, and it would be better for everybody if you use parentheses.</p> <pre><code>if ((hand[0] in winning_cards and hand[1]=='Ace') or (hand[0] == 'Ace' and hand[1] in winning_cards)): </code></pre> <p>although you might try other formu...
0
2016-08-03T03:32:47Z
[ "python", "if-statement", "logical-operators" ]
What is the order of operations for 'and' and 'or'?
38,733,885
<p>In Python is this:</p> <pre><code>def blackjack_check(hand): # hand is a tuple winning_cards = [10,'Jack','Queen','King'] if hand[0] in winning_cards and hand[1] == 'Ace': return True elif hand[0] == 'Ace' and hand[1] in winning_cards: return True else: return False </code></...
1
2016-08-03T03:29:27Z
38,733,915
<p>Yes, the second code block is equivalent to the first one. According to <a href="https://docs.python.org/3/reference/expressions.html#operator-precedence" rel="nofollow">the documentation</a>, <code>or</code> has lower precedence than <code>and</code>. It means that the if statement is evaluated as</p> <pre><code>i...
4
2016-08-03T03:33:10Z
[ "python", "if-statement", "logical-operators" ]
What is the order of operations for 'and' and 'or'?
38,733,885
<p>In Python is this:</p> <pre><code>def blackjack_check(hand): # hand is a tuple winning_cards = [10,'Jack','Queen','King'] if hand[0] in winning_cards and hand[1] == 'Ace': return True elif hand[0] == 'Ace' and hand[1] in winning_cards: return True else: return False </code></...
1
2016-08-03T03:29:27Z
38,734,359
<p><a href="http://stackoverflow.com/a/38733915/736937">vaultah's answer</a> addresses your actual question perfectly -- they deserve the upvote and checkmark.</p> <p>But I think programming blackjack in every language you're learning is an excellent way to better understand it, so I threw together code to show a diff...
2
2016-08-03T04:22:39Z
[ "python", "if-statement", "logical-operators" ]
NumPy boolean array warning?
38,733,897
<p>I have a few numpy arrays, lets say <code>a</code>, <code>b</code>, and <code>c</code>, and have created a <code>mask</code> to apply to all of them. </p> <p>I am trying to mask them as such:</p> <p><code>a = a[mask]</code></p> <p>where <code>mask</code> is a <code>bool</code> array. It is worth noting that I hav...
2
2016-08-03T03:31:10Z
38,734,025
<p>False == 0, and True == 1. If your mask is a list, and not an ndarray, you can get some unexpected behaviour:</p> <pre><code>&gt;&gt;&gt; a = np.array([1,2,3]) &gt;&gt;&gt; mask_list = [True, False, True] &gt;&gt;&gt; a[mask_list] __main__:1: FutureWarning: in the future, boolean array-likes will be handled as a b...
3
2016-08-03T03:45:32Z
[ "python", "arrays", "numpy", "boolean", "bitmask" ]
Convert RDD of LabeledPoint to DataFrame toDF() Error
38,733,928
<p>I have a dataframe df which contains 13 values separated with comma. I want to get in df2 a dataFrame wich contains labeledPoint. firt value is label, twelve others are features. I use a split and select method to divide string with 13 value into an array of 13 values. map method allow me to create labeledPoint. Err...
0
2016-08-03T03:35:03Z
38,864,086
<p>The Error come from the index x[0] should be replace by x[0][0]. So :</p> <pre><code>df2 = df.select(split(df[0], ',')).map(lambda x: LabeledPoint(float(x[0][0]), x[0][-12:])).toDF() </code></pre>
1
2016-08-10T04:12:24Z
[ "python", "apache-spark", "pyspark", "rdd", "spark-dataframe" ]
Losing merged cells border while editing Excel file with openpyxl
38,734,044
<p>I have two sheets in an Excel file and the first one is a cover sheet which I don't need to edit. There are few merged cells in the cover sheet. But when I edit the file using openpyxl not even touch the cover sheet, I lose borders from the merged cells. Is there any fix to this problem? I am using Load_workbook('ex...
0
2016-08-03T03:48:07Z
38,736,739
<p>This is covered in the <a href="http://openpyxl.readthedocs.io/en/latest/styles.html#styling-merged-cells" rel="nofollow">documentation of openpyxl</a>.</p>
1
2016-08-03T07:10:54Z
[ "python", "excel", "openpyxl" ]
How to partially update a spark dataframe (update some rows)
38,734,126
<p>I am using Spark 1.5.2 with Python3. I have two dataframes in pyspark. They look like:</p> <pre><code>old_df = src | rank ------ | ------ a| 1 b| 1 c| 1 d| 1 e| 1 f| 1 g| 1 </code></pre> <p>and</p> <pre><code>new_df = src| rank ---|----------------- a| 0...
0
2016-08-03T03:54:12Z
38,736,989
<p>You can resolve this with sql functions and join..</p> <pre><code>import org.apache.spark.sql.funtions._ odl_df.join(new_df, "src") .withColumn("finalRank", when(new_df("rank").isNull, odl_df("rank")) .otherwise(new_df("rank")) .drop(new_df("rank")) .drop(odl_df("rank")) .withColumnRenam...
0
2016-08-03T07:23:21Z
[ "python", "apache-spark" ]
Python File I/O issue: Bypassing For Loop?
38,734,209
<pre><code>def findWord(word): f = open("words.txt", "r") given_line = f.readlines() for line in f: if str(word) in line: part = line[0] ## print(line+"\n"+str(word)+" is a "+part) return True else: return False print("fail") f.close() ...
0
2016-08-03T04:05:16Z
38,734,257
<p>First off, delete this line:</p> <pre><code>given_line = f.readlines() </code></pre> <p>This is reading the contents of the file into an unused <code>given_line</code> variable and leaving <code>f</code> positioned at the end of the file. Your <code>for</code> loop therefore has nothing to loop over.</p> <hr> <p...
0
2016-08-03T04:10:13Z
[ "python", "io" ]
Python File I/O issue: Bypassing For Loop?
38,734,209
<pre><code>def findWord(word): f = open("words.txt", "r") given_line = f.readlines() for line in f: if str(word) in line: part = line[0] ## print(line+"\n"+str(word)+" is a "+part) return True else: return False print("fail") f.close() ...
0
2016-08-03T04:05:16Z
38,734,286
<p><code>for line in f:</code> never runs because you have already read the file contents and the cursor is at the end of the file.</p> <p>You should do:</p> <p><code>for line in given_line:</code></p> <p>Or you could put this statement just before your for loop:</p> <p><code>f.seek(0)</code></p> <p>It places the ...
0
2016-08-03T04:13:23Z
[ "python", "io" ]
Creating an list of dictionaries that hold a variable sized array
38,734,234
<p>I'm trying to create the following data structure (that's not optimal, I know, but is necessary given my input data):</p> <p>A list of 100 dictionaries with the same two keys, "x" and "y", where each key holds a variable length numpy array. "y" holds a vector and "x" holds an array of images, so an example shape fo...
1
2016-08-03T04:08:22Z
38,734,342
<p>I assume the input list of lengths is a list of pairs, or something similar.</p> <pre><code>input_lengths = [(12,17), (8,50), (2,7)] pre_filled_list = [{'x' : [None]*x, 'y' : [None]*y} for x,y in input_lengths] print(pre_filled_list) </code></pre> <p>Pre_filled list is a list of dictionaries, each with two keys; e...
0
2016-08-03T04:20:11Z
[ "python", "arrays", "list", "numpy", "dictionary" ]
Creating an list of dictionaries that hold a variable sized array
38,734,234
<p>I'm trying to create the following data structure (that's not optimal, I know, but is necessary given my input data):</p> <p>A list of 100 dictionaries with the same two keys, "x" and "y", where each key holds a variable length numpy array. "y" holds a vector and "x" holds an array of images, so an example shape fo...
1
2016-08-03T04:08:22Z
38,734,562
<p>What about:</p> <pre><code>import numpy as np dims = [(42,43), (46,9), (47,49), (60,14)] output = [{'x':np.zeros((x,3,10,50)), 'y':np.zeros((y,))} for (x,y) in dims] print(len(output)) # 4, matches len(dims) print(type(output[0]['x'])) # &lt;type 'numpy.ndarray'&gt; print(type(output[0]['y'])) ...
0
2016-08-03T04:42:27Z
[ "python", "arrays", "list", "numpy", "dictionary" ]
Static classes being initialised on import. How does python 2 initialise static classes on import
38,734,294
<p>I am trying to introduce python 3 support for the package <a href="https://pypi.python.org/pypi/mime" rel="nofollow">mime</a> and the code is doing something I have never seen before. </p> <p>There is a class <code>Types()</code> that is used in the package as a static class. </p> <pre><code>class Types(with_metac...
2
2016-08-03T04:13:54Z
38,734,950
<p>Without posting more of your code, it's hard to say. I will say that I was able to get that package ported to Python 3 with only a few changes (print statement -> function, <code>basestring</code> -> <code>str</code>, adding a dot before same-package imports, and a really ugly hack to compensate for their love of <...
2
2016-08-03T05:18:09Z
[ "python", "class", "import", "static" ]
Python regex - Replace bracketed text with contents of brackets
38,734,335
<p>I'm trying to write a Python function that replaces instances of text surrounded with curly braces with the contents of the braces, while leaving empty brace-pairs alone. For example: </p> <p><code>foo {} bar {baz}</code> would become <code>foo {} bar baz</code>. </p> <p>The pattern that I've created to match this...
3
2016-08-03T04:19:33Z
38,734,403
<p>You can use a <em>capturing group</em> to replace a part of the match:</p> <pre><code>&gt;&gt;&gt; re.sub(r"{([^{}]+)}", r"\1", "foo{}bar{baz}") 'foo{}barbaz' &gt;&gt;&gt; re.sub(r"{([^{}]+)}", r"\1", "foo {} bar {baz}") 'foo {} bar baz' </code></pre>
2
2016-08-03T04:26:18Z
[ "python", "regex", "string", "substitution", "backreference" ]
Python regex - Replace bracketed text with contents of brackets
38,734,335
<p>I'm trying to write a Python function that replaces instances of text surrounded with curly braces with the contents of the braces, while leaving empty brace-pairs alone. For example: </p> <p><code>foo {} bar {baz}</code> would become <code>foo {} bar baz</code>. </p> <p>The pattern that I've created to match this...
3
2016-08-03T04:19:33Z
38,737,329
<p>When you use <code>"\g&lt;0&gt;"[1:-1]</code> as a replacement pattern, you only slice the <code>"\g&lt;0&gt;"</code> <em>string</em>, not the actual value this backreference refers to.</p> <p>If you need to use your "trimming" approach, you need to pass the match data object to the <code>re.sub</code>:</p> <pre><...
2
2016-08-03T07:39:42Z
[ "python", "regex", "string", "substitution", "backreference" ]
Pandas: Faster way to iterate through a dataframe and add new data based on operations
38,734,369
<p>I want to pandas to look into values in 2 columns in each row of df1, look for the match in another df2, and paste this in a new column in df1 in the same row and continue</p> <pre><code>alp=list("ABCDEFGHIJKLMNOPQRTSUVQXYZ") df1['NewCol'] = (np.random.choice(alp)) #create new col and input random values for i in ...
1
2016-08-03T04:23:20Z
38,734,663
<p>You could use <code>apply</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html" rel="nofollow">docs</a>), but a faster way to do this if you have a lot of data would be to create a version of <code>df2</code> with a <code>MultiIndex</code> (<a href="http://pandas.pydata....
0
2016-08-03T04:53:50Z
[ "python", "pandas" ]
How to plot a two column pandas dataframe's elements as an histogram?
38,734,460
<p>I have the following pandas dataframe:</p> <pre><code> A B 1 3 0 2 1 4 0 1 0 3 </code></pre> <p>I would like to plot the frequency of B instnaces given A, something like this:</...
3
2016-08-03T04:31:54Z
38,734,570
<p>I'm not entirely sure what you mean by "plot the frequency of the elements in B given the frequency of A", but this gives the expected output :</p> <pre><code>In [4]: df Out[4]: A B 3995 1 3 3996 0 2 3997 1 4 3998 0 1 3999 0 3 In [8]: df['data'] = df['A']*df['B'] In [9]: df Out[9]: A B ...
2
2016-08-03T04:43:37Z
[ "python", "python-3.x", "pandas", "matplotlib" ]
How to plot a two column pandas dataframe's elements as an histogram?
38,734,460
<p>I have the following pandas dataframe:</p> <pre><code> A B 1 3 0 2 1 4 0 1 0 3 </code></pre> <p>I would like to plot the frequency of B instnaces given A, something like this:</...
3
2016-08-03T04:31:54Z
38,734,736
<p>I believe if you are trying to plot the frequency of occurrence of values in column b, this might help.</p> <pre><code>from collections import Counter vals = list(df['b']) cntr = Counter(vals) # Out[30]: Counter({1: 1, 2: 1, 3: 2, 4: 1}) vals = [(key,cntr[key]) for key in cntr] x = [tup[0] for tup in vals] y = [tu...
1
2016-08-03T05:01:22Z
[ "python", "python-3.x", "pandas", "matplotlib" ]
How to plot a two column pandas dataframe's elements as an histogram?
38,734,460
<p>I have the following pandas dataframe:</p> <pre><code> A B 1 3 0 2 1 4 0 1 0 3 </code></pre> <p>I would like to plot the frequency of B instnaces given A, something like this:</...
3
2016-08-03T04:31:54Z
38,734,831
<p>Here is my way:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt df = pd.DataFrame([[1,3],[0,2],[1,4],[0,1],[0,3]]) df.columns = ['A', 'B'] x = df.loc[:,'A'].values y = df.loc[:,'B'].values plt.bar(x, y, label = 'Bar', align='center',) plt.xticks(x) plt.show() </code></pre> <p><a href="http://i....
1
2016-08-03T05:09:37Z
[ "python", "python-3.x", "pandas", "matplotlib" ]
How to plot a two column pandas dataframe's elements as an histogram?
38,734,460
<p>I have the following pandas dataframe:</p> <pre><code> A B 1 3 0 2 1 4 0 1 0 3 </code></pre> <p>I would like to plot the frequency of B instnaces given A, something like this:</...
3
2016-08-03T04:31:54Z
38,734,967
<p>Sounds like this is what you want: You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.value_counts.html" rel="nofollow">Series.value_counts()</a></p> <pre><code>print(df['B'].value_counts().plot(kind='bar')) </code></pre> <p><a href="http://i.stack.imgur.com/5Qdwj.png" rel="no...
3
2016-08-03T05:19:52Z
[ "python", "python-3.x", "pandas", "matplotlib" ]
Python 2 and Python 3 - Running in Command Prompt
38,734,521
<p>Having various projects in both Python 2 and Python 3 (with both python versions installed), I was looking for a more intuitive way to run scripts via Command Prompt than <code>py -3 script.py</code>.</p> <p>Python 2 already took <code>python script.py</code>, so ideally <code>python3 script.py</code> should invoke...
0
2016-08-03T04:37:34Z
38,734,522
<p>Searching did not yield good results, so I thought I should share the process I took with anyone looking for this in the future.</p> <ol> <li>Make sure the Python 3 folder is present in the PATH environment variable. </li> <li>Locate the "python.exe" file in the Python 3 folder.</li> <li>Copy and Paste the "python....
3
2016-08-03T04:37:34Z
[ "python", "windows", "command-prompt" ]
Simplifying the extraction of particular string patterns with a multiple if-else and split()
38,734,649
<p>Given a string like this:</p> <pre><code>&gt;&gt;&gt; s = "X/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;Y/PROPN/pobj_&gt;,/PUNCT/punct" </code></pre> <p>First I want to split the string by underscores, i.e.:</p> <pre><code>&gt;&gt;&gt; s.split('_') ['X/NOUN/dobj&gt;', 'hold/VERB/...
2
2016-08-03T04:51:42Z
38,734,996
<pre><code>s = 'X/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;Y/PROPN/pobj_&gt;,/PUNCT/punct' def get_sentinal(node): if not node: return '-' # Assuming the node won't contain both '&lt;' and '&gt;' at a same time for index in [0, -1]: if node[index] in '&lt;...
3
2016-08-03T05:21:32Z
[ "python", "regex", "string", "split" ]
Simplifying the extraction of particular string patterns with a multiple if-else and split()
38,734,649
<p>Given a string like this:</p> <pre><code>&gt;&gt;&gt; s = "X/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;Y/PROPN/pobj_&gt;,/PUNCT/punct" </code></pre> <p>First I want to split the string by underscores, i.e.:</p> <pre><code>&gt;&gt;&gt; s.split('_') ['X/NOUN/dobj&gt;', 'hold/VERB/...
2
2016-08-03T04:51:42Z
38,735,351
<p>Yes, although it's not pretty:</p> <pre><code>s = "X/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;Y/PROPN/pobj_&gt;,/PUNCT/punct" import re out = [] for part in s.split('_'): Left, Mid, Right = re.search('^([&lt;&gt;]|)(.*?)([&lt;&gt;]|)$', part).groups() tail = ['-'] if not...
1
2016-08-03T05:46:42Z
[ "python", "regex", "string", "split" ]
Simplifying the extraction of particular string patterns with a multiple if-else and split()
38,734,649
<p>Given a string like this:</p> <pre><code>&gt;&gt;&gt; s = "X/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;Y/PROPN/pobj_&gt;,/PUNCT/punct" </code></pre> <p>First I want to split the string by underscores, i.e.:</p> <pre><code>&gt;&gt;&gt; s.split('_') ['X/NOUN/dobj&gt;', 'hold/VERB/...
2
2016-08-03T04:51:42Z
38,735,440
<p>Instead of my other answer with regexes, you can drop a lot of lines and a lot of slicing, if you know that <code>string.strip('&lt;&gt;')</code> will strip <em>either</em> character from <em>both ends</em> of the string, in one move.</p> <p>This code is about halfway between your original and my regex answer in li...
1
2016-08-03T05:53:23Z
[ "python", "regex", "string", "split" ]
Simplifying the extraction of particular string patterns with a multiple if-else and split()
38,734,649
<p>Given a string like this:</p> <pre><code>&gt;&gt;&gt; s = "X/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;Y/PROPN/pobj_&gt;,/PUNCT/punct" </code></pre> <p>First I want to split the string by underscores, i.e.:</p> <pre><code>&gt;&gt;&gt; s.split('_') ['X/NOUN/dobj&gt;', 'hold/VERB/...
2
2016-08-03T04:51:42Z
38,735,501
<p>Use this:</p> <pre><code>import re s_split = "X/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;Y/PROPN/pobj_&gt;,/PUNCT/punct".split('_') for i, text in enumerate(s_split): Left, Mid, Right = re.search('^([&lt;&gt;]?)(.*?)([&lt;&gt;]?)$', text).groups() s_split[i] = Mid.split('/...
2
2016-08-03T05:57:20Z
[ "python", "regex", "string", "split" ]
Simplifying the extraction of particular string patterns with a multiple if-else and split()
38,734,649
<p>Given a string like this:</p> <pre><code>&gt;&gt;&gt; s = "X/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;Y/PROPN/pobj_&gt;,/PUNCT/punct" </code></pre> <p>First I want to split the string by underscores, i.e.:</p> <pre><code>&gt;&gt;&gt; s.split('_') ['X/NOUN/dobj&gt;', 'hold/VERB/...
2
2016-08-03T04:51:42Z
38,736,245
<p>I did not use regex and groups but it can be solution as shorter way.</p> <pre><code>&gt;&gt;&gt; result=[] &gt;&gt;&gt; nodes=['X/NOUN/dobj&gt;','hold/VERB/ROOT','&lt;membership/NOUN/dobj', '&lt;with/ADP/prep','&lt;Y/PROPN/pobj','&gt;,/PUNCT/punct'] &gt;&gt;&gt; for node in nodes: ... nd=node.replace("&gt;",("...
0
2016-08-03T06:44:58Z
[ "python", "regex", "string", "split" ]
Simplifying the extraction of particular string patterns with a multiple if-else and split()
38,734,649
<p>Given a string like this:</p> <pre><code>&gt;&gt;&gt; s = "X/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;Y/PROPN/pobj_&gt;,/PUNCT/punct" </code></pre> <p>First I want to split the string by underscores, i.e.:</p> <pre><code>&gt;&gt;&gt; s.split('_') ['X/NOUN/dobj&gt;', 'hold/VERB/...
2
2016-08-03T04:51:42Z
38,739,840
<p>Even shorter with a list comprehension and some regex magic:</p> <pre><code>import re s = "X/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;Y/PROPN/pobj_&gt;,/PUNCT/punct" rx = re.compile(r'([&lt;&gt;])|/') items = [list(filter(None, match)) \ for item in s.split('_') \ for...
1
2016-08-03T09:37:09Z
[ "python", "regex", "string", "split" ]
Is there a better way to swap string without a placeholder
38,735,328
<p>I have a string:</p> <pre><code>&gt;&gt;&gt; s = 'Y/NOUN/dobj&gt;_hold/VERB/ROOT_&lt;membership/NOUN/dobj_&lt;with/ADP/prep_&lt;X/PROPN/pobj_&gt;,/PUNCT/punct' </code></pre> <p>And the aim is to change the position of <code>Y/</code> to <code>X/</code>, i.e. something like:</p> <pre><code>&gt;&gt;&gt; s.replace('...
1
2016-08-03T05:45:06Z
38,736,034
<p>In Python, an easy way using a regex is via a lambda in the <code>re.sub</code> replacement part where you can evaluate/check texts captured with capturing groups and select appropriate replacement:</p> <p>So, <code>(X|Y)/</code> (<em>I assume <code>X</code> and <code>Y</code> are potentially multicharacter string ...
2
2016-08-03T06:33:15Z
[ "python", "regex", "string", "replace", "swap" ]
filter() and get() don't give correct GQLQuery results
38,735,372
<p>So I'm building a small wiki using Google App Engine, where if you type in a URL like <code>/newpage</code>, it redirects you to it if it already exists, else it redirects you to <code>/edit/newpage/</code> where you can edit (or in this case, add) the contents of the page. After the editing, it redirects you to the...
0
2016-08-03T05:48:23Z
38,742,367
<p>You are performing a query to retrieve the WikiPage, at times (due to eventual consistency) the query will not find the page just created.</p> <p>You need to spend some time reading up on Eventual Consistency, it is important to understand concept this when using the data store.</p> <p>I suggest you consider using...
1
2016-08-03T11:32:12Z
[ "python", "google-app-engine", "redirect", "google-cloud-datastore", "gql" ]
Pivot a groupby object in Pandas?
38,735,384
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame([ [123, 'abc', '121'], [124, 'abc', '121'], [456, 'def', '121'], [123, 'abc', '122'], [123, 'abc', '122'], [456, 'def', '145'], [456, 'def', '145'], [456, 'def', '146'], ], columns=['...
3
2016-08-03T05:49:12Z
38,735,489
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>, where parameter inde...
2
2016-08-03T05:56:24Z
[ "python", "pandas" ]
Pivot a groupby object in Pandas?
38,735,384
<p>I have the following dataframe:</p> <pre><code>df = pd.DataFrame([ [123, 'abc', '121'], [124, 'abc', '121'], [456, 'def', '121'], [123, 'abc', '122'], [123, 'abc', '122'], [456, 'def', '145'], [456, 'def', '145'], [456, 'def', '146'], ], columns=['...
3
2016-08-03T05:49:12Z
38,735,764
<p>Check out <code>groupby</code> and <code>apply</code>. Their respective docs are <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow">here</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofoll...
2
2016-08-03T06:15:12Z
[ "python", "pandas" ]
Packing an integer number to 3 bytes in Python
38,735,421
<p>With background knowledge of C I want to serialize an integer number to 3 bytes. I searched a lot and found out I should use struct packing. I want something like this:</p> <pre><code>number = 1195855 buffer = struct.pack("format_string", number) </code></pre> <p>Now I expect buffer to be something like <code>['\x...
2
2016-08-03T05:52:31Z
38,735,535
<p>It is possible, using either <code>&gt;</code> or <code>&lt;</code> in your format string:</p> <pre><code>import struct number = 1195855 def print_buffer(buffer): print(''.join(["%02x" % ord(b) for b in buffer])) # Python 2 #print(buffer.hex()) # Python 3 # Little Endian...
3
2016-08-03T05:59:13Z
[ "python" ]
Python Tkinter button stuck down after press
38,735,643
<p>I press this tkinter button, and the function bound to it finishes, but the button is stuck down. The rest of the gui is fine, its responsive, everything normal except for the button that is stuck down. I can even press the "stuck down" button again, and the bound function executes and finishes, but the button is st...
-2
2016-08-03T06:06:13Z
38,748,117
<p>I have found what is causing this, it is the fact that I am using the 'bind' function instead of the 'command'.</p> <p>When I use this, the button sticks if you move the mouse off the button before the callback finishes (you can only realistically do this if you have a lot of work to do in the callback):</p> <pre>...
0
2016-08-03T15:40:49Z
[ "python", "button", "tkinter" ]
Brookstone rover 2.0 Python program to control from computer isn't working
38,735,708
<p>I have a python program that controls a Brookstone Rover 2.0 from a computer through openCV and pygame and I've been working on this for 7 hours now and it has been nothing but errors after errors and this is what it's showing me now</p> <pre><code> PS C:\users\sessi\desktop&gt; C:\Users\sessi\Desktop\rover\ps3r...
-1
2016-08-03T06:11:21Z
38,737,318
<p>At </p> <p><a href="https://github.com/simondlevy/RoverPylot" rel="nofollow">https://github.com/simondlevy/RoverPylot</a></p> <p>it says:</p> <blockquote> <p>Tips for Windows</p> <p>Rob Crawley has put a lot of work into getting RoverPylot to work smoothly on Windows 10. Here are his changes:</p> <p...
0
2016-08-03T07:39:20Z
[ "python", "python-2.7", "python-3.x", "opencv", "pygame" ]
How to use Hyperlinked in Django Rest Framework?
38,735,842
<p>I just want to add url in some serializer fields.</p> <pre><code>class PageListSerializer(ModelSerializer): slider = SerializerMethodField() lookup_field = 'title' class Meta: model = Page fields = [ 'is_active', 'category', 'title', 'slu...
-1
2016-08-03T06:21:25Z
38,736,770
<p>Refer the <a href="http://www.django-rest-framework.org/tutorial/5-relationships-and-hyperlinked-apis/" rel="nofollow">hyperlink</a> API and make sure that url is defined in your url.py</p>
0
2016-08-03T07:12:25Z
[ "python", "django", "django-rest-framework" ]
A function that works on a function and returns a function
38,736,095
<p>Suppose I want to define a meta-function that accept a function as an argument and returns a new modified function. Something like</p> <pre><code>metaf(f) -&gt; f**2 </code></pre> <p>So whatever <code>f</code> would result, <code>metaf</code> would result with the answer to the power of two (and if the result cann...
1
2016-08-03T06:37:31Z
38,736,261
<p>You should be able to use <code>*args</code> and <code>**kwargs</code> to gobble up all other arguments and pass them on like so:</p> <pre><code>def squarer(f): return lambda *args, **kwargs: f(*args, **kwargs)**2 &gt;&gt;&gt; squarer(lambda x: x+1)(3) 16 &gt;&gt;&gt; squarer(lambda x: x+1)(4) 25 &gt;&gt;&gt;...
3
2016-08-03T06:45:38Z
[ "python" ]
A function that works on a function and returns a function
38,736,095
<p>Suppose I want to define a meta-function that accept a function as an argument and returns a new modified function. Something like</p> <pre><code>metaf(f) -&gt; f**2 </code></pre> <p>So whatever <code>f</code> would result, <code>metaf</code> would result with the answer to the power of two (and if the result cann...
1
2016-08-03T06:37:31Z
38,736,292
<p>I believe this is what you are after:</p> <pre><code>def metaf(f): def func(*r, **kw): return f(*r, **kw) ** 2 return func </code></pre> <p>And now let's define some <code>f</code>...</p> <pre><code>def f(a, b): return a + b </code></pre> <p>And here is converting it:</p> <pre><code>mynewf =...
4
2016-08-03T06:47:16Z
[ "python" ]
How to proceed multipart/form-data or application/x-www-form-urlencoded request using requests module in python?
38,736,179
<p>Our API clients support only multipart/form-data and application/x-www-form-urlencoded format. So, when I try to access their API:</p> <pre><code>import requests import json url = "http://api.client.com/admin/offer" headers = {"Content-Type": "multipart/form-data", "API-Key": "fffffffffffffffffffffffffffffffffffff...
-1
2016-08-03T06:41:41Z
38,736,498
<blockquote> <p>Our API clients support only multipart/form-data and application/x-www-form-urlencoded format</p> </blockquote> <p>Yet you are setting the <code>Content-type</code> <em>header</em> to <code>application/json</code>, which is not <code>multipart/form-data</code> nor <code>application/x-www-form-urlen...
2
2016-08-03T06:57:54Z
[ "python", "python-requests", "urllib" ]
Python: Issue with Writing over Lines?
38,736,230
<p>So, this is the code I'm using in Python to remove lines, hence the name "cleanse." I have a list of a few thousand words and their parts-of-speech:</p> <blockquote> <p>NN by</p> <p>PP at</p> <p>PP at</p> </blockquote> <p>... This is the issue. For whatever reason (one I can't figure out and have be...
0
2016-08-03T06:44:19Z
38,736,326
<pre><code>for i in saveList: f.write(n+"\n") </code></pre> <p>You basically print the value of <code>n</code> over and over.</p> <p>Try this:</p> <pre><code>for i in saveList: f.write(i+"\n") </code></pre>
1
2016-08-03T06:49:06Z
[ "python", "file", "io" ]
Python: Issue with Writing over Lines?
38,736,230
<p>So, this is the code I'm using in Python to remove lines, hence the name "cleanse." I have a list of a few thousand words and their parts-of-speech:</p> <blockquote> <p>NN by</p> <p>PP at</p> <p>PP at</p> </blockquote> <p>... This is the issue. For whatever reason (one I can't figure out and have be...
0
2016-08-03T06:44:19Z
38,736,421
<p>If you just want to delete "duplicated lines", I've modified your reading code:</p> <pre><code>saveList = [] duplicates = [] with open("words.txt", "r") as ins: for line in ins: if line not in duplicates: duplicates.append(line) saveList.append(line) </code></pre> <p>Additionally take the corre...
0
2016-08-03T06:53:39Z
[ "python", "file", "io" ]
Python: Issue with Writing over Lines?
38,736,230
<p>So, this is the code I'm using in Python to remove lines, hence the name "cleanse." I have a list of a few thousand words and their parts-of-speech:</p> <blockquote> <p>NN by</p> <p>PP at</p> <p>PP at</p> </blockquote> <p>... This is the issue. For whatever reason (one I can't figure out and have be...
0
2016-08-03T06:44:19Z
38,738,095
<pre><code>def cleanseArchive(): f = open("words.txt", "r+") f.seek(0) given_line = f.readlines() saveList = set() for x,y in enumerate(given_line): t=(y) saveList.add(t) f.close() os.remove("words.txt") f = open("words.txt", "a") for i in saveList: f.write(i) </code></pre> <p>Finished product! I ended up digg...
0
2016-08-03T08:15:57Z
[ "python", "file", "io" ]
Python: Issue with Writing over Lines?
38,736,230
<p>So, this is the code I'm using in Python to remove lines, hence the name "cleanse." I have a list of a few thousand words and their parts-of-speech:</p> <blockquote> <p>NN by</p> <p>PP at</p> <p>PP at</p> </blockquote> <p>... This is the issue. For whatever reason (one I can't figure out and have be...
0
2016-08-03T06:44:19Z
38,738,823
<p>Let's clean up this code you gave us in your update:</p> <pre><code>def cleanseArchive(): f = open("words.txt", "r+") given_line = f.readlines() f.seek(0) saveList = set(given_line) f.close() os.remove("words.txt") f = open("words.txt", "a") f.write(saveList) </code></pre> <p>We hav...
0
2016-08-03T08:51:43Z
[ "python", "file", "io" ]
How do I make button press first stopping a playing audio file and then playing its own audio?
38,736,340
<p>My problem is, that the audio files under each button are quite lengthy and if I pressed the wrong button, I would have to wait it to play to end. How can I make every button press to 1) stop the possible playing audio file and then 2) play it's own file? I'm using mpg123 to play the audio files and file names are p...
0
2016-08-03T06:49:59Z
38,740,803
<p>You can use <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess</a> asynchronously so the function call returns immediately. I think it is possible to get a "handle" object to communicate with the external process that also allows you to "<a href="http://stackoverflow.com/questions/...
0
2016-08-03T10:19:42Z
[ "python", "button", "audio", "raspberry-pi", "gpio" ]
Can't figure out well why my function is returning True with anagrams
38,736,714
<p>This is my function (says if 2 compared words are anagrams or not):</p> <pre><code>def are_anagrams(word1, word2): word1list = list(word1) word2list = list(word2) anagramfalse = False anagramtrue = True if (word1 == word2): return anagramfalse if (word1list.sort()) == (word2list.sort...
0
2016-08-03T07:09:32Z
38,736,848
<p><code>sort</code> does not do what you think. Observe:</p> <pre><code>&gt;&gt;&gt; x = list('lopped') &gt;&gt;&gt; print(x.sort()) None </code></pre> <p>Since <code>None == None</code> is always True, the function always returns True.</p> <p>Further, the code can be simplified:</p> <pre><code>def are_anagrams(w...
1
2016-08-03T07:15:51Z
[ "python", "python-3.x" ]
Can't figure out well why my function is returning True with anagrams
38,736,714
<p>This is my function (says if 2 compared words are anagrams or not):</p> <pre><code>def are_anagrams(word1, word2): word1list = list(word1) word2list = list(word2) anagramfalse = False anagramtrue = True if (word1 == word2): return anagramfalse if (word1list.sort()) == (word2list.sort...
0
2016-08-03T07:09:32Z
38,736,901
<p>Here's the issue: <code>wordlist.sort()</code> will return <code>None</code> because it does the sorting <strong>in place</strong> comparing <code>None</code> to <code>None</code> will always evaluate to <code>True</code> and yield falsified results. You should be using <code>sorted()</code> which instead returns th...
1
2016-08-03T07:18:27Z
[ "python", "python-3.x" ]
How to check input against a huge list?
38,736,722
<p>This is my code:</p> <pre><code>while True: print(vehiclelist) reg = input('Enter registration number of vehicle: ') if reg in vehiclelist: break else: print("Invalid") </code></pre> <p>But it keeps showing its invalid, this is the output:</p> <blockquote> <p>[Ca...
0
2016-08-03T07:09:51Z
38,736,851
<p>Here the problem is <code>vehicle_list</code> is a list of Vehicle objects and you can not directly search for a registration number inside a list of vehicle object.</p> <p>A better design pattern is to use a dictionary in which <code>regNo</code> will appear as key and vehicle object will appear as value.</p> <p>...
1
2016-08-03T07:16:07Z
[ "python" ]
How to check input against a huge list?
38,736,722
<p>This is my code:</p> <pre><code>while True: print(vehiclelist) reg = input('Enter registration number of vehicle: ') if reg in vehiclelist: break else: print("Invalid") </code></pre> <p>But it keeps showing its invalid, this is the output:</p> <blockquote> <p>[Ca...
0
2016-08-03T07:09:51Z
38,766,816
<p>You need to iterate the individual car objects and compare the <code>regNo</code></p> <pre><code>def getInput(): while True: print(vehiclelist) reg = input('Enter registration number of vehicle: ') for car in vehiclelist: if reg == car.regNo: return ...
0
2016-08-04T12:03:26Z
[ "python" ]
create a table using file contents python
38,736,806
<p>if the file for example contains:</p> <ul> <li>A: GHJIG</li> <li>B: AHYFASF</li> <li>C: IYDDFG</li> </ul> <p><code>f = open(example.txt)</code></p> <p>I want to store the file contents in a table and then the program should ask the user to enter a character and print the line without the alphabet.</p> <ul> <li>i...
0
2016-08-03T07:14:04Z
38,737,131
<p>Try this:</p> <pre><code>with open('test.txt','r') as file: content = file.readlines() my_dict = {} for line in content: split = line.split(':') my_dict[split[0]] = split[1] input = raw_input("Choose a letter") if input in my_dict: print my_dict[input] </code></pre> <p>It would be better to us...
0
2016-08-03T07:30:42Z
[ "python" ]
create a table using file contents python
38,736,806
<p>if the file for example contains:</p> <ul> <li>A: GHJIG</li> <li>B: AHYFASF</li> <li>C: IYDDFG</li> </ul> <p><code>f = open(example.txt)</code></p> <p>I want to store the file contents in a table and then the program should ask the user to enter a character and print the line without the alphabet.</p> <ul> <li>i...
0
2016-08-03T07:14:04Z
38,784,384
<p>Try the solution below, you can provide a useful message if the user enters any alphabet which is not present in your txt file.</p> <pre><code>with open('/home/pydev/Desktop/t1.txt', 'r') as file_obj: content = file_obj.readlines() sample_dict = {} for value in content: sample_dict[value.split(':')[0]] = v...
0
2016-08-05T08:13:53Z
[ "python" ]
Python to get specific last 2 or 3 characters
38,736,812
<p>I'm looking for a Python script that will get the last 2 or 3 specific characters. To be more specific, I'm looking to cut the IP name to the last 2 or 3 digits.</p> <pre><code>import socket ip = socket.gethostbyname(socket.gethostname())[-3:0] </code></pre> <p>I was thinking of just slicing the ip address and get...
1
2016-08-03T07:14:09Z
38,736,865
<p>Another option is to <code>lstrip</code> a possibly leading <code>'.'</code>:</p> <pre><code>import socket ip = socket.gethostbyname(socket.gethostname())[-3:].lstrip('.') </code></pre> <p>An example:</p> <pre><code>ip1 = '192.168.1.10' ip2 = '192.168.1.100' print(ip1[-3:].lstrip('.')) &gt;&gt; 10 print(ip2[-3:]....
1
2016-08-03T07:16:42Z
[ "python" ]
Python to get specific last 2 or 3 characters
38,736,812
<p>I'm looking for a Python script that will get the last 2 or 3 specific characters. To be more specific, I'm looking to cut the IP name to the last 2 or 3 digits.</p> <pre><code>import socket ip = socket.gethostbyname(socket.gethostname())[-3:0] </code></pre> <p>I was thinking of just slicing the ip address and get...
1
2016-08-03T07:14:09Z
38,736,869
<pre><code>import socket ip = socket.gethostbyname(socket.gethostname()).split('.')[-1] </code></pre>
6
2016-08-03T07:16:49Z
[ "python" ]
ElasticSearch and special characters
38,736,828
<p>I can not figure out how to look up words with special characters.</p> <p>For example, I have two documents:</p> <p>1) We are looking for C++ and C# developers <br/> 2) We are looking for C developers</p> <p>I want only to find a document which contains <code>C++</code>.</p> <p>Code for creating an index, docume...
0
2016-08-03T07:14:45Z
39,289,658
<p>Thanks <a href="http://ru.stackoverflow.com/a/551949/181420">Andrew</a>, I solved the problem. The problem was that the standard analyzer was used for indexing, and not <em>my_analyzer</em>. Thus, I forgot to use the mapping. The correct version:</p> <pre><code>data = { "settings": { "analysis": { ...
0
2016-09-02T10:01:13Z
[ "python", "elasticsearch" ]
How to check the python socket recvfrom() data
38,736,833
<p>I am working on socket programming in python. Using ESP python i have created a socket to server and sending a request (in API packet format, according to server code it will respond). In receiving socket, i need to check the data(if data is received, it need continue to next operation. If not, i need to send reques...
0
2016-08-03T07:15:03Z
38,738,533
<p>If you don't mind a blocking call, I usually use settimeout to wait for a message. settimeout will raise an exception if it doesn't receive a message in time. </p> <p>So basically you could do something like this:</p> <pre><code>s.settimeout(1) try: recvpack, payload = s.recvfrom(1024) except error: recvpa...
0
2016-08-03T08:38:05Z
[ "python", "sockets", "recv", "recvfrom" ]
python classes inheriting from each other
38,736,838
<p>I am having 2 Python files in same directory. one.py and two.py containing classes First and Second respectively. <strong>I want import classes and inherit each other and use methods defined in each other</strong>. </p> <p>one.py</p> <pre><code>from two import Second class First(Second): def first(self): ...
0
2016-08-03T07:15:10Z
38,736,932
<p>The actual problem you're encountering is that you're trying to do a circular import, which has nothing to do with your circular inheritance. (There's plenty of material on SO on how to avoid that.)</p> <p>However, note that circular inheritance is also not possible, as a class is only available for subclassing onc...
1
2016-08-03T07:20:10Z
[ "python", "class", "inheritance" ]
Equivalent code of __getitem__ in __iter__
38,736,872
<p>I am trying to understand more about <code>__iter__</code> in Python 3. For some reason <code>__getitem__</code> is better understood by me than <code>__iter__</code>. I think I get somehow don't get the corresponding <strong>next</strong> implemention followed with <code>__iter__</code>.</p> <p>I have this followi...
0
2016-08-03T07:17:02Z
38,737,160
<p>In general, a really good approach is to make <code>__iter__</code> a generator by <code>yield</code>ing values. This might be <em>less</em> intuitive but it is straight-forward; you just yield back the results you want and <code>__next__</code> is then provided automatically for you:</p> <pre><code>class Item: ...
4
2016-08-03T07:32:16Z
[ "python", "python-3.x", "iterator" ]
Equivalent code of __getitem__ in __iter__
38,736,872
<p>I am trying to understand more about <code>__iter__</code> in Python 3. For some reason <code>__getitem__</code> is better understood by me than <code>__iter__</code>. I think I get somehow don't get the corresponding <strong>next</strong> implemention followed with <code>__iter__</code>.</p> <p>I have this followi...
0
2016-08-03T07:17:02Z
38,737,183
<p>Iter returns a iterator, mainly a generator as @machineyearning told at the comments, with next you can iterate over the object, see the example:</p> <pre><code>class Item: def __init__(self): self.elems = range(10) self.current = 0 def __iter__(self): return (x for x in self.elem...
0
2016-08-03T07:32:56Z
[ "python", "python-3.x", "iterator" ]
Python whois.whois returns a property object
38,736,894
<p>I'm running whois.whois on Python 3.5 as follows:</p> <pre><code>def simpleWhois(url): try: result = whois.whois(url) return result except Exception as error: print(type(error), error, url) return pd.Series.empty </code></pre> <p>On most URLs e.g. 'google.com' I get a Pandas...
0
2016-08-03T07:18:11Z
38,760,068
<p>I still don't understand why I got a property object, but for this particular problem I came up with the following solution:</p> <pre><code> def simpleWhois(url): try: result = whois.whois(url) return result except: error = sys.exc_info()[0] print("Error: %s, %s, for %s " % (type(error), error, u...
0
2016-08-04T06:35:43Z
[ "python", "pandas", "whois" ]
raise *error doesn't work in Python 2.7; how can I raise a previously captured exception?
38,736,940
<p>My code works, but I am thinking there is something wrong with my understanding, or possibly (gasp) an error in Python's <code>raise</code> behavior.</p> <p>I am looping over a set of arguments. I capture the <em>first</em> error and want to raise it after I have finished looping, with the original traceback etc a...
3
2016-08-03T07:20:38Z
38,737,103
<p>Maybe, you could just do this:</p> <pre><code>for arg in arguments: try: process(arg) except ValueError: raise </code></pre> <p>Also, if you're going to do this multiple times, you could just wrap it in a function:</p> <pre><code>def raise_error(err): raise err[0], err[1]. err[2] erro...
0
2016-08-03T07:29:29Z
[ "python", "python-2.7", "syntax", "exception-handling" ]
TypeError: Can't convert 'coroutine' object to str implicitly
38,736,986
<p>trying to pull a JSON object from a <code>.json</code> with python 3.5.2 using async and I'm returned with this error <code>TypeError: Can't convert 'coroutine' object to str implicitly</code> and <code>sys:1: RuntimeWarning: coroutine 'Configuration.parseField' was never awaited</code></p> <p><strong>I'm using dis...
0
2016-08-03T07:23:13Z
38,738,371
<p>try</p> <pre><code>class Configuration: def __init__(self, filename): with open(filename, 'r') as f: self.data = json.load(f) def __getattr__(self, name): return self.data[name] </code></pre> <p>This way you can use</p> <pre><code>c = Configuration('config.json') bot_token = c...
0
2016-08-03T08:30:21Z
[ "python", "asynchronous" ]
PySide application crashes when setting a new widget to QScrollArea
38,737,106
<p>This is a simplification of an application I wrote.</p> <p>The application's main window has a button and a checkbox. The checkbox resides inside a QScrollArea (via a widget). The checkbox has a number stating how many times that checkbox was created. Clicking on the button will open a dialog with a refresh button....
1
2016-08-03T07:29:41Z
38,750,447
<p>It looks like Python is trying to delete an object (or one of its child objects) which is no longer there - but quite what causes that to happen is not completely clear to me. The problematic object is the widget set on the scroll-area. If you excplicitly keep a reference to it:</p> <pre><code> def set_scroll_wi...
1
2016-08-03T17:46:55Z
[ "python", "qt", "pyside" ]
Loss of precision while converting floats to strings in pandas
38,737,134
<p>I am converting in Python some floats (some shorter some longer) to strings and getting unexpected (?) results:</p> <p><strong>Case 1</strong></p> <pre><code>pd.options.display.float_format = '{:.2f}'.format pd.DataFrame({'x': [12345.67]}) x 0 12345.67 </code></pre> <p><strong>Case 2</strong></p> <...
2
2016-08-03T07:30:47Z
38,737,328
<p>I'm afraid this "issue" happens in the Python (instead of pandas) side. When you have some instant values like <code>1234589890878708980.67</code> it's recognized as <code>float</code> and loses precision instantly, e.g.:</p> <pre><code>&gt;&gt;&gt; 1234589890878708980.67 1.234589890878709e+18 &gt;&gt;&gt; 12345898...
3
2016-08-03T07:39:40Z
[ "python", "string", "pandas", "floating-point" ]