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 |
|---|---|---|---|---|---|---|---|---|---|
Python script hangs on cursor.execute() | 39,668,988 | <p><strong>I'm a newbie in Python</strong></p>
<p>I'm debugging an existing script which is as follows,</p>
<pre><code>print "Table name: %s " %table_name_r
print "Between: %s " % between
cursor = db.cursor()
print "Total Rows: %s " % cursor.rowcount
cursor.execute("""select contactid,li_url_clean,li_company,compli... | -1 | 2016-09-23T20:25:30Z | 39,669,484 | <p>You haven't executed the query yet, so the database doesn't know the amount of rows that will be in the result. See also <a href="https://docs.python.org/2/library/sqlite3.html#sqlite3.Cursor.rowcount" rel="nofollow">the docs on rowcount</a>.</p>
<p>It states:</p>
<blockquote>
<p>As required by the Python DB API... | 1 | 2016-09-23T21:00:42Z | [
"python",
"mysql"
] |
better way to write queries with 2 selection criteria | 39,669,082 | <p>I am writing a web app where database query comes from two selection boxes, one is about <code>sex</code> and the other is about <code>class_type</code>. In my code, I have a base query which has the following form</p>
<pre><code>q = User.query.with_entities(*(getattr(User, col) for col in cols))
</code></pre>
... | 1 | 2016-09-23T20:32:22Z | 39,671,464 | <p>You could do this:</p>
<pre><code>filters = {}
if sex != 'all':
filters['sex'] = sex
if class_type != 'all':
filters['class_type'] = class_type
rows = q.filter_by(**filters)
</code></pre>
<p>You would only need one condition per attribute, and an empty dictionary for <code>filters</code> would result in a ... | 1 | 2016-09-24T00:56:43Z | [
"python",
"sql",
"sqlalchemy",
"flask-sqlalchemy"
] |
Trying to create a sha256 key and hash in Elixir (converting from python code) | 39,669,113 | <p>I am in the middle of creating an Elixir project that uses Google Cloud Storage. Some of our customer requirements dictate that each customer utilize their own separate encryption keys.</p>
<p>I can create them using the Google code provided manually, however I was wondering about automating this (mostly out of my ... | 0 | 2016-09-23T20:34:58Z | 39,669,969 | <p>It seems that in elixir, you are hashing the base64 encoded key, while the original python implementation hashes the raw bytes of the key.</p>
<p>The following should work:</p>
<pre><code>key = :crypto.strong_rand_bytes(32)
base64_key = Base.encode64(key)
base64_hash = :sha256 |> :crypto.hash(key) |> Base.en... | 2 | 2016-09-23T21:43:03Z | [
"python",
"google-cloud-storage",
"elixir",
"sha256"
] |
Function not updating global variable | 39,669,122 | <p>I'm writing a program that simulates a game of Bunko for my compSci class, but I'm having issues getting the function <code>scoreCalc</code> to modify the global variable <code>playerScore</code>. The game pits a player against the computer, so I wanted to be able to use one function to determine the score and just ... | 0 | 2016-09-23T20:35:24Z | 39,669,157 | <p>If you pass <code>playerScore</code> as a parameter and then do operations on it inside a function, <em>the global variable <code>playerScore</code> won't be changed</em>. </p>
<p>Why? <em>Numbers in Python are <a href="http://stackoverflow.com/a/8059504/4354477">immutable</a>.</em> </p>
<p>Wait, what?? Yes, when ... | 4 | 2016-09-23T20:38:07Z | [
"python"
] |
Function not updating global variable | 39,669,122 | <p>I'm writing a program that simulates a game of Bunko for my compSci class, but I'm having issues getting the function <code>scoreCalc</code> to modify the global variable <code>playerScore</code>. The game pits a player against the computer, so I wanted to be able to use one function to determine the score and just ... | 0 | 2016-09-23T20:35:24Z | 39,669,526 | <p>You clearly know how to modify a global variable, which you did for sixCount. You probably used to do that with playerScore, but changed it when trying to make the function useful for calculating anybody's score (stated goal in the OP).</p>
<p>In order to make the function work like a function, it needs to be ... a... | 1 | 2016-09-23T21:04:23Z | [
"python"
] |
If there difference between `\A` vs `^` (caret) in regular expression? | 39,669,147 | <p>Python's <a href="https://docs.python.org/2/library/re.html" rel="nofollow"><code>re</code> module documentation</a> says:</p>
<blockquote>
<p><code>^</code>: (Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.</p>
<p><code>\A</code>: Matches only at t... | 2 | 2016-09-23T20:37:36Z | 39,669,293 | <p><code>\A</code> is unambiguous string start anchor. <code>^</code> can change its behavior depending on whether the <code>re.M</code> modifier is used or not.</p>
<p><em>When to use <code>\A</code> and when to use <code>^</code>?</em></p>
<p>When you want to match either start of a string <em>OR</em> a line, you u... | 1 | 2016-09-23T20:47:06Z | [
"python",
"regex",
"python-2.7"
] |
If there difference between `\A` vs `^` (caret) in regular expression? | 39,669,147 | <p>Python's <a href="https://docs.python.org/2/library/re.html" rel="nofollow"><code>re</code> module documentation</a> says:</p>
<blockquote>
<p><code>^</code>: (Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.</p>
<p><code>\A</code>: Matches only at t... | 2 | 2016-09-23T20:37:36Z | 39,669,301 | <p>Both of these match:</p>
<pre><code>re.search('^abc', 'abc')
re.search('\Aabc', 'abc')
</code></pre>
<p>This also matches:</p>
<pre><code>re.search('^abc', 'firstline\nabc', re.M)
</code></pre>
<p>This does not:</p>
<pre><code>re.search('\Aabc', 'firstline\nabc', re.M)
</code></pre>
| 2 | 2016-09-23T20:47:31Z | [
"python",
"regex",
"python-2.7"
] |
Python Pandas: Reuse stored means correctly to replace nan | 39,669,165 | <p>Over some data, I computed means columnwise.</p>
<p>Let's say the data looks like this</p>
<pre><code> A B C ... Z
0.1 0.2 0.15 ... 0.17
. . . .
. . . .
. . . .
</code></pre>
<p>I used the mean() function of DataFrame and as result I got</p>
<pre><code>A some_mean_A
B ... | 0 | 2016-09-23T20:38:48Z | 39,669,365 | <p><code>df.mean()</code> returns a Series. In that Series, values are the means of columns and the indices are the column names. It is a one-dimensional structure. However, if you read that file using <code>pd.read_csv</code>'s default parameters, it will read it as a DataFrame: one column for the column names, and an... | 2 | 2016-09-23T20:51:58Z | [
"python",
"python-3.x",
"pandas"
] |
heroku server 500 error after a git push it works locally though | 39,669,258 | <p>I did a git push and then all of a sudden my app responds with a server error. I have been trying to get my my scheduler to work it works fine locally. It gave me a problem but I fixed it using a git pull request. it was working fine locally and then all of sudden server error 500. I did heroku logs and got this res... | 0 | 2016-09-23T20:44:27Z | 39,686,505 | <p>Maybe your local Django version is earlier then in requirements.txt, because in Django 1.8 <a href="https://docs.djangoproject.com/en/1.10/releases/1.8/#django-core-context-processors" rel="nofollow">built-in template context processors have been moved to django.template.context_processors</a>.</p>
<p>Try this exam... | 0 | 2016-09-25T11:54:11Z | [
"python",
"django",
"git",
"heroku",
"deployment"
] |
pandas dataframe issue with special characters | 39,669,277 | <p>I am struggling with the following issue with pandas data frame
Python 2.7.12
pandas 0.18.1</p>
<pre><code>df = pd.read_csv(file_name, encoding='utf-16', header=0, index_col=False, error_bad_lines=False,
names=['Package_Name','Crash_Report_Date_And_Time','Crash_Report_Millis_Since_Epoch','Devic... | 1 | 2016-09-23T20:45:40Z | 39,712,081 | <p>So the solution was really simple. In Pandas 0.18 I had to specify the <code>lineterminator='n'</code></p>
<pre><code>df = pd.read_csv(file_name,lineterminator='\n', encoding='utf-16', delimiter=',', header=0, index_col=False, error_bad_lines=False,...
</code></pre>
<p>This simple flag fixed my issue. </p>
| 0 | 2016-09-26T20:46:07Z | [
"python",
"pandas"
] |
How do you get input value if value already exists as an attribute in Selenium? | 39,669,368 | <p>I am trying to get the value of a user input in selenium webdriver, however, the webdriver is returning the text from the 'value' attribute instead. Is this a bug in Selenium? How can I get what the user actually entered?</p>
<pre><code><input id="budget" name="budget" type="text" size="10" maxlength="10" class=... | 0 | 2016-09-23T20:52:33Z | 39,669,591 | <p>Try to execute JavaScript code:</p>
<pre><code>driver.execute_script("document.getElementById('id_value').value")
</code></pre>
| 0 | 2016-09-23T21:08:58Z | [
"python",
"selenium-webdriver"
] |
How do you get input value if value already exists as an attribute in Selenium? | 39,669,368 | <p>I am trying to get the value of a user input in selenium webdriver, however, the webdriver is returning the text from the 'value' attribute instead. Is this a bug in Selenium? How can I get what the user actually entered?</p>
<pre><code><input id="budget" name="budget" type="text" size="10" maxlength="10" class=... | 0 | 2016-09-23T20:52:33Z | 39,669,624 | <blockquote>
<p>Is this a bug in Selenium?</p>
</blockquote>
<p>No, this is not a bug, behaviour is absolutely correct. </p>
<p>Actually you're getting the attribute value from already found element instead of refreshed element where attribute value already stored with old value in the cache. That's why you're gett... | 0 | 2016-09-23T21:11:39Z | [
"python",
"selenium-webdriver"
] |
Python function gets stuck (no error) but I can't understand why | 39,669,380 | <p>The function does what I want it to, but when it's done it just sits there rather than continuing from where I called it and I can't figure out why. The code is:</p>
<pre><code>x = 9
y = 9
n = 10
ty = 1
tx = 1
while ty <= y:
while tx <= x:
vars()["p" + str(ty) + str(tx)] = 0
tx += 1
t... | 0 | 2016-09-23T20:53:32Z | 39,670,256 | <p>I wasn't able to work out what was happening (turns out if I left it for a few minutes it would actually finish though), instead, I realised that I didn't need to use recursion to achieve what I wanted (and I also realised the function didn't actually do what I want to do).</p>
<p>For anyone interested, I simplifie... | 0 | 2016-09-23T22:10:43Z | [
"python",
"python-3.x"
] |
Python function gets stuck (no error) but I can't understand why | 39,669,380 | <p>The function does what I want it to, but when it's done it just sits there rather than continuing from where I called it and I can't figure out why. The code is:</p>
<pre><code>x = 9
y = 9
n = 10
ty = 1
tx = 1
while ty <= y:
while tx <= x:
vars()["p" + str(ty) + str(tx)] = 0
tx += 1
t... | 0 | 2016-09-23T20:53:32Z | 39,670,720 | <p>If anyone is interested in what the original code did, I rearranged the conditionals to prune the tree of function calls:</p>
<pre><code>x = 9
y = 9
n = 10
ty = 1
tx = 1
while ty <= y:
while tx <= x:
vars()["p" + str(ty) + str(tx)] = 0
tx += 1
ty += 1
tx = 1
tn = 1
while tn <=... | 0 | 2016-09-23T23:02:09Z | [
"python",
"python-3.x"
] |
Python function gets stuck (no error) but I can't understand why | 39,669,380 | <p>The function does what I want it to, but when it's done it just sits there rather than continuing from where I called it and I can't figure out why. The code is:</p>
<pre><code>x = 9
y = 9
n = 10
ty = 1
tx = 1
while ty <= y:
while tx <= x:
vars()["p" + str(ty) + str(tx)] = 0
tx += 1
t... | 0 | 2016-09-23T20:53:32Z | 39,780,210 | <p>Note for people not going through the change history: This is based on the comments on other answers. UPDATE: Better version.</p>
<pre><code>import itertools
def permutations(on, total):
all_indices = range(total)
for indices in itertools.combinations(all_indices, on):
board = ['0'] * total
... | 0 | 2016-09-29T21:20:32Z | [
"python",
"python-3.x"
] |
How to remotely connect python tcp client and server? | 39,669,392 | <p>I have just written some python server and client using tcp protocol. I am using linux, and want to connect to a windows machine which isn't in my local network. How can i do that? I know it is something about NAT, but i can't find out how to do it properly. Could you please give me step by step guide? Thanks.</p>
| 0 | 2016-09-23T20:54:11Z | 39,670,628 | <p>Just use sockets? You need to ensure that the network the windows laptop is on is configured to forward a specified port to the laptop. (means it can be accessed externally) You can then use sockets to connect to the laptop on the port you designate. </p>
| 0 | 2016-09-23T22:51:22Z | [
"python",
"tcp",
"server",
"client"
] |
Python: multithreading complex objects | 39,669,463 | <pre><code>class Job(object):
def __init__(self, name):
self.name = name
self.depends = []
self.waitcount = 0
def work(self):
#does some work
def add_dependent(self, another_job)
self.depends.append(another_job)
self.waitcount += 1
</code></pre>
<p>so, wa... | 0 | 2016-09-23T20:58:44Z | 39,680,984 | <p>Here's a complete, executable program that appears to work fine. I expect you're mostly seeing "weird" behavior because, as I suggested in a comment, you're counting job successors instead of job predecessors. So I renamed things with "succ" and "pred" in their names to make that much clearer. <code>daemon</code>... | 1 | 2016-09-24T21:07:30Z | [
"python",
"multithreading"
] |
if statement value not changing in loop if called from another function in python | 39,669,489 | <p>there. I was creating a program and ran into a problem that baffles me and my understanding of basic code (or my understanding of my eyesight).</p>
<p>According to me this code should print out</p>
<blockquote>
<p>Test</p>
</blockquote>
<p>immediately as the program starts and then when ext() is called from Tim... | 0 | 2016-09-23T21:01:01Z | 39,669,610 | <p>You need to specify <code>loop</code> as a global variable. In <code>ext()</code> it thinks that you are defining a new variable called <code>loop</code> while you actually want to modify the global variable. So the correct code would be this one:</p>
<pre><code>from threading import Timer, Thread
from time import ... | 0 | 2016-09-23T21:10:42Z | [
"python",
"if-statement",
"timer",
"definition"
] |
if statement value not changing in loop if called from another function in python | 39,669,489 | <p>there. I was creating a program and ran into a problem that baffles me and my understanding of basic code (or my understanding of my eyesight).</p>
<p>According to me this code should print out</p>
<blockquote>
<p>Test</p>
</blockquote>
<p>immediately as the program starts and then when ext() is called from Tim... | 0 | 2016-09-23T21:01:01Z | 39,669,642 | <p>You have two problems... well, three really. First, <code>ext</code> is referencing a local variable called <code>loop</code> not the global. Second, you don't really start the thread because you called the function instead of passing in its reference. Third... you no longer sleep when <code>loop</code> is set so yo... | 0 | 2016-09-23T21:12:53Z | [
"python",
"if-statement",
"timer",
"definition"
] |
Python mock call_args_list unpacking tuples for assertion on arguments | 39,669,538 | <p>I'm having some trouble dealing with the nested tuple which <code>Mock.call_args_list</code> returns.</p>
<pre><code>def test_foo(self):
def foo(fn):
fn('PASS and some other stuff')
f = Mock()
foo(f)
foo(f)
foo(f)
for call in f.call_args_list:
for args in call:
... | 3 | 2016-09-23T21:05:12Z | 39,669,649 | <p>A nicer way might be to build up the expected calls your self then use a direct assertion:</p>
<pre><code>>>> from mock import call, Mock
>>> f = Mock()
>>> f('first call')
<Mock name='mock()' id='31270416'>
>>> f('second call')
<Mock name='mock()' id='31270416'>
>... | 3 | 2016-09-23T21:13:39Z | [
"python",
"unit-testing",
"python-unittest",
"python-unittest.mock"
] |
Python mock call_args_list unpacking tuples for assertion on arguments | 39,669,538 | <p>I'm having some trouble dealing with the nested tuple which <code>Mock.call_args_list</code> returns.</p>
<pre><code>def test_foo(self):
def foo(fn):
fn('PASS and some other stuff')
f = Mock()
foo(f)
foo(f)
foo(f)
for call in f.call_args_list:
for args in call:
... | 3 | 2016-09-23T21:05:12Z | 39,669,722 | <p>I think that many of the difficulties here are wrapped up in the treatment of the "call" object. It can be thought of as a tuple with 2 members <code>(args, kwargs)</code> and so it's frequently nice to unpack it:</p>
<pre><code>args, kwargs = call
</code></pre>
<p>Once it's unpacked, then you can make your asser... | 2 | 2016-09-23T21:20:48Z | [
"python",
"unit-testing",
"python-unittest",
"python-unittest.mock"
] |
Keep PyQt UI Responsive With Threads | 39,669,556 | <p>This is my first question here so please bear with me.</p>
<p>I have created a relatively complex PyQt program and am trying to implement threads so that when the program encounters a part of the program which is particularly CPU intensive, the GUI will remain refreshed and responsive throughout. Sadly though, I am... | 0 | 2016-09-23T21:06:26Z | 39,672,773 | <p>Here's a simple demo of threading in pyqt5. Qt has it's own threading class that works pretty well.</p>
<pre><code>from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import pyqtSignal
import sys
import time
class TheBoss(QtWidgets.QWidget):
def __init__(self, parent=None):
super(TheBoss, self... | 0 | 2016-09-24T05:09:16Z | [
"python",
"multithreading",
"user-interface",
"crash",
"python-multithreading"
] |
I want to inherit from Beautifulsoup Class to do the following tasks | 39,669,653 | <p>I am running on Python 3.5.1 with Beautifulsoup4.</p>
<p>I currently have this code: </p>
<pre><code>from bs4 import BeautifulSoup
import html5lib
class LinkFinder(BeautifulSoup):
def __init__(self):
super().__init__()
def handle_starttag(self, name, attrs):
print(name)
</code></pre>
<p>When I inst... | 0 | 2016-09-23T21:13:54Z | 39,670,412 | <p>Not sure why do you need to use <code>BeautifulSoup</code> in such an uncommon way. If you want to simply get the names of all the elements in the HTML tree recursively:</p>
<pre><code>from bs4 import BeautifulSoup
data = """<html><head><title>my name is good</title></head><body>... | 2 | 2016-09-23T22:28:32Z | [
"python",
"html",
"python-3.x",
"web-scraping",
"beautifulsoup"
] |
I want to inherit from Beautifulsoup Class to do the following tasks | 39,669,653 | <p>I am running on Python 3.5.1 with Beautifulsoup4.</p>
<p>I currently have this code: </p>
<pre><code>from bs4 import BeautifulSoup
import html5lib
class LinkFinder(BeautifulSoup):
def __init__(self):
super().__init__()
def handle_starttag(self, name, attrs):
print(name)
</code></pre>
<p>When I inst... | 0 | 2016-09-23T21:13:54Z | 39,671,790 | <p>If you want to go this way, change your implementation to accept the markup during initialization and <a href="https://github.com/JinnLynn/beautifulsoup/blob/f29f8d278462efb370168f2329b070fa51706013/bs4/__init__.py#L310" rel="nofollow"><code>handle_starttag</code></a> to grab all passed args:</p>
<pre><code>class L... | 1 | 2016-09-24T02:00:46Z | [
"python",
"html",
"python-3.x",
"web-scraping",
"beautifulsoup"
] |
Analyze data using python | 39,669,659 | <p>I have a csv file in the following format: </p>
<pre><code>30 1964 1 1
30 1962 3 1
30 1965 0 1
31 1959 2 1
31 1965 4 1
33 1958 10 1
33 1960 0 1
34 1959 0 2
34 1966 9 2
34 1958 30 1
34 1960 1 1
34 1961 10 1
34 1967 7 1
34 1960 0 1
35 1... | 0 | 2016-09-23T21:14:38Z | 39,670,402 | <p>I am not entirely sure whether I understood your logic clearly for determining the age with the maximum survival rate. Assuming that the age that has the heighest number of 1s have the heighest survival rate the following code is written</p>
<p>I have done the reading part a little differently as the data set acted... | 1 | 2016-09-23T22:27:14Z | [
"python",
"data-analysis"
] |
how to call a callback function after certain amount of time | 39,669,718 | <p>I'm using Twisted along with Txmongo lib.
In the following function, I want to invoke cancelTest() 5 secs later. But the code does not work. How can I make it work?</p>
<pre><code>from twisted.internet import task
def diverge(self, d):
if d == 'Wait':
self.flag = 1
# self.timeInit = time.time()... | 2 | 2016-09-23T21:20:19Z | 39,670,509 | <p>In general <code>reactor.callLater()</code> is the function you want. So if the function needs to be called 5 seconds later, your code would look like this:</p>
<pre><code>from twisted.internet import reactor
reactor.callLater(5, cancelTest)
</code></pre>
<p>One thing that is strange is that your <code>task.deferL... | 0 | 2016-09-23T22:38:10Z | [
"python",
"twisted"
] |
how to call a callback function after certain amount of time | 39,669,718 | <p>I'm using Twisted along with Txmongo lib.
In the following function, I want to invoke cancelTest() 5 secs later. But the code does not work. How can I make it work?</p>
<pre><code>from twisted.internet import task
def diverge(self, d):
if d == 'Wait':
self.flag = 1
# self.timeInit = time.time()... | 2 | 2016-09-23T21:20:19Z | 39,691,433 | <p>you're doing almost everything right; you just didn't get the Clock part correctly.</p>
<p><strong>twisted.internet.task.Clock</strong> is a deterministic implementation of IReactorTime, which is mostly used in unit/integration testing for getting a deterministic output from your code; you shouldn't use that in pro... | 0 | 2016-09-25T20:19:01Z | [
"python",
"twisted"
] |
Retrieve header of column if it has a certain value | 39,669,798 | <p>I have a csv file with headers in the following format:</p>
<p><code>column1</code>,<code>column2</code>,<code>column3</code></p>
<p><code>True</code>,<code>False</code>,<code>False</code></p>
<p><code>False</code>,<code>True</code>,<code>True</code></p>
<p>In python, I would like to print the column name if a v... | 0 | 2016-09-23T21:28:37Z | 39,670,121 | <p>This works:</p>
<pre><code>import csv
with open("my.csv", 'r') as f:
reader = csv.reader(f, skipinitialspace=True)
headers = next(reader)
# Start counting from 2 (Row #1 is headers)
for row_number, row in enumerate(reader, 2):
for column, val in enumerate(row): # On each column in the row
... | 1 | 2016-09-23T21:56:53Z | [
"python",
"python-3.x",
"csv"
] |
Python cannot read a file which contains a specific string | 39,669,822 | <p>I've written a function to remove certain words and characters for a string. The string in question is read into the program using a file. The program works fine except when a file, anywhere, contains the following anywhere in the body of the file.</p>
<blockquote>
<p>Security Update for Secure Boot (3177404) Thi... | 0 | 2016-09-23T21:30:00Z | 39,671,308 | <p>Your code may be hanging because your <code>.replace()</code> call is in a <code>while</code> loop. If, for any particular line of your <code>.csv</code> file, the <code>replacement[0]</code> string is a <em>substring</em> of its corresponding <code>replacement[1]</code>, and if either of them appears in your critic... | 1 | 2016-09-24T00:29:31Z | [
"python",
"file",
"python-3.x"
] |
Python Pandas: Retrieve id of data from a chunk | 39,669,824 | <p>The dataset is read chunk by chunk, because it is to big. The ids are the first column and I would like to store them in data structure like array. So far it is not working. It looks like this</p>
<pre><code>tf = pd.read_csv('data.csv', chunksize=chunksize)
for chunk in tf:
here I wanna store the ids chunk["Id"... | 0 | 2016-09-23T21:30:03Z | 39,669,850 | <p>IIUC you can do it this way:</p>
<pre><code>ids = pd.DataFrame()
tf = pd.read_csv('data.csv', chunksize=chunksize)
for chunk in tf:
ids = pd.concat([ids, chunk['Id']], ignore_index=True)
</code></pre>
<p>you can always access <code>ids</code> Series as NumPy array:</p>
<pre><code>ids.values
</code></pre>
| 1 | 2016-09-23T21:32:05Z | [
"python",
"python-3.x",
"pandas"
] |
Importing hidden function from Python module | 39,669,832 | <p>I'd like to import <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/k_means_.py#L626" rel="nofollow"><code>_init_centroids</code></a> function from <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/k_means_.py" rel="nofollow">scikit-learn/sklearn/clust... | 1 | 2016-09-23T21:30:58Z | 39,669,856 | <p>"Hidden" functions are a recommendation in Python, you can import them.</p>
<p>Try</p>
<pre><code>from scikit-learn.sklearn.cluster.k_means_ import _init_centroids
</code></pre>
| 2 | 2016-09-23T21:32:59Z | [
"python",
"scikit-learn",
"python-module"
] |
Importing hidden function from Python module | 39,669,832 | <p>I'd like to import <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/k_means_.py#L626" rel="nofollow"><code>_init_centroids</code></a> function from <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/k_means_.py" rel="nofollow">scikit-learn/sklearn/clust... | 1 | 2016-09-23T21:30:58Z | 39,669,903 | <p>In Python nothing is really private, so you import this function explicitly: </p>
<pre><code>from sklearn.cluster.k_means_ import _init_centroids
</code></pre>
| 1 | 2016-09-23T21:37:08Z | [
"python",
"scikit-learn",
"python-module"
] |
weird behaviour possibly from my knowledge or sqlalchemy or turbogears | 39,669,973 | <p>Suppose I got two models. Account and Question.</p>
<pre><code>class Account(DeclarativeBase):
__tablename__ = 'accounts'
id = Column(Integer, primary_key=True)
user_name = Column(Unicode(255), unique=True, nullable=False)
</code></pre>
<p>and my Question model be like:</p>
<pre><code>class Question(... | 0 | 2016-09-23T21:43:35Z | 39,670,094 | <p>From <a href="http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html" rel="nofollow">Relationship Loading Techniques</a>:</p>
<blockquote>
<p>By default, all inter-object relationships are <strong>lazy loading</strong>.</p>
</blockquote>
<p>In other words in its default configuration the relationshi... | 2 | 2016-09-23T21:54:09Z | [
"python",
"sqlalchemy",
"turbogears2"
] |
get desired element in numpy array of unequal row lengths, without using for loop | 39,670,027 | <p>i have the below numpy array:</p>
<pre><code>array([['apple','banana','orange'],
['car','bike','train','ship','plane','scooter'],
['red','purple']], dtype=object)
</code></pre>
<p>the individual rows in the array are of unequal length, I want to get the last element of each row. I can get this by running a f... | 0 | 2016-09-23T21:47:55Z | 39,670,059 | <p>using Pandas:</p>
<pre><code>In [87]: a
Out[87]: array([['apple', 'banana', 'orange'], ['car', 'bike', 'train', 'ship', 'plane', 'scooter'], ['red', 'purple']], dtype=object)
In [88]: df = pd.DataFrame(a)
In [93]: df
Out[93]:
0
0 [apple, banana, orange]
... | 1 | 2016-09-23T21:50:20Z | [
"python",
"arrays",
"pandas",
"numpy"
] |
get desired element in numpy array of unequal row lengths, without using for loop | 39,670,027 | <p>i have the below numpy array:</p>
<pre><code>array([['apple','banana','orange'],
['car','bike','train','ship','plane','scooter'],
['red','purple']], dtype=object)
</code></pre>
<p>the individual rows in the array are of unequal length, I want to get the last element of each row. I can get this by running a f... | 0 | 2016-09-23T21:47:55Z | 39,670,083 | <p>Using loop comprehension : <code>np.array([i[-1] for i in arr],dtype=object)</code> might just be an efficient and fast way, specially if the lists are long enough. But since you are asking for a non-loopy solution, here's a way using <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.htm... | 0 | 2016-09-23T21:52:55Z | [
"python",
"arrays",
"pandas",
"numpy"
] |
get desired element in numpy array of unequal row lengths, without using for loop | 39,670,027 | <p>i have the below numpy array:</p>
<pre><code>array([['apple','banana','orange'],
['car','bike','train','ship','plane','scooter'],
['red','purple']], dtype=object)
</code></pre>
<p>the individual rows in the array are of unequal length, I want to get the last element of each row. I can get this by running a f... | 0 | 2016-09-23T21:47:55Z | 39,670,407 | <p>Use a list of list if the fastest:</p>
<pre><code>import numpy as np
import random
items = ['apple','banana','orange', 'car','bike','train','ship','plane','scooter', 'red','purple']
a = [random.sample(items, random.randint(2, 10)) for _ in range(1000)]
b = np.array(a)
%timeit [x[-1] for x in a] # 62.1 µs
%timeit... | 1 | 2016-09-23T22:27:45Z | [
"python",
"arrays",
"pandas",
"numpy"
] |
Simple Python code for a starter | 39,670,090 | <p>I am trying to write a code that a user can input raw data that will pull up a numerical grade from a list, AND pair that numerical value with a letter grade. ie: the fourth grade in the list is 86, so it will PRINT 86 as well as the letter grade B.</p>
<p>Here is what I have so far:</p>
<hr>
<pre><code>grades = ... | 0 | 2016-09-23T21:53:16Z | 39,670,185 | <p>The problem that you are experiencing is <code>grades</code> contains only Strings. '1' is a String just like 'hello'. In python, Strings will not be equal to numbers, so comparing them will always be false. In addition, you are comparing the entirety of <code>grades</code> to a number, which will also evaluate to <... | 0 | 2016-09-23T22:02:51Z | [
"python",
"list"
] |
Simple Python code for a starter | 39,670,090 | <p>I am trying to write a code that a user can input raw data that will pull up a numerical grade from a list, AND pair that numerical value with a letter grade. ie: the fourth grade in the list is 86, so it will PRINT 86 as well as the letter grade B.</p>
<p>Here is what I have so far:</p>
<hr>
<pre><code>grades = ... | 0 | 2016-09-23T21:53:16Z | 39,670,186 | <p>You need to be careful with indentation, python is a language indented.</p>
<p>Try this:</p>
<pre><code># define lettergrade function
def lettergrade(grades):
if grades >=90:
return('A')
elif grades >=80 and grades <90:
return('B')
elif grades >=70 and grades <80:
... | 0 | 2016-09-23T22:03:03Z | [
"python",
"list"
] |
Simple Python code for a starter | 39,670,090 | <p>I am trying to write a code that a user can input raw data that will pull up a numerical grade from a list, AND pair that numerical value with a letter grade. ie: the fourth grade in the list is 86, so it will PRINT 86 as well as the letter grade B.</p>
<p>Here is what I have so far:</p>
<hr>
<pre><code>grades = ... | 0 | 2016-09-23T21:53:16Z | 39,670,248 | <p>I am confused here, If you want the user input why do you want a list of values then? all you have to do is to wait for user input and check which grade that input belongs too. Please comment If you want some changes!!</p>
<pre><code>x = raw_input("Enter Score: ")
score = float(x)
try:
if grades >=90:
... | 0 | 2016-09-23T22:09:34Z | [
"python",
"list"
] |
Simple Python code for a starter | 39,670,090 | <p>I am trying to write a code that a user can input raw data that will pull up a numerical grade from a list, AND pair that numerical value with a letter grade. ie: the fourth grade in the list is 86, so it will PRINT 86 as well as the letter grade B.</p>
<p>Here is what I have so far:</p>
<hr>
<pre><code>grades = ... | 0 | 2016-09-23T21:53:16Z | 39,670,276 | <p>This should achieve what you are looking for:</p>
<pre><code>grades = [62, 68, 93, 75, 89, 85]
def LetterGrade(grade):
if grade >= 90:
result = [grade, 'A']
elif grade >= 80 and grades < 90:
result = [grade, 'B']
elif grade >= 70 and grades < 80:
result = [grade... | 1 | 2016-09-23T22:12:28Z | [
"python",
"list"
] |
Cross-compiling greenlet for linux arm target | 39,670,135 | <p>I want to build greenlet to use on arm32 linux box. I have an ubuntu machine, with my gcc cross-compiler for the arm target. How do I build greenlet for my target from my ubuntu machine?</p>
| 0 | 2016-09-23T21:58:52Z | 39,798,938 | <p>Build gevent with dependencies on QEMU raspberry pi.</p>
| 0 | 2016-09-30T19:37:42Z | [
"python",
"arm"
] |
Why ImportError only with from? | 39,670,196 | <p>I have two packages, <code>a</code> and <code>b</code>. They are in the same directory, and <code>b</code> is dependent on <code>a</code> (but NOT the other way around). When I run <code>from . import a</code> in <code>b\some_package.py</code>, I get <code>ImportError: cannot import name a</code>. When I run <code>i... | 0 | 2016-09-23T22:04:18Z | 39,670,739 | <p>Package relative imports cannot refer to modules outside of the package. This is impossible in the general sense because it assumes that module-relative paths are always the same as file system directories. But modules can be installed in many places and can be inside archives such as eggs.</p>
<p>If you install pa... | 0 | 2016-09-23T23:04:33Z | [
"python",
"python-2.7",
"import",
"python-import"
] |
Ubuntu 16.04, Python 2.7 - ImportError: No module named enum | 39,670,197 | <p>First time using Ubuntu. I installed Anaconda 4.1.1 (Python 2.7). I was trying to use enum but I got an import error.</p>
<pre><code>import enum
Traceback (most recent call last):
File "<ipython-input-1-13948d6bb7b8>", line 1, in <module>
import enum
ImportError: No module named enum
</code></pre>
<p... | 1 | 2016-09-23T22:04:19Z | 39,670,215 | <p>Try <code>pip install enum34</code>. Enum is in the Python 3 stdlib. <code>enum34</code> is a backport.</p>
| 0 | 2016-09-23T22:06:17Z | [
"python",
"python-2.7",
"ubuntu",
"enums",
"ubuntu-16.04"
] |
How to generate unique loopback IPv6 address in Python? | 39,670,201 | <p>I need to be able to generate a unique IPv6 loopback address that I can use to for communication between processes within the host but not outside of it.</p>
<p>For IPv4 I found:</p>
<pre><code>>>> import random, ipaddress
>>> ipaddress.IPv4Address('127.0.0.1') + random.randrange(2**24 - 2)
IPv4A... | -1 | 2016-09-23T22:05:09Z | 39,670,442 | <p>IPv6 only has a single loopback address: <code>::1</code>. This is detailed in <a href="https://tools.ietf.org/html/rfc4291#section-2.5.3" rel="nofollow">RFC 4291, IP Version 6 Addressing Architecture, Section 2.5.3 The Loopback Address</a>:</p>
<blockquote>
<p>2.5.3. The Loopback Address</p>
<p>The unicast... | 1 | 2016-09-23T22:31:23Z | [
"python",
"ipv6"
] |
How to execute file in Python with arguments using import? | 39,670,233 | <p>I read that you can execute a file using <code>import</code> like this<br>
<strong>file.py</strong>:</p>
<pre><code>#!/usr/bin/env python
import file2
</code></pre>
<p><strong>file2.py</strong>:</p>
<pre><code>#!/usr/bin/env python
print "Hello World!"
</code></pre>
<p>And <strong>file.py</strong> will print <co... | 0 | 2016-09-23T22:07:25Z | 39,670,260 | <p>Import is not meant for execution of scripts. It is used in order to fetch or "import" functions, classes and attributes it contains.</p>
<p>If you wish to execute the script using a different interpreter, and give it arguments, you should use <a href="https://docs.python.org/3/library/subprocess.html#using-the-sub... | 1 | 2016-09-23T22:11:09Z | [
"python",
"python-2.7",
"python-import"
] |
How to execute file in Python with arguments using import? | 39,670,233 | <p>I read that you can execute a file using <code>import</code> like this<br>
<strong>file.py</strong>:</p>
<pre><code>#!/usr/bin/env python
import file2
</code></pre>
<p><strong>file2.py</strong>:</p>
<pre><code>#!/usr/bin/env python
print "Hello World!"
</code></pre>
<p>And <strong>file.py</strong> will print <co... | 0 | 2016-09-23T22:07:25Z | 39,670,283 | <p>Program arguments are available in <code>sys.argv</code> and can be used by any module. You could change file2.py to</p>
<pre><code>import sys
print "Here are my arguments", sys.argv
</code></pre>
<p>You can use the <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">argparse</a> module for mo... | 1 | 2016-09-23T22:14:12Z | [
"python",
"python-2.7",
"python-import"
] |
How to divide the below line in python? | 39,670,305 | <pre><code>comm_ip_addr_one, comm_ip_addr_two, mac_addr_one, mac_addr_two = compute_ip_address()
</code></pre>
<p>Currently it is more than 80 characters in a line.</p>
<p>When I gave the function name in next line it is invalid syntax.</p>
<p>Please suggest some ways i can split? ... | 0 | 2016-09-23T22:16:42Z | 39,670,338 | <p>Parens make the <code>tuple</code> unpacking explicit and allow you to split the variables being assigned to:</p>
<pre><code>(comm_ip_addr_one, comm_ip_addr_two,
mac_addr_one, mac_addr_two) = compute_ip_address()
</code></pre>
<p>Or you can use a line continuation character to allow the function call on the next... | 4 | 2016-09-23T22:20:23Z | [
"python",
"python-2.x",
"pep8"
] |
Efficiently select random matrix indices with given probabilities | 39,670,445 | <p>I have a numpy array of probabilities, such as:</p>
<pre><code>[[0.1, 0, 0.3,],
0.2, 0, 0.05],
0, 0.15, 0.2 ]]
</code></pre>
<p>I want to select an element (e.g., select some indices (i,j)) from this matrix, with probability weighted according to this matrix. The actual matrices this will be working w... | 0 | 2016-09-23T22:32:07Z | 39,670,513 | <p>You don't need a list of tuple to choice. Just use a <code>arange(n)</code> array, and convert it back to two dimension by <code>unravel_index()</code>.</p>
<pre><code>import numpy as np
p = np.array(
[[0.1, 0, 0.3,],
[0.2, 0, 0.05],
[0, 0.15, 0.2]]
)
p_flat = p.ravel()
ind = np.arange(len(p_flat))
re... | 3 | 2016-09-23T22:38:50Z | [
"python",
"numpy",
"matrix"
] |
While loop not printing inputs, quitting doesn't break out of while loop | 39,670,472 | <pre><code>#Initialization
count=0
name=0
#Input
while name!='-999':
count=count+1
name=input("Enter stock name OR -999 to Quit:")
shares=int(input("Enter number of shares:"))
pp=float(input("Enter purchase price:"))
sp=float(input("Enter selling price:"))
commission=float(input("Enter commissi... | -1 | 2016-09-23T22:33:56Z | 39,670,544 | <p>You should break out of the loop as soon as you get -999, instead of continuing the current iteration right until the end.</p>
<p>Secondly you could collect the items in a string and only output that after the loop:</p>
<pre><code>#Initialization
count=0
name=0
result = ''
#Input
while True:
count=count+1
... | 0 | 2016-09-23T22:42:15Z | [
"python",
"python-3.x",
"while-loop"
] |
While loop not printing inputs, quitting doesn't break out of while loop | 39,670,472 | <pre><code>#Initialization
count=0
name=0
#Input
while name!='-999':
count=count+1
name=input("Enter stock name OR -999 to Quit:")
shares=int(input("Enter number of shares:"))
pp=float(input("Enter purchase price:"))
sp=float(input("Enter selling price:"))
commission=float(input("Enter commissi... | -1 | 2016-09-23T22:33:56Z | 39,670,551 | <p>You are checking the value of <code>name</code> <em>before</em> you enter <code>-999</code>. Change your loop to this:</p>
<pre><code>while True:
x = input("Enter stock name OR -999 to Quit:")
if x == '-999':
break
count = count+1
name = x
shares = int(input("Enter number of shares:"))
... | 0 | 2016-09-23T22:42:48Z | [
"python",
"python-3.x",
"while-loop"
] |
While loop not printing inputs, quitting doesn't break out of while loop | 39,670,472 | <pre><code>#Initialization
count=0
name=0
#Input
while name!='-999':
count=count+1
name=input("Enter stock name OR -999 to Quit:")
shares=int(input("Enter number of shares:"))
pp=float(input("Enter purchase price:"))
sp=float(input("Enter selling price:"))
commission=float(input("Enter commissi... | -1 | 2016-09-23T22:33:56Z | 39,670,573 | <p>At the moment you break out of the loop, "-999" is the value stored as the name of the stock so that's what gets printed.The other values belong to the stock whose information you entered prior to entering the "-999."</p>
| 0 | 2016-09-23T22:44:52Z | [
"python",
"python-3.x",
"while-loop"
] |
How to start and stop a python program in C++? | 39,670,506 | <p>I am trying start another program in C++(windows).
The C++ needs to execute <code>starter.bat --debug --verbose</code>, in the <code>starter.bat</code>, it runs <code>%SF_HOME%\files\program-start.pyc %*</code>. After the program runs, how could I stop the <code>program-start.pyc</code> in C++? How to send <code>con... | 0 | 2016-09-23T22:37:34Z | 39,670,589 | <p>I'm rusty with Windows, however sending a CTRL-C to task is done using "kill", either the program (the UNIX world) or function in C (signal.h). You need the process ID of the Python task. Given how you started the Python program, it should write its PID to a file known to your C++ program, which would read that file... | -3 | 2016-09-23T22:46:21Z | [
"python",
"c++",
"batch-file"
] |
How to iterate through more than one nuke node class using nuke.allNodes() in a for loop? | 39,670,522 | <p>nuke.allNodes() can filter for one specific node class i.e. nuke.allNodes("Transform"). But how to do it if i want to have it filter more? Some work around?</p>
<p>perhaps place them in: var = []</p>
<p>But how do i access lets say motionblur value in a example (this dose not work):</p>
<pre><code>for i in var:
... | 0 | 2016-09-23T22:39:24Z | 39,735,914 | <p>I'm a little confused because in your code you have <code>i.knob("motionblur")</code>. The string in <code>.knob()</code> should be a name of a knob not the name of a node type. </p>
<p>I would suggest iterating through all the nodes and checking the type of each node. Then do whatever you need to on that type of n... | 0 | 2016-09-27T23:40:13Z | [
"python",
"nuke"
] |
Python - import instance of class from module | 39,670,621 | <p>I have created this class with <code>parse()</code>:</p>
<pre><code>class PitchforkSpider(scrapy.Spider):
name = "pitchfork_reissues"
allowed_domains = ["pitchfork.com"]
#creates objects for each URL listed here
start_urls = [
"http://pitchfork.com/reviews/best/reissues/?page=1",... | 0 | 2016-09-23T22:50:21Z | 39,670,705 | <p>You're calling <code>parse</code> with a string literal:</p>
<pre><code>reissues = pitchfork_reissues.parse('response')
</code></pre>
<p>I guess that should be a variable name? Like so:</p>
<pre><code>reissues = pitchfork_reissues.parse(response)
</code></pre>
<p><strong>Edit</strong></p>
<p>A Spider's <code>pa... | 0 | 2016-09-23T23:00:55Z | [
"python",
"class",
"scrapy-spider"
] |
lxml installation: error: command 'gcc' failed with exit status 1 | 39,670,672 | <p>I'm trying to install lxml, but I'm getting some sort of error.</p>
<pre><code># pip install lxml
DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6
Collecting lxml
Using cached lxml-3.6.4.tar.gz
Installing c... | 0 | 2016-09-23T22:57:45Z | 39,671,457 | <p>The solution was to run:</p>
<pre><code>yum install python-lxml
</code></pre>
| 0 | 2016-09-24T00:55:56Z | [
"python",
"pip",
"lxml"
] |
accessing sub directory in python | 39,670,673 | <p>I'm trying to access a folder that is in the current directory in which I am writing my code. the folder I am currently in is cs113</p>
<p>I've tried to do </p>
<pre><code>file2 = open("/cs113/studentstoires/Zorine.txt", "r)"
</code></pre>
<p>Would someone please tell me whey this doesn't work I've also tried to... | 0 | 2016-09-23T22:57:52Z | 39,670,749 | <p>If it's in the current directory, and <strong>it's the directory where you execute the script from</strong>, you should write the path without the <code>/</code> up front like so:</p>
<pre><code>file2 = open("studentstories/Zorine.txt", "r")
</code></pre>
| 0 | 2016-09-23T23:05:48Z | [
"python",
"file",
"text",
"directory"
] |
Modyfing pdf and returning it as a django response | 39,670,706 | <p>I need to modify the existing pdf and return it as a response in Django. So far, I have found this solution to modify the file:</p>
<pre><code>def some_view(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
response['Cont... | 0 | 2016-09-23T23:00:59Z | 39,671,735 | <p>You can write the output PDF to the <code>response</code> object. So instead of this:</p>
<pre><code>response.write(output)
</code></pre>
<p>do this:</p>
<pre><code>output.write(response)
</code></pre>
<p>This will write the contents of the PDF to the response instead of the string version of the <code>output</c... | 0 | 2016-09-24T01:49:43Z | [
"python",
"django",
"pdf"
] |
Pygame drawings only appear once I exit window | 39,670,807 | <p>I've created a rect, using Pygame display but it only appears
in the Pygame window when I exit the window. </p>
<p>Have I done something wrong with my game loop?
I'm trying to set keydown events but it's not
registering in the game loop. Maybe it's because
the Pygame window only appears after I exit?</p>
| -3 | 2016-09-23T23:12:07Z | 39,672,723 | <p>Got it.
I had incorrect indentation in my while loop.</p>
<p>However, when I run print(event) Python shows KEYDOWN but my rect won't move.</p>
<p>Here is a bit of my code:</p>
<pre><code>gameDisplay=pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('SssSss')
lead_x = 300
lead_y = 300
gameDispl... | -1 | 2016-09-24T05:03:09Z | [
"python",
"pygame",
"keydown"
] |
How to search for a pattern which is variable length 8 alphanumeric in python 2.7 from content type HTML/Text (in Gmail) | 39,670,899 | <p>I'm new to python. I'm trying to find a pattern from the Inbox of gmail. Able to fetch the gmail content in html format and not as plain text. Also, I'm not able to identify the pattern of the temporary password (which I need to fetch). the password is of length 8 and is randomly picked from @#$-_!0-9a-zA-Z The pass... | 0 | 2016-09-23T23:23:59Z | 39,671,159 | <p>You need a capturing group inside your regex, they are declared with parenthesis :</p>
<pre><code>pswrd = re.findall(r'<span style=3D"font-size:28px">+(.*)</span>', str(body), re.I|re.M)
</code></pre>
<p>To make this more accurate, instead of capturing everything with <code>.*</code> you can also make ... | 1 | 2016-09-24T00:03:56Z | [
"python",
"html"
] |
Random sampling with Hypothesis | 39,670,903 | <p>In Hypothesis, there is an <a href="http://hypothesis.readthedocs.io/en/latest/data.html#choices" rel="nofollow">corresponding <code>sampled_from()</code> strategy</a> to <a href="https://docs.python.org/3/library/random.html#random.choice" rel="nofollow"><code>random.choice()</code></a>:</p>
<pre><code>In [1]: fro... | 1 | 2016-09-23T23:24:35Z | 39,672,025 | <p>It feels like this should be possible with the <code>lists</code> strategy, but I couldn't make it work. By aping the <a href="https://github.com/HypothesisWorks/hypothesis-python/blob/3.5.1/src/hypothesis/strategies.py#L400-L418" rel="nofollow"><code>sampled_from</code></a> code, I was able to make something that s... | 1 | 2016-09-24T02:55:09Z | [
"python",
"unit-testing",
"testing",
"random",
"python-hypothesis"
] |
Random sampling with Hypothesis | 39,670,903 | <p>In Hypothesis, there is an <a href="http://hypothesis.readthedocs.io/en/latest/data.html#choices" rel="nofollow">corresponding <code>sampled_from()</code> strategy</a> to <a href="https://docs.python.org/3/library/random.html#random.choice" rel="nofollow"><code>random.choice()</code></a>:</p>
<pre><code>In [1]: fro... | 1 | 2016-09-23T23:24:35Z | 39,687,646 | <p>You could do:</p>
<pre><code>permutations(elements).map(lambda x: x[:n])
</code></pre>
| 1 | 2016-09-25T13:59:18Z | [
"python",
"unit-testing",
"testing",
"random",
"python-hypothesis"
] |
data type error while saving file to csv in python | 39,670,912 | <p>I am simply trying to save data to a csv file in python using numpy.</p>
<p>This is what I am doing:</p>
<pre><code>np.savetxt('data.csv', array, delimiter=',', fmt='%.4f')
</code></pre>
<p>however I am getting a following error </p>
<pre><code>Mismatch between array dtype ('<U1') and format specifier ('%.4f'... | 0 | 2016-09-23T23:26:11Z | 39,671,106 | <p>The <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html" rel="nofollow"><code>dtype</code></a> of an np.array is its data type. In this case, <code>'<U1'</code> stands for unsigned integer data of width 1 byte, aka an <code>unsigned char</code> in c-style languages. This being integral, ... | 0 | 2016-09-23T23:56:00Z | [
"python",
"csv",
"numpy"
] |
Installation of OpenCV in Ubuntu 14.04 | 39,670,940 | <p>I built OpenCV from Source but I can't manage to use it. Every time I try to even load an image with the next code I get <code>No module named cv2.cv</code>. Why is that happening? How can I fix it?</p>
<pre><code>from cv2.cv import *
img = LoadImage("/home/User/Desktop/Image.png")
NamedWindow("opencv")
ShowImage(... | 2 | 2016-09-23T23:30:49Z | 39,671,531 | <p>You've likely installed opencv 3, which doesn't have the <code>cv2.cv</code> module. It's all in <code>cv2</code> now. </p>
<p>To verify run this in a python interpreter </p>
<pre><code>import cv2
print cv2.__version__
</code></pre>
<p>Anything like <code>3.0.0</code> or <code>3.1.0</code> means that the <code>c... | 1 | 2016-09-24T01:07:57Z | [
"python",
"opencv"
] |
Installation of OpenCV in Ubuntu 14.04 | 39,670,940 | <p>I built OpenCV from Source but I can't manage to use it. Every time I try to even load an image with the next code I get <code>No module named cv2.cv</code>. Why is that happening? How can I fix it?</p>
<pre><code>from cv2.cv import *
img = LoadImage("/home/User/Desktop/Image.png")
NamedWindow("opencv")
ShowImage(... | 2 | 2016-09-23T23:30:49Z | 39,677,259 | <p>Presumable you did:</p>
<pre><code>git clone [email protected]:opencv/opencv.git
mkdir build; cd build
cmake ../opencv && make && sudo make install
</code></pre>
<p>But if you do this:</p>
<pre><code>cd opencv
git describe
</code></pre>
<p>You will get something like</p>
<pre><code>3.1.0-1374-g7f14... | 0 | 2016-09-24T14:09:36Z | [
"python",
"opencv"
] |
Installation of OpenCV in Ubuntu 14.04 | 39,670,940 | <p>I built OpenCV from Source but I can't manage to use it. Every time I try to even load an image with the next code I get <code>No module named cv2.cv</code>. Why is that happening? How can I fix it?</p>
<pre><code>from cv2.cv import *
img = LoadImage("/home/User/Desktop/Image.png")
NamedWindow("opencv")
ShowImage(... | 2 | 2016-09-23T23:30:49Z | 39,693,262 | <p>I found the solution to my problem. I had to install <code>python-opencv</code> as follows:</p>
<pre><code>sudo apt-get install python-opencv
</code></pre>
<p>After that OpenCV works fine.</p>
| 2 | 2016-09-26T00:45:00Z | [
"python",
"opencv"
] |
Index into a Python iterator | 39,671,167 | <p>I have an iterator <code>iterator</code> and a list of indices <code>indices</code> (repeats possible) and I want to extract just those elements from my iterator. At the moment I'm doing</p>
<pre><code>indices = sorted(indices)
deltas = [indices[0]] + [indices[i+1] - indices[i] for i in range(len(indices) - 1)]
out... | 1 | 2016-09-24T00:05:10Z | 39,671,316 | <p>If memory isn't a constraint, I would just find the max index and prepopulate an array of iterator values up to that max index. You're going to have to compute the intermediate values anyway, so you really don't gain anything by computing the deltas.</p>
<pre><code>max_index = max(indices)
data = [v for v in itert... | 0 | 2016-09-24T00:31:05Z | [
"python",
"iterator",
"itertools"
] |
Index into a Python iterator | 39,671,167 | <p>I have an iterator <code>iterator</code> and a list of indices <code>indices</code> (repeats possible) and I want to extract just those elements from my iterator. At the moment I'm doing</p>
<pre><code>indices = sorted(indices)
deltas = [indices[0]] + [indices[i+1] - indices[i] for i in range(len(indices) - 1)]
out... | 1 | 2016-09-24T00:05:10Z | 39,671,379 | <p>You definitely don't need the double loop as you can do this with a single loop and without creating deltas but the check code becomes more complicated:</p>
<pre><code>it = iter(sorted(indices))
index = next(it)
for i, datum in enumerate(iterator):
if i != index:
continue
output.append(datum)
tr... | 0 | 2016-09-24T00:42:57Z | [
"python",
"iterator",
"itertools"
] |
How can I specify a subset of a numpy matrix for placement of smaller matrix? | 39,671,174 | <p>I have an image pyramid with a down sample rate of 2. That is, the bottom of my pyramid is a an image of shape <code>(256, 256)</code>, where the next level is <code>(128, 128)</code>, etc.</p>
<p>My goal is to display this pyramid into a single image. The first image is placed on the left. The second is placed in ... | 0 | 2016-09-24T00:05:50Z | 39,671,388 | <p>Here is an example.</p>
<p>Create a pyramid first:</p>
<pre><code>import numpy as np
import pylab as pl
import cv2
img = cv2.imread("earth.jpg")[:, :, ::-1]
size = 512
imgs = []
while size >= 2:
imgs.append(cv2.resize(img, (size, size)))
size //= 2
</code></pre>
<p>And here is the code to merge the i... | 1 | 2016-09-24T00:44:52Z | [
"python",
"numpy",
"image-processing"
] |
How to find an html element using Beautiful Soup and regex strings | 39,671,175 | <p>I am trying to find the following <code><li></code> element in an html document using python 3, beautiful soup and regex strings.</p>
<pre><code><li style="text-indent:0pt; margin-top:0pt; margin-bottom:0pt;" value="394">KEANE J.
The plaintiff is a Sri Lankan national of Tamil ethnicity. While he was a... | 1 | 2016-09-24T00:05:59Z | 39,676,625 | <blockquote>
<p>it has something to do with the element present?</p>
</blockquote>
<p>Absolutely, in this case, aside from the text node, the <code>li</code> element has other children. This is documented in the <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#string" rel="nofollow"><code>.string</co... | 1 | 2016-09-24T13:02:57Z | [
"python",
"html",
"regex",
"beautifulsoup"
] |
Use {% with %} tag in Django HTML template | 39,671,265 | <p>I have a list of areas like this : </p>
<pre><code>areas = ['Anaheim', 'Westminster', 'Brea'...]
</code></pre>
<p>I would like to display them in HTML as:</p>
<pre><code><option value="Anaheim(Orange)">Anaheim</option>
<option value="Westminster(Orange)">Westminster</option>
<option va... | 1 | 2016-09-24T00:20:30Z | 39,671,325 | <p>You could use <code>extends</code> instead of <code>with</code>:</p>
<pre><code>{% extends area|add:"(orange)" %}
</code></pre>
| 1 | 2016-09-24T00:32:32Z | [
"python",
"django-templates"
] |
Use {% with %} tag in Django HTML template | 39,671,265 | <p>I have a list of areas like this : </p>
<pre><code>areas = ['Anaheim', 'Westminster', 'Brea'...]
</code></pre>
<p>I would like to display them in HTML as:</p>
<pre><code><option value="Anaheim(Orange)">Anaheim</option>
<option value="Westminster(Orange)">Westminster</option>
<option va... | 1 | 2016-09-24T00:20:30Z | 39,671,338 | <p>Maybe if you try only put the text next to the template variable like:</p>
<pre><code>{%for area in areas%}
<option value="{{area}}(Orange)">{{area}}</option>
{%endfor%}
</code></pre>
<p>I don't know why you try but is the same for me. </p>
| 2 | 2016-09-24T00:34:17Z | [
"python",
"django-templates"
] |
Subtracting the rows of a column from the preceding rows in a python pandas dataframe | 39,671,322 | <p>I have a .dat file which takes thousands of rows in a column (say, the column is time, t), now I want to find the interval between the rows in the column, that means subtracting the value of second row from first row, and so on.. (to find dt). Then I wish to make a new column with those interval values and plot it ... | 0 | 2016-09-24T00:31:52Z | 39,673,856 | <p>One easy way to perform an operation involving values from different rows is simply to copy the required values one the same row and then apply a simple row-wise operation. </p>
<p>For instance, in your example, we'd have a dataframe with one <code>time</code> column and some other data, like so: </p>
<pre><code>i... | 1 | 2016-09-24T07:41:27Z | [
"python",
"mysql",
"pandas",
"data-manipulation"
] |
Classes, Objects, Inheritance? | 39,671,340 | <p>I'm supposed to create three classes: a parent, and child 1 and child 2.<br>
Child 1 and 2 are supposed to inherit from the Parent class.
So I believe I've done that. </p>
<pre><code>class Parent:
"""Parent Object"""
def __init__(self):
self.greeting = "Hi I'm a Parent Object!"
class ChildA(Pare... | 0 | 2016-09-24T00:35:17Z | 39,671,494 | <pre><code>class Parent(object):
def __init__(self):
self.greeting = "Hi I am a parent"
def __str__(self):
return self.greeting
class Child(Parent):
def __init__(self):
super(Child, self).__init__()
self.greeting = "Hi I am Child"
def __str__(self):
return se... | 0 | 2016-09-24T01:02:15Z | [
"python",
"class",
"object",
"inheritance"
] |
Classes, Objects, Inheritance? | 39,671,340 | <p>I'm supposed to create three classes: a parent, and child 1 and child 2.<br>
Child 1 and 2 are supposed to inherit from the Parent class.
So I believe I've done that. </p>
<pre><code>class Parent:
"""Parent Object"""
def __init__(self):
self.greeting = "Hi I'm a Parent Object!"
class ChildA(Pare... | 0 | 2016-09-24T00:35:17Z | 39,671,496 | <blockquote>
<p>Child 1 and 2 are supposed to inherit from the Parent class. So I believe I've done that</p>
</blockquote>
<p>Yes, in the first code, you have, but not in the second code. </p>
<blockquote>
<p>I have to write a parent object and child 1 and 2 objects that will print out their respective strings</p... | 1 | 2016-09-24T01:02:39Z | [
"python",
"class",
"object",
"inheritance"
] |
Python: AttributeError: 'int' object has no attribute 'final_stat | 39,671,345 | <p>I am stuck in a program. I can't post only the part of the code with error because it is dependent on the rest of the code. So, I have posted the complete code in the link below. Just look at like no. 113 and 114. When I am using <code>fs = fsa.final_state</code> it is giving me the error: <code>AttributeError: 'int... | 0 | 2016-09-24T00:36:30Z | 39,671,422 | <p>I've looked through your code. On this line here:</p>
<pre><code>print("'%s'\t%s" % (input, NDRecognize(input, days)))
</code></pre>
<p>Your passing the parameter <code>days</code> to <code>NDRecognize</code>. But when I do <code>print(type(days))</code> I get <code>int</code>. However the <code>days</code> parame... | 0 | 2016-09-24T00:49:20Z | [
"python",
"class",
"object"
] |
Python Spin Boxes are copying each other and I don't see why? | 39,671,392 | <p>I am writing a code to create a time calendar, and for some reason the starting and ending time dials are mirroring each other. I have looked over everything, but I can't see any reason why the code would do such a thing. </p>
<p>Here is the code?</p>
<pre><code>from Tkinter import *
import math
Master = Tk()
def... | 0 | 2016-09-24T00:45:48Z | 39,671,973 | <p>The answer is that <code>Spinbox</code> has no <code>text</code> configuration parameter: It has <code>textvariable</code>, for which it's accepting <code>text</code> as an abbreviation. This means you have two independent Spinbox widgets both using the <code>textvariable</code> of <code>Hour</code> and two indepe... | 1 | 2016-09-24T02:44:40Z | [
"python",
"tkinter"
] |
Way to loop over Counter by number of times present? | 39,671,397 | <p>I am using collections.Counter and I am trying to loop over the elements. However if I have <code>t=Counter("AbaCaBA")</code> and use a for loop to print each element, it would only print one of each letter:</p>
<pre><code> for i in t:
print(i)
</code></pre>
<p>would print:</p>
<pre><code> a
C
... | 0 | 2016-09-24T00:46:29Z | 39,671,440 | <p>When you iterate over a <code>Counter</code> you are iterating over the keys. In order to get the counts at the same time you could do something like:</p>
<pre><code>for i, count in t.items():
print('{} {}s'.format(count, i))
</code></pre>
| 1 | 2016-09-24T00:52:34Z | [
"python"
] |
Way to loop over Counter by number of times present? | 39,671,397 | <p>I am using collections.Counter and I am trying to loop over the elements. However if I have <code>t=Counter("AbaCaBA")</code> and use a for loop to print each element, it would only print one of each letter:</p>
<pre><code> for i in t:
print(i)
</code></pre>
<p>would print:</p>
<pre><code> a
C
... | 0 | 2016-09-24T00:46:29Z | 39,671,534 | <p>Discovered the elements() method shortly after posting this, here: <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow">https://docs.python.org/3/library/collections.html#collections.Counter</a></p>
<p>It returns an iterator that repeats each element as many times as it is... | 1 | 2016-09-24T01:08:45Z | [
"python"
] |
Error scraping friend list from Twitter user w/ api.lookup_users: Too many terms specified in query | 39,671,406 | <p>The code below was provided to another user who was scraping the "friends" (not followers) list of a specific Twitter user. For some reason, I get an error when using "api.lookup_users". The error states "Too many terms specified in query". Ideally, I would like to scrape the followers and output a csv with the scre... | 0 | 2016-09-24T00:47:56Z | 39,676,698 | <p>From the error you get, it seems that you are putting too many ids at once in the api.lookup_users request. Try splitting you list of ids in smaller parts and make a request for each part. </p>
<pre><code>import time
import tweepy
import csv
#Twitter API credentials
consumer_key = ""
consumer_secret = ""
access_ke... | 0 | 2016-09-24T13:12:05Z | [
"python",
"tweepy"
] |
Python class initialization - attributes memory | 39,671,455 | <p>So I was writing a program in Python, which would take all my university classes (from csv) and print info about them. I've wrote a simple class <code>Subject</code> to manage everything better. In my uni there are classes in even weeks, odd weeks, and every-week classes, and I have lectures, exercises and laborator... | 1 | 2016-09-24T00:55:20Z | 39,671,467 | <p>You need to declare the attributes inside the <code>__init__</code> method. Here's an example </p>
<pre><code>class Subject:
def __init__(self, name, number, type):
self.number = number
self.name = name
self.dummyData = []
self.even = {}
self.odd = {}
self.all = {}
... | 0 | 2016-09-24T00:57:22Z | [
"python",
"class",
"initialization"
] |
What is "|="statement mean in python? | 39,671,474 | <p>what is "|="statement mean? This Code is just creat maze, and this is my first time to see this |= statement
i'm stack in here please help me</p>
<pre><code>width = 10
height = 8
grid = ["23" * 89 for i in xrange(height)]
N, S, E, W = 1, 2, 4, 8
HORIZONTAL, VERTICAL = 0, 1
def divide(grid, mx, my, ax, ay):
dx... | -1 | 2016-09-24T00:59:01Z | 39,671,518 | <p>The <code>|</code> symbol, and by extension <code>|=</code> is a bitwise OR. This applies OR logic to the underlying bits. For example:</p>
<pre><code>00001001
00011000
-------- |
00011001
</code></pre>
<p>So <code>9 | 24 = 25</code></p>
| 1 | 2016-09-24T01:06:47Z | [
"python"
] |
assign output of help to a variable instead of stdout in python | 39,671,504 | <p>I want to do something like this in the python interpreter.</p>
<pre><code>myhelp = help(myclass)
</code></pre>
<p>but the output goes to stdout. Is it possible to assign it to a variable?</p>
<p>Thanks!</p>
| 3 | 2016-09-24T01:04:21Z | 39,671,543 | <p>You can capture stdout while <code>help(myclass)</code> runs:</p>
<pre><code>from cStringIO import StringIO
import sys
stdout = sys.stdout
buffer = StringIO()
sys.stdout = buffer
help(myclass)
sys.stdout = stdout
myhelp = buffer.getvalue()
</code></pre>
| 4 | 2016-09-24T01:09:51Z | [
"python"
] |
Getting the first item for a tuple for eaching a row in a list in pyspark | 39,671,521 | <p>I'm a bit new to Spark and I am trying to do a simple mapping.<br>
My data is like the following:</p>
<pre><code>RDD((0, list(tuples)), ..., (19, list(tuples))
</code></pre>
<p>What I want to do is grabbing the first item in each tuple, so ultimately something like this: </p>
<pre><code>RDD((0, list(first item of... | 0 | 2016-09-24T01:07:00Z | 39,671,588 | <p>Something like this? </p>
<p><code>kv</code> here meaning "key-value" and mapping <a href="https://docs.python.org/3/library/operator.html#operator.itemgetter" rel="nofollow"><code>itemgetter</code></a> over the values. So, <code>map</code> within a <code>map</code> :-)</p>
<pre><code>from operator import itemgett... | 0 | 2016-09-24T01:18:23Z | [
"python",
"apache-spark",
"pyspark"
] |
Getting the first item for a tuple for eaching a row in a list in pyspark | 39,671,521 | <p>I'm a bit new to Spark and I am trying to do a simple mapping.<br>
My data is like the following:</p>
<pre><code>RDD((0, list(tuples)), ..., (19, list(tuples))
</code></pre>
<p>What I want to do is grabbing the first item in each tuple, so ultimately something like this: </p>
<pre><code>RDD((0, list(first item of... | 0 | 2016-09-24T01:07:00Z | 39,671,590 | <p>You can use <code>mapValues</code> to convert the list of tuples to a list of tuple[0]:</p>
<pre><code>rdd.mapValues(lambda x: [t[0] for t in x])
</code></pre>
| 1 | 2016-09-24T01:18:31Z | [
"python",
"apache-spark",
"pyspark"
] |
flask redirect "XMLHttpRequest cannot load..." error localhost | 39,671,533 | <p>Running flask locally, trying to call:</p>
<pre><code>@app.route('/foo_route', methods=['POST'])
@cross_origin(origin='*')
def foo():
return redirect("https://www.google.com/")
</code></pre>
<p>And I get the following error:</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="https://www.google.com/" re... | 0 | 2016-09-24T01:08:10Z | 39,672,103 | <p>I was having this same problem too! It is not a Chrome bug, it is built into chrome for security. (Cross Origin Resource Sharing) is a header that has to be present in the apache <code>httpd.conf or apache.conf or .htaccess</code> configuration file. If you are on NGINX, you have to edit the <code>defaults.conf or n... | 0 | 2016-09-24T03:12:51Z | [
"python",
"flask",
"flask-cors"
] |
flask redirect "XMLHttpRequest cannot load..." error localhost | 39,671,533 | <p>Running flask locally, trying to call:</p>
<pre><code>@app.route('/foo_route', methods=['POST'])
@cross_origin(origin='*')
def foo():
return redirect("https://www.google.com/")
</code></pre>
<p>And I get the following error:</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="https://www.google.com/" re... | 0 | 2016-09-24T01:08:10Z | 39,682,129 | <p>What I decided to do was to pass the url to the client and then have the client redirect.</p>
<pre><code>@app.route('/foo_route', methods=['POST'])
@cross_origin(origin='*')
def foo():
return "https://www.google.com/"
</code></pre>
<p>Then on the client (javascript):</p>
<pre><code>window.location.href = serv... | 0 | 2016-09-25T00:04:46Z | [
"python",
"flask",
"flask-cors"
] |
Count how many times a variable is called | 39,671,587 | <p>I want to add something that will count how many times a variable is used (like variable <code>c</code>) and output in number of times variable <code>c</code> was used. What functions can I use? Here's the code:</p>
<pre><code>#! /usr/bin/python
question = raw_input
y = "Blah"
c = "Blahblahb"
print "Is bacon awe... | 0 | 2016-09-24T01:17:57Z | 39,671,624 | <p>If I'm understanding your question correctly, you can try this:</p>
<pre><code>question = raw_input
y = "Blah"
c = "Blahblahb"
y_counter = 0
c_counter = 0
print "Is bacon awesome"
if question() = "Yes":
print y
y_counter = y_counter + 1
else:
print c
c_counter = c_counter + 1
print "Blah"
if ques... | 0 | 2016-09-24T01:26:07Z | [
"python",
"variables",
"counting"
] |
Count how many times a variable is called | 39,671,587 | <p>I want to add something that will count how many times a variable is used (like variable <code>c</code>) and output in number of times variable <code>c</code> was used. What functions can I use? Here's the code:</p>
<pre><code>#! /usr/bin/python
question = raw_input
y = "Blah"
c = "Blahblahb"
print "Is bacon awe... | 0 | 2016-09-24T01:17:57Z | 39,671,625 | <p>You could have a counter variable. Lets call it 'count'. Every time you print c, you increment count by 1. I've pasted the code below. You can print the count variable in the end</p>
<pre><code>question = raw_input
y = "Blah"
c = "Blahblahb"
count=0
print "Is bacon awesome"
if question() == "Yes":
print y
els... | 0 | 2016-09-24T01:26:11Z | [
"python",
"variables",
"counting"
] |
Count how many times a variable is called | 39,671,587 | <p>I want to add something that will count how many times a variable is used (like variable <code>c</code>) and output in number of times variable <code>c</code> was used. What functions can I use? Here's the code:</p>
<pre><code>#! /usr/bin/python
question = raw_input
y = "Blah"
c = "Blahblahb"
print "Is bacon awe... | 0 | 2016-09-24T01:17:57Z | 39,671,631 | <p>You could do this simply enough using an incrementing variable.</p>
<pre><code>counter = 0
# Event you want to track
counter += 1
</code></pre>
<p>Your Python 2.7 code, with a counter:</p>
<pre><code>question = raw_input
y = "Blah"
c = "Blahblahb"
counter = 0
print "Is bacon awesome"
if question() = "Yes":
... | 0 | 2016-09-24T01:26:44Z | [
"python",
"variables",
"counting"
] |
Count how many times a variable is called | 39,671,587 | <p>I want to add something that will count how many times a variable is used (like variable <code>c</code>) and output in number of times variable <code>c</code> was used. What functions can I use? Here's the code:</p>
<pre><code>#! /usr/bin/python
question = raw_input
y = "Blah"
c = "Blahblahb"
print "Is bacon awe... | 0 | 2016-09-24T01:17:57Z | 39,671,869 | <p>You will have to increment a counter and there a many ways to do that. One way is to encapsulate in a <code>class</code> and use <code>property</code>, but this uses more advanced features of python:</p>
<pre><code>class A(object):
def __init__(self):
self.y_count = 0
@property
def y(self):
... | 0 | 2016-09-24T02:18:29Z | [
"python",
"variables",
"counting"
] |
Is my understanding of Hashsets correct?(Python) | 39,671,661 | <p>I'm teaching myself data structures through this python book and I'd appreciate if someone can correct me if I'm wrong since a hash set seems to be extremely similar to a hash map.</p>
<p><strong>Implementation:</strong>
A Hashset is a list [] or array where each index points to the head of a linkedlist</p>
<p>So ... | 0 | 2016-09-24T01:34:25Z | 39,671,749 | <p>For your first question - why is the average time complexity of a lookup O(1)? - this statement is in general only true if you have a good hash function. An ideal hash function is one that causes a nice spread on its elements. In particular, hash functions are usually chosen so that the probability that any two elem... | 0 | 2016-09-24T01:52:48Z | [
"python",
"algorithm",
"data-structures"
] |
Is my understanding of Hashsets correct?(Python) | 39,671,661 | <p>I'm teaching myself data structures through this python book and I'd appreciate if someone can correct me if I'm wrong since a hash set seems to be extremely similar to a hash map.</p>
<p><strong>Implementation:</strong>
A Hashset is a list [] or array where each index points to the head of a linkedlist</p>
<p>So ... | 0 | 2016-09-24T01:34:25Z | 39,671,924 | <p>The lookup time wouldn't be <code>O(n)</code> because not all items need to be searched, it also depends on the number of buckets. More buckets would decrease the probability of a collision and reduce the chain length.</p>
<p>The number of buckets can be kept as a constant factor of the number of entries by resizin... | 0 | 2016-09-24T02:31:50Z | [
"python",
"algorithm",
"data-structures"
] |
Is my understanding of Hashsets correct?(Python) | 39,671,661 | <p>I'm teaching myself data structures through this python book and I'd appreciate if someone can correct me if I'm wrong since a hash set seems to be extremely similar to a hash map.</p>
<p><strong>Implementation:</strong>
A Hashset is a list [] or array where each index points to the head of a linkedlist</p>
<p>So ... | 0 | 2016-09-24T01:34:25Z | 39,672,157 | <p>A lot has been written here about open hash tables, but some fundamental points are missed.</p>
<p>Practical implementations generally have O(1) lookup and delete because they guarantee buckets won't contain more than a fixed number of items (the <em>load factor</em>). But this means they can only achieve <em>amort... | 0 | 2016-09-24T03:25:54Z | [
"python",
"algorithm",
"data-structures"
] |
Using index on an empty list in python | 39,671,669 | <p>For the following program, in the addEntry(self, dictKey, dictVal) function, I don't understand why the following line of code doesn't generate indexing error:</p>
<pre><code>if hashBucket[i][0] == dictKey
</code></pre>
<p><code>self.buckets</code> is initially a list of empty list:
<code>self.buckets = [[],[]...[... | 1 | 2016-09-24T01:36:02Z | 39,671,755 | <p>Since <code>hashBucket</code> is an empty list at first, <code>for i in range(len(hashBucket)):</code> is essentially <code>for i in range(0):</code>, meaning it never gets to the conditional <code>if hashBucket[i][0] == dictKey</code> on the first call to <code>addEntry</code>.</p>
| 2 | 2016-09-24T01:53:44Z | [
"python",
"list",
"indexing",
"hash"
] |
Using index on an empty list in python | 39,671,669 | <p>For the following program, in the addEntry(self, dictKey, dictVal) function, I don't understand why the following line of code doesn't generate indexing error:</p>
<pre><code>if hashBucket[i][0] == dictKey
</code></pre>
<p><code>self.buckets</code> is initially a list of empty list:
<code>self.buckets = [[],[]...[... | 1 | 2016-09-24T01:36:02Z | 39,671,759 | <p>when you try to loop over an empty list, nothing is going to happen, fire up a python interpeter and try this</p>
<pre><code>>>> for i in range(len([])):
... print(i)
...
>>>
</code></pre>
<p>Nothing gets printed, so in the same way if <code>hashBucket</code> is empty then everything inside ... | 2 | 2016-09-24T01:54:54Z | [
"python",
"list",
"indexing",
"hash"
] |
Using index on an empty list in python | 39,671,669 | <p>For the following program, in the addEntry(self, dictKey, dictVal) function, I don't understand why the following line of code doesn't generate indexing error:</p>
<pre><code>if hashBucket[i][0] == dictKey
</code></pre>
<p><code>self.buckets</code> is initially a list of empty list:
<code>self.buckets = [[],[]...[... | 1 | 2016-09-24T01:36:02Z | 39,671,783 | <p>When executed for first time hashBucket is empty. So range is empty. So this for loop doesn't do anything. 'for i in range(len(hashBucket)):'
I think.
Is that right?</p>
| 0 | 2016-09-24T01:59:54Z | [
"python",
"list",
"indexing",
"hash"
] |
How to prevent Django Rest Framework from validating the token if 'AllowAny' permission class is used? | 39,671,786 | <p>Let me show you my code first:</p>
<p>In <code>settings.py</code></p>
<pre><code>....
DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
....
</code></pre>
<p>My <code>my_view.py</code>:... | 2 | 2016-09-24T02:00:21Z | 39,671,870 | <p>I think the answer to <a href="http://stackoverflow.com/questions/33539606/excluding-basic-authentication-in-a-single-view-django-rest-framework">this question</a> applies here as well.</p>
<p>If you don't want to check tokens for one view, you can add <code>@authentication_classes([])</code> to the view. That shou... | 0 | 2016-09-24T02:18:32Z | [
"python",
"django",
"django-rest-framework"
] |
How to prevent Django Rest Framework from validating the token if 'AllowAny' permission class is used? | 39,671,786 | <p>Let me show you my code first:</p>
<p>In <code>settings.py</code></p>
<pre><code>....
DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
)
....
</code></pre>
<p>My <code>my_view.py</code>:... | 2 | 2016-09-24T02:00:21Z | 39,671,872 | <p>You seem to be mixing up <strong>authentication</strong> and <strong>authorization</strong>.</p>
<p>By using the <code>@permission_classes</code> decorator on your view, you have overridden the default authorization from settings. But you still have the default authentication classes from settings.</p>
<p>Try add... | 1 | 2016-09-24T02:18:41Z | [
"python",
"django",
"django-rest-framework"
] |
Get a "for" object in loop | 39,671,791 | <p>What I'm trying to do first is to add all the values in a tuple or function, I do no know if I'm doing with the best option but finally I achieve it, well, the second it's that in my example code I would like to get the last value of a for loop, because it was the unique idea I had to make it plus all the values, at... | -1 | 2016-09-24T02:00:58Z | 39,672,053 | <p>There is a <code>sum</code> function to sum all the numbers in an iterable.</p>
<pre><code>def fun(*args):
valores = args
print valores
if len(valores) >= 3:
print 'es mayor'
suma = sum(valores)
print suma
print valores[-1]
else:
print 'es menor'
fun(10,1... | 0 | 2016-09-24T03:01:50Z | [
"python"
] |
python urlib in loop | 39,671,810 | <p>my requirement is to read some page which has so many links available in order
i have to stop at suppose at 4th link
and i have to read and connect to the url at that particular link
save the link contents in a list
again the connected link has so many links and i have to connected to the link at 4th position again
... | 0 | 2016-09-24T02:06:05Z | 39,672,086 | <p>Without knowing the particular site you're talking about this is just a guess, but could it be that the links in the page you're interested in are relative and not absolute? If that's the case when you reset url in the for loop then it would be set to an incomplete link like /link.php instead of <a href="http://exa... | 0 | 2016-09-24T03:10:15Z | [
"python",
"urllib"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.