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 |
|---|---|---|---|---|---|---|---|---|---|
Any alternative or improvement of my recursive/iterative approach? | 37,557,700 | <p>I'm trying to write a parent searching code using python 3.</p>
<p>Parent is a 0-based-array that contain a parent of that element.
For example, parent=[0,0] means that </p>
<ol>
<li><p>Parent of the first element is itself.</p></li>
<li><p>Parent of the second element is the first element, therefore second eleme... | 0 | 2016-06-01T00:36:47Z | 37,557,783 | <p>You didn't give us any data to test it on, so I'm assuming @Cel Skeggs identified the key difference in her comment. Fleshing out her suggestion (but untested because - again - you supplied no data):</p>
<pre><code>def getParent4(table):
chain = []
while table != parent[table]:
chain.append(table)
... | 2 | 2016-06-01T00:48:00Z | [
"python",
"algorithm",
"python-3.x",
"recursion",
"genetic-algorithm"
] |
How do I install Pandas on windows(32bit) | 37,557,788 | <p>I have tried to install pandas as like procudure...</p>
<pre><code>Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
>pip freeze
numpy==1.11.1rc1
pytz==2016.4
>pip install "pandas-0.18.1-cp35-cp35m-win32.whl"
pandas-0.18.1-cp35-cp35m-win32.whl is not a supported ... | 0 | 2016-06-01T00:48:23Z | 37,558,721 | <p>It's highly recommended to use the <a href="https://docs.continuum.io/anaconda/install#id2" rel="nofollow">anaconda</a> distribution on windows. See also <a href="http://pandas.pydata.org/#best-way-to-install" rel="nofollow">pandas docs</a> on the matter.</p>
<p>If you install via <code>pip</code> you will need com... | 0 | 2016-06-01T03:03:36Z | [
"python",
"pandas",
"install",
"pip"
] |
How do I install Pandas on windows(32bit) | 37,557,788 | <p>I have tried to install pandas as like procudure...</p>
<pre><code>Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
>pip freeze
numpy==1.11.1rc1
pytz==2016.4
>pip install "pandas-0.18.1-cp35-cp35m-win32.whl"
pandas-0.18.1-cp35-cp35m-win32.whl is not a supported ... | 0 | 2016-06-01T00:48:23Z | 37,559,169 | <p>It is quite likely that the version of pip you are using is outdated. Upgrade pip using <code>python -m pip install --upgrade pip</code> and you should be able to install pandas </p>
| 0 | 2016-06-01T03:57:13Z | [
"python",
"pandas",
"install",
"pip"
] |
min() arg empty sequence | 37,557,802 | <p>I am learning object oriented concepts in python. Below, I have created a class and a method in it. I am trying to find the minimum of a list by directly calling the <code>min()</code> function and also by calling the class method
<code>findMin()</code>. </p>
<p>The below code gives me an error:</p>
<blockquote>
... | 0 | 2016-06-01T00:50:38Z | 37,557,845 | <p>You are confusing <code>nums</code> with <code>self.nums</code>.</p>
<p>When you write:</p>
<pre><code> nums=list()
</code></pre>
<p>You are setting a variable on the class.</p>
<p>When you write:</p>
<pre><code> def findMin(self, nums):
</code></pre>
<p>You are receiving the parameter in a local variabl... | 1 | 2016-06-01T00:56:36Z | [
"python",
"python-2.7"
] |
min() arg empty sequence | 37,557,802 | <p>I am learning object oriented concepts in python. Below, I have created a class and a method in it. I am trying to find the minimum of a list by directly calling the <code>min()</code> function and also by calling the class method
<code>findMin()</code>. </p>
<p>The below code gives me an error:</p>
<blockquote>
... | 0 | 2016-06-01T00:50:38Z | 37,557,849 | <p>You do not need to call <code>sort</code>. You make a mistake there is no <code>nums</code> property in your class. Store a list in your instance of a class, like here:</p>
<pre><code>class Solution(object):
def __init__(self, nums):
self.nums = nums
def findMin(self):
return min(self.nums)... | 0 | 2016-06-01T00:57:07Z | [
"python",
"python-2.7"
] |
Execute python script -- Ajax and Flask | 37,557,814 | <p>I apologize if this is unclear or anything like that. I'm very very new to web programming of any kind, so please be patient. When a link is clicked, I want to run a python script and then display the results. What is currently happening is it's just returning the HTML page. I have an <em>idea</em> of why but no clu... | -1 | 2016-06-01T00:52:37Z | 37,558,439 | <p>There are a few things here that need to be fixed to get things working (or at least how I understand you want them to work).</p>
<p>If you're going to be using Flask, you don't need the route to point to a Python script. You can route to something like <code>/cputemp</code> and then run a function that returns the... | 1 | 2016-06-01T02:26:17Z | [
"javascript",
"python",
"ajax",
"flask"
] |
How do I universally ignore all unicode errors in python? | 37,557,847 | <p>Running python2.7 here. I am writing a quick and dirty little script to do some web scraping, and I just want the unicode handler to just ignore all unicode errors.</p>
<p>That is, I am totally fine if it just drops whatever characters it can't convert to ascii anywhere in the program. This is just a throwaway sc... | 0 | 2016-06-01T00:56:55Z | 37,557,962 | <blockquote>
<p>I am totally fine if it just drops whatever characters it can't convert to ascii anywhere in the program</p>
</blockquote>
<p>Then you want to explicitly <a href="https://docs.python.org/2/howto/unicode.html#the-unicode-type" rel="nofollow">create your Unicode objects</a> from the <code>ascii</code> ... | 1 | 2016-06-01T01:15:22Z | [
"python",
"python-2.7",
"unicode"
] |
How do you run , in Windows , this python script meant for Linux? | 37,557,880 | <p>I am using Python 3.5 on a Windows 7 computer.</p>
<p>I am trying to run a python script designed to run in Linux found in this book
Learning Python Network Programming by Dr. M. O. Faruque Sarker and Sam Washington Jun 17, 2015
Chapter 6. IP and DNS
GeoIP look-ups</p>
<p>..........The code is saved in my C drive ... | -4 | 2016-06-01T01:01:10Z | 37,557,902 | <p>In a Windows command prompt, run the following commands:</p>
<pre><code>c:
cd \Python35
python geoiplookup.py --hostname=amazon.co.uk
</code></pre>
| 0 | 2016-06-01T01:05:12Z | [
"python",
"linux",
"python-3.x"
] |
How do you run , in Windows , this python script meant for Linux? | 37,557,880 | <p>I am using Python 3.5 on a Windows 7 computer.</p>
<p>I am trying to run a python script designed to run in Linux found in this book
Learning Python Network Programming by Dr. M. O. Faruque Sarker and Sam Washington Jun 17, 2015
Chapter 6. IP and DNS
GeoIP look-ups</p>
<p>..........The code is saved in my C drive ... | -4 | 2016-06-01T01:01:10Z | 37,557,910 | <p>You aren't running the Python script, you're in the Python interpreter and attempting to run each line of code.</p>
<p>Look at your Linux output:</p>
<pre><code>$ python 6_3_geoip_lookup.py --hostname=amazon.co.uk
IP address: 178.236.6.251
Country: IE
Continent: EU
Time zone: Europe/Dublin
</code></pre>
<p>Tha... | 2 | 2016-06-01T01:06:15Z | [
"python",
"linux",
"python-3.x"
] |
How do you run , in Windows , this python script meant for Linux? | 37,557,880 | <p>I am using Python 3.5 on a Windows 7 computer.</p>
<p>I am trying to run a python script designed to run in Linux found in this book
Learning Python Network Programming by Dr. M. O. Faruque Sarker and Sam Washington Jun 17, 2015
Chapter 6. IP and DNS
GeoIP look-ups</p>
<p>..........The code is saved in my C drive ... | -4 | 2016-06-01T01:01:10Z | 37,559,088 | <p>EDIT: It looks like on Python 3.5 the geoip package is having issues (I found someone reporting an issue <a href="https://github.com/mirumee/saleor/issues/458" rel="nofollow">here</a> that has the same error message as you on a different method). the commenters seem to be mentioning that the package looks abandoned,... | 1 | 2016-06-01T03:49:10Z | [
"python",
"linux",
"python-3.x"
] |
How do you run , in Windows , this python script meant for Linux? | 37,557,880 | <p>I am using Python 3.5 on a Windows 7 computer.</p>
<p>I am trying to run a python script designed to run in Linux found in this book
Learning Python Network Programming by Dr. M. O. Faruque Sarker and Sam Washington Jun 17, 2015
Chapter 6. IP and DNS
GeoIP look-ups</p>
<p>..........The code is saved in my C drive ... | -4 | 2016-06-01T01:01:10Z | 37,582,873 | <p>Solved:</p>
<p>Follow Kush131's pprint code to solve my challenge. </p>
<p>If you are using Python 3.5 in Windows , you need to do these extra steps to get the output Kush131 could get in Mac.</p>
<p>After </p>
<pre><code>pip install win-unicode-console
</code></pre>
<p>You will still have problems getting R... | 0 | 2016-06-02T04:49:01Z | [
"python",
"linux",
"python-3.x"
] |
How do you run , in Windows , this python script meant for Linux? | 37,557,880 | <p>I am using Python 3.5 on a Windows 7 computer.</p>
<p>I am trying to run a python script designed to run in Linux found in this book
Learning Python Network Programming by Dr. M. O. Faruque Sarker and Sam Washington Jun 17, 2015
Chapter 6. IP and DNS
GeoIP look-ups</p>
<p>..........The code is saved in my C drive ... | -4 | 2016-06-01T01:01:10Z | 37,590,662 | <p>Another solution is to add PYTHONIOENCODING (a Python-specific environment variable) to your Windows Path environment variable . The code will run but the Russian and Asian characters will still be replaced with ??? like the output in Solution 1</p>
<p>..........i.e.
Add this Python-specific environment variable
PY... | 0 | 2016-06-02T11:34:01Z | [
"python",
"linux",
"python-3.x"
] |
Using sklearn's 'predict' function | 37,558,158 | <p>If I trained up a model using sklearn using a lot of dummy variables for categorical values. What is best practice for feeding a single row of features into this model to get the prediction result? Obviously the inputs for the dataset I am trying to score will have have dramatically less columns then the dataset I u... | 0 | 2016-06-01T01:42:32Z | 37,568,085 | <p>It's an error to extend features depending on table state, cause you can't repeat it with another data. If you want to create features this way, you should use a constructor that will remember structure of features. Since you gave no example of data, here is the main idea how you can make a constructor:</p>
<pre><c... | 0 | 2016-06-01T12:01:34Z | [
"python",
"scikit-learn",
"svm",
"random-forest",
"predict"
] |
Binomial classification using a list comprehension python | 37,558,213 | <p>I'm working with <code>pandas</code>, and I want to add a new <code>Serie</code> with a binomial classification if a word is within a sentence.</p>
<p>For example:</p>
<pre><code>year = [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012]
state = ['hello', 'my friend', 'hello and', 'coding', 'python', 'hello', 'who is... | 0 | 2016-06-01T01:50:41Z | 37,558,266 | <p>How about using <code>pandas</code> <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#string-handling" rel="nofollow"><code>Series.str</code></a>:</p>
<pre><code>>>> pd['hello'] = pd['state'].str.contains('hello')
>>> pd
state year hello
0 hello 2010 True
1 ... | 3 | 2016-06-01T01:59:23Z | [
"python",
"python-2.7",
"python-3.x",
"pandas",
"list-comprehension"
] |
Binomial classification using a list comprehension python | 37,558,213 | <p>I'm working with <code>pandas</code>, and I want to add a new <code>Serie</code> with a binomial classification if a word is within a sentence.</p>
<p>For example:</p>
<pre><code>year = [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012]
state = ['hello', 'my friend', 'hello and', 'coding', 'python', 'hello', 'who is... | 0 | 2016-06-01T01:50:41Z | 37,558,268 | <p>A possible list comprehension equivalent is:</p>
<pre><code>data['hello'] = [(1 if 'hello' in item else 0) for item in data['state']]
</code></pre>
<p>If True/False is acceptable:</p>
<pre><code>data['hello'] = ['hello' in item for item in data['state']]
</code></pre>
| 2 | 2016-06-01T01:59:29Z | [
"python",
"python-2.7",
"python-3.x",
"pandas",
"list-comprehension"
] |
Pick x (f.e. first) characters from a List entry then pick random entries from the new list | 37,558,242 | <p>I have a list of strings and i would like to pick a specific number of characters from each string (list entry). I found a bit about slicing strings but I have no idea how to make it work with lists. Also i have no idea if this is the method to go with at all.
Example:
I have a list </p>
<pre><code>['abcd12', 'efgh... | 0 | 2016-06-01T01:55:17Z | 37,558,276 | <p>You can combine <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow"><em>list comprehension</em></a> with string slicing and you get following:</p>
<pre><code>>>> l = ['abcd12', 'efgh34', 'ijkl56', 'mnop78']
>>> [x[:2] for x in l]
['ab', 'ef', 'ij', '... | 2 | 2016-06-01T02:00:28Z | [
"python",
"list"
] |
Python Sklearn - Deprecation Warning | 37,558,271 | <p>I am a beginner in Python and Sklearn. Wondering whether I am missing something here. I am getting the following warning message: </p>
<blockquote>
<p>DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17
and willraise ValueError in 0.19.</p>
</blockquote>
<p>Here is the code:</p>
<pre><code>imp... | 1 | 2016-06-01T01:59:49Z | 37,559,359 | <p>If you read the warning message and do a bit of debugging you will realize that the warning arises because your inputs to the model are unidimensional. You can see this link: <a href="http://stackoverflow.com/questions/36537764/sklearn-train-model-with-single-sample-raises-a-deprecationwarning">Sklearn train model w... | 0 | 2016-06-01T04:20:01Z | [
"python",
"scikit-learn"
] |
Python Sklearn - Deprecation Warning | 37,558,271 | <p>I am a beginner in Python and Sklearn. Wondering whether I am missing something here. I am getting the following warning message: </p>
<blockquote>
<p>DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17
and willraise ValueError in 0.19.</p>
</blockquote>
<p>Here is the code:</p>
<pre><code>imp... | 1 | 2016-06-01T01:59:49Z | 37,560,083 | <p>I guess your question was answered <a href="http://stackoverflow.com/questions/35082140/preprocessing-in-scikit-learn-single-sample-depreciation-warning">here</a>, this is probably a <strong>duplicate</strong>.</p>
| 1 | 2016-06-01T05:25:32Z | [
"python",
"scikit-learn"
] |
Initializing parent class instance attributes | 37,558,324 | <p>I understand how to initialize a parent class to get their instance attributes in a child class, but not exactly what's going on behind the scenes to accomplish this. (Note: not using super intentionally here, just to make illustration clear)</p>
<p>Below we extend <code>class A</code> by adding an extra attribute ... | 0 | 2016-06-01T02:07:59Z | 37,558,555 | <p>The answer is simple: <code>self</code>.</p>
<p>As a very rough overview, when instantiating a class, <em>an object</em> is created. This is more or less literally just an empty container without affiliation to anything.* This "empty container" is then passed to the <code>__init__</code> method of the class that is... | 2 | 2016-06-01T02:42:56Z | [
"python",
"inheritance",
"super"
] |
Matplotlib: set axis tight only to x or y axis | 37,558,329 | <p>I have a plot look like this:</p>
<p><a href="http://i.stack.imgur.com/5ePuJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/5ePuJ.png" alt="enter image description here"></a></p>
<p>Obviously, the left and right side is a waste of space, so I set</p>
<pre><code>plt.axis('tight')
</code></pre>
<p>But this... | 1 | 2016-06-01T02:08:41Z | 37,561,377 | <p><a href="http://i.stack.imgur.com/0ZElf.png"><img src="http://i.stack.imgur.com/0ZElf.png" alt="enter image description here"></a></p>
<p>After <code>plt.autoscale(enable=True, axis='x', tight=True)</code>:</p>
<p><a href="http://i.stack.imgur.com/vkFQC.png"><img src="http://i.stack.imgur.com/vkFQC.png" alt="enter... | 5 | 2016-06-01T06:50:20Z | [
"python",
"matplotlib"
] |
How to execute many SELECT statements at once using python sqlite | 37,558,417 | <p>I have some business logic that iterates many many times and needs to perform a simple query every time. Rather than make a call to the db every time I would like to store the SELECT statements as an array of strings or something similar and then execute all of the statements at once after the loop. Is this possible... | 0 | 2016-06-01T02:22:15Z | 37,558,452 | <p>I suspect you'd be better off if you work out a "larger" query and then decompose the result set <em>after</em> retrieving the information.</p>
<p>In other words, rather than <em>three</em> calls to the database (one each for Alice, Betty and Claire), use something like:</p>
<pre><code>select stuff from a_table
wh... | 1 | 2016-06-01T02:27:39Z | [
"python",
"sqlite"
] |
How to execute many SELECT statements at once using python sqlite | 37,558,417 | <p>I have some business logic that iterates many many times and needs to perform a simple query every time. Rather than make a call to the db every time I would like to store the SELECT statements as an array of strings or something similar and then execute all of the statements at once after the loop. Is this possible... | 0 | 2016-06-01T02:22:15Z | 37,561,327 | <p>The <a href="https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.execute" rel="nofollow">documentation</a> says:</p>
<blockquote>
<p><code>execute()</code> will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use <a href="https://docs.... | 1 | 2016-06-01T06:47:27Z | [
"python",
"sqlite"
] |
Converting document-term count in Pandas series into a python list | 37,558,429 | <p>I currently have a Pandas Series object where the index name is a term in the document, and the value is how many times the term occurred in the document. An example is shown below:</p>
<pre><code>>>> import pandas as pd
>>> s = pd.Series([1, 4, 1, 2], index=["green", "blue", "red", "yellow"])
>... | 1 | 2016-06-01T02:24:29Z | 37,558,479 | <p>Do it using NumPy, not an explicit loop:</p>
<pre><code>>>> np.repeat(s.index.values, s.values)
array(['green', 'blue', 'blue', 'blue', 'blue', 'red', 'yellow', 'yellow'], dtype=object)
</code></pre>
| 3 | 2016-06-01T02:31:41Z | [
"python",
"pandas",
"nlp"
] |
Do I need to close file again after with open file as fp closed file in python | 37,558,437 | <pre><code>with open(filename, 'r') as fp:
do something
fp.close()
</code></pre>
<p>I know with open as will call <strong>exit</strong> which will call close method to close the opened file. But I saw a lot of people still tried to close the file again, python does not bother to close a closed file? which is the b... | 0 | 2016-06-01T02:26:05Z | 37,558,454 | <p>You absolutely should not call <code>fp.close()</code> after the end of the <code>with</code> block, which closes it automatically. That code you show is simply broken. It should be:</p>
<pre><code>with open(filename, 'r') as fp:
do something
</code></pre>
| 3 | 2016-06-01T02:28:13Z | [
"python"
] |
Converting 2D Numpy array of grayscale values to a PIL image | 37,558,523 | <p>Say I have a 2D Numpy array of values on the range 0 to 1, which represents a grayscale image. How do I then convert this into a PIL Image object? All attempts so far have yielded extremely strange scattered pixels or black images.</p>
<pre><code>for x in range(image.shape[0]):
for y in range(image.shape[1]):... | 1 | 2016-06-01T02:38:33Z | 37,559,320 | <p>Do you need a <code>pillow</code> image? This works with matplotlib quite easily:</p>
<pre><code>import numpy
from matplotlib import pyplot as plt
x = numpy.random.rand(10, 10)*255
plt.imshow(x, cmap='gray', interpolation='nearest', vmin=0, vmax=255)
plt.savefig('text.png')
plt.show()
</code></pre>
<p>From: <a hre... | 1 | 2016-06-01T04:15:05Z | [
"python",
"numpy",
"python-imaging-library"
] |
Converting 2D Numpy array of grayscale values to a PIL image | 37,558,523 | <p>Say I have a 2D Numpy array of values on the range 0 to 1, which represents a grayscale image. How do I then convert this into a PIL Image object? All attempts so far have yielded extremely strange scattered pixels or black images.</p>
<pre><code>for x in range(image.shape[0]):
for y in range(image.shape[1]):... | 1 | 2016-06-01T02:38:33Z | 37,559,440 | <p>If I understood you question, you want to get a grayscale image using PIL. </p>
<p>If this is the case, you do not need to multiply each pixels by 255.</p>
<p>The following worked for me</p>
<pre><code>import numpy as np
from PIL import Image
# Creates a random image 100*100 pixels
mat = np.random.random((100,10... | 1 | 2016-06-01T04:29:02Z | [
"python",
"numpy",
"python-imaging-library"
] |
Django - Upload Image with the current user (Loggedin) | 37,558,554 | <p>How do I save an Image in a specific folder, depending of whom is Loggedin?
My program creates a folder for every user that registers
after they login, they are able to upload some images.</p>
<p>The problem is when I try to save my image, I need to specify the path where is going to be Uploaded (with the userID)</... | 0 | 2016-06-01T02:42:54Z | 37,559,238 | <p>Lets say you have your model like as follows(Demonstration only):</p>
<pre><code>class StudentPhotos(models.Model):
image = models.ImageField(upload_to=name)
user = models.ForeignKey(User)
</code></pre>
<p>Here <strong>name</strong> (upload_to=name) can be function as follows:</p>
<pre><code>def name(ins... | 0 | 2016-06-01T04:05:24Z | [
"python",
"django",
"django-models",
"django-views"
] |
Python eval() SyntaxError when reading string with punctuation | 37,558,559 | <p>I am trying to read a file with lines that look like this:</p>
<pre><code>1A11:A,GSEKMSTAISVLLAQAVFLLLTSQR,0.724,0,0,1,0,0,1.000,225.000,0.004,0.915
</code></pre>
<p>With this code:</p>
<pre><code>for line in datafile:
line = line.split(',')
for element in line:
line[count] = eval(element)
</code>... | -1 | 2016-06-01T02:43:12Z | 37,558,589 | <p><code>eval(string)</code> evaluates an expression. So the string that you pass in has to evaluate to a value. When Python tries to evaluate <code>1A11:A</code> it hits an error as expected. To both Python and human readers that string looks like junk. An acceptable input string would be something like <code>x+1</cod... | 0 | 2016-06-01T02:48:42Z | [
"python",
"python-3.x",
"eval"
] |
Python eval() SyntaxError when reading string with punctuation | 37,558,559 | <p>I am trying to read a file with lines that look like this:</p>
<pre><code>1A11:A,GSEKMSTAISVLLAQAVFLLLTSQR,0.724,0,0,1,0,0,1.000,225.000,0.004,0.915
</code></pre>
<p>With this code:</p>
<pre><code>for line in datafile:
line = line.split(',')
for element in line:
line[count] = eval(element)
</code>... | -1 | 2016-06-01T02:43:12Z | 37,558,674 | <p><code>eval()</code> returns the evaluated result of whatever string is passed to it.</p>
<p>In your case "1A11:A" can't be evaluated to a values. Even if you remove that element what about the second element is it a variable? else that also would return an error.</p>
| 0 | 2016-06-01T02:58:38Z | [
"python",
"python-3.x",
"eval"
] |
Python eval() SyntaxError when reading string with punctuation | 37,558,559 | <p>I am trying to read a file with lines that look like this:</p>
<pre><code>1A11:A,GSEKMSTAISVLLAQAVFLLLTSQR,0.724,0,0,1,0,0,1.000,225.000,0.004,0.915
</code></pre>
<p>With this code:</p>
<pre><code>for line in datafile:
line = line.split(',')
for element in line:
line[count] = eval(element)
</code>... | -1 | 2016-06-01T02:43:12Z | 37,559,276 | <p>As I mentioned in my comment above, using <code>eval()</code> is a pretty awful idea, and lots of people much smarter and more experienced than me agree, so I go with it, and you should too.</p>
<p>First, we are assuming that each line has the same structure and the same number of elements with the same transformat... | 1 | 2016-06-01T04:10:03Z | [
"python",
"python-3.x",
"eval"
] |
Pandas: sum all rows | 37,558,572 | <p>I have a <code>DataFrame</code> that looks like this:</p>
<pre><code>score num_participants
0 20
1 15
2 5
3 10
4 12
5 15
</code></pre>
<p>I need to find the number of participants with <code>score</code> that is greater than or equal to the <code>score</code> in the current row:</p>
<pre>... | 2 | 2016-06-01T02:45:11Z | 37,558,643 | <p>This is a reverse <code>cumsum</code>. Reverse the list, <code>cumsum</code>, then reverse back.</p>
<pre><code>df.iloc[::-1].cumsum().iloc[::-1]
score num_participants
0 15 77
1 15 57
2 14 42
3 12 37
4 9 27
5 ... | 7 | 2016-06-01T02:54:39Z | [
"python",
"pandas",
"dataframe"
] |
Pandas: sum all rows | 37,558,572 | <p>I have a <code>DataFrame</code> that looks like this:</p>
<pre><code>score num_participants
0 20
1 15
2 5
3 10
4 12
5 15
</code></pre>
<p>I need to find the number of participants with <code>score</code> that is greater than or equal to the <code>score</code> in the current row:</p>
<pre>... | 2 | 2016-06-01T02:45:11Z | 37,558,661 | <p>Unless <code>score</code> is already sorted, how about</p>
<pre><code>df['num_participants_with_score_greater_or_equal'] = df.sort_values('score', ascending=False).num_participants.cumsum()
</code></pre>
<p>to make <code>score</code> is in the right order. You can restore the original order by <code>.sort_index()<... | 1 | 2016-06-01T02:57:14Z | [
"python",
"pandas",
"dataframe"
] |
PostgreSQL - Unable to create table - data type point has no default operator class for access method "btree" | 37,558,584 | <p>so I'm working on a project to learn SQL, Python, and some server-side stuff and I'm pretty stumped at this point, after much searching. I want to create two identical tables, and I have the following code:</p>
<pre><code>import psycopg2 as db
import json
with open('config.json', 'r') as f:
config = json.load(f)
... | 0 | 2016-06-01T02:48:00Z | 37,559,003 | <p>PostgreSQL version doesn't support creating a normal or unique b-tree index on the <code>point</code> data type (true up to and including 9.5 at least). So you can't use <code>point</code> as part of a <code>PRIMARY KEY</code>.</p>
<pre><code>test=> CREATE TABLE test_table( xy point primary key );
ERROR: data t... | 1 | 2016-06-01T03:37:58Z | [
"python",
"sql",
"postgresql",
"psycopg2"
] |
Read string from ArrayBuffer received via websocket | 37,558,695 | <p>I am using python <a href="https://github.com/dpallot/simple-websocket-server" rel="nofollow">SimpleWebSocketServer</a>, with a modified <code>SimpleExample.py</code> and Chrome.</p>
<p>Everything works fine when I send strings from browser to python, but when I send string from python to browser, I don't have the ... | 1 | 2016-06-01T03:00:28Z | 37,559,299 | <p>Try this - go back to receiving the message as an arraybuffer, and apply something like this to make a string:</p>
<pre><code>function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint16Array(buf));
}
function onMessage(event) {
console.log(ab2str(event.data));
}
</code></pre>
<p>this assumes yo... | 0 | 2016-06-01T04:12:55Z | [
"javascript",
"python",
"websocket",
"blob",
"arraybuffer"
] |
How to replace Django's primary key with a different integer that is unique for that table | 37,558,821 | <p>I have a Django web application that uses the default auto-incremented positive integers as the primary key. This key is used throughout the application and is frequently inserted into the URL. I don't want to expose this number to the public so that they can guess the number of users or other entities in my Databas... | 1 | 2016-06-01T03:18:15Z | 37,561,570 | <p>You need to separate two concerns:</p>
<ol>
<li><p>The primary key, currently an auto-incrementing integer, is the best choice for a simple, relatively predictable unique identifier that can be enforced on the database level.</p></li>
<li><p>That does not mean you have to expose it to users in your URLs.</p></li>
<... | 2 | 2016-06-01T07:00:36Z | [
"python",
"mysql",
"django",
"hash"
] |
How to replace Django's primary key with a different integer that is unique for that table | 37,558,821 | <p>I have a Django web application that uses the default auto-incremented positive integers as the primary key. This key is used throughout the application and is frequently inserted into the URL. I don't want to expose this number to the public so that they can guess the number of users or other entities in my Databas... | 1 | 2016-06-01T03:18:15Z | 37,605,582 | <h2>The Idea</h2>
<p>I would recommend to you the same approach that is used by <a href="http://instagram-engineering.tumblr.com/post/10853187575/sharding-ids-at-instagram" rel="nofollow">Instragam</a>. Their requirements seems to closely follow yours.</p>
<blockquote>
<p>Generated IDs should be sortable by time (s... | 3 | 2016-06-03T03:47:27Z | [
"python",
"mysql",
"django",
"hash"
] |
How to replace Django's primary key with a different integer that is unique for that table | 37,558,821 | <p>I have a Django web application that uses the default auto-incremented positive integers as the primary key. This key is used throughout the application and is frequently inserted into the URL. I don't want to expose this number to the public so that they can guess the number of users or other entities in my Databas... | 1 | 2016-06-01T03:18:15Z | 37,607,198 | <p>Keep the <code>AUTO_INCREMENT</code>, but pass it around in a semi-secret way: In a cookie. It takes a bit of coding to establish the cookie, set it, and read it. But cookies are hidden from all but serious hackers.</p>
| -2 | 2016-06-03T06:17:53Z | [
"python",
"mysql",
"django",
"hash"
] |
wxpython drag and drop: drop only if the cursor is inside the target listctrl object | 37,558,897 | <p>I am trying to create a small app using <code>wxpython</code> where a user can drag some text from a <code>listctrl</code> object (the source) and drop it in another <code>listctrl</code> object (the target).</p>
<p>I would like to write this app in such a way that <strong>an text string is dropped into the target ... | 0 | 2016-06-01T03:25:43Z | 37,575,431 | <pre><code>import wx
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin
class TextDropTargetListCtrl(wx.TextDropTarget):
def __init__(self, object, parent):
wx.TextDropTarget.__init__(self)
self.object = object
self.parent = parent
def OnDropText(self, x, y, data):
... | 1 | 2016-06-01T17:40:39Z | [
"python",
"drag-and-drop",
"wxpython",
"wxwidgets",
"listctrl"
] |
json.dumps() not saving content to file | 37,558,926 | <p>I am using python 2.7 on mac. The following code creates a file 'test.json' with no content in it. </p>
<pre><code>with open('test.json', 'w') as fout: json.dumps({'name': u'lala'}, fout)
</code></pre>
<p>When using <code>json.dump()</code>, the file does have content. Why is this so?</p>
| -2 | 2016-06-01T03:29:22Z | 37,558,944 | <p><a href="https://docs.python.org/2/library/json.html#json.dumps" rel="nofollow"><code>dumps</code></a> serializes object to a string instead of file:</p>
<blockquote>
<p>Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the... | 3 | 2016-06-01T03:31:44Z | [
"python",
"json"
] |
Getting correct values from variables in functions in Tkinter | 37,558,960 | <p>This is likely a simple problem related to how variables stored in a dictionary are given values within a function.</p>
<p>I'm trying to get the value of a Boolean variable I'm storing in a dictionary <code>(self.controller.Page1_data["Step1Complete"])</code> that I set to <code>"True"</code> in the code below. </p... | 0 | 2016-06-01T03:33:45Z | 37,563,686 | <p>The short version of the answer is this: When you are using tkinter variables you need to use set and get functions to access the value of the variables. Also in an unrelated issue, in a class you don't need to define a function before calling it and it is better to have __init__ on top of your class (cf class PageF... | 1 | 2016-06-01T08:45:35Z | [
"python",
"function",
"variables",
"tkinter"
] |
Prevent overflow when multiply numpy image array | 37,559,092 | <p>I am working with images in numpy and at some point I scale an image.</p>
<pre><code>import scipy.misc as msc
import numpy as np
...
img_rgb = msc.imread(img_fn)
im_scaled = img_rgb * factor
</code></pre>
<p>The result sometimes looks ugly with bright regions showing black spots. This seems to b... | 1 | 2016-06-01T03:49:35Z | 37,559,132 | <p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.clip.html" rel="nofollow"><code>numpy.clip()</code></a>, it does exactely that.</p>
<p>However, the image is probably not going to be pretty either. Usually, what you want is to convert the image values from byte, in the range of ... | 1 | 2016-06-01T03:53:01Z | [
"python",
"numpy"
] |
invalid literal for int() with base 10: when trying with a value with "," present in it | 37,559,228 | <pre class="lang-none prettyprint-override"><code>>>> x='2,33'
>>> type(x)
<type 'str'>
>>> y=int(x)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
y=int(x)
ValueError: invalid literal for int() with base 10: '2,33'
>>>
</code></pr... | 0 | 2016-06-01T04:04:36Z | 37,559,269 | <p>It depends what you want to achieve. If you want to keep either 2 or 33 in your example, you can use :</p>
<pre><code>>>> y = int(x.split(',')[0])
>>> y
2
>>> type(y)
<type 'int'>
</code></pre>
<p>If you want both values to be concatenated, you can use :</p>
<pre><code>>>>... | 0 | 2016-06-01T04:09:12Z | [
"python",
"string",
"int"
] |
invalid literal for int() with base 10: when trying with a value with "," present in it | 37,559,228 | <pre class="lang-none prettyprint-override"><code>>>> x='2,33'
>>> type(x)
<type 'str'>
>>> y=int(x)
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
y=int(x)
ValueError: invalid literal for int() with base 10: '2,33'
>>>
</code></pr... | 0 | 2016-06-01T04:04:36Z | 37,559,285 | <p>Assuming you want the integer part only, you can try stripping the part after the comma, e.g.:</p>
<pre><code>int(x[:x.find(',')])
</code></pre>
| 0 | 2016-06-01T04:11:04Z | [
"python",
"string",
"int"
] |
Why is this code slow in python? | 37,559,255 | <p>I'm new to python.<br/>
I know a bit c++, worked with arrays. Arrays in c++ are not this slow.<br/>
Is it the list that slows it down? I'm not sure if it's possible to use tuples.<br/></p>
<pre><code>import random
list1=[]
n=1000000
for i in range(n):
list1.append(random.randint(1,6))
x1=list1.count(1)
x2=list... | -5 | 2016-06-01T04:07:18Z | 37,559,308 | <p>It is not the list that dominates the running time, but the call to <code>random.randint</code>. If you replace <code>list1.append(random.randint(1,6))</code> with <code>list1.append(1)</code> it'd be easily 10 times faster.</p>
<p>Also, a list comprehension should be slightly faster than <code>for</code> loop wit... | 0 | 2016-06-01T04:13:51Z | [
"python"
] |
Why is this code slow in python? | 37,559,255 | <p>I'm new to python.<br/>
I know a bit c++, worked with arrays. Arrays in c++ are not this slow.<br/>
Is it the list that slows it down? I'm not sure if it's possible to use tuples.<br/></p>
<pre><code>import random
list1=[]
n=1000000
for i in range(n):
list1.append(random.randint(1,6))
x1=list1.count(1)
x2=list... | -5 | 2016-06-01T04:07:18Z | 37,559,348 | <p>Running <code>random.randint(1, 6)</code> a million times is slow, it has little to do with your list:</p>
<pre><code>In [18]: %timeit for i in xrange(1000000): random.randint(1, 6)
1 loops, best of 3: 1.33 s per loop
</code></pre>
<p>You can get even faster if you ditch <code>random.randint()</code> and switch to... | 3 | 2016-06-01T04:18:40Z | [
"python"
] |
Matching two string lists that partially match into another list | 37,559,280 | <p>I am trying to match a List containing strings (50 strings) with a list containing strings that are part of some of the strings of the previous list (5 strings). I will post the complete code in order to give context below but I also want to give a short example:</p>
<pre><code>List1 = ['abcd12', 'efgh34', 'ijkl56'... | 0 | 2016-06-01T04:10:17Z | 37,559,423 | <p>Using a nested for loop:</p>
<pre><code>def intersect(List1, List2):
# empty list for values that match
ret = []
for i in List2:
for j in List1:
if i in j:
ret.append(j)
return ret
List1 = ['abcd12', 'efgh34', 'ijkl56', 'mnop78']
List2 = ['abc', 'ijk']
print(inte... | 2 | 2016-06-01T04:27:45Z | [
"python",
"list",
"match"
] |
Matching two string lists that partially match into another list | 37,559,280 | <p>I am trying to match a List containing strings (50 strings) with a list containing strings that are part of some of the strings of the previous list (5 strings). I will post the complete code in order to give context below but I also want to give a short example:</p>
<pre><code>List1 = ['abcd12', 'efgh34', 'ijkl56'... | 0 | 2016-06-01T04:10:17Z | 37,559,426 | <p>This may not be the most efficient way, but it works</p>
<pre><code>matches = []
for seq_1 in List1:
for seq_2 in List2:
if seq_1 in seq_2 or seq_2 in seq_1:
matches.append(seq_1)
continue
</code></pre>
| 2 | 2016-06-01T04:28:03Z | [
"python",
"list",
"match"
] |
Matching two string lists that partially match into another list | 37,559,280 | <p>I am trying to match a List containing strings (50 strings) with a list containing strings that are part of some of the strings of the previous list (5 strings). I will post the complete code in order to give context below but I also want to give a short example:</p>
<pre><code>List1 = ['abcd12', 'efgh34', 'ijkl56'... | 0 | 2016-06-01T04:10:17Z | 37,559,464 | <p>Try</p>
<pre><code>[l1 for l1 in List1 if any([l2 in l1 for l2 in List2])]
</code></pre>
| 1 | 2016-06-01T04:31:15Z | [
"python",
"list",
"match"
] |
Matching two string lists that partially match into another list | 37,559,280 | <p>I am trying to match a List containing strings (50 strings) with a list containing strings that are part of some of the strings of the previous list (5 strings). I will post the complete code in order to give context below but I also want to give a short example:</p>
<pre><code>List1 = ['abcd12', 'efgh34', 'ijkl56'... | 0 | 2016-06-01T04:10:17Z | 37,559,472 | <p>You can just compare strings, I remove any duplicates from a result list from list1 that contain list2 items. This basically does it what you want:</p>
<pre><code>f = []
for i in list1:
for j in list2:
if j in i:
f.append(i)
result = list(set(f))
</code></pre>
| 1 | 2016-06-01T04:31:54Z | [
"python",
"list",
"match"
] |
Issues in writing to a list from a csv file | 37,559,446 | <p>I'm having trouble figuring what I have done wrong in this code. It appears to be stuck in a infinite loop and I have to kill the process. In the end this code will be used to convert files to Geojson format, however before I start writing to Geojson I want to make sure I can open and append to the dictionary.</p>... | -1 | 2016-06-01T04:29:39Z | 37,559,554 | <p>In your <code>while</code> loop, you don't do anything if (num_count > (list_len-2)), so this loop doesn't end, and only the first row is displayed.</p>
<p>More precisely, when you append the first row to <code>my_list</code>, the length of this one is 1. The if clause becomes <code>if (num_count < (1 - 2))</cod... | 0 | 2016-06-01T04:39:35Z | [
"python",
"csv"
] |
Issues in writing to a list from a csv file | 37,559,446 | <p>I'm having trouble figuring what I have done wrong in this code. It appears to be stuck in a infinite loop and I have to kill the process. In the end this code will be used to convert files to Geojson format, however before I start writing to Geojson I want to make sure I can open and append to the dictionary.</p>... | -1 | 2016-06-01T04:29:39Z | 37,559,555 | <p>You're stuck in the <code>while</code> loop.</p>
<p>Your problem is that <code>num_count+=2</code> never happens unless <code>num_count < (list_len-2)</code> happens to be true. <code>list_len</code> is equal to <code>1</code> the first time you append to it and thus <code>num_count</code> is never incremented.<... | 0 | 2016-06-01T04:39:36Z | [
"python",
"csv"
] |
What do all the distributions available in scipy.stats look like? | 37,559,470 | <h1>Visualizing <a href="http://docs.scipy.org/doc/scipy/reference/stats.html" rel="nofollow"><code>scipy.stats</code></a> distributions</h1>
<p>A histogram can be made of <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.norm.html#scipy.stats.norm" rel="nofollow">the <code>scipy.stats</code> no... | 4 | 2016-06-01T04:31:48Z | 37,559,471 | <h1>Visualizing all <a href="http://docs.scipy.org/doc/scipy/reference/stats.html"><code>scipy.stats</code> distributions</a></h1>
<p>Based on the <a href="http://docs.scipy.org/doc/scipy/reference/stats.html">list of <code>scipy.stats</code> distributions</a>, plotted below are the <a href="https://en.wikipedia.org/w... | 15 | 2016-06-01T04:31:48Z | [
"python",
"matplotlib",
"scipy",
"statistics",
"distribution"
] |
How to convert selenium.webdriver.get_cookies() to cookie text file for use with pycurl | 37,559,480 | <p>selenium.webdriver.get_cookies() gives me two dictionaries of value/pairs. I assume each of these dictionaries is a cookie. How do I write these cookies to a text file that will work with the following code to load the cookies from the cookie.txt file to a curl session?</p>
<pre><code>p = pycurl.Curl()
cookiefile =... | 1 | 2016-06-01T04:32:37Z | 38,176,576 | <p>Everything I have found since asking this question points to the answer to this question: <a href="https://unix.stackexchange.com/questions/36531/format-of-cookies-when-using-wget">https://unix.stackexchange.com/questions/36531/format-of-cookies-when-using-wget</a>, being the answer to my question as well (<a href="... | 0 | 2016-07-04T03:31:45Z | [
"python",
"selenium",
"curl",
"cookies"
] |
flip svg upside-down and rightside-left | 37,559,482 | <p>Given the location of the shape doesn't matter, is there a built-in python function that allow us to flip the svg path? Or could we do it by adjusting the svg values?</p>
| -1 | 2016-06-01T04:32:54Z | 37,560,901 | <p>You can do it in the SVG via a transform attribute.</p>
<pre><code>transform="scale(-1, -1)"
</code></pre>
<p>should do it.</p>
| 1 | 2016-06-01T06:23:56Z | [
"python",
"svg"
] |
Shuffle portion of rows in DataFrame | 37,559,487 | <p>I have come across some previous posts regarding how to shuffle row values (<a href="http://stackoverflow.com/questions/24701217/randomizing-shuffling-rows-in-a-dataframe-in-pandas">Randomizing/Shuffling rows in a dataframe in pandas</a>). For me though, I was wondering how to shuffle a portion of those rows, rather... | 1 | 2016-06-01T04:33:00Z | 37,559,671 | <p>You can use slicing in the shuffle command:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 5), columns=list('ABCDE'))
print df
A=df.values
_= [np.random.shuffle(i) for i in A[: ,1:4]]
df2=pd.DataFrame(A, columns=list('ABCDE'))
print df2
</code></pre>
| 0 | 2016-06-01T04:50:20Z | [
"python",
"dataframe",
"shuffle"
] |
Python push single file into android device with different names until the device runs out of memory | 37,559,502 | <p>I know "adb push" command could be used to push files to android device. But in Python how do i push single file for example file.txt(size of about 50 KB) into android sdcard with different names(for ex. file1.txt, file2.txt etc) until the device storage is full. Any idea much appreciated.</p>
| 1 | 2016-06-01T04:34:27Z | 37,658,540 | <p>I found an alternative solution to this problem. In a python while loop push a single file into SD Card and use "adb mv" to rename the file in the SD Card after pushing the file, continue this until the device memory is full.</p>
| 0 | 2016-06-06T13:17:23Z | [
"python"
] |
Errors when importing files into spyder (Correct directory) | 37,559,561 | <p>Here is my code</p>
<pre><code>import pandas as pd
all_ages = pd.read_csv("all-ages.csv")
all_ages.head(5)
</code></pre>
<p>And I have already put the csv file in the working directory, but I still encounter </p>
<blockquote>
<p>OSError: File b'all-ages.csv' does not exist</p>
</blockquote>
<p>But if I type ea... | 3 | 2016-06-01T04:40:09Z | 37,559,693 | <p>You'd better provide the <strong>absolute file path</strong>. Python uses the current working directory which depends on where you invoke/run your python script. </p>
<p>Even you put your python script and csv file "all-ages.csv" under the same directory, the current working directory might be different.</p>
<p>Fo... | 1 | 2016-06-01T04:52:23Z | [
"python",
"csv",
"pandas",
"anaconda",
"spyder"
] |
django makemessages issue | 37,559,647 | <p>I am running python 2.7 and django 1.8.11 on Windows 7.</p>
<p>After adding in the necessary translation string literals, I am trying to translate my site. I have followed the instructions as per the <a href="https://docs.djangoproject.com/en/1.8/topics/i18n/translation/#message-files" rel="nofollow">docs</a>. This... | 0 | 2016-06-01T04:47:52Z | 37,636,182 | <p>I am not sure how or why, but when I tried this yesterday, it did not work, but now does work. Very frustrating.</p>
<p>I had to run the <code>makemessages</code> command <strong>one extra directory inside my project root directory.</strong></p>
<p>I hope this helps someone out there.</p>
| 0 | 2016-06-05T00:00:14Z | [
"python",
"django",
"translation"
] |
Pandas Column Manipulation | 37,559,691 | <p>I am trying to manipulate a pandas df so I can count the frequency of occurrences of a data point in one column after a specific occurrence another column. My psuedo code below probably sums it up best. Any help would be much appreciated!</p>
<pre><code>import datetime
import time
import pandas as pd
# Set number ... | 0 | 2016-06-01T04:52:06Z | 37,560,093 | <p>Assuming you want the count for the cases between every instance where <code>X>0</code>, as opposed to the count for the remainder of the entire <code>DataFrame</code> after each <code>X>0</code>:</p>
<p>You could create a new <code>column</code> that indicates where the <code>X>0</code> condition holds <c... | 0 | 2016-06-01T05:26:29Z | [
"python",
"pandas"
] |
Remove paragraphs and saving everything to one line | 37,559,723 | <p>Hi there I am not sure how to explain, I have this problem. Currently I have some text as shown below:</p>
<pre><code> picture gallery
see also
adaptation
ecology
extreme environment clothing
extremophile
lexen life in extreme environments
natural environment
references
"extre... | 2 | 2016-06-01T04:55:12Z | 37,559,772 | <p>Replace <code>/\s+/g</code> (every instance of at least one white-space character) with <code>" "</code>. (I'm not familiar with Python, unfortunately, so I don't know what the method call would be.)</p>
| 1 | 2016-06-01T04:59:39Z | [
"python",
"regex",
"python-2.7"
] |
Remove paragraphs and saving everything to one line | 37,559,723 | <p>Hi there I am not sure how to explain, I have this problem. Currently I have some text as shown below:</p>
<pre><code> picture gallery
see also
adaptation
ecology
extreme environment clothing
extremophile
lexen life in extreme environments
natural environment
references
"extre... | 2 | 2016-06-01T04:55:12Z | 37,559,776 | <p>If it's a file:</p>
<pre><code>text = file('path/to/your/file.txt').read()
new_text = text.replace('\n', ' ')
print(new_text) # this will have no new lines
with open('output.txt', 'wr') as out:
out.write(new_text) #this will write it to a file
</code></pre>
<p>You could also use regex, like PJSCopeland said:</... | 4 | 2016-06-01T04:59:51Z | [
"python",
"regex",
"python-2.7"
] |
Remove paragraphs and saving everything to one line | 37,559,723 | <p>Hi there I am not sure how to explain, I have this problem. Currently I have some text as shown below:</p>
<pre><code> picture gallery
see also
adaptation
ecology
extreme environment clothing
extremophile
lexen life in extreme environments
natural environment
references
"extre... | 2 | 2016-06-01T04:55:12Z | 37,559,864 | <p>Please note, that the result given in the answer is quite creative at the right margin, it dropped history from input data ;-) <strong>Update</strong>: Latest comment indicates, data comes from file, thus updated answer.</p>
<p>Taking this as a small unwanted glitch, I suggest to <strong>neither</strong> use regula... | 2 | 2016-06-01T05:07:39Z | [
"python",
"regex",
"python-2.7"
] |
Function that opens a web page and returns a dictionary of all the links and their text | 37,559,794 | <p>Write a function that opens a web page and returns a dictionary of all thelinks and their text on that page. A link is defined by an HTML tag that looks like</p>
<p>< ahref="http://my.computer.com/some/file.html">link text < /a></p>
<p>The link is everything in quotes after thehref=, and the text is everyt... | 1 | 2016-06-01T05:01:19Z | 37,559,930 | <pre><code>def Urls(webpage):
url = webpage
page = urllib.request.urlopen(url)
url_list = {}
for line in page:
if '<a href=' in line:
try:
url = line.split('<a href="')[-1].split('">')[0]
txt = line.split('<a href="')[-1].split('">')[-1]... | 0 | 2016-06-01T05:14:09Z | [
"python"
] |
Function that opens a web page and returns a dictionary of all the links and their text | 37,559,794 | <p>Write a function that opens a web page and returns a dictionary of all thelinks and their text on that page. A link is defined by an HTML tag that looks like</p>
<p>< ahref="http://my.computer.com/some/file.html">link text < /a></p>
<p>The link is everything in quotes after thehref=, and the text is everyt... | 1 | 2016-06-01T05:01:19Z | 37,559,956 | <pre><code>r=re.compile("<\s*a\s*href=\"(.*?)\">(.*?)<\s*/a\s*>")
list = r.findall(line)
for tuple in list:
url_list[tuple[0]] = tuple[1]
</code></pre>
| 0 | 2016-06-01T05:16:10Z | [
"python"
] |
Function that opens a web page and returns a dictionary of all the links and their text | 37,559,794 | <p>Write a function that opens a web page and returns a dictionary of all thelinks and their text on that page. A link is defined by an HTML tag that looks like</p>
<p>< ahref="http://my.computer.com/some/file.html">link text < /a></p>
<p>The link is everything in quotes after thehref=, and the text is everyt... | 1 | 2016-06-01T05:01:19Z | 37,561,789 | <p>While the answers suggesting to tackle this problem with regular expressions <em>might</em> work, they'll fail (unless you take measures) when e.g. the link is split over several lines. E.g. this is perfectly valid HTML:</p>
<pre><code><a
href="../path">link</a>
</code></pre>
<p>There are some other ed... | 2 | 2016-06-01T07:12:07Z | [
"python"
] |
Function that opens a web page and returns a dictionary of all the links and their text | 37,559,794 | <p>Write a function that opens a web page and returns a dictionary of all thelinks and their text on that page. A link is defined by an HTML tag that looks like</p>
<p>< ahref="http://my.computer.com/some/file.html">link text < /a></p>
<p>The link is everything in quotes after thehref=, and the text is everyt... | 1 | 2016-06-01T05:01:19Z | 37,562,321 | <p>Using <code>requests</code> and <code>SoupStrainer</code> for simplicity/efficiency:</p>
<pre><code>import requests
from bs4 import BeautifulSoup, SoupStrainer
def get_urls(webpage):
res = requests.get(webpage)
links = [l for l in BeautifulSoup(res.text, parseOnlyThese=SoupStrainer('a'))
... | 0 | 2016-06-01T07:38:36Z | [
"python"
] |
How do I sort this python list by the number? | 37,560,037 | <p>I am trying to sort a number of people based on their score, and then print out the top 3 people and their scores. Right now it looks like this:</p>
<pre><code>List = ['A 3.0', 'B 4.0', 'C 13.0'] #My list
Sorted = sorted(List, key = lambda item:item.split(" ")[1], reverse = True) #Sorting script
print("Top three sc... | 1 | 2016-06-01T05:21:39Z | 37,560,078 | <p>Change the second line as below.. (the split item is a string. convert that into a float, it will work.)</p>
<pre><code>Sorted = sorted(List, key = lambda item:float(item.split(" ")[1]), reverse = True) #Sorting script
</code></pre>
| 2 | 2016-06-01T05:24:52Z | [
"python",
"list",
"sorting"
] |
How do I sort this python list by the number? | 37,560,037 | <p>I am trying to sort a number of people based on their score, and then print out the top 3 people and their scores. Right now it looks like this:</p>
<pre><code>List = ['A 3.0', 'B 4.0', 'C 13.0'] #My list
Sorted = sorted(List, key = lambda item:item.split(" ")[1], reverse = True) #Sorting script
print("Top three sc... | 1 | 2016-06-01T05:21:39Z | 37,560,080 | <p>Just convert it to float to have numeric ordering like this: </p>
<pre><code>Sorted = sorted(List, key = lambda item:float(item.split(" ")[1]), reverse = True) #Sorting script
</code></pre>
| 0 | 2016-06-01T05:25:07Z | [
"python",
"list",
"sorting"
] |
How do I sort this python list by the number? | 37,560,037 | <p>I am trying to sort a number of people based on their score, and then print out the top 3 people and their scores. Right now it looks like this:</p>
<pre><code>List = ['A 3.0', 'B 4.0', 'C 13.0'] #My list
Sorted = sorted(List, key = lambda item:item.split(" ")[1], reverse = True) #Sorting script
print("Top three sc... | 1 | 2016-06-01T05:21:39Z | 37,560,219 | <p>If you are not specific about using lists,I suggest you to do create an object/tuple of something similar to the below</p>
<pre><code> new_tuple= [('A', 3.0),('B', 4.0),('C', 13.0)]#create an object
Sorted = sorted(tuple, key = lambda new:new[1], reverse = True) #Sorting script
print("Top three scorers and their ... | 0 | 2016-06-01T05:35:28Z | [
"python",
"list",
"sorting"
] |
ImportError shows up with py.test, but not when running the app | 37,560,196 | <p>Unlike in this question:
<a href="http://stackoverflow.com/questions/37469473/importing-modules-from-a-sibling-directory-for-use-with-py-test">Importing modules from a sibling directory for use with py.test</a>
I can import something from my app, but there's an import error (looking like a circular dependency) that ... | 3 | 2016-06-01T05:33:57Z | 37,582,329 | <p>Setting the PYTHONPATH should do the trick.</p>
<pre><code>$ export PYTHONPATH=<ABSOLUTE PATH TO TOPMOST myapp dir>
</code></pre>
<p>(in this example, it is the path to myapp/myapp; and ensure you've <em>exported</em> <code>PYTHONPATH</code>, not only set it).</p>
<p>and from myapp run either </p>
<pre><co... | 3 | 2016-06-02T03:51:22Z | [
"python",
"python-3.x",
"importerror",
"py.test",
"circular-dependency"
] |
ImportError shows up with py.test, but not when running the app | 37,560,196 | <p>Unlike in this question:
<a href="http://stackoverflow.com/questions/37469473/importing-modules-from-a-sibling-directory-for-use-with-py-test">Importing modules from a sibling directory for use with py.test</a>
I can import something from my app, but there's an import error (looking like a circular dependency) that ... | 3 | 2016-06-01T05:33:57Z | 37,639,906 | <p>Another way of doing this is to put a <code>conftest.py</code> file into the top level of <code>myapp</code>, or in <code>myapp/tests</code>. Like this:</p>
<pre><code>$ pwd
/home/nico/temp/projects_structures/test04/myapp/tests
$ touch conftest.py
$ cd ..
$ py.test
=================================================... | 1 | 2016-06-05T08:29:49Z | [
"python",
"python-3.x",
"importerror",
"py.test",
"circular-dependency"
] |
How to iterate a cursor in mongodb using python? | 37,560,364 | <p><strong>My document structure is something like this....</strong></p>
<p><a href="http://i.stack.imgur.com/B2WlG.png" rel="nofollow"><img src="http://i.stack.imgur.com/B2WlG.png" alt="enter image description here"></a></p>
<p><strong>I ran this query</strong></p>
<pre><code>test_run_names = self._database.suite... | 0 | 2016-06-01T05:46:16Z | 37,560,513 | <p>Maybe you have an element without name.</p>
<p>Try this instead:</p>
<pre><code>for t in test_run_names
print (t.get('name'))
</code></pre>
| 1 | 2016-06-01T05:57:12Z | [
"python",
"mongodb",
"mongodb-query"
] |
Sending to the stdin of a program in python3 | 37,560,427 | <p>I have to files, <strong>main.py</strong> and <strong>child.py</strong>.</p>
<p>I am trying to send a string to the stdin of <strong>main.py</strong>.</p>
<p>This is my incomplete code:</p>
<h1>main.py</h1>
<pre><code>from subprocess import *
import time
def main():
program = Popen(['python.exe'. 'child.py'... | 1 | 2016-06-01T05:51:24Z | 37,560,878 | <p>What you need is something along the lines of (in <code>main.py</code>):</p>
<pre><code>from subprocess import Popen, PIPE, STDOUT
x = Popen(['some_child.exe', 'parameter'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
while x.poll() is None:
child_output = x.stdout.readline()
print(child_output)
if b'Do yo... | 4 | 2016-06-01T06:22:12Z | [
"python",
"python-3.x",
"stdin"
] |
How to change value of second duplicate in row | 37,560,548 | <p>I have not been able to find an answer to the following online. Your valuable help would be much appreciated. </p>
<p>I have a <code>DataFrame</code> like this with 20k rows:</p>
<pre><code>ID Date Country
2008-0001 2008-01-02 India
2008-0001 2008-01-02 France
2008-0002 200... | 1 | 2016-06-01T05:59:31Z | 37,560,895 | <p>The below works with the sample data, and assumes you have data for several years that you all want to relabel according to the same logic:</p>
<pre><code>df.Date = pd.to_datetime(df.Date) # to datetime to extract years
years = df.groupby(df.Date.dt.year) # analysis per year
new_df = pd.DataFrame()
for year, data i... | 0 | 2016-06-01T06:23:38Z | [
"python",
"pandas"
] |
How to change value of second duplicate in row | 37,560,548 | <p>I have not been able to find an answer to the following online. Your valuable help would be much appreciated. </p>
<p>I have a <code>DataFrame</code> like this with 20k rows:</p>
<pre><code>ID Date Country
2008-0001 2008-01-02 India
2008-0001 2008-01-02 France
2008-0002 200... | 1 | 2016-06-01T05:59:31Z | 37,564,122 | <p>I believe this will get it done:</p>
<pre><code>isdup = df.duplicated(subset=['ID1', 'ID2'])
dups, uniques = df[isdup], df[~isdup]
ids = ['ID1', 'ID2']
for i, row in dups.iterrows():
while (row[ids] == uniques[ids]).all(axis=1).any():
row.loc['ID2'] += 1
uniques = uniques.append(row)
id1 = unique... | 0 | 2016-06-01T09:05:40Z | [
"python",
"pandas"
] |
Tree View fields are not updating while Onchange in Odoo-8 | 37,560,697 | <p>This is my Python code. which inherits hr.employee, res.partner and sale.order. </p>
<pre><code>from openerp.osv import fields, osv
#Inheriting the hr.employee object
class hr_employee(osv.osv):
_inherit = "hr.employee"
_columns = {
'customer_ids': fields.many2many('res.partner', 'lead_emp... | 0 | 2016-06-01T06:10:17Z | 37,571,610 | <p>Try to use the "magic numbers" documented under <code>def write</code> in openerp.osv.orm.BaseModel (V7) or openerp.models.Model (V8+):</p>
<pre class="lang-py prettyprint-override"><code>def on_change_partner_id(self, ...):
# ...
emp_tuple_list=[(5,)] # without (5,) it won't delete all old data
for emp... | 0 | 2016-06-01T14:30:50Z | [
"python",
"xml",
"openerp",
"onchange",
"odoo-8"
] |
How to pipe a Python's cmd class' input/output to another Python process? | 37,560,719 | <p>Currently, I'm running an experiment with <a href="https://github.com/intrig-unicamp/mininet-wifi" rel="nofollow">Mininet-Wifi</a>. It's CLI is Python's <strong>Cmd</strong> module and this is how I am able to get accurate information about the simulated network environment. The simulator is running as its own proce... | 1 | 2016-06-01T06:11:18Z | 37,561,515 | <p>I guess you want to realize the function something like netstat -oan | findstr 80 (this is on windows to find the port 80), this is the pipeline command to pass the output of netstat -oan to the command findstr. </p>
<p>Then the python code is something like:</p>
<pre><code>import subprocess
p1 = subprocess.Popen... | 0 | 2016-06-01T06:57:42Z | [
"python",
"linux",
"cmd",
"subprocess",
"piping"
] |
sparkRDD and large file comparison | 37,560,727 | <p>Scenario: I've 85789142 JSON documents, and a textfile with 32227957 items.</p>
<p>The textfile would look like:</p>
<pre><code>url1
url2
url3
</code></pre>
<p>And a sample JSON document: </p>
<pre><code>{"key1":"value1","key2":"value2","url":"some_url"}
</code></pre>
<p>I want to find the JSON documents corres... | 0 | 2016-06-01T06:11:44Z | 37,569,114 | <p>I would suggest you to parse your json file using sparkSQL and load the textfile as a DataFrame of one column too. Then you could simply join the two datasets, without any need to collect the first file to the driver, which is your scalability issue now...</p>
| 0 | 2016-06-01T12:47:51Z | [
"python",
"json",
"apache-spark",
"pyspark"
] |
Incorrect output from my implementation of SHA-256 | 37,560,786 | <p>For a personal project, I'm working on implementing SHA-256 in Python 3, without using the <code>hashlib</code> module (since that would defeat the purpose of learning how SHA-256 works). I've been working from the <a href="https://en.wikipedia.org/wiki/SHA-2#Pseudocode" rel="nofollow">Wikipedia pseudocode</a>, but ... | 0 | 2016-06-01T06:15:35Z | 37,589,888 | <p>SHA1 works on bits, not bytes. Therefore, the 64 bit length at the end of the padding is expressed in bits as well; the mistake is in the line</p>
<pre><code>msg.extend([int(x,2) for x in '{:064b}'.format(len(s))])
</code></pre>
<p>which should be</p>
<pre><code>msg.extend([int(x,2) for x in '{:064b}'.format(len(... | 1 | 2016-06-02T10:57:00Z | [
"python",
"python-3.x",
"sha256",
"sha"
] |
custom authentication in backend - Creating user at runtime without saving | 37,560,850 | <p>While searching online on how to accomplish custom authentication in Django I came across <a href="http://django.zone/blog/posts/custom-authentication-backends-django/" rel="nofollow">this</a> and <a href="https://www.djangorocks.com/tutorials/creating-a-custom-authentication-backend/creating-a-simple-authentication... | 0 | 2016-06-01T06:19:49Z | 37,561,509 | <blockquote>
<p>My question is where does the</p>
<pre><code>user = Client.objects.get(email=username)
</code></pre>
<p>get its user from</p>
</blockquote>
<p>Apparently, <code>Client</code> is a <code>models.Model</code>. This means that represents a single record of the relevant table in your database, where... | 0 | 2016-06-01T06:57:26Z | [
"python",
"django",
"authentication"
] |
BruteForce attack program in python not working | 37,560,922 | <p>I have developed a zipfile password cracker which does a brute force attack. The password of the zipfile is 1234. When ever I run the program it gives me this error:</p>
<pre><code>Traceback (most recent call last):
File "C:\Users\Kartikey\Desktop\cracking\bruteforce\bruteforce.py", line 51, in <module>
... | -1 | 2016-06-01T06:24:58Z | 37,560,966 | <p><code>itertools.combinations_with_replacement()</code> produces <em>tuples</em> with individual characters, not strings:</p>
<pre><code>>>> import itertools
>>> gen = itertools.combinations_with_replacement('1234', 3)
>>> next(gen)
('1', '1', '1')
</code></pre>
<p>Use <code>''.join()</co... | 3 | 2016-06-01T06:27:13Z | [
"python",
"zipfile",
"cracking"
] |
Import error when trying to execute a python script from C++ in Visual Studio 2013-15 | 37,560,949 | <p>I am currently working with Keras for a gesture recognition project.
So I installed Anaconda and Python 2.7 and I made some script that work well with Spyder.</p>
<p>After this, I wanted to use them from my main software that is a Visual Studio 2015 C++ project.
So I use "python.h" for this but I have <strong>impor... | 1 | 2016-06-01T06:26:21Z | 37,583,404 | <p>Ok I fixed it. In fact I had two pythons versions on my computer and Visual Studio took the wrong one.</p>
| 0 | 2016-06-02T05:32:41Z | [
"python",
"c++",
"visual-studio",
"python-2.7",
"numpy"
] |
pycharm: pass console variables to script | 37,560,990 | <p>I'm running a script which loads some huge amount of data using pickles.
For this big amount of data, running the script takes a lot of time which in turn makes it very hard to work with (especially to debug).</p>
<p>For solving the problem above I thought about passing some of the variables defined in the console ... | 0 | 2016-06-01T06:28:31Z | 37,561,184 | <p>Never mind. I can just create a function in the script and then call it from the console instead of having <code>__main__</code>.
For example, for a script A.py, add a function b(params) and then in the console just run </p>
<pre><code>from <pathToA>.A import *
b(params)
</code></pre>
| 0 | 2016-06-01T06:38:46Z | [
"python",
"pycharm"
] |
How to unify command line arguments(Flags) for two different binaries in python | 37,561,099 | <p>I have combined two binaries into one for comparison purpose.py file. The two binaries are doing the very similar work essentially but using two sets of CLI arguments.
E.g., </p>
<p>First python binary <code>Par</code>: <code>myPar -myParArgs_1 '1' -myParArgs_2 'a'</code></p>
<p>Second cpp binary <code>Bin</code>... | 0 | 2016-06-01T06:33:39Z | 37,561,153 | <p>You can write a third script, be it either python, bash or batch file (depending on OS) that takes the said argument set and calls each binary respectively in order.</p>
<p>In python it should look something like</p>
<pre><code>from sys import argv
import subprocess
call_args = sys.argv[1:] #first position is scr... | 1 | 2016-06-01T06:36:33Z | [
"python",
"command-line-interface",
"flags"
] |
How to unify command line arguments(Flags) for two different binaries in python | 37,561,099 | <p>I have combined two binaries into one for comparison purpose.py file. The two binaries are doing the very similar work essentially but using two sets of CLI arguments.
E.g., </p>
<p>First python binary <code>Par</code>: <code>myPar -myParArgs_1 '1' -myParArgs_2 'a'</code></p>
<p>Second cpp binary <code>Bin</code>... | 0 | 2016-06-01T06:33:39Z | 37,562,085 | <p>A parent script can spawn others scripts using subprocess package. The most popular one is Popen and Call (Call is an application of Popen)</p>
<p>Link: <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">https://docs.python.org/2/library/subprocess.html</a></p>
<pre><code>**(For example, @c... | 0 | 2016-06-01T07:26:29Z | [
"python",
"command-line-interface",
"flags"
] |
Serving JPG files via wsgiref.simple_server in Python 3 - "write() argument must be a bytes instance" | 37,561,294 | <p>I am trying to make a HTTP server in Python3. For the beginning, I only want a server that serves a single JPG file. Here's my code:</p>
<pre><code>from wsgiref.simple_server import make_server
def simple_app(environ, start_response):
headers = [('Content-type', 'image/jpeg')]
start_response('200 OK', head... | 0 | 2016-06-01T06:45:23Z | 37,643,068 | <p>Return data as list</p>
<pre><code>return [data]
</code></pre>
| 1 | 2016-06-05T14:35:16Z | [
"python",
"python-3.x",
"wsgiref"
] |
Attempting to scrape some information from Amazon. While implementing the next page link, a lot of data is missing | 37,561,348 | <pre><code>class A1Spider(scrapy.Spider):
name = "amazon"
allowed_domains = ["www.amazon.com"]
start_urls = (
'http://www.amazon.com/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=golf+balls',
)
def __init__(self):
self.page = 0
def parse(self, response):
self.page += 1
... | 0 | 2016-06-01T06:48:25Z | 37,563,862 | <p>I think you need to:</p>
<pre><code>yield scrapy.Request(NextBottom_a, callback=self.parse, dont_filter=True)
</code></pre>
<p>to get to the next pages - while using <code>dont_filter</code> ensuring that scrapy doesn't decide you already called this url elsewhere and you don't actually need it.</p>
| 0 | 2016-06-01T08:53:54Z | [
"python",
"scrapy",
"web-crawler"
] |
Negative float Issue - Python (Tkinter) | 37,561,499 | <p>I am having trouble with a line of my code where I can do positive numbers but I can't add a <code>-</code> sign in front of the numbers to make it a negative number.</p>
<p>Here is the code:</p>
<pre><code>as_meter = dict(mm=0.001, cm=0.01, inch=0.0254,ft=0.3048, yd=0.9144, m=1.0,km=1000.0, mi=1609.344,)
def upda... | 0 | 2016-06-01T06:56:50Z | 37,561,720 | <p>Instead of casting directly the entered text to float, you can check if there is a minus character at the beginning of the string:</p>
<pre><code>def update_length(self, *args):
entered_value = self.Text_Length_Left.get()
if entered_value.startswith('-'):
sign = -1
entered_value = entered_... | 0 | 2016-06-01T07:08:53Z | [
"python",
"python-3.x",
"tkinter"
] |
Search and replace strings in 2GB text file size | 37,561,545 | <p>I want to search and replace some file paths in text files.
on average the my file size is above 2 GB.</p>
<p>for example:
i have a folder in my D drive "D:\LargeFilesFolder".
and all files exist in the folder.</p>
<pre><code>"D:\LargeFilesFolder\large_file_v001.txt"
"D:\LargeFilesFolder\large_file_v002.txt"
"D:\L... | 1 | 2016-06-01T06:59:23Z | 37,561,757 | <p>Iterate over the lines and write a new file. Then move the new file over the old file.</p>
<pre><code>with open(outputfilename, "w") as outputfile:
with open(inputfilename, "r") as inputfile:
for line in inputfile:
# replace in line and write to outputfile
shutil.move(outputfilename, inputf... | 5 | 2016-06-01T07:10:51Z | [
"python"
] |
Removing string extra characters via python string functions | 37,561,563 | <p>Here is the web CSS from which I want to extract the Location information.</p>
<pre><code><div class="location">
<div class="listing-location">Location</div>
<div class="location-areas">
<span class="location">Al Bayan</span>
âª,âª
<span class="location"&... | 1 | 2016-06-01T07:00:20Z | 37,561,852 | <p>There is a one line solution. Consider <code>a</code> as your string.</p>
<pre><code>In [38]: [i.replace(" ","") for i in filter(None,(a.decode('unicode_escape').encode('ascii','ignore')).split('\n'))]
Out[38]: ['Al Bayan,', 'Nepal']
</code></pre>
| 0 | 2016-06-01T07:15:09Z | [
"python",
"string",
"python-2.7",
"python-3.x",
"beautifulsoup"
] |
Removing string extra characters via python string functions | 37,561,563 | <p>Here is the web CSS from which I want to extract the Location information.</p>
<pre><code><div class="location">
<div class="listing-location">Location</div>
<div class="location-areas">
<span class="location">Al Bayan</span>
âª,âª
<span class="location"&... | 1 | 2016-06-01T07:00:20Z | 37,561,865 | <p>You're reading it wrong, just the read the spans with class location</p>
<pre><code>soup = BeautifulSoup(html, "html.parser")
locList = [loc.text for loc in soup.find_all("span", {"class" : "location"})]
print(locList)
</code></pre>
<p>This prints exactly what you wanted:</p>
<pre><code>['Al Bayan', 'Nepal']
</co... | 1 | 2016-06-01T07:15:41Z | [
"python",
"string",
"python-2.7",
"python-3.x",
"beautifulsoup"
] |
Removing string extra characters via python string functions | 37,561,563 | <p>Here is the web CSS from which I want to extract the Location information.</p>
<pre><code><div class="location">
<div class="listing-location">Location</div>
<div class="location-areas">
<span class="location">Al Bayan</span>
âª,âª
<span class="location"&... | 1 | 2016-06-01T07:00:20Z | 37,561,940 | <p>You can use regexp to filter only letter and spaces :</p>
<pre><code>>>> import re
>>> re.findall('[A-Za-z ]+', area_result)
['Al Bayan', ' Nepal']
</code></pre>
<p>Hope it'll be helpful.</p>
| 0 | 2016-06-01T07:19:24Z | [
"python",
"string",
"python-2.7",
"python-3.x",
"beautifulsoup"
] |
Python How to remove \" from a string | 37,561,748 | <p>I got this code from somewhere online, and saved it in a variable called "doc".</p>
<pre><code>doc = """{"Grade": " \"B+\" "}"""
</code></pre>
<p>I want doc to print</p>
<pre><code>{"Grade": " B+ "}
</code></pre>
<p>So that I can use ast.literal_eval() to convert "doc" into a dictionary.</p>
<p>But when I t... | 5 | 2016-06-01T07:10:31Z | 37,561,994 | <p>We can just convert the repeated double quotes to a single set of double quotes with <a href="https://docs.python.org/2/library/re.html#re.sub" rel="nofollow"><code>re.sub()</code></a>:</p>
<pre><code>In [95]: doc = """{"Grade": " \"B+\" "}"""
In [96]: doc
Out[96]: '{"Grade": " "B+" "}'
In [98]: re.sub(r'["]\... | 2 | 2016-06-01T07:22:01Z | [
"python"
] |
Python How to remove \" from a string | 37,561,748 | <p>I got this code from somewhere online, and saved it in a variable called "doc".</p>
<pre><code>doc = """{"Grade": " \"B+\" "}"""
</code></pre>
<p>I want doc to print</p>
<pre><code>{"Grade": " B+ "}
</code></pre>
<p>So that I can use ast.literal_eval() to convert "doc" into a dictionary.</p>
<p>But when I t... | 5 | 2016-06-01T07:10:31Z | 37,562,885 | <p>Ok I assume that you have a string in the form <code>{"key": "value"}</code> in which the value could contain unquoted double quotes. In your example, we have <code>Grade</code> for key and <code>"B+"</code> for value.</p>
<p>In that case, you can either remove the inner quotes or correctly quote them, but you shou... | 1 | 2016-06-01T08:05:57Z | [
"python"
] |
What does a dtype of 'O' mean? | 37,561,991 | <p>I have a dataframe in pandas and I'm trying to figure out what the types of its values are. I am unsure what the type is of column <code>'Test'</code>. However, when I run <code>myFrame['Test'].dtype</code>, I get;</p>
<pre><code>dtype('O')
</code></pre>
<p>What does this mean?</p>
| 4 | 2016-06-01T07:22:00Z | 37,562,101 | <p>It means:</p>
<pre><code>'O' (Python) objects
</code></pre>
<p><a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.dtypes.html">Source</a>.</p>
<blockquote>
<p>The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, w... | 5 | 2016-06-01T07:27:02Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
What does a dtype of 'O' mean? | 37,561,991 | <p>I have a dataframe in pandas and I'm trying to figure out what the types of its values are. I am unsure what the type is of column <code>'Test'</code>. However, when I run <code>myFrame['Test'].dtype</code>, I get;</p>
<pre><code>dtype('O')
</code></pre>
<p>What does this mean?</p>
| 4 | 2016-06-01T07:22:00Z | 37,562,112 | <p>It means "a python object", i.e. not one of the builtin scalar types supported by numpy.</p>
<pre><code>np.array([object()]).dtype
=> dtype('O')
</code></pre>
| 3 | 2016-06-01T07:27:46Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
How would someone know, when to pass an object as an argument to functions | 37,562,055 | <p>Let say I have a string </p>
<pre><code>my_str = "Hello World"
func1 = getattr(__builtins__, 'len')
func1
<built-in function len>
func1()
Traceback (most recent call last):
ââFile "<stdin>", line 1, in <module>
TypeError: len() takes exactly one argument (0 given)
func1(my_str)
11
</code></pr... | 1 | 2016-06-01T07:25:10Z | 37,562,251 | <p>This issue is potentially much more complicated than you describe. functions can also take optional arguments (providing default values), a variable number of positional arguments (<code>*args</code>), keyword arguments (<code>**kwargs</code>).</p>
<p>To inspect function's arg-spec, you can use <a href="https://doc... | 2 | 2016-06-01T07:34:53Z | [
"python",
"python-2.7",
"functional-programming"
] |
How would someone know, when to pass an object as an argument to functions | 37,562,055 | <p>Let say I have a string </p>
<pre><code>my_str = "Hello World"
func1 = getattr(__builtins__, 'len')
func1
<built-in function len>
func1()
Traceback (most recent call last):
ââFile "<stdin>", line 1, in <module>
TypeError: len() takes exactly one argument (0 given)
func1(my_str)
11
</code></pr... | 1 | 2016-06-01T07:25:10Z | 37,695,676 | <p>The problem can be solved if following question can answered.</p>
<p>whether a function/method is a part of an object or not?
In given example, func1 is an independent function and func2 is a method of 'str' object.</p>
<p>"<code>__self__</code>" attribute can be used to answer that.</p>
<pre><code>my_str = "Hell... | 1 | 2016-06-08T07:17:08Z | [
"python",
"python-2.7",
"functional-programming"
] |
Search in dictionary, merge key and value then put in list | 37,562,086 | <p>in continuation of my last question (<a href="http://stackoverflow.com/questions/37559280/matching-two-string-lists-that-partially-match-into-another-list">Matching two string lists that partially match into another list</a>) I stumbled upon another problem. Perhaps i should first post the code so far:</p>
<pre><co... | 1 | 2016-06-01T07:26:29Z | 37,567,130 | <p>With the permission of 'cyphase' from the #python channel on freenode I'd like to post his great answer to prevent unnecessary work for others:</p>
<pre><code>def searchReadsInDict(RandomSequences, RandomChoices):
start_time = timeit.default_timer()
mydict = makeSuffixDict(RandomSequences)
Matches_RC... | 0 | 2016-06-01T11:16:58Z | [
"python",
"list",
"dictionary"
] |
Python | NumPy | Coordinates - An issue with conversion of geographical coordinates | 37,562,165 | <p>I have a pretty simple issue: I need to convert the file with geographical coordinates like </p>
<pre><code>Lat Long
50 0 50 35 1 40
50 2 50 35 10 20
50 3 1 35 13 22
50 2 38 35 14 40
49 59 6 35 13 22
49 57 14 35 13 21
49 57 10 35 13 0
49 57 0 35 6 20
</code></pre>
<p>to the <... | 2 | 2016-06-01T07:29:54Z | 37,563,105 | <p>This can be done in a more Pythonic way as follows. </p>
<pre><code>import numpy as np
f = open('data.txt','r')
data = np.loadtxt(f)
coords = [(el[:3],el[3:]) for el in data]
print coords
output = [(c[0][0]+c[0][1]/60.+c[0][2]/3600.,c[1][0]+c[1][1]/60.+c[1][2]/3600.) for c in coords]
print output
</code></pre>... | 2 | 2016-06-01T08:17:05Z | [
"python",
"numpy",
"coordinates",
"coordinate-systems",
"coordinate-transformation"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.