title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to input a line word by word in Python? | 37,760,124 | <p>I have multiple files, each with a line with, say ~10M numbers each. I want to check each file and print a 0 for each file that has numbers repeated and 1 for each that doesn't.</p>
<p>I am using a list for counting frequency. Because of the large amount of numbers per line I want to update the frequency after acce... | 1 | 2016-06-11T05:04:39Z | 37,760,164 | <p>The way you are asking it is not possible I guess. You can't read word by word as such in python . Something of this can be done:</p>
<pre><code>f = open('words.txt')
for word in f.read().split():
print(word)
</code></pre>
| 0 | 2016-06-11T05:11:12Z | [
"python",
"input"
] |
How to input a line word by word in Python? | 37,760,124 | <p>I have multiple files, each with a line with, say ~10M numbers each. I want to check each file and print a 0 for each file that has numbers repeated and 1 for each that doesn't.</p>
<p>I am using a list for counting frequency. Because of the large amount of numbers per line I want to update the frequency after acce... | 1 | 2016-06-11T05:04:39Z | 37,760,181 | <p>Read the line, split the line, copy the array result into a set. If the size of the set is less than the size of the array, the file contains repeated elements</p>
<pre><code>with open('filename', 'r') as f:
for line in f:
# Here is where you do what I said above
</code></pre>
<p>To read the file word ... | 1 | 2016-06-11T05:13:04Z | [
"python",
"input"
] |
How to filter price range for products in django? | 37,760,233 | <p>I am trying to filter my products list by price specified by user(min and max price).I have two input box for taking price range.'price' is one of the column in my database table.I am getting error as int() argument must be a string or a number, not 'dict'.I have include my template file and small part of views file... | 0 | 2016-06-11T05:20:22Z | 37,760,306 | <p>Maybe this line wrong <code>filter_price2=Add_prod.objects.all().aggregate(Max('price'))</code>
Cause aggragate will return a dict</p>
<p>See this docs <a href="https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#cheat-sheet" rel="nofollow">Aggragation</a></p>
<p>Try thisï¼
<code>my_products=Add_prod.obj... | 1 | 2016-06-11T05:32:08Z | [
"python",
"django",
"django-views"
] |
How to filter price range for products in django? | 37,760,233 | <p>I am trying to filter my products list by price specified by user(min and max price).I have two input box for taking price range.'price' is one of the column in my database table.I am getting error as int() argument must be a string or a number, not 'dict'.I have include my template file and small part of views file... | 0 | 2016-06-11T05:20:22Z | 37,762,439 | <p>Use aggregation (<a href="https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#cheat-sheet" rel="nofollow">cheatsheet</a>) as follows to determine the maximum <code>price</code>:</p>
<pre><code>from decimal import Decimal as D
...
price1 = D(request.GET.get('min_price', 0))
price2 = D(request.GET.get('max_... | 0 | 2016-06-11T10:05:02Z | [
"python",
"django",
"django-views"
] |
Find the speed of download for a progressbar | 37,760,238 | <p>I'm writing a script to download videos from a website. I've added a report hook to get download progress. So, far it shows the percentage and size of the downloaded data. I thought it'd be interesting to add download speed and eta.<br>
Problem is, if I use a simple <code>speed = chunk_size/time</code> the speeds sh... | 0 | 2016-06-11T05:21:34Z | 37,858,470 | <pre><code>_count = n if count > n else count
time_history = time_history[-_count:]
time_weights = list(range(1,len(time_history))) #just a simple linear weights
time_diff = [(i-j)*k for i,j in zip(time_history[1:], time_history[:-1],time_weights)]
speed = blockSize*(sum(time_weights)) / sum(time_diff)
</code></pre>... | 1 | 2016-06-16T11:55:04Z | [
"python",
"performance",
"python-3.x",
"download",
"urllib"
] |
Change Breadth First Search to Depth First Search, N- Queen Solver | 37,760,256 | <p>I would appreciate if someone helps me understand how to change the Breadth First Search to Depth First Search, or which steps I need to follow.</p>
<p>The algorithm is basically in the next functions:</p>
<ol>
<li>canPlace</li>
<li>getpositions</li>
<li>loopBoard</li>
</ol>
<p><strong>CODE:</strong></p>
<pre><c... | 0 | 2016-06-11T05:24:45Z | 37,761,953 | <p>The difference between DFS and BFS is in the way you are exploring the nodes of the graph.
In the DFS algorithm, you are first exploring the last node added into the stack (last in first out) whereas in the BFS algorithm, you are exploring it on the basis of first in first out (queue).</p>
<p>The resulting change i... | 0 | 2016-06-11T09:07:40Z | [
"python",
"search",
"depth-first-search",
"breadth-first-search",
"n-queens"
] |
How to test translation symmetry in Python? | 37,760,287 | <p>We get two character values from a user that define a mapping (character translation), such as <code>'a' -> 'p'</code>. How would we test other pairs of strings to see if that same mapping/translation holds across all characters in the strings. For example:</p>
<pre><code>'abcd', 'pqrs' returns True
'aaa', 'ppp... | -3 | 2016-06-11T05:29:23Z | 37,760,411 | <p>You can do this by subtracting the ASCII value with the first one from the user.</p>
<pre><code>'abcd' = [97 98 99 100] subtract it by 'a' give you [0 1 2 3].
'pqrs' = [112 113 114 115] subtract it by 'p' give you [0 1 2 3].
</code></pre>
<p>so if the result of subtraction gives you the same result, return <code>T... | 1 | 2016-06-11T05:45:54Z | [
"python"
] |
How to test translation symmetry in Python? | 37,760,287 | <p>We get two character values from a user that define a mapping (character translation), such as <code>'a' -> 'p'</code>. How would we test other pairs of strings to see if that same mapping/translation holds across all characters in the strings. For example:</p>
<pre><code>'abcd', 'pqrs' returns True
'aaa', 'ppp... | -3 | 2016-06-11T05:29:23Z | 37,760,415 | <p>We want to confirm that the offset (shift) of characters from one string to another is consistent. Make sure the target strings are of the same length; calculate the offset and use <code>all()</code> and generator expression combination to try to ensure the logic completes on the first miss, if any, rather than con... | 5 | 2016-06-11T05:46:08Z | [
"python"
] |
pytest -> How to use fixture return value in test method under a class | 37,760,366 | <p>I have a fixture that returns a value like this:</p>
<pre><code>import pytest
@pytest.yield_fixture(scope="module")
def oneTimeSetUp(browser):
print("Running one time setUp")
if browser == 'firefox':
driver = webdriver.Firefox()
print("Running tests on FF")
else:
driver = webdri... | 0 | 2016-06-11T05:39:47Z | 37,761,165 | <p>There's a technique outlined in the <a href="https://pytest.org/latest/unittest.html" rel="nofollow">py.text unittest integration documentation</a> that may be helpful to you ... using the built-in <code>request</code> fixture. Otherwise, I'm not aware of way to access the return value of a fixture without providing... | 1 | 2016-06-11T07:29:18Z | [
"python",
"python-3.x",
"automated-tests",
"py.test",
"python-unittest"
] |
Drawing rectangle on python Tkinter canvas that covers the entire canvas does not show border on top and left | 37,760,370 | <p>I'm trying to create a rectangle inside a Tkinter (Python 2.7) canvas that is the same dimension as the canvas. Here is the relevant part of the code:</p>
<pre><code>self.canvas = Canvas(self, width=100, height=100, backround="yellow")
self.canvas.create_rectangle(0,0,100,100)
</code></pre>
<p>This draws a rectang... | 1 | 2016-06-11T05:40:16Z | 37,763,035 | <p>Unfortunately, the canvas border is included in the drawable region. Try setting the <code>borderwidth</code> and <code>highlightthickness</code> attributes to zero on the canvas.</p>
<p>You'll also want to adjust the coordinates of your rectangle to end at 99, since counting starts at zero (if the width is 100, th... | 2 | 2016-06-11T11:09:01Z | [
"python",
"tkinter"
] |
Cannot pickle Scikit learn NearestNeighbor classifier - can't pickle instancemethod objects | 37,760,380 | <p>I'm trying to pickle NearestNeighbor model but it says can't pickle instancemethod objects.</p>
<p>The code:</p>
<pre><code>import cPickle as pickle
from sklearn.neighbors import NearestNeighbors
nbrs = NearestNeighbors(n_neighbors=50, algorithm='ball_tree', metric=self.distanceCIE2000_classifier)
nbrs.fit(allVal... | 0 | 2016-06-11T05:41:42Z | 37,760,997 | <p>Somewhere within the <code>NearestNeighbors</code> instance is an attribute that refers to the instance method that you passed to it in the <code>metric</code> argument. Pickle won't pickle instance methods, hence the error.</p>
<p>One way around it is to move method <code>distanceCIE2000_classifier()</code> out of... | 0 | 2016-06-11T07:08:52Z | [
"python",
"pickle"
] |
Writing a file after a string | 37,760,489 | <p>I want to read and write grades(numbers) after a certain subject tag(string). So I have everything but I can't figure out how to find the tag and write after without replacing the numbers that were after it. </p>
<p>So, for example, valid input would be:</p>
<pre><code>MAT54324524342211
</code></pre>
<p>And what ... | 0 | 2016-06-11T05:58:44Z | 37,769,012 | <p>Please try not to reimplement things which already come with the standard library.</p>
<p>Some implementation of your script using <a href="https://docs.python.org/3/library/json.html" rel="nofollow">json</a> would be this:</p>
<pre><code>import os
import json
def read_grades(filename):
if os.path.exists(fil... | 0 | 2016-06-11T22:27:54Z | [
"python",
"string",
"file",
"python-3.x",
"fwrite"
] |
Cannot get data from Queue | 37,760,754 | <p>I'm trying to use a joinable queue and i didn't get anything when join()
is called on queue</p>
<pre><code>from multiprocessing import JoinableQueue,Pool
q = JoinableQueue()
def pat(i):
q.put("hello"+str(i))
q.join()
print(q.get())
with Pool(5) as p:
(p.map_async(pat,range(5))).get()
res = q.ge... | 0 | 2016-06-11T06:38:07Z | 37,762,902 | <p><code>.run()</code> directly runs the process target function in the main process. Use <code>.start()</code> to fork a new process.</p>
| 0 | 2016-06-11T10:55:54Z | [
"python",
"queue",
"multiprocessing"
] |
URLretrieve - Return control to program when download fails/network error | 37,760,797 | <p>I'm writing a script to download videos from a website, using <code>urlretrieve</code>. My internet connection is somewhat erratic and goes down now and then.<br>
When my network fails, <code>urlretrieve</code> hangs, and doesn't pass control back to my program so I can handle the error.<br>
How do I go about solv... | 0 | 2016-06-11T06:43:22Z | 37,833,535 | <p>Use the <a href="http://docs.python-requests.org/en/master/" rel="nofollow">requests</a> library. Requests will throw a <code>ConnectionError</code> <a href="http://docs.python-requests.org/en/master/user/quickstart/#errors-and-exceptions" rel="nofollow">exception</a> when problems with the Network arise. Refer to t... | 1 | 2016-06-15T11:00:34Z | [
"python",
"python-3.x",
"urllib"
] |
Detect swapping in python | 37,760,854 | <p>What is the best way to determine if the computer running my script is using swap memory? It should be as cross-platform as possible. One solution would be to run a program like <code>top</code> as a subprocess, but I would hope there's a better way.</p>
| 2 | 2016-06-11T06:49:44Z | 37,762,177 | <p>I saw in this thread <a href="http://stackoverflow.com/questions/3372444/profile-memory-allocation-in-python-with-support-for-numpy-arrays" title="stackoverflow article">Stackoverflow: Profile Memory Allocation in Python</a> an explanation of how you can record the use of your memory in real time. Then directly prin... | 2 | 2016-06-11T09:35:10Z | [
"python",
"memory"
] |
Detect swapping in python | 37,760,854 | <p>What is the best way to determine if the computer running my script is using swap memory? It should be as cross-platform as possible. One solution would be to run a program like <code>top</code> as a subprocess, but I would hope there's a better way.</p>
| 2 | 2016-06-11T06:49:44Z | 37,765,190 | <p>You can use the module <code>psutil</code>. It is not a module in standard library though and you have to install it using <code>pip</code> package manager.</p>
<pre><code>pip install psutil
</code></pre>
<p>The swap usage data can be gathered using <code>psutil.swap_memory()</code>. It returns a named tuple.</p>
... | 2 | 2016-06-11T15:05:09Z | [
"python",
"memory"
] |
python copy all files larger than x then rename all new files | 37,760,886 | <p>I need a script to copy all files larger than 5mb from a given folder to a new folder that the script needs to create on desktop. Then it needs to rename all files in increasing order also changing extension.
For example files: slides.ppt, math.doc, essay.docx
to:lec1.doc, lec2.doc, lec3.doc</p>
<p>I got this scri... | 0 | 2016-06-11T06:54:05Z | 37,760,908 | <p>Try the <a href="https://docs.python.org/3/library/shutil.html" rel="nofollow"><code>shutil</code></a> package. It handles high level file operations</p>
<pre><code>import shutil
#do something
shutil.move(source,destination)
</code></pre>
<p>where source and destination might be files or folders.<br>
Just set dest... | 0 | 2016-06-11T06:57:08Z | [
"python",
"python-3.5"
] |
python copy all files larger than x then rename all new files | 37,760,886 | <p>I need a script to copy all files larger than 5mb from a given folder to a new folder that the script needs to create on desktop. Then it needs to rename all files in increasing order also changing extension.
For example files: slides.ppt, math.doc, essay.docx
to:lec1.doc, lec2.doc, lec3.doc</p>
<p>I got this scri... | 0 | 2016-06-11T06:54:05Z | 37,760,914 | <p>You can use the <code>rename</code> method from <code>os</code></p>
<pre><code>import os
os.rename(src, dst)
</code></pre>
<p>where the <code>src</code> is the original file or directory name and <code>dst</code> is the new name. </p>
| 0 | 2016-06-11T06:57:57Z | [
"python",
"python-3.5"
] |
Python code to do GET request from pipedrive API | 37,760,916 | <p>I am using python-pipedrive to wrap Pipedrive's API though it doesn't quite work out of the box on python3 (which I'm using) so I modified it. I'm having trouble with just the Http requests portion.</p>
<p>This is what taught me how to use Httplib2: <a href="https://github.com/jcgregorio/httplib2/wiki/Examples-Pyth... | 1 | 2016-06-11T06:58:16Z | 37,760,977 | <p>You need to provide the <code>api_token</code> as a query parameter. Concatenate the stings like this </p>
<pre><code>PIPEDRIVE_API_URL = "https://api.pipedrive.com/v1/"
route = 'persons/123'
api_token = '1234abcd1234abcd'
response, data = http.request(PIPEDRIVE_API_URL + route + '?api_token=' + api_token,
me... | 0 | 2016-06-11T07:06:22Z | [
"python"
] |
samuelcolvin's django-bootstrap3-datetimepicker not showing calendar when clicked on input field | 37,760,920 | <p>I am trying to use <a href="https://github.com/tutorcruncher/django-bootstrap3-datetimepicker" rel="nofollow">samuelcolvin's django-bootstrap3-datetimepicker</a> in which its based on <a href="https://github.com/Eonasdan/bootstrap-datetimepicker" rel="nofollow">Eonasdan's bootstrap-datetimepicker</a> but forked from... | 0 | 2016-06-11T06:59:06Z | 38,899,135 | <h1>Settings.py</h1>
<p>In the Installed Apps Add 'Bootstrap3_datetime'</p>
<h1>template</h1>
<p>Add The following Lines into the HTML Head Tag</p>
<p>{% block header %}
{% load static %} </p>
<pre><code> <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap /3.0.0 css/bootstrap.css">
<... | 0 | 2016-08-11T14:26:26Z | [
"python",
"django",
"bootstrap-datetimepicker",
"eonasdan-datetimepicker"
] |
Trying to pull stock data from Yahoo Finance using Python 3.5 | 37,760,924 | <p>Hello I have this code but am getting these errors</p>
<p><strong>main loop 'tuple' object has no attribute 'read'</strong> AND
<strong>main loop module 'urllib' has no attribute 'urlopen'</strong></p>
<pre><code>def pullData(stock):
try:
fileLine = stock+'.txt'
urlToVisit = 'http://chartapi.fi... | -2 | 2016-06-11T06:59:20Z | 37,761,405 | <p>In Python 3, <code>urlopen()</code> is in <a href="https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen" rel="nofollow"><code>urllib.request</code></a>, so you can do this:</p>
<pre><code>from urllib.request import urlopen
sourceCode = urlopen(urlToVisit).read()
</code></pre>
<p>Regarding ... | 0 | 2016-06-11T08:04:59Z | [
"python"
] |
How to access parse.com REST API after migrating to local server? | 37,760,995 | <p>I have been using parse as my project server and now that I have migrated the data to local server, successfully made dashboard work; but I cannot find a way to access <code>api.parse.com/1/</code> API.</p>
<p>I used to use python to make REST requests and it is basically establishes socket connection with <code>ap... | 0 | 2016-06-11T07:08:48Z | 37,761,064 | <p>Ahh I found out the answer:</p>
<p>You make socket connection with <code>address</code> and <code>port</code> where the <code>parse-server</code> is running, and then instead of doing</p>
<pre><code>conn.request("GET", "/1/login?%s"%...)
</code></pre>
<p>You do:</p>
<pre><code>conn.request("GET", "/parse/login?%... | 0 | 2016-06-11T07:16:24Z | [
"python",
"api",
"rest",
"parse.com"
] |
scrapy use the same session to access website | 37,761,025 | <p>I want to use the same session to access some urls. After reading the docs about cookie, I do like this below:</p>
<pre><code>def start_requests(self):
yield scrapy.Request(self.getUrl, meta={'cookiejar': 0}, callback=self.downloadPic)
def downloadPic(self, response):
yield scrapy.Request(self.vcodeUrl, me... | -1 | 2016-06-11T07:11:15Z | 37,772,548 | <p>well, the simplest and forceful way is open the firebug, to see what exactly are in the request headers, then copy all the value, except things like cookie that will change, that needed you set it in the program.
Be like the browser.</p>
| 0 | 2016-06-12T09:14:19Z | [
"python",
"session",
"cookies",
"scrapy"
] |
My map reduce which used to work previously doesn't work anymore | 37,761,161 | <p>I had written a map reduce program using hadoop streaming in python which used to work on the udacity training virtual machine .To run the hadoop streaming command they had an <code>alias = hs mapper reducer input output</code> .... and it worked perfectly
Now i switched over to the cloudera training VM and i tried ... | -2 | 2016-06-11T07:29:05Z | 37,878,897 | <p>It most probably seems like an error with the <strong>reading of input</strong> data files. All of the 8 map tasks are failing to happen.
Perhaps there maybe a problem with <strong>file size</strong>, or in the mapper.
Have a read, this may help:</p>
<p><a href="https://github.com/RevolutionAnalytics/rmr2/issues/11... | 0 | 2016-06-17T10:13:23Z | [
"python",
"hadoop",
"mapreduce",
"bigdata"
] |
Syntax Error when using except ValueError? | 37,761,173 | <pre><code>group = range(1, 1001)
for num in group:
num_length = len(str(num))
for i in range(num_length):
if str(num)[i] == '1' or str(num)[i] == '7':
group.remove(num)
except ValueError:
pass
else:
pass
</code></pre>
<p>I am trying to remove number... | -1 | 2016-06-11T07:31:28Z | 37,761,201 | <p><code>ValueError</code> shows the element you trying to remove in the list not exists in the list. And You have to use <code>try</code> and <code>execpt</code>. That's why it's shows <code>invalid syntax</code>.</p>
<pre><code>try:
#Your action
except ValueError:
pass
</code></pre>
<p>But your problem you ... | 0 | 2016-06-11T07:36:31Z | [
"python",
"python-3.x",
"python-3.5"
] |
Syntax Error when using except ValueError? | 37,761,173 | <pre><code>group = range(1, 1001)
for num in group:
num_length = len(str(num))
for i in range(num_length):
if str(num)[i] == '1' or str(num)[i] == '7':
group.remove(num)
except ValueError:
pass
else:
pass
</code></pre>
<p>I am trying to remove number... | -1 | 2016-06-11T07:31:28Z | 37,761,211 | <p><code>except</code> is part of a special block called <code>try-except</code>. This is an example of usage:</p>
<pre><code>n = int(input())
try:
print(5 // n)
except ZeroDivisionError:
print("You entered zero!")
</code></pre>
<p>So to make your block actually catch raised exceptions, you need to wrap the p... | 1 | 2016-06-11T07:38:04Z | [
"python",
"python-3.x",
"python-3.5"
] |
Syntax Error when using except ValueError? | 37,761,173 | <pre><code>group = range(1, 1001)
for num in group:
num_length = len(str(num))
for i in range(num_length):
if str(num)[i] == '1' or str(num)[i] == '7':
group.remove(num)
except ValueError:
pass
else:
pass
</code></pre>
<p>I am trying to remove number... | -1 | 2016-06-11T07:31:28Z | 37,761,266 | <p>If you use except you also need try. For in depth information, check the <a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">documentation on error handling</a> out. </p>
<p>Also, to check if a character is in a string you can use the in keyword. </p>
<p>Additionally changing a list while itera... | 1 | 2016-06-11T07:45:54Z | [
"python",
"python-3.x",
"python-3.5"
] |
Syntax Error when using except ValueError? | 37,761,173 | <pre><code>group = range(1, 1001)
for num in group:
num_length = len(str(num))
for i in range(num_length):
if str(num)[i] == '1' or str(num)[i] == '7':
group.remove(num)
except ValueError:
pass
else:
pass
</code></pre>
<p>I am trying to remove number... | -1 | 2016-06-11T07:31:28Z | 37,761,284 | <p>First, <code>range</code> objects are immutable, which means you cannot remove an element from a <code>range</code> object. Moreover, it is now possible to remove elements from a sequence you are iterating over.</p>
<p>Second, the <code>except</code> block must be related to a <code>try</code> block containing the ... | 2 | 2016-06-11T07:48:29Z | [
"python",
"python-3.x",
"python-3.5"
] |
How do I select and store columns greater than a number in pandas? | 37,761,238 | <p>I have a pandas DataFrame with a column of integers. I want the rows containing numbers greater than 10. I am able to evaluate True or False but not the actual value, by doing:</p>
<pre><code>df['ints'] = df['ints'] > 10
</code></pre>
<p>I don't use Python very often so I'm going round in circles with this. </p... | 0 | 2016-06-11T07:41:15Z | 37,761,260 | <p>Sample DF:</p>
<pre><code>In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
In [80]: df
Out[80]:
a b c
0 6 11 11
1 14 7 8
2 13 5 11
3 13 7 11
4 13 5 9
5 5 11 9
6 9 8 6
7 5 11 10
8 8 10 14
9 7 14 13
</code></pre>
<p>present only ... | 2 | 2016-06-11T07:44:41Z | [
"python",
"pandas"
] |
Python OpenCV face detection code sometimes raises `'tuple' object has no attribute 'shape'` | 37,761,340 | <p>I am trying to build a face detection application in python using opencv.<br>
Please see below for my code snippets:</p>
<pre><code> # Loading the Haar Cascade Classifier
cascadePath = "/home/work/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
# Dictionary to store image name... | 0 | 2016-06-11T07:56:01Z | 37,761,418 | <p>From your error understand that you are trying to read the <code>shape</code>. But <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/arrays.ndarray.html" rel="nofollow">shape</a> is the attribute of <code>numpy.ndarray</code>. You are trying to read the shape from the result of face detection. But that will ... | 1 | 2016-06-11T08:05:54Z | [
"python",
"opencv",
"face-detection"
] |
Python OpenCV face detection code sometimes raises `'tuple' object has no attribute 'shape'` | 37,761,340 | <p>I am trying to build a face detection application in python using opencv.<br>
Please see below for my code snippets:</p>
<pre><code> # Loading the Haar Cascade Classifier
cascadePath = "/home/work/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
# Dictionary to store image name... | 0 | 2016-06-11T07:56:01Z | 37,761,472 | <p>To get the number of faces it should be:</p>
<p><code>print "Number of faces found in-> ", img_fname, " are ", len(faces)</code>.</p>
<p>I would also recommend that to convert image to gray scale you should write:</p>
<p><code>gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)</code> instead of <code>gray = cv2.cvtCo... | 1 | 2016-06-11T08:10:54Z | [
"python",
"opencv",
"face-detection"
] |
Python OpenCV face detection code sometimes raises `'tuple' object has no attribute 'shape'` | 37,761,340 | <p>I am trying to build a face detection application in python using opencv.<br>
Please see below for my code snippets:</p>
<pre><code> # Loading the Haar Cascade Classifier
cascadePath = "/home/work/haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath)
# Dictionary to store image name... | 0 | 2016-06-11T07:56:01Z | 37,761,914 | <p>The cause of the problem is that <code>detectMultiScale</code> returns an empty tuple <code>()</code> when there's no matches, but a <code>numpy.ndarray</code> when there are matches.</p>
<pre><code>>>> faces = classifier.detectMultiScale(cv2.imread('face.jpg'))
>>> print(type(faces), faces)
<c... | 1 | 2016-06-11T09:02:48Z | [
"python",
"opencv",
"face-detection"
] |
How to get a float from python to JavaScript without cgi | 37,761,484 | <p>I am running an apache server from a Raspberry Pi and have a python script that returns sensor input by printing it. This properly prints it to the console. Currently I have a php script that gets this output and shuts off a light if the sensor is reading is high, before printing it again. This also works when run f... | 3 | 2016-06-11T08:11:55Z | 37,785,070 | <p>Right. It's probably user permission issues, because you get the output running script under your user from terminal. And browser, which is running it under server's user, returns an empty string.</p>
<p>Check <code>www-data</code> (or whatever) permissions when running script from your server. Set error reporting ... | 1 | 2016-06-13T08:32:26Z | [
"javascript",
"php",
"python",
"ajax",
"raspberry-pi2"
] |
Launch Excel file from Python on Mac | 37,761,517 | <p>I'd like to start an Excel file from Python on a Mac. When I hardcode the file path like in the following lines it works fine.</p>
<pre><code>import os
os.system("open -a 'Microsoft Excel.app' 'path/file.xlsx'")
</code></pre>
<p>But the problem is that instead of hardcoding the path my solution should look somethi... | 1 | 2016-06-11T08:15:49Z | 37,761,555 | <p>Try this maybe: </p>
<p>os.system("open -a 'Microsoft Excel.app' '%s'" % file_path)</p>
| 1 | 2016-06-11T08:20:20Z | [
"python",
"excel",
"osx",
"file",
"path"
] |
Read inputs from stdin/file and raise errors for less inputs | 37,761,652 | <p>Lets say we have a simple python code like this:</p>
<pre><code>num1 = input()
num2 = input()
res = sum(num1,num2)
</code></pre>
<p>As per my requirements, I should be able to convert above code(that I got as some input from user) in such a way, that I should be able to supply inputs to it from a predefined file... | 0 | 2016-06-11T08:30:47Z | 37,761,717 | <p>Well as far as I know there's no way to tell Pythons input function to read from anything but stdin. Without rewriting your code to use file objects, you could just redirect a file to stdin. This would send an eof at end of file and raise the error you're expecting.</p>
<p>For example run:</p>
<pre><code>python sc... | 1 | 2016-06-11T08:37:35Z | [
"python"
] |
How to select or highlight all items in a QTreeWidget? | 37,761,656 | <p>I'm trying to build a context menu that user can right-click on a QTreeWidget and select all items. </p>
| 1 | 2016-06-11T08:31:10Z | 37,782,704 | <p>Here's a way that will recursively go through each item and its children and select them all. It takes advantage of the <a href="http://pyqt.sourceforge.net/Docs/PyQt4/qtreewidget.html#invisibleRootItem" rel="nofollow"><code>invisibleRootItem</code></a> at the root of each <code>QTreeWidget</code>. You could also ... | 0 | 2016-06-13T05:59:50Z | [
"python",
"pyqt",
"pyqt4",
"qtreewidget",
"qtreewidgetitem"
] |
How to select or highlight all items in a QTreeWidget? | 37,761,656 | <p>I'm trying to build a context menu that user can right-click on a QTreeWidget and select all items. </p>
| 1 | 2016-06-11T08:31:10Z | 37,799,483 | <p>You can use <code>QTreeView.selectAll()</code> but only after setting the selection mode to something that allows multiple selection (using <code>QAbstractItemView.setSelectionMode()</code>).</p>
<p>Example (in PyQt4 use QtGui instead of QtWidgets):</p>
<pre><code>from PyQt5 import QtWidgets
app = QtWidgets.QAppl... | 0 | 2016-06-13T21:32:11Z | [
"python",
"pyqt",
"pyqt4",
"qtreewidget",
"qtreewidgetitem"
] |
How do I create a DataFrame containing a column where rows are greater than a number? | 37,761,702 | <p>I have a DataFrame with these columns:</p>
<pre><code>ID int64
Key int64
Reference object
sKey float64
sName float64
fKey int64
cName object
ints int32
</code></pre>
<p>I want to create a ne... | 0 | 2016-06-11T08:35:48Z | 37,761,731 | <p>You can use one of many available <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html" rel="nofollow">indexers</a>. I would recommend <code>.ix</code>, because it seems to be <a href="http://stackoverflow.com/a/37761363/5741205">faster</a>:</p>
<pre><code>df_greater_10 = df.ix[df.ints >= 1997, ['c... | 2 | 2016-06-11T08:38:28Z | [
"python",
"pandas"
] |
How do I create a DataFrame containing a column where rows are greater than a number? | 37,761,702 | <p>I have a DataFrame with these columns:</p>
<pre><code>ID int64
Key int64
Reference object
sKey float64
sName float64
fKey int64
cName object
ints int32
</code></pre>
<p>I want to create a ne... | 0 | 2016-06-11T08:35:48Z | 37,761,750 | <p>Not sure why you haven't tried <code>df[df.ints >= 1997]['ints']</code> first (Maybe I am missing someting, your dataframe is very big?). Here's a demo of how it would work below</p>
<pre><code>>>> pd.DataFrame({'ints': [1, 2, 3, 10, 11], 'other': ['a', 'b', 'c', 'y', 'z']})
', 'y', 'z']})
ints othe... | 1 | 2016-06-11T08:41:52Z | [
"python",
"pandas"
] |
Vim-plug plugin manager unable to use post-update hooks on YouCompleteMe plugin | 37,761,718 | <p>I am using vim-plug plugin manager and it worked great until I tried to install Youcompleteme plugin with it. I tried putting <code>Plug 'Valloric/YouCompleteMe', { 'do': './install.py' }</code> on my <code>.vimrc</code> and tried <code>PlugInstall!</code> and <code>PlugUpdate!</code> without success. I read the doc... | 0 | 2016-06-11T08:37:36Z | 37,765,626 | <p>It might be timing out while downloading.</p>
<p>You can clone Valloric/YouCompleteMe to .vim/plugged and then do the <a href="http://github.com/Valloric/YouCompleteMe#installation" rel="nofollow">Installation</a>. </p>
<p>You can still keep <code>Plug 'Valloric/YouCompleteMe'</code> in you .vimrc, so it will upda... | 0 | 2016-06-11T15:48:31Z | [
"python",
"linux",
"vim",
"vim-plugin",
"youcompleteme"
] |
.bat file execution in python not giving the required results | 37,761,916 | <p>This is the content of my bat file</p>
<p>Proselint is an exe file</p>
<pre><code>proselint C:\Users\Rahul\Desktop\proselint-0.5.3\proselint\proselint\something.md > ooo.txt
</code></pre>
<p>Running the bat file by double clicking it produces the following output </p>
<pre><code>C:\Users\Rahul\Desktop\proseli... | 0 | 2016-06-11T09:02:58Z | 37,763,171 | <p>Your .bat file must contain <code>@echo off</code> in the first line, like:</p>
<pre><code>@echo off
command parameter > ooo.txt
</code></pre>
<p>If you do not specify <code>@echo</code> to <code>off</code> every line that is going to be executed will be printed to your console.</p>
<p>I hope this fixes your ... | 0 | 2016-06-11T11:24:57Z | [
"python",
"operating-system",
"subprocess"
] |
TypeError: 'NoneType' object is not iterable. Why do I get this error? | 37,761,974 | <p>The function <em>compute_root</em> uses Newton's method of successive approximation to find good enough approximations of the zeroes of polynomials (herein lies the problem). The function <em>evalPoly</em> computes the value of a polynomial at a particular x value, and the function <em>ddx2</em> computes the derivat... | -2 | 2016-06-11T09:11:16Z | 37,762,013 | <p>Your function <code>ddx2(tpl)</code> lacks a return value.</p>
| 1 | 2016-06-11T09:17:13Z | [
"python",
"recursion"
] |
TypeError: 'NoneType' object is not iterable. Why do I get this error? | 37,761,974 | <p>The function <em>compute_root</em> uses Newton's method of successive approximation to find good enough approximations of the zeroes of polynomials (herein lies the problem). The function <em>evalPoly</em> computes the value of a polynomial at a particular x value, and the function <em>ddx2</em> computes the derivat... | -2 | 2016-06-11T09:11:16Z | 37,762,079 | <p>Function evalPoly
once it returns ans it never returns degree : you may want to use return (ans,degree)</p>
<p>similarly in in else loop</p>
<p>also ddx2 does not return any function.</p>
| 0 | 2016-06-11T09:24:26Z | [
"python",
"recursion"
] |
TypeError: 'NoneType' object is not iterable. Why do I get this error? | 37,761,974 | <p>The function <em>compute_root</em> uses Newton's method of successive approximation to find good enough approximations of the zeroes of polynomials (herein lies the problem). The function <em>evalPoly</em> computes the value of a polynomial at a particular x value, and the function <em>ddx2</em> computes the derivat... | -2 | 2016-06-11T09:11:16Z | 37,762,087 | <p>Change:</p>
<pre><code>def ddx2(tpl):
lst = list(tpl)
for i in range(len(lst)):
lst[i] = lst[i]*i
if i != 0:
lst[i-1] = lst[i]
del lst[-1]
tpl = tuple(lst)
</code></pre>
<p>To:</p>
<pre><code>def ddx2(tpl):
lst = list(tpl)
for i in range(len(lst)):
lst[i... | 0 | 2016-06-11T09:25:38Z | [
"python",
"recursion"
] |
Django website on Apache with wsgi failing | 37,762,090 | <p>so i'm about to lunch my first django website , i currently have a server that has been configured to host php websites and i've decided to test a simple empty project to get familiar with the process </p>
<p>so the python version in this server is bit old (2.6) so i couldn't install latest version of django , i ... | 0 | 2016-06-11T09:25:50Z | 37,763,494 | <p><code>DocumentRoot</code> directive is the main root of your problem. (<a href="https://httpd.apache.org/docs/current/mod/core.html#documentroot" rel="nofollow">ref</a>)</p>
<p>try this config:</p>
<pre><code><VirtualHost 111.111.111.111*:80>
ServerName novadmin20.com
WSGIDaemonProcess testing python-path... | 0 | 2016-06-11T12:04:15Z | [
"python",
"django",
"apache",
"centos",
"mod-wsgi"
] |
Tensorflow error: InvalidArgumentError: Different number of component types. | 37,762,210 | <p>I want to input batches of shuffled images to be training, and I write the code according to <a href="https://github.com/TensorVision/TensorVision/blob/master/examples/inputs/generic_input.py" rel="nofollow">the generic input images in TensorVision</a>, but I get an error. I cannot figure it where it is wrong.
This ... | 0 | 2016-06-11T09:40:15Z | 37,762,704 | <p>The error is due to wrong argument <code>shapes</code> for function <a href="https://www.tensorflow.org/versions/r0.9/api_docs/python/io_ops.html#batch" rel="nofollow"><code>tf.train.batch</code></a>. The argument <code>shapes</code> should be left to default, or should be:</p>
<blockquote>
<p>shapes: (Optional) ... | 0 | 2016-06-11T10:35:51Z | [
"python",
"tensorflow",
"deep-learning"
] |
Python: is isalnum() the same as isalpha with isdigit? | 37,762,230 | <p>Is there a way to concretely verify this? I tried to solve a coding question but it seems one of the test cases (not revealed to me) takes this as wrong. In what kinds of cases does this fail to be true?</p>
| -5 | 2016-06-11T09:43:13Z | 37,762,386 | <p>From the documentation of Python 3:</p>
<blockquote>
<p><code>str.isalnum()</code><br>
<em>Return true if all characters in the string are alphanumeric and there is at least one character, false otherwise. A character c is alphanumeric if one the following returns True: c.isalpha(), c.isdecimal(), c.isdigit(), ... | 1 | 2016-06-11T10:00:01Z | [
"python",
"string"
] |
Python: is isalnum() the same as isalpha with isdigit? | 37,762,230 | <p>Is there a way to concretely verify this? I tried to solve a coding question but it seems one of the test cases (not revealed to me) takes this as wrong. In what kinds of cases does this fail to be true?</p>
| -5 | 2016-06-11T09:43:13Z | 37,762,495 | <p>There are cases when both <code>isalpha</code> and <code>isdigit</code> returns <code>False</code>, but <code>isalnum</code> returns <code>True</code>. So <code>isalnum</code> is not just a combination of the other two.</p>
<pre><code>>>> 'a1'.isalpha(), 'a1'.isdigit(), 'a1'.isalnum()
(False, False, True)
... | 0 | 2016-06-11T10:10:23Z | [
"python",
"string"
] |
Ignore nested structures in numpy's array creation | 37,762,275 | <p>I want to write to a vlen hdf5 dataset, for that I am using <code>h5py.Dataset.write_direct</code> to speed up the process. Suppose I have a list of numpy arrays (e.g. given by <code>cv2.findContours</code>), and by dataset:</p>
<pre><code>dataset = h5file.create_dataset('dataset', \
... | 1 | 2016-06-11T09:48:22Z | 37,762,631 | <p>One solution appears to be to create the "outer" array first (with an 'object' dtype), then fill the elements with the inner array.</p>
<p>Thus:</p>
<pre><code>contours = [np.zeros((10,), 'int32'), np.zeros((10,), 'int32')]
a = np.empty(len(contours), dtype=np.object)
for i in range(len(contours)):
a[i] = cont... | 0 | 2016-06-11T10:26:57Z | [
"python",
"arrays",
"list",
"numpy"
] |
Ignore nested structures in numpy's array creation | 37,762,275 | <p>I want to write to a vlen hdf5 dataset, for that I am using <code>h5py.Dataset.write_direct</code> to speed up the process. Suppose I have a list of numpy arrays (e.g. given by <code>cv2.findContours</code>), and by dataset:</p>
<pre><code>dataset = h5file.create_dataset('dataset', \
... | 1 | 2016-06-11T09:48:22Z | 37,762,696 | <p>In this version</p>
<pre><code>contours_np = np.empty((len(contours),), dtype=object)
for i, contour in enumerate(contours):
contours_np[i] = contour
</code></pre>
<p>you can replace the loop with the single statement</p>
<pre><code>contours_np[...] = contours
</code></pre>
| 1 | 2016-06-11T10:34:18Z | [
"python",
"arrays",
"list",
"numpy"
] |
Separating elements of a Pandas DataFrame in Python | 37,762,372 | <p>I have a pandas DataFrame that looks like the following:</p>
<pre><code> Time Measurement
0 0 1
1 1 2
2 2 3
3 3 4
4 4 5
5 0 2
6 1 3
7 2 4
8 3 5
9 4 6
10... | 1 | 2016-06-11T09:58:04Z | 37,762,748 | <p>IIUC, you may set a multiindex so that you can index your DF accessing experiments and subexperiments easily:</p>
<pre><code>In [261]: dfi = df.set_index([df.index//15+1, df.index//5 - df.index//15*3 + 1])
In [262]: dfi
Out[262]:
Time Measurement
1 1 0 1
1 1 2
1 2 ... | 1 | 2016-06-11T10:40:15Z | [
"python",
"pandas",
"dataframe"
] |
Looping through a python pivot table | 37,762,735 | <p>I have a pivot table that I have created (pivotTable) using:</p>
<pre><code>pivotTable= dayData.pivot_table(index=['sector'], aggfunc='count')
</code></pre>
<p>which has produced the following pivot table:</p>
<pre><code> sector id
broad_sector
Communications ... | -1 | 2016-06-11T10:38:38Z | 37,764,398 | <p>This snippet will get you the values as asked. </p>
<pre><code>for sector_name, sector_count, _ in pivotTable.to_records():
print(sector_name, sector_count)
</code></pre>
| 0 | 2016-06-11T13:38:53Z | [
"python",
"pandas"
] |
Looping through a python pivot table | 37,762,735 | <p>I have a pivot table that I have created (pivotTable) using:</p>
<pre><code>pivotTable= dayData.pivot_table(index=['sector'], aggfunc='count')
</code></pre>
<p>which has produced the following pivot table:</p>
<pre><code> sector id
broad_sector
Communications ... | -1 | 2016-06-11T10:38:38Z | 37,764,455 | <p>well, i don't understand why do you need this (because looping through DF is <strong>very</strong> slow), but you can do it this way:</p>
<pre><code>In [403]: for idx, row in pivotTable.iterrows():
.....: sectorName = idx
.....: sectorCount = row['sector']
.....: print(sectorName, s... | 1 | 2016-06-11T13:44:58Z | [
"python",
"pandas"
] |
To find the value on X axis corresponding to an arbitrary value of Y that doesn't contain in the list used to plot the data in python | 37,762,875 | <p>I have a set of values for redshift and have the corresponding set of values for deceleration parameter of universe. The plot is given:</p>
<p><a href="http://i.stack.imgur.com/H91Jg.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/H91Jg.jpg" alt="enter image description here"></a></p>
<p>Now I need the valu... | 0 | 2016-06-11T10:52:47Z | 37,767,853 | <p>Your code had some issues. I only have <kbd>Python 3</kbd> here so if you have any problem understanding something just ask (changed a bit the <code>print</code> and the <code>input</code> function parts).</p>
<p>You did not define the <code>H02</code> so I just stated it was equal to <code>H0</code>. Correct that ... | 2 | 2016-06-11T19:40:30Z | [
"python",
"matplotlib"
] |
To find the value on X axis corresponding to an arbitrary value of Y that doesn't contain in the list used to plot the data in python | 37,762,875 | <p>I have a set of values for redshift and have the corresponding set of values for deceleration parameter of universe. The plot is given:</p>
<p><a href="http://i.stack.imgur.com/H91Jg.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/H91Jg.jpg" alt="enter image description here"></a></p>
<p>Now I need the valu... | 0 | 2016-06-11T10:52:47Z | 37,771,620 | <p>The corrected program(Previously corrected by <code>@armatita</code> ) is: (where I put <code>zf=2</code> in the output)</p>
<pre><code>from pylab import*
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
fig, ax = subplots()
k = 0
omega, B, H0 = 0.6911, 0.019921992722139001, 67.74
#H02 = H0 +... | 1 | 2016-06-12T07:04:23Z | [
"python",
"matplotlib"
] |
Unresolved references in PyCharm | 37,762,896 | <p>I downloaded my old project from the repository and there are a lot of unresolved references now, how can I fix them?</p>
<p><a href="http://i.stack.imgur.com/EH32e.png" rel="nofollow"><img src="http://i.stack.imgur.com/EH32e.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/VXa... | -1 | 2016-06-11T10:55:07Z | 37,762,999 | <p>You should configure your Python interpreter and get Django installed. In the <a href="https://www.jetbrains.com/help/pycharm/2016.1/configuring-python-interpreter-for-a-project.html" rel="nofollow">documentation</a> you 'll see:</p>
<blockquote>
<p><strong>Selecting Python interpreter for a project</strong></p>
... | 0 | 2016-06-11T11:05:42Z | [
"python",
"django",
"python-2.7",
"django-models",
"pycharm"
] |
Unresolved references in PyCharm | 37,762,896 | <p>I downloaded my old project from the repository and there are a lot of unresolved references now, how can I fix them?</p>
<p><a href="http://i.stack.imgur.com/EH32e.png" rel="nofollow"><img src="http://i.stack.imgur.com/EH32e.png" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/VXa... | -1 | 2016-06-11T10:55:07Z | 37,763,079 | <p>If you are working with a virtualenv you have to configure your project to let Pycharm know what interpreter should be used and where are its dependencies.</p>
<p><a href="https://www.jetbrains.com/help/pycharm/2016.1/adding-existing-virtual-environment.html" rel="nofollow">https://www.jetbrains.com/help/pycharm/20... | 0 | 2016-06-11T11:13:54Z | [
"python",
"django",
"python-2.7",
"django-models",
"pycharm"
] |
Building a matrix of 'rolled' rows efficiently in Numpy | 37,762,904 | <p>I'd like to construct a <code>(n,n)</code>-array from a one dimensional array, where each row is shifted (with wrapping) by one relative to the previous one. The following code does this:</p>
<pre><code>import numpy as np
r = np.array([1, 2, 3, 4, 5])
n = len(r)
MM = np.zeros((n, n), dtype=r.dtype)
for k in range(... | 3 | 2016-06-11T10:56:03Z | 37,763,111 | <p>Take a look at <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.circulant.html" rel="nofollow"><code>scipy.linalg.circulant</code></a></p>
<pre><code>In [255]: r
Out[255]: array([1, 2, 3, 4, 5])
In [256]: circulant(r).T
Out[256]:
array([[1, 2, 3, 4, 5],
[5, 1, 2, 3, 4],
[4, ... | 4 | 2016-06-11T11:18:18Z | [
"python",
"numpy",
"scipy"
] |
Django store csv float items in database | 37,762,918 | <p>I have a csv file with data like:</p>
<p><code>Company,104.95,102.8,102.6,104.5,104.5,102.75...\n</code> etc. </p>
<p>I am storing float values like this <code>prices[1:len(prices)]</code> in</p>
<p><code>models.CommaSeparatedIntegerField(blank=True, null=True, max_length=10000)</code> </p>
<p>but after the valu... | 2 | 2016-06-11T10:56:50Z | 37,763,105 | <p>You can convert them to floats like so:</p>
<pre><code>float_prices = [float(p) for p in prices[1:len(prices)]]
</code></pre>
<p>That said, <code>CommaSeparatedIntegerField</code> will only validate a comma-separated list of <strong>integers</strong>. Neither strings nor floats are valid for that field - so it's o... | 3 | 2016-06-11T11:17:07Z | [
"python",
"django",
"csv"
] |
Django store csv float items in database | 37,762,918 | <p>I have a csv file with data like:</p>
<p><code>Company,104.95,102.8,102.6,104.5,104.5,102.75...\n</code> etc. </p>
<p>I am storing float values like this <code>prices[1:len(prices)]</code> in</p>
<p><code>models.CommaSeparatedIntegerField(blank=True, null=True, max_length=10000)</code> </p>
<p>but after the valu... | 2 | 2016-06-11T10:56:50Z | 37,763,370 | <p>Use a CharField instead (with a leading <code>_</code>)</p>
<pre><code>_float_prices = models.CharField(max_length=10000, blank=True)
</code></pre>
<p>and the <code>@property</code> decorator with JSON serialization</p>
<pre><code>@property
def float_prices(self):
return json.loads(self._float_prices)
@float... | 0 | 2016-06-11T11:50:23Z | [
"python",
"django",
"csv"
] |
Python, TOR, Requests - 'module' object has no attribute 'inet_pton' | 37,763,173 | <p>I am trying to make a GET request over TOR which is listening on 127.0.0.1:9050</p>
<p>I've installed request socks: pip install -U requests[socks]</p>
<pre><code> import requests
tor_proxy = {'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050'}
r = requests.get("http://www.google.com", proxie... | 2 | 2016-06-11T11:25:18Z | 37,763,800 | <p>The problem is with the library itself, in particular PySocks <a href="https://github.com/Anorov/PySocks/blob/master/socks.py#L517" rel="nofollow">socks.py</a>, <a href="https://docs.python.org/2/library/socket.html#socket.inet_pton" rel="nofollow">inet_pton</a> is only available on unix:</p>
<p><strong>socket.ine... | 4 | 2016-06-11T12:36:17Z | [
"python",
"tor"
] |
Python GPIO add_event_detect each state individually | 37,763,175 | <p>I currently have a few lever-type on off switch that I would like to have the status printed as soon as it switches on/off independantly off all the other switches.</p>
<p>So far, I have come this far:</p>
<pre><code>import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
GPIO.setup(7, GPIO.IN) # s... | 0 | 2016-06-11T11:25:24Z | 37,766,822 | <p>I don't have a raspberry-pi on me right now so I can't test this, but I'm pretty sure the following is what you need.</p>
<pre><code>lever_num_by_pin = [7: 2, 11: 3]
def printOn(pin):
print "switch", lever_num_by_pin[pin], "on"
def printOff(pin):
print "switch", lever_num_by_pin[pin], "off"
for pin in lever_... | 1 | 2016-06-11T17:47:49Z | [
"python",
"raspberry-pi",
"gpio"
] |
Unicode Objects must be encoded before hashing error | 37,763,235 | <p>Questions dealing with similar issues: <a href="http://stackoverflow.com/questions/7585307/typeerror-unicode-objects-must-be-encoded-before-hashing">SO 1</a>, <a href="https://stackoverflow.com/questions/13265439/python-3-3-unicode-objects-must-be-encoded-before-hashing">SO 2</a>, <a href="https://stackoverflow.com/... | 1 | 2016-06-11T11:32:15Z | 37,763,456 | <p><a href="https://docs.python.org/3/library/hashlib.html#module-hashlib" rel="nofollow">"Parameter msg can be of any type supported by hashlib."</a>.</p>
<p><a href="https://docs.python.org/3/library/hashlib.html#module-hashlib" rel="nofollow">"Note: Feeding string objects into is not supported, as hashes work on b... | 1 | 2016-06-11T12:00:01Z | [
"python",
"python-3.x",
"encode",
"hmac"
] |
filling forward conditional result | 37,763,267 | <p>I have a DataFrame with columns <code>A</code> and <code>B</code>. Now I want to produce column <code>C</code> like this:</p>
<pre><code> A B C
index
1 0 50 NaN
2 1 60 60
3 0 40 60
4 0 30 60
5 1 40 40
</code></pre>
<p><code>C</code> gets the value of <code>... | 1 | 2016-06-11T11:37:20Z | 37,763,310 | <p>You can select the values of B where A==1, then fill forward:</p>
<pre><code>a = pd.DataFrame({"A":[0,1,0,0,1], "B":[50,60,40,30,40]}, index=[1,2,3,4,5])
a["C"] = a.B[a.A == 1]
a = a.fillna(method="ffill")
</code></pre>
<p>The ffill method propagates forward the last valid observation to fill in the NaNs. See <a h... | 2 | 2016-06-11T11:43:20Z | [
"python",
"numpy",
"pandas",
"dataframe",
"vectorization"
] |
filling forward conditional result | 37,763,267 | <p>I have a DataFrame with columns <code>A</code> and <code>B</code>. Now I want to produce column <code>C</code> like this:</p>
<pre><code> A B C
index
1 0 50 NaN
2 1 60 60
3 0 40 60
4 0 30 60
5 1 40 40
</code></pre>
<p><code>C</code> gets the value of <code>... | 1 | 2016-06-11T11:37:20Z | 37,763,419 | <p>alternative method, one-liner, which seems to be bit faster:</p>
<pre><code>In [301]: df['C'] = pd.Series(np.where(df.A==1, df.B, np.nan), index=df.index).ffill()
In [302]: df
Out[302]:
A B C
1 0 50 NaN
2 1 60 60.0
3 0 40 60.0
4 0 30 60.0
5 1 40 40.0
</code></pre>
<p>Setup 500K rows DF:</... | 1 | 2016-06-11T11:55:34Z | [
"python",
"numpy",
"pandas",
"dataframe",
"vectorization"
] |
PiCamera Flask, start and stop preview | 37,763,294 | <p>I am creating a little web interface in Flask to control the Raspberry Pi camera using the PiCamera python module. I have a working index page which displays a stream from the camera. However, when I POST stop_preview() via an input button the app fails and I cannot work out what I am doing wrong. Here's some of my ... | 2 | 2016-06-11T11:41:27Z | 37,770,297 | <p>First of all, the <code>start_preview</code> and <code>stop_preview</code> methods of picamera just start and stop the preview, which is the overlay video that appears on the Pi's own display. These methods do not start or stop the camera itself.</p>
<p>To stop the camera, you have to get the background thread in m... | 1 | 2016-06-12T02:55:47Z | [
"python",
"flask",
"raspberry-pi"
] |
Cleaning files with multiple duplicates | 37,763,443 | <p>I recently had to copy in emergency my database on my website.</p>
<p>I scraped it using some functions I made in Python using my admin codes.
The database is formated like :</p>
<pre><code>Name:
Phone Number:
Has played the game:
</code></pre>
<p>Everything was copied in <code>.txt</code> file but sometimes, ... | 1 | 2016-06-11T11:58:41Z | 37,763,837 | <p>You can use regular expressions to run string matching and replacing in your text file fix this.
You can do this with python or in simply in an editor like notepad++.
search for the expression:</p>
<pre><code>Name:.+(Name: (?!Name:).+)
</code></pre>
<p>and replace it with </p>
<pre><code>$1
</code></pre>
<p>In ... | 0 | 2016-06-11T12:39:24Z | [
"python",
"database",
"file"
] |
Cleaning files with multiple duplicates | 37,763,443 | <p>I recently had to copy in emergency my database on my website.</p>
<p>I scraped it using some functions I made in Python using my admin codes.
The database is formated like :</p>
<pre><code>Name:
Phone Number:
Has played the game:
</code></pre>
<p>Everything was copied in <code>.txt</code> file but sometimes, ... | 1 | 2016-06-11T11:58:41Z | 37,764,117 | <p>I am assuming you know how to read the text file line by line in python. Assuming that you read each line into a string called s </p>
<pre><code>>>> s = "Name: Name: Name: Bob"
>>> s2 = "Name: Bob"
>>>
>>> s_split = s.split(":")
>>> s_split
['Name', ' Name', ' Name', '... | 0 | 2016-06-11T13:09:34Z | [
"python",
"database",
"file"
] |
Cleaning files with multiple duplicates | 37,763,443 | <p>I recently had to copy in emergency my database on my website.</p>
<p>I scraped it using some functions I made in Python using my admin codes.
The database is formated like :</p>
<pre><code>Name:
Phone Number:
Has played the game:
</code></pre>
<p>Everything was copied in <code>.txt</code> file but sometimes, ... | 1 | 2016-06-11T11:58:41Z | 37,764,772 | <p>Say you have this in <code>db.txt</code></p>
<pre><code>Phone Number:
Phone Number: Phone Number: Phone Number: 0118521358 Name: Name: Name: Name: Bob
Has played the game:
Name: Name: Name: Name: Bob
</code></pre>
<p>You can try a little script like this</p>
<pre><code>import re
#create a new file called new_fi... | 1 | 2016-06-11T14:18:49Z | [
"python",
"database",
"file"
] |
Setting new variables in a while loop with calculations PYTHON | 37,763,444 | <p>I'm running a population model, and the wrong numbers always come out because I'm setting the variables to new values, but then when I want to use the old variables, the loop automatically updates itself and uses the new ones.</p>
<pre><code>juvenile_population = 10
adult_population = 10
senile_population = 1
juven... | 1 | 2016-06-11T11:58:44Z | 37,763,486 | <p>You are overwriting the existing values with new values. With Python you can merge all four lines into one like this:</p>
<pre><code>juvenile_population, adult_population, senile_population, total_population = adult_population * birth_rate, juvenile_population * juvenile_survival, (adult_population * adult_survival... | 1 | 2016-06-11T12:03:33Z | [
"python",
"variables",
"while-loop"
] |
Setting new variables in a while loop with calculations PYTHON | 37,763,444 | <p>I'm running a population model, and the wrong numbers always come out because I'm setting the variables to new values, but then when I want to use the old variables, the loop automatically updates itself and uses the new ones.</p>
<pre><code>juvenile_population = 10
adult_population = 10
senile_population = 1
juven... | 1 | 2016-06-11T11:58:44Z | 37,764,304 | <p>Per @Selcuk, you could use variable unpacking directly, but even with nicer formatting it looks unwieldly:</p>
<pre><code>juvenile_population, adult_population, senile_population, total_population = (adult_population * birth_rate,
juvenile... | 0 | 2016-06-11T13:28:49Z | [
"python",
"variables",
"while-loop"
] |
Invalid syntax error when applying lambda for multiple columns processing | 37,763,508 | <p>I have the following code that should put either 0 or 1 into the column <code>INDICATOR</code> depending on if-then rules (values of columns <code>T</code> and <code>S</code>):</p>
<pre><code>rawdata_base['INDICATOR'] = rawdata_base.apply(lambda row:
'1' if row['T']=='2' and str(... | -1 | 2016-06-11T12:05:55Z | 37,763,562 | <p>You can't stack conditionals like that in python. Ternary conditional operators can only take 3 inputs (hence ternary): <code>a if b else c</code>.</p>
<p>If you want to stack them, then I don't think you want a <code>lambda</code> here. Make your own function:</p>
<pre><code>def myfunc(row):
if row['T']=='2' ... | 1 | 2016-06-11T12:10:11Z | [
"python",
"lambda"
] |
Invalid syntax error when applying lambda for multiple columns processing | 37,763,508 | <p>I have the following code that should put either 0 or 1 into the column <code>INDICATOR</code> depending on if-then rules (values of columns <code>T</code> and <code>S</code>):</p>
<pre><code>rawdata_base['INDICATOR'] = rawdata_base.apply(lambda row:
'1' if row['T']=='2' and str(... | -1 | 2016-06-11T12:05:55Z | 37,763,677 | <p>You are missing '='. It should be 'axis=1' not 'axis 1'</p>
| 1 | 2016-06-11T12:22:32Z | [
"python",
"lambda"
] |
Invalid syntax error when applying lambda for multiple columns processing | 37,763,508 | <p>I have the following code that should put either 0 or 1 into the column <code>INDICATOR</code> depending on if-then rules (values of columns <code>T</code> and <code>S</code>):</p>
<pre><code>rawdata_base['INDICATOR'] = rawdata_base.apply(lambda row:
'1' if row['T']=='2' and str(... | -1 | 2016-06-11T12:05:55Z | 37,774,123 | <p>As @gipsy mentioned, one of the errors was the lack of <code>=</code> (<code>axis=1</code>). However, the main error was to miss <code>str</code> in this line of code <code>elif 'A' in str(row['S']):</code></p>
| 0 | 2016-06-12T12:14:53Z | [
"python",
"lambda"
] |
ValueError: labels ['timestamp'] not contained in axis | 37,763,715 | <p>I am learning machine learning and I came across this <a href="https://github.com/azabet/Machine-Learning" rel="nofollow">code</a>.
I am trying to run the file <code>"Recommender-Systems.py"</code> from the above source. But it throws an error <br>
<code>ValueError: labels ['timestamp'] not contained in axis.</code>... | 0 | 2016-06-11T12:26:44Z | 37,764,074 | <p>Your data is missing the headers so it's being wrongly inferred by the first row.</p>
<p>You need to change a little bit the <code>Recommender-Systems.py</code> and manually inform the headers.</p>
<p>The right header is available in the <code>README</code> file from your data set.</p>
<p>Change your file to some... | 1 | 2016-06-11T13:04:13Z | [
"python",
"machine-learning",
"svm",
"data-science"
] |
Python leave 10% branches with max weight NetworkX graph | 37,763,835 | <p>I have graph and counted network density, and now I should keep only the branches that have maximum weight ( first 10% of network density, fo example 20 branches with biggest weight from 200 ). I cant find how to do that?</p>
| 1 | 2016-06-11T12:39:17Z | 37,766,000 | <p>The question is slightly confusing, so, I am happy to amend the response if more information surfaces later on.</p>
<blockquote>
<p>I have graph and counted network density,</p>
</blockquote>
<p>By which I am assuming that you have an undirected (?) weighted network. And consequently, network density (for the we... | 1 | 2016-06-11T16:23:57Z | [
"python",
"graph",
"networkx"
] |
How to get the Document Vector from Doc2Vec in gensim 0.11.1? | 37,763,883 | <p>Is there a way to get the document vectors of unseen and seen documents from Doc2Vec in the gensim 0.11.1 version? </p>
<ul>
<li><p>For example, suppose I trained the model on 1000 thousand - Can I get
the doc vector for those 1000 docs? </p></li>
<li><p>Is there a way to get document vectors of unseen document... | 0 | 2016-06-11T12:45:03Z | 38,151,941 | <p>For the first bullet point, you can do it in gensim 0.11.1</p>
<pre><code>from gensim.models import Doc2Vec
from gensim.models.doc2vec import LabeledSentence
documents = []
documents.append( LabeledSentence(words=[u'some', u'words', u'here'], labels=[u'SENT_1']) )
documents.append( LabeledSentence(words=[u'some', ... | 1 | 2016-07-01T18:32:48Z | [
"python",
"gensim",
"word2vec",
"doc2vec"
] |
Read the echo output of php file in python | 37,763,957 | <p>I have a database on backendless cloud service which has no support for python.</p>
<p>So i'm establishing the connection between the python code and the database using php files.</p>
<p>The insertion is working fine as there is no response from the php file to the python.</p>
<p>However in the retrieving i need ... | -1 | 2016-06-11T12:53:47Z | 37,764,150 | <p>Use the <code>subprocess</code> module to execute the PHP code from python.</p>
<p>Assuming that your PHP script write to standard output <a href="https://docs.python.org/2/library/subprocess.html#subprocess.check_output" rel="nofollow"><code>subprocess.check_output()</code></a> would be the easiest, or you could u... | 0 | 2016-06-11T13:13:20Z | [
"php",
"python",
"backendless"
] |
Read the echo output of php file in python | 37,763,957 | <p>I have a database on backendless cloud service which has no support for python.</p>
<p>So i'm establishing the connection between the python code and the database using php files.</p>
<p>The insertion is working fine as there is no response from the php file to the python.</p>
<p>However in the retrieving i need ... | -1 | 2016-06-11T12:53:47Z | 37,764,154 | <p>To read from stdout with python you can use subprocess module</p>
<pre><code>import subprocess
p = subprocess.Popen("ls",stdout=subprocess.PIPE) # in your case, "ls" change with php command
print p.communicate() # here you will get ls output
</code></pre>
<p>But I don't think that this is a good solution to solve... | 0 | 2016-06-11T13:13:50Z | [
"php",
"python",
"backendless"
] |
RuntimeWarning: invalid value encountered in power while plotting poisson distribution | 37,764,085 | <p>I want to run this piece of code </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import factorial
def poisson(k, lamb):
return (lamb**k/factorial(k)) * np.exp(-lamb)
x_plot = np.linspace(0, 10, 100)
plt.plot(x_plot, poisson(x_plot, parameters), 'r-', lw=2)
plt.show()
</code... | 2 | 2016-06-11T13:05:28Z | 37,764,608 | <p>I don't really know which <code>factorial</code> you are using. But when I use <code>math.factorial</code>, the code cannot even work. Then I tried with the <code>scipy.misc.factorial</code>, which can really take <code>numpy array</code> as an input. And when I run the following, it give me no error or warning.</p>... | 2 | 2016-06-11T14:01:16Z | [
"python",
"matplotlib",
"runtime"
] |
Error when using Matplotlib.image in Python | 37,764,266 | <p>Okay, so I just started <a href="http://matplotlib.org/users/image_tutorial.html" rel="nofollow">this</a> tutorial using Anaconda in PyCharm. I imported the correct libraries, but when I try to upload my image using this code:</p>
<pre><code>img = mpimg.imread('FileName.png')
</code></pre>
<p>I get this error mess... | 2 | 2016-06-11T13:24:49Z | 37,764,388 | <p>Make sure that there is that file in the folder...
Try this command to list the files in that folder just to make sure that python atleast recognizes or reads the files.</p>
<pre><code>import os
print (os.listdir('your path'))
</code></pre>
| 2 | 2016-06-11T13:38:08Z | [
"python",
"matplotlib",
"pycharm"
] |
How does the timeline_markers list work in Blender? | 37,764,302 | <p>I have the following code:</p>
<pre><code>import bpy
import math
import random
Markers = []
for marker in bpy.context.scene.timeline_markers:
frame = marker.frame
Markers.extend([frame])
print('-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+')
print(Markers)
Markers = sorted(Mar... | 0 | 2016-06-11T13:28:40Z | 37,764,483 | <p>Not problem with your code. The code works fine that's why it's shows like that. You are assign to the same variable that's why it's shows different output. When you execute <code>print(Markers)</code> it's giving the original result. After <code>Markers = sorted(Markers)</code> the list is modified. So assign to so... | 0 | 2016-06-11T13:47:35Z | [
"python",
"list",
"blender"
] |
How does the timeline_markers list work in Blender? | 37,764,302 | <p>I have the following code:</p>
<pre><code>import bpy
import math
import random
Markers = []
for marker in bpy.context.scene.timeline_markers:
frame = marker.frame
Markers.extend([frame])
print('-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+')
print(Markers)
Markers = sorted(Mar... | 0 | 2016-06-11T13:28:40Z | 37,771,958 | <p>You are assuming that the timeline_markers are stored as a sorted list, this is not the case. While they are presented to python as a common list/array, they are stored internally by blender as a linked list. If you trace the source code back you will find they use ListBase as defined in <a href="https://developer.b... | 0 | 2016-06-12T07:58:48Z | [
"python",
"list",
"blender"
] |
What does CPython actually do when "=" is performed on primitive type variables? | 37,764,401 | <p>For instance:</p>
<pre><code>a = some_process_that_generates_integer_result()
b = a
</code></pre>
<p>Someone told me that <em>b</em> and <em>a</em> will point to same chunk of integer object, thus <em>b</em> would modify the reference count of that object. The code is executed in function <code>PyObject* ast2obj_e... | 4 | 2016-06-11T13:39:27Z | 37,764,949 | <p>First of all, there are no âprimitive objectsâ in Python. Everything is an object, of the same kind, and they are all handled in the same way on the language level. As such, the following assignments work the same way regardless of the values which are assigned:</p>
<pre><code>a = some_process_that_generates_in... | 7 | 2016-06-11T14:38:23Z | [
"python",
"cpython",
"reference-counting"
] |
Merge two csv files based on key and secondary key | 37,764,425 | <p>I would like to merge two csv files as follows:</p>
<p><strong>csv1:</strong></p>
<pre><code>formula,solver,runtime,conflicts
CBS_k3_n100_m403_b30_13.cnf,SWDiA5BY,0.001842,318
CBS_k3_n100_m403_b30_13.cnf,glucose,0.001842,318
</code></pre>
<p><strong>csv2:</strong></p>
<pre><code>formula,entropy,num sols
CBS_k3_n... | 1 | 2016-06-11T13:42:17Z | 37,764,686 | <p>Why don't you use pandas. Its pretty easy to do this in pandas</p>
<pre><code>import pandas as pd
df1=pd.read_csv("1.csv")
df=pd.read_csv("2.csv")
result=df1.merge(df,on="formula")
result.to_csv("result.csv")
</code></pre>
<p>also you can use <code>result=df1.merge(df,on="formula",how="outer")</code> to keep those... | 2 | 2016-06-11T14:09:02Z | [
"python",
"csv"
] |
Spark MLlib recommender engine's methods | 37,764,465 | <p>I'm using pySpark MLlib and the method of ALS from the box for collaborative filtering. Just wondering, does Spark provide some other methods of doing filtering (for calculating distance), for example Pearson's or Cosine's? Can they be done in Spark environment? </p>
<p>Many thanks!</p>
| 1 | 2016-06-11T13:46:05Z | 37,768,979 | <p>Yes Spark has an implementation of Cosine similarity. </p>
<pre><code>https://github.com/apache/spark/blob/master/examples/src/main/scala/org/apache/spark/examples/mllib/CosineSimilarity.scala
</code></pre>
<p>Example in scala</p>
<pre><code> // Load and parse the data file.
val rows = sc.textFile(params.i... | 1 | 2016-06-11T22:20:24Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-mllib"
] |
Detect when the "x" or close button is pressed | 37,764,489 | <p>How would you know when the user pressed the "x" button on the close button in a python tkinter program and do an event?</p>
| 1 | 2016-06-11T13:48:31Z | 37,764,541 | <p>You can override the closing protocol.</p>
<pre><code>def on_close():
#custom close options, here's one example:
close = messagebox.askokcancel("Close", "Would you like to close the program?")
if close:
root.destroy()
root.protocol("WM_DELETE_WINDOW", on_close)
</code></pre>
| 1 | 2016-06-11T13:54:06Z | [
"python",
"python-3.x",
"tkinter"
] |
creating a empty JSON file and uptaing it by pandas dataframe's row on python | 37,764,518 | <p>So, I have a pandas dataframe with large no. of rows. whose one row might look like this and more.</p>
<pre><code>data_store.iloc[0]
Out[5]:
mac_address 00:03:7f:05:c0:06
Visit 1/4/2016
st... | 0 | 2016-06-11T13:51:42Z | 37,764,691 | <p>your desired JSON file is not a valid JSON file, here is the error message thrown by the <a href="http://jsonlint.com/" rel="nofollow">online JSON validator</a>:</p>
<p>Input:</p>
<pre><code>{
"mac_address": "00:03:7f:05:c0:06" {
"cities": [{
"City Name1": "Wittenbergplatz",
"Ci... | 2 | 2016-06-11T14:09:55Z | [
"python",
"json",
"pandas",
"dataframe"
] |
python tkinter display time in a windows | 37,764,627 | <p>i am starting with GUI in python with tkinter.and i want to display current time as HH:MM:SS in the center of my windows(with big digit if possible).this is the app code:
a basic full screen windows with a background picture.</p>
<pre><code>import Tkinter as tk
from Tkinter import Tk, Frame, BOTH
import Tkinter
fro... | 0 | 2016-06-11T14:02:42Z | 37,764,942 | <p>Add a <code>compound</code> parameter to your <code>myvar</code> object with value <code>Tkinter.CENTER</code> and also a <code>text</code>parameter with the time string.
To create time string add</p>
<pre><code>import time
time_string = time.strftime('%H:%M:%S')
</code></pre>
<p>Now your <code>myvar</code> will l... | 0 | 2016-06-11T14:37:46Z | [
"python",
"time",
"tkinter",
"display"
] |
python tkinter display time in a windows | 37,764,627 | <p>i am starting with GUI in python with tkinter.and i want to display current time as HH:MM:SS in the center of my windows(with big digit if possible).this is the app code:
a basic full screen windows with a background picture.</p>
<pre><code>import Tkinter as tk
from Tkinter import Tk, Frame, BOTH
import Tkinter
fro... | 0 | 2016-06-11T14:02:42Z | 37,766,767 | <p>When using place you can use relative coordinates. To place a widget in the center of another widget use <code>relx</code> and <code>relx</code>. You can tell it which widget to be relative to with the <code>in_</code> parameter; by default it will be centered in its parent.</p>
<p>For example:</p>
<pre><code>time... | 0 | 2016-06-11T17:43:13Z | [
"python",
"time",
"tkinter",
"display"
] |
How to do OR masking operation in Image processing in python? | 37,764,648 | <p>I have a code in C# which is giving me a masking result. But I couldn't do it in python. Can anyone help me on how to do it? Is it possible in python? I almost went through the python openCV documentation</p>
<pre><code>public void OROPeration()
{
IplImage orImage = Cv.CreateImage(src.Size, BitDep... | 1 | 2016-06-11T14:05:22Z | 37,764,802 | <p>Theres a function in opencv, <code>bitwise_or</code>, I guess it'd do what you want. </p>
<pre><code>import cv2
fin_image = cv2.bitwise_or(src_image, masking_image)
</code></pre>
| 1 | 2016-06-11T14:22:03Z | [
"python",
"opencv",
"image-processing",
"mask"
] |
How to create an iterator that produces items where no item has a single character represented more than n number times in python? | 37,764,682 | <p>I have created a script that uses the following code to iterate over all combinations of characters in the sCharacters string:</p>
<pre><code>sCharacters = "abcdefghijklmnopqrstuvwxyz0123456789"
iKeyLength = len(sCharacters)
for sCharacterCombination in itertools.product(sCharacters, repeat=iKeyLength):
# Do S... | 2 | 2016-06-11T14:08:42Z | 37,765,901 | <p>Here's some code that's more efficient than your current approach.</p>
<p>First, we use itertool's <code>combinations_with_replacement</code> function to create combinations of the desired length, filtering out combinations that have more than the desired number of repetitions. Then we permute each combination; the... | 1 | 2016-06-11T16:16:13Z | [
"python",
"python-3.x",
"itertools"
] |
Serving Django site over HTTPS | 37,764,725 | <p>I have built a website in Django but I would like to serve it "as HTTPS" (encrypted over port 443).</p>
<p>I already have a certificate, but how do I configure Django to use it? Could it really be Django doesn't support this out of the box and if so how should I go about serving the site as HTTPS?</p>
<p>Server is... | 0 | 2016-06-11T14:13:29Z | 37,764,943 | <p>It is not related to Django but it actually being supported. so follow this steps : </p>
<p><strong>1. Getting A Certificate</strong>
use <a href="https://letsencrypt.org" rel="nofollow">letsencrypt</a> because it's free!</p>
<p><strong>2. Updating Repositories And Installing Tools</strong>
enter this command in t... | 5 | 2016-06-11T14:37:59Z | [
"python",
"django",
"ssl",
"https"
] |
Pandas - Conditional Calculation Based on Shift Values from Two Other Columns | 37,764,741 | <p>I'm sure this question is easy, but it has been stumping me for too long, so would REALLY appreciate some direction</p>
<p>I'm looking to add a column to a dataframe based on the results of two other columns</p>
<p>I want to identify if the stock is equal to the stock in the prior row and the date is equal to the ... | 2 | 2016-06-11T14:15:14Z | 37,764,767 | <p><strong>UPDATE3:</strong> <em>"And we are looking to see how many times in a row stocks traded on the bid or offer"</em></p>
<pre><code>In [112]: g = df.groupby(['Stock','Date'])
In [113]: df['Count'] = g['BidOffer'].apply(lambda x: (x == x.shift()).cumsum()) + 1
In [114]: df
Out[114]:
Stock Date Tim... | 1 | 2016-06-11T14:18:01Z | [
"python",
"numpy",
"pandas",
"dataframe"
] |
Incorrect Looping and returning of variable | 37,764,898 | <p>My code below is checking if the input (quantity) is a number. If it is a number first time, it returns the number fine. However, if you were to put a letter in, and then when the function loops enter a number, '0' is returned rather than the number you inputted.</p>
<pre><code>def quantityFunction():
valid = F... | 1 | 2016-06-11T14:32:00Z | 37,765,028 | <p>You function is not correct actually, you are using <code>while</code> loop together with a <code>recursion function</code>, which is not necessary in this case. </p>
<p>While, You could try the following code, which is a bit modification based on your function but use only <code>while</code> loop. </p>
<pre><code... | 3 | 2016-06-11T14:46:18Z | [
"python"
] |
Simultaneous while loops ? PYTHON | 37,764,956 | <p>Currently the code below works, but I should have a disease factor and a population number trigger to go along with it. Basically the juvenile and seniles can be affected by disease, but only once the total population reaches a 'trigger point' set by the user. I'm not sure how to do this, as if I put an extra clause... | -1 | 2016-06-11T14:38:59Z | 37,765,244 | <p>Inside your <code>while</code> loop just put the lines of code that account for the affecting of the disease inside an <code>if</code> block, otherwise do the usual population keep doing the normal population update during each iteration of the while loop, but keep them outside the <code>if</code> block.</p>
<pre><... | 1 | 2016-06-11T15:11:18Z | [
"python",
"if-statement",
"while-loop",
"counter",
"simultaneous"
] |
python selenium getting all text in ul class | 37,764,972 | <p>How can I get selenium to locate and click on each of these links in python, and copy the texts that pops up from it?</p>
<p>I'm looking to not do it via xpath because i'm still very new to it, but it you could give me some pointers how I can do it by the usual CSS Selectors, etc, that would be great! </p>
<pre><c... | -1 | 2016-06-11T14:40:21Z | 37,765,070 | <p>Oh, I solved it.. </p>
<pre><code>element = driver.find_element_by_id("keyDev-A")
element.click()
element2 = driver.find_element_by_class_name("content")
print(element2.text)
</code></pre>
<p>All I have to do now is to iterate <code>keyDev</code> from <code>A</code> to <code>F</code> :)</p>
| 0 | 2016-06-11T14:52:07Z | [
"python",
"selenium"
] |
Scraping data which loaded when you select something | 37,765,026 | <p>I need to scrape car makes and model. Now I can scrape car makes select option list but can't scrape car models select option list because it is loaded when you select car make.</p>
<p>Maybe you have any ideas how I could get car models select options list which is loaded when you select car make.</p>
<p>Here is m... | 1 | 2016-06-11T14:46:07Z | 37,765,766 | <p>You need to post data:</p>
<p><a href="http://i.stack.imgur.com/6bBdr.png" rel="nofollow"><img src="http://i.stack.imgur.com/6bBdr.png" alt="enter image description here"></a></p>
<p>The <em>parent_id</em> is the value in each option inside the <em>make_id</em> <em>select</em>:</p>
<pre><code>import requests
fro... | 1 | 2016-06-11T16:02:39Z | [
"python",
"beautifulsoup",
"python-requests"
] |
argmax with masked arrays | 37,765,118 | <p>I stumbled over a strange fact concerning masked unsigned integer arrays and <code>np.ma.argmax</code>.</p>
<p>Consider the following array:</p>
<pre><code>>>> marr = np.ma.array(np.array([[2,2,2], [3,3,3], [1,1,1]]), mask=False, dtype=np.uint16)
>>> marr
masked_array(data =
[[2 2 2]
[3 3 3]
[... | 0 | 2016-06-11T14:57:12Z | 37,765,607 | <p>Here's the code for <code>np.ma.argmax</code> (via <code>ipython</code> <code>??</code> magic) (version '1.11.0')</p>
<pre><code>Definition: np.ma.argmax(a, axis=None, fill_value=None)
Source:
def argmax(a, axis=None, fill_value=None):
"Function version of the eponymous method."
if fill_value is None:
... | 1 | 2016-06-11T15:46:48Z | [
"python",
"arrays",
"numpy"
] |
Assigning 2d array in vector of indices | 37,765,120 | <p>Given 2d array <code>k = np.zeros((M, N))</code> and list of indices in the range <code>0, 1 .., M-1</code> of size <code>N</code> called <code>places = np.random.random_integers(0, M-1, N)</code> how do I assign 1 in each column of <code>k</code> in the <code>places[i]</code> index where i is running index.
I would... | 1 | 2016-06-11T14:57:28Z | 37,765,390 | <pre><code>rslt = np.zeros((M, N))
for i, v in enumerate(places): rslt[v,i]=1
</code></pre>
<p>Full code:</p>
<pre><code>import numpy as np
N = 5
M=3
#places = np.random.random_integers(0, M-1, N)
places= 0, 0, 1, 1, 2
rslt = np.zeros((M, N))
for i, v in enumerate(places): rslt[v,i]=1
print(rslt)
Out [34]:
[[ 1. 1.... | 1 | 2016-06-11T15:24:40Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.