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,complink from """+ table_name_r +""" where li_company is not null and id_auto between """+between)
print "Execution complete"
</code></pre>
<p>I'm getting the below output,</p>
<pre><code>Table name: li_records
Between: 4 and 6
Total Rows: -1
</code></pre>
<p>I have 2 questions here,</p>
<p>1.) (Resolved) My table <code>li_records</code> have 91 rows in it then why I'm getting the rowcount as -1?</p>
<p>2.) Why my script hangs up on <code>cursor.execute</code>?</p>
<p><strong>Question 1 resolved: Like many of you pointed out the reason I'm getting '-1' is because I have not executed the query yet</strong></p>
<p>Any help is appreciated.
Thanks in advance.</p>
| -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 Spec, the rowcount attribute âis -1
in case no executeXX() has been performed on the cursor [..]</p>
</blockquote>
<p>As to why your <code>execute</code> method hangs, I don't know. Could you construct the query string outside of the method call like so:</p>
<pre><code>query = "select contactid,li_url_clean,li_company,complink from " + table_name_r + " where li_company is not null and id_auto between " + between
cursor.execute(query)
</code></pre>
<p>If you do it like that, you can also <code>print</code> it before executing. That way you can check more easily to see if there's anything wrong with the query.</p>
| 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>
<p>And depending on whether <code>sex</code> and <code>class_type</code> are chosen to be <code>all</code>, I break the cases as follows</p>
<pre><code>if sex=='all' and class_type=='all':
rows = q.all()
elif sex=='all' and class_type!='all':
rows = q.filter_by(class_type=class_type)
elif sex!='all' and class_type=='all':
rows = q.filter_by(sex=sex)
else:
rows = q.filter_by(sex=sex, class_type=class_type)
</code></pre>
<p>Is there a better way to write this logic?</p>
| 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 query with no <code>WHERE</code> clause.</p>
| 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 curiosity). The python code <a href="https://cloud.google.com/storage/docs/encryption#customer-supplied_encryption_keys" rel="nofollow">provided by Google</a> is:</p>
<pre><code>import base64
import hashlib
import os
key = os.urandom(32)
print "Key: %sSHA256 hash: %s" % (base64.encodestring(key), base64.encodestring(hashlib.sha256(key).digest()))
</code></pre>
<p>I thought I put together some Elixir code to do the trick:</p>
<pre><code>key = 32 |> :crypto.strong_rand_bytes |> Base.encode64
hash = :sha256 |> :crypto.hash(key) |> Base.encode64
IO.puts "Key: #{key}\nSHA256 hash: #{hash}"
</code></pre>
<p>However, when I try to use my Elixir-generated key and hash Google complains as so:</p>
<pre><code>{
"domain": "global",
"extendedHelp": "https://cloud.google.com/storage/docs/encryption#customer-supplied_encryption_keys",
"message": "Missing a SHA256 hash of the encryption key, or it is not base64 encoded, or it does not match the encryption key.",
"reason": "customerEncryptionKeySha256IsInvalid"
}
</code></pre>
<p>Naturally, the Python code works, so there seems to be some difference going on here.</p>
<p>Anyone have any ideas as to why this is? Thanks!</p>
| 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.encode64
IO.puts "Key: #{base64_key}\nSHA256 hash: #{base64_hash}"
</code></pre>
| 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 pass an in argument to increment the correct score respectively. However, the function is not saving the value of <code>playerScore</code> across multiple plays, resetting to 0 with each round. I'm new to functions, so I'm sure the issue is likely something trivial, but I appreciate any and all help!</p>
<pre class="lang-python prettyprint-override"><code>dieList = []
sixCount = 0
playerScore = 0
def rollDice():
global sixCount
sixCount = 0
dieList.clear()
die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
dieList.append(die1)
dieList.append(die2)
dieList.append(die3)
print(dieList)
for x in dieList:
if x == 6:
sixCount += 1
print("sixCount:", sixCount)
return
def scoreCalc(x):
if sixCount == 1:
x += 1
elif sixCount == 2:
x += 5
elif sixCount == 3:
x += 21
return x
print()
print("Player's turn!")
print('*' * 30)
input("Press ENTER to roll the dice")
print()
rollDice()
print("Score:", scoreCalc(playerScore))
</code></pre>
| 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 you do any operation on a number and populate some variable with the result (e.g. <code>i += 2</code>), <em>a new number object is created</em>. So, when you pass <code>playerScore</code> to a function, <em>a whole new object is getting passed</em>, so, what <code>scoreCalc</code> gets is not the actual <code>playerScore</code>, but its copy. Needless to say that changing the copy doesn't change the original.</p>
<p>The following will do the trick:</p>
<pre><code>def scoreCalc():
global playerScore
if sixCount == 1:
playerScore += 1
elif sixCount == 2:
playerScore += 5
elif sixCount == 3:
playerScore += 21
return playerScore
</code></pre>
| 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 pass an in argument to increment the correct score respectively. However, the function is not saving the value of <code>playerScore</code> across multiple plays, resetting to 0 with each round. I'm new to functions, so I'm sure the issue is likely something trivial, but I appreciate any and all help!</p>
<pre class="lang-python prettyprint-override"><code>dieList = []
sixCount = 0
playerScore = 0
def rollDice():
global sixCount
sixCount = 0
dieList.clear()
die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
dieList.append(die1)
dieList.append(die2)
dieList.append(die3)
print(dieList)
for x in dieList:
if x == 6:
sixCount += 1
print("sixCount:", sixCount)
return
def scoreCalc(x):
if sixCount == 1:
x += 1
elif sixCount == 2:
x += 5
elif sixCount == 3:
x += 21
return x
print()
print("Player's turn!")
print('*' * 30)
input("Press ENTER to roll the dice")
print()
rollDice()
print("Score:", scoreCalc(playerScore))
</code></pre>
| 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 function. Meaning that it takes an input and gives an output, and nothing else matters. You then just need to use that output.</p>
<pre><code>def scoreCalc(sixCount):
x = 0
if sixCount == 1:
x += 1
elif sixCount == 2:
x += 5
elif sixCount == 3:
x += 21
return x
# now use it
playerScore += scoreCalc(sixCount)
</code></pre>
<p>Notice how scoreCalc doesn't care about any global variables. It just gives the score for its input. You then apply that score where it belongs.</p>
<p>These functions might also be useful. It's better not to give them any global variables. Handle the results where they matter, and just let these functions do their job, and nothing else.</p>
<pre><code># return a list of d6 outputs
def rollDice(number_of_dice):
return [random.randint(1,6) for _ in range(number_of_dice)]
# takes a list of d6 outputs and returns the count of sixes
def countSixes(dieList):
return sum([1 for x in dieList if x==6])
</code></pre>
| 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 the start of the string.</p>
</blockquote>
<p>Is there any difference when using them?</p>
| 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 use <code>^</code>, when you only need to match the start of a string <em>regardless of any modifiers</em>, use <code>\A</code>. You may re-use one and the same string pattern but compile it with different flags.</p>
<p>This also means that if you are using <code>re.M</code> flag, and you want to match the string start and then line start positions, you will mix the <code>\A</code> and <code>^</code> inside that pattern.</p>
| 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 the start of the string.</p>
</blockquote>
<p>Is there any difference when using them?</p>
| 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 some_mean_B
...
Z some_mean_Z
</code></pre>
<p>For replacing NaN, I use fillna(). It works for the case of computing the mean and using it during the same execution.</p>
<p>But as soon as I save the means in a file and read it to use it in a different .py file, I get rubbish. The reason is the file with the means are not interpreted correctly. In the new dataset, each NaN of the column A should be replaced by some_mean_A. Same for B and the rest till Z. But this is not happening, because by reading the means with read_csv(), I get the following</p>
<pre><code>0 1
A some_mean_A
B some_mean_B
...
Z some_mean_Z
</code></pre>
<p>When I use this with fillna(), I do not get the expected result.</p>
<p>So, I hope you are understanding my problem. Do you know how to solve this problem?</p>
<p>EDIT 1.0:</p>
<p>This is how I compute and store the means:</p>
<pre><code>df_mean = df.mean()
df.fillna(df_mean, inplace=True) // df is the dataframe for dataset where it works
df_mean.to_csv('mean.csv')
</code></pre>
<p>This is how I read the means:</p>
<pre><code>df_mean = pd.read_csv('mean.csv', header=None)
</code></pre>
| 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 another column for the means. To get the same data structure, you need to specify the index and pass <code>squeeze=True</code>. This way, pandas will read it into a Series:</p>
<pre><code>df_mean = pd.read_csv('mean.csv', header=None, index_col=0, squeeze=True)
</code></pre>
<p>would give you the same Series for the mean vector. You can add <code>rename_axis(None)</code> at the end to get rid of the index name (I think this requires pandas 0.18.0):</p>
<pre><code>df_mean = pd.read_csv('mean.csv', header=None, index_col=0).squeeze().rename_axis(None)
</code></pre>
| 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 response</p>
<p>my procfile</p>
<pre><code>web: gunicorn gettingstarted.wsgi --log-file -
worker: celery -A blog worker -B -l info
</code></pre>
<p>my requirements.txt</p>
<pre><code> amqp==1.4.9
anyjson==0.3.3
attrs==16.2.0
beautifulsoup4==4.4.1
billiard==3.3.0.23
celery==3.1.23
cffi==1.8.3
click==6.6
cryptography==1.5
cssselect==0.9.2
decorator==4.0.10
dj-database-url==0.4.0
Django==1.10.1
django-bootstrap-pagination==1.6.2
django-celery==3.1.17
django-crispy-forms==1.6.0
django-dynamic-scraper==0.11.2
django-haystack==2.4.1
django-markdown-deux==1.0.5
django-pagedown==0.1.1
django-redis-cache==1.6.5
django-taggit==0.18.1
feedparser==5.2.1
future==0.15.2
gunicorn==19.4.5
html5lib==0.9999999
httplib2==0.9.2
idna==2.1
jsonpath-rw==1.4.0
kombu==3.0.35
lxml==3.6.4
markdown2==2.3.1
oauth2client==2.2.0
oauthlib==1.1.2
parsel==1.0.3
Pillow==3.2.0
ply==3.8
psycopg2==2.6.1
pyasn1==0.1.9
pyasn1-modules==0.0.8
pycparser==2.14
PyDispatcher==2.0.5
pyOpenSSL==16.1.0
pytz==2016.6.1
queuelib==1.4.2
redis==2.10.5
requests==2.9.1
requests-oauthlib==0.6.1
rsa==3.4.2
Scrapy==1.1.2
scrapy-djangoitem==1.1.1
scrapyd==1.1.0
service-identity==16.0.0
simplejson==3.8.2
six==1.10.0
tweepy==3.5.0
Twisted==16.4.1
uritemplate==0.6
w3lib==1.15.0
whitenoise==3.0
Whoosh==2.7.4
zope.interface==4.3.2
</code></pre>
<p>this all works locally though</p>
<p>I have scaled my web and worker to zero and started them back up still nothin. I have not seen any L,H,R error codes </p>
<p>EDIT</p>
<p>this part of my output</p>
<pre><code> 2016-09-24T02:23:53.832216+00:00 app[worker.1]:
</code></pre>
<p>its red, this color just started happening. Earlier in the day I had using django celery beat locally I get error 'PeriodicTask' object has no attribute '_default_manager' and I fixed it following a pul request</p>
<pre><code>obj = self.model._default_manager.get(pk=self.model.pk)
</code></pre>
<p>turned to</p>
<pre><code>98 Model = type(self.model)
99 obj = Model._default_manager.get(pk=self.model.pk)
</code></pre>
<h1>EDIT</h1>
<p>set my production DEBUG to True so I could see if I could see something. And it said</p>
<pre><code>ImportError: No module named 'django.core.context_processors'
</code></pre>
<p>this was not in my heroku logs and as i mentioned before this works locally. I believe this is called failing silently. gonna see if I can figure this out. If someone has any idea what's going on and how to fix this, let me know. Right now google is my friend.</p>
| 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 example settings:</p>
<pre><code>TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.template.context_processors.media',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
</code></pre>
| 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','Device', 'Android_OS_Version','App_Version_Name','App_Version_Code','Exception_Class_Name','Exception_Message','Throwing_File_Name','Throwing_Class_Name','Throwing_Method_Name','Throwing_Line_Number','Native_Crash_Library','Native_Crash_Location','Crash_Link'])
</code></pre>
<p>I debug the code and found following data is not inserting properly in the dataframe. </p>
<p>There are some special characters in the <code>Exception_Message</code> field which is telling pandas to move rest of the data on that row to the next row. </p>
<p>Some how Pandas is not reading the file properly. </p>
<p>Following is the output for both the rows. 137 and 138 are the row numbers.</p>
<pre><code>Package_Name Crash_Report_Date_And_Time \
137 com.vcast.mediamanager 2016-09-05 14:54:13
138 NaN Class.java
Crash_Report_Millis_Since_Epoch Device Android_OS_Version \
137 1473087253130 victara 22
138 java.lang.Class classForName -2
App_Version_Name App_Version_Code \
137 14.3.34 1.503050e+09
138 NaN NaN
Exception_Class_Name \
137 java.lang.ClassNotFoundException
138 https://play.google.com/apps/publish?dev_acc=0...
Exception_Message Throwing_File_Name Throwing_Class_Name \
137 Invalid name: com.strumsoft.appen NaN NaN
138 NaN NaN NaN
Throwing_Method_Name Throwing_Line_Number Native_Crash_Library \
137 NaN NaN NaN
138 NaN NaN NaN
Native_Crash_Location Crash_Link account_id
137 NaN NaN NONE
138
NaN NaN NONE
</code></pre>
<p>Row 138 is created erroneously with some data from row 137. <code>Exception Message</code> field in 137 has some value which is breaking that row to the next row. Which is wrong.</p>
<p>I tried different encoding nothing helped. Can anyone please help?</p>
| 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="exemplifiable" value="100" data-example="20.00">
</code></pre>
<p><strong>Test Code</strong></p>
<pre><code>locator = 'budget'
element = self.find_element_by_id(locator)
element.send_keys('5')
value = element.get_attribute('value')
print(value)
# prints 100 instead of 5
</code></pre>
| 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="exemplifiable" value="100" data-example="20.00">
</code></pre>
<p><strong>Test Code</strong></p>
<pre><code>locator = 'budget'
element = self.find_element_by_id(locator)
element.send_keys('5')
value = element.get_attribute('value')
print(value)
# prints 100 instead of 5
</code></pre>
| 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 getting previous value. </p>
<p>You should find the same element again after <code>send_keys()</code> with new value and then you'll find the actual result which you want as below :-</p>
<pre><code>locator = 'budget'
element = self.find_element_by_id(locator)
element.send_keys('5')
value = self.find_element_by_id(locator).get_attribute('value')
print(value)
</code></pre>
| 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
ty += 1
tx = 1
tn = 1
while tn <= n:
vars()["m" + str(tn)] = tn
tn += 1
t = x * y
tm = n
def recursion(z):
global tm
if z < n:
for x in range(n):
recursion(z + 1)
else:
if tm > 0:
tv = "m" + str(tm)
otm = eval(tv)
while eval(tv) < t - n + tm:
vars()[tv] = eval(tv) + 1
print(tv + " = " + str(eval(tv)))
vars()[tv] = otm + 1
print(tv + " = " + str(eval(tv)))
if tm > 1:
vars()["m" + str(tm - 1)] = eval("m" + str(tm - 1)) + 1
print(str("m" + str(tm - 1) + " = " + str(eval("m" + str(tm -1)))))
tm -= 1
recursion(1)
print("done")
</code></pre>
<p>I've put the return in where I would expect it to end but as far as I know it shouldn't actually need it. </p>
<p>Can anyone see what I've done to cause it to get stuck?</p>
<p>Thanks</p>
| 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 simplified and rewrote it to be a few while loops instead:</p>
<pre><code>x = 9
y = 9
t = x * y
n = 10
tt = 1
while tt <= t:
vars()["p" + str(tt)] = 0
tt += 1
tn = 1
while tn <= n:
vars()["m" + str(tn)] = tn
vars()["p" + str(tn)] = 1
tn += 1
def cl():
w = ""
tt = 1
while tt <= t:
w = w + str(eval("p" + str(tt)))
tt += 1
p.append(w)
tm = n
tv = "m" + str(tm)
p = []
while m1 < t - n + tm - 1:
cl()
while tm == n and eval(tv) < t - n + tm:
vars()["p" + str(eval(tv))] = 0
vars()[tv] = eval(tv) + 1
vars()["p" + str(eval(tv))] = 1
cl()
tm -= 1
tv = "m" + str(tm)
while tm < n and tm > 0:
if eval(tv) < t - n + tm:
vars()["p" + str(eval(tv))] = 0
vars()[tv] = eval(tv) + 1
vars()["p" + str(eval(tv))] = 1
while tm < n:
tm += 1
ptv = tv
tv = "m" + str(tm)
vars()["p" + str(eval(tv))] = 0
vars()[tv] = eval(ptv) + 1
vars()["p" + str(eval(tv))] = 1
else:
tm -= 1
tv = "m" + str(tm)
</code></pre>
| 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
ty += 1
tx = 1
tn = 1
while tn <= n:
vars()["m" + str(tn)] = tn
tn += 1
t = x * y
tm = n
def recursion(z):
global tm
if z < n:
for x in range(n):
recursion(z + 1)
else:
if tm > 0:
tv = "m" + str(tm)
otm = eval(tv)
while eval(tv) < t - n + tm:
vars()[tv] = eval(tv) + 1
print(tv + " = " + str(eval(tv)))
vars()[tv] = otm + 1
print(tv + " = " + str(eval(tv)))
if tm > 1:
vars()["m" + str(tm - 1)] = eval("m" + str(tm - 1)) + 1
print(str("m" + str(tm - 1) + " = " + str(eval("m" + str(tm -1)))))
tm -= 1
recursion(1)
print("done")
</code></pre>
<p>I've put the return in where I would expect it to end but as far as I know it shouldn't actually need it. </p>
<p>Can anyone see what I've done to cause it to get stuck?</p>
<p>Thanks</p>
| 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 <= n:
vars()["m" + str(tn)] = tn
tn += 1
t = x * y
tm = n
def recursion(z):
global tm
if tm > 0:
if z < n:
for x in range(n):
recursion(z + 1)
else:
tv = "m" + str(tm)
otm = eval(tv)
while eval(tv) < t - n + tm:
vars()[tv] = eval(tv) + 1
print(tv + " = " + str(eval(tv)))
vars()[tv] = otm + 1
print(tv + " = " + str(eval(tv)))
if tm > 1:
vars()["m" + str(tm - 1)] = eval("m" + str(tm - 1)) + 1
print(str("m" + str(tm - 1) + " = " + str(eval("m" + str(tm -1)))))
tm -= 1
recursion(1)
print("done")
</code></pre>
<p>This could be made much clearer through the use of lists and range objects, but that takes effort.</p>
| 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
ty += 1
tx = 1
tn = 1
while tn <= n:
vars()["m" + str(tn)] = tn
tn += 1
t = x * y
tm = n
def recursion(z):
global tm
if z < n:
for x in range(n):
recursion(z + 1)
else:
if tm > 0:
tv = "m" + str(tm)
otm = eval(tv)
while eval(tv) < t - n + tm:
vars()[tv] = eval(tv) + 1
print(tv + " = " + str(eval(tv)))
vars()[tv] = otm + 1
print(tv + " = " + str(eval(tv)))
if tm > 1:
vars()["m" + str(tm - 1)] = eval("m" + str(tm - 1)) + 1
print(str("m" + str(tm - 1) + " = " + str(eval("m" + str(tm -1)))))
tm -= 1
recursion(1)
print("done")
</code></pre>
<p>I've put the return in where I would expect it to end but as far as I know it shouldn't actually need it. </p>
<p>Can anyone see what I've done to cause it to get stuck?</p>
<p>Thanks</p>
| 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
for index in indices:
board[index] = '1'
yield ''.join(board)
</code></pre>
| 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, waitcount is based on the number of jobs you have in depends</p>
<pre><code>job_board = {}
# create a dependency tree
for i in range(1000):
# create random jobs
j = Job(<new name goes here>)
# add jobs to depends if dependent
# record it in job_board
job_board[j.name] = j
# example
# jobC is in self.depends of jobA and jobB
# jobC would have a waitcount of 2
rdyQ = Queue.Queue()
def worker():
try:
job = rdyQ.get()
success = job.work()
# if this job was successful create dependent jobs
if success:
for dependent_job in job.depends:
dependent_job.waitcount -= 1
if dependent_job.waitcount == 0:
rdyQ.put(dependent_job)
</code></pre>
<p>and then i would create threads</p>
<pre><code>for i in range(10):
t = threading.Thread( target=worker )
t.daemon=True
t.start()
for job_name, job_obj in job_board.iteritems():
if job_obj.waitcount == 0:
rdyQ.put(job_obj)
while True:
# until all jobs finished wait
</code></pre>
<p>Now here is an example:</p>
<pre><code># example
# jobC is in self.depends of jobA and jobB
# jobC would have a waitcount of 2
</code></pre>
<p>now in this scenario, if both jobA and jobB are running and they both tried to decrement waitcount of jobC, weird things were happening</p>
<p>so i put a lock </p>
<pre><code>waitcount_lock = threading.Lock()
</code></pre>
<p>and changed this code to:</p>
<pre><code># if this job was successful create dependent jobs
if success:
for dependent_job in job.depends:
with waitcount_lock:
dependent_job.waitcount -= 1
if dependent_job.waitcount == 0:
rdyQ.put(dependent_job)
</code></pre>
<p>and strange things still happen</p>
<p>i.e. same job was being processed by multiple threads, as if the job was put into the queue twice</p>
<p>is it not a best practice to have/modify nested objects when complex objects are being pass amongst threads?</p>
| 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> threads are also usually a Bad Idea, so this code arranges to shut down all the threads cleanly when the work is over. Note too the use of assertions to verify that implicit beliefs are actually true ;-)</p>
<pre><code>import threading
import Queue
import random
NTHREADS = 10
NJOBS = 10000
class Job(object):
def __init__(self, name):
self.name = name
self.done = False
self.succs = []
self.npreds = 0
def work(self):
assert not self.done
self.done = True
return True
def add_dependent(self, another_job):
self.succs.append(another_job)
another_job.npreds += 1
def worker(q, lock):
while True:
job = q.get()
if job is None:
break
success = job.work()
if success:
for succ in job.succs:
with lock:
assert succ.npreds > 0
succ.npreds -= 1
if succ.npreds == 0:
q.put(succ)
q.task_done()
jobs = [Job(i) for i in range(NJOBS)]
for i, job in enumerate(jobs):
# pick some random successors
possible = xrange(i+1, NJOBS)
succs = random.sample(possible,
min(len(possible),
random.randrange(10)))
for succ in succs:
job.add_dependent(jobs[succ])
q = Queue.Queue()
for job in jobs:
if job.npreds == 0:
q.put(job)
print q.qsize(), "ready jobs initially"
lock = threading.Lock()
threads = [threading.Thread(target=worker,
args=(q, lock))
for _ in range(NTHREADS)]
for t in threads:
t.start()
q.join()
# add sentinels so threads end cleanly
for t in threads:
q.put(None)
for t in threads:
t.join()
for job in jobs:
assert job.done
assert job.npreds == 0
</code></pre>
<h2>CLARIFYING THE LOCK</h2>
<p>In a sense, the lock in this code protects "too much". The potential problem it's addressing is that multiple threads <em>may</em> try to decrement the <code>.npreds</code> member of the same <code>Job</code> object simultaneously. Without mutual exclusion, the stored value at the end of that may be anywhere from 1 smaller than its initial value, to the correct result (the initial value minus the number of threads trying to decrement it).</p>
<p>But there's no need to also mutate the queue under lock protection. Queues do their own thread-safe locking. So, e.g., the code could be written like so instead:</p>
<pre><code> for succ in job.succs:
with lock:
npreds = succ.npreds = succ.npreds - 1
assert npreds >= 0
if npreds == 0:
q.put(succ)
</code></pre>
<p>It's generally best practice to hold a lock for as little time as possible. However, I find this rewrite harder to follow. Pick your poison ;-)</p>
| 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 Timer thread the loop variable will change to False, essentially returning false on the if statement and not continuing to print out 'Test'.</p>
<p>But even though ext() is called(I tested this) the if statement gets on being called and loop does not change to False. </p>
<pre><code>from threading import Timer, Thread
from time import sleep
loop = True
def hello():
while True:
if loop == True:
print('Test')
sleep(0.5)
def ext():
loop = False
th = Thread(target=hello)
th.start()
t = Timer(5, ext())
t.start()
</code></pre>
<p>Please help as I have been stuck for this for several hours.</p>
| 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 sleep
loop = True
def hello():
while True:
if loop == True:
print('Test')
sleep(0.5)
def ext():
global loop
loop = False
th = Thread(target=hello)
th.start()
t = Timer(5, ext)
t.start()
</code></pre>
<p>You also need to change the one before last line and instead of calling <code>ext</code> pass it to <code>Timer</code></p>
| 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 Timer thread the loop variable will change to False, essentially returning false on the if statement and not continuing to print out 'Test'.</p>
<p>But even though ext() is called(I tested this) the if statement gets on being called and loop does not change to False. </p>
<pre><code>from threading import Timer, Thread
from time import sleep
loop = True
def hello():
while True:
if loop == True:
print('Test')
sleep(0.5)
def ext():
loop = False
th = Thread(target=hello)
th.start()
t = Timer(5, ext())
t.start()
</code></pre>
<p>Please help as I have been stuck for this for several hours.</p>
| 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 your code ends up eating a full cpu in a tight loop. Fixing the first two would be</p>
<pre><code>from threading import Timer, Thread
from time import sleep
loop = True
def hello():
while True:
if loop == True:
print('Test')
sleep(0.5)
def ext():
global loop
loop = False
th = Thread(target=hello)
th.start()
t = Timer(5, ext)
t.start()
</code></pre>
| 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:
for arg in args:
self.assertTrue(arg.startswith('PASS'))
</code></pre>
<p>I would like to know if there is a better way to unpack that call_args_list on the mock object in order to make my assertion. This loop works, but it feels like there must be a more straight forward way.</p>
| 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'>
>>> expected_calls = [call(s + ' call') for s in ('first', 'second')]
>>> f.assert_has_calls(expected_calls)
</code></pre>
<p>Note that the calls must be sequential, if you don't want that then override the <code>any_order</code> kwarg to the assertion. </p>
<p>Also note that it's permitted for there to be extra calls before or after the
specified calls. If you don't want that, you'll need to add another assertion:</p>
<pre><code>>>> assert f.call_count == len(expected_calls)
</code></pre>
<hr>
<p>Addressing the comment of mgilson, here's an example of creating a dummy object that you can use for wildcard equality comparisons:</p>
<pre><code>>>> class AnySuffix(object):
... def __eq__(self, other):
... try:
... return other.startswith('PASS')
... except Exception:
... return False
...
>>> f = Mock()
>>> f('PASS and some other stuff')
<Mock name='mock()' id='28717456'>
>>> f('PASS more stuff')
<Mock name='mock()' id='28717456'>
>>> f("PASS blah blah don't care")
<Mock name='mock()' id='28717456'>
>>> expected_calls = [call(AnySuffix())]*3
>>> f.assert_has_calls(expected_calls)
</code></pre>
<p>And an example of the failure mode:</p>
<pre><code>>>> Mock().assert_has_calls(expected_calls)
AssertionError: Calls not found.
Expected: [call(<__main__.AnySuffix object at 0x1f6d750>),
call(<__main__.AnySuffix object at 0x1f6d750>),
call(<__main__.AnySuffix object at 0x1f6d750>)]
Actual: []
</code></pre>
| 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:
for arg in args:
self.assertTrue(arg.startswith('PASS'))
</code></pre>
<p>I would like to know if there is a better way to unpack that call_args_list on the mock object in order to make my assertion. This loop works, but it feels like there must be a more straight forward way.</p>
| 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 assertions separately for args and kwargs (since one is a tuple and the other a dict)</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:
args, kwargs = call
self.assertTrue(all(a.startswith('PASS') for a in args))
</code></pre>
<p>Note that sometimes the terseness isn't helpful (e.g. if there is an error):</p>
<pre><code>for call in f.call_args_list:
args, kwargs = call
for a in args:
self.assertTrue(a.startswith('PASS'), msg="%s doesn't start with PASS" % a)
</code></pre>
| 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 having some difficulties with the threading.</p>
<p>I am using Python 2.7 for reasons that I don't believe to be relevant.</p>
<p>Anyway, the entire program runs within one class and calls upon a PyQt designer .ui file in order to display the actual GUI. When a particular button is pressed, in order to shred a file, it calls a function within that class that then starts a thread using the 'thread' module, yes, outdated, I know. The shredding function that is then called from this commences the shredding of the file. Throughout the shredding of the file, the actual shredding function interacts and adds bits to the GUI in order to keep the user up to date on what is happening.</p>
<p>During the execution of the function the GUI continues to be refreshed, however it does become a little laggy, I can cope with that. However, when that function is complete, instead of smoothly continuing and allowing the user to keep using the program, the program throws a complete hissy fit and simply just stops working and has to be closed.</p>
<p>Hopefully someone can assist me here. I would greatly appreciate as much detail as possible as I have been searching around for a way to cope with this for a good number of weeks now.</p>
<p>Edit: I should clarify that I am using PyQt4.</p>
<p>Thanks,
BoshJailey</p>
| 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).__init__(parent)
self.resize(300,200)
self.VL = QtWidgets.QVBoxLayout(self)
self.label = QtWidgets.QLabel()
self.VL.addWidget(self.label)
self.logger = Logger()
self.logger.sec_signal.connect(self.label.setText)
self.logger.start()
def closeEvent(self,event):
self.logger.terminate()
class Logger(QtCore.QThread):
sec_signal = pyqtSignal(str)
def __init__(self, parent=None):
super(Logger, self).__init__(parent)
self.current_time = 0
self.go = True
def run(self):
#this is a special fxn that's called with the start() fxn
while self.go:
time.sleep(1)
self.sec_signal.emit(str(self.current_time))
self.current_time += 1
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app.setApplicationName("Thread Example")
window = TheBoss()
window.show()
sys.exit(app.exec_())
</code></pre>
| 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 instantiate the class by the following code:
<code>findmylink = LinkFinder()</code> and when I load my html with the following code <code>findmylink.feed("""<html><head><title>my name is good</title></head><body>hello world</body></html>""",'html5lib')</code>.</p>
<p>I got the following error in my console:</p>
<pre><code>'NoneType' object is not callable
</code></pre>
<p>I actually wish to duplicate the following sample code (in my case, I wishes to use Beautifulsoup instead of <code>html.parser</code>)</p>
<pre><code>from html.parser import HTMLParser
class LinkFinder(HTMLParser):
def __init__(self):
super().__init__()
def handle_starttag(self, tag, attrs):
print(tag)
</code></pre>
<p>When I re-instantiate the class by the following code: <code>findmylink = LinkFinder()</code> and when I load my html with the following code <code>findmylink.feed("""<html><head><title>my name is good</title></head><body>hello world</body></html>""")</code> I get the following output:</p>
<pre><code>html
head
title
body
</code></pre>
<p>which is the desired output.</p>
| 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>hello world</body></html>"""
soup = BeautifulSoup(data, "html5lib")
for elm in soup.find_all():
print(elm.name)
</code></pre>
<p>Prints:</p>
<pre><code>html
head
title
body
</code></pre>
| 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 instantiate the class by the following code:
<code>findmylink = LinkFinder()</code> and when I load my html with the following code <code>findmylink.feed("""<html><head><title>my name is good</title></head><body>hello world</body></html>""",'html5lib')</code>.</p>
<p>I got the following error in my console:</p>
<pre><code>'NoneType' object is not callable
</code></pre>
<p>I actually wish to duplicate the following sample code (in my case, I wishes to use Beautifulsoup instead of <code>html.parser</code>)</p>
<pre><code>from html.parser import HTMLParser
class LinkFinder(HTMLParser):
def __init__(self):
super().__init__()
def handle_starttag(self, tag, attrs):
print(tag)
</code></pre>
<p>When I re-instantiate the class by the following code: <code>findmylink = LinkFinder()</code> and when I load my html with the following code <code>findmylink.feed("""<html><head><title>my name is good</title></head><body>hello world</body></html>""")</code> I get the following output:</p>
<pre><code>html
head
title
body
</code></pre>
<p>which is the desired output.</p>
| 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 LinkFinder(BeautifulSoup):
def __init__(self, markup):
super().__init__(markup, 'html.parser')
def handle_starttag(self, name, namespace, nsprefix, attrs):
print(name)
</code></pre>
<p>Initializing with:</p>
<pre><code>l = LinkFinder("""<html><head><title>my name is good</title></head><body>hello world</body></html>""")
</code></pre>
<p>Prints out:</p>
<pre><code>html
head
title
body
</code></pre>
<p>I'm pretty sure the <code>BeautifulSoup</code> class has overloaded <code>__getattr__</code> to return <code>None</code> on non-defined attributes instead of raising <code>AttributeError</code>; that's what's causing your error:</p>
<pre><code>print(type(BeautifulSoup().feed))
NoneType
print(type(BeautifulSoup().feedededed))
NoneType
</code></pre>
<p>and, <code>BeautifulSoup</code> doesn't have a <code>feed</code> function as <code>HTMLParser</code> does (it does have a <a href="https://github.com/JinnLynn/beautifulsoup/blob/f29f8d278462efb370168f2329b070fa51706013/bs4/__init__.py#L193" rel="nofollow"><code>_feed</code></a> and that calls the underlying <code>feed</code> of the <code>builder</code> object with <code>self.markup</code>) so you get a <code>None</code> object which you call.</p>
| 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 1964 13 1
35 1963 0 1
</code></pre>
<p>The first column denotes the age and the last column denotes the survival rate(1 if patient survives 5 years or longer;2 if patient died within 5 years)
I have to calculate which age has the highest survival rate. I am new to python and I cannot figure out how to proceed. I was able to calculate the most repeated age using the mode function but I cannot figure out how to check one column and print the corresponding other column. Please help.</p>
<p>I was able to find an answer where I had to analyze just the first row.</p>
<pre><code>import csv
import matplotlib.pyplot as plt
import numpy as np
df = open('Dataset.csv')
csv_df=csv.reader(df)
a=[]
b=[]
for row in csv_df:
a.append(row[0])
b.append(row[3])
print('The age that has maximum reported incidents of cancer is '+ mode(a))
</code></pre>
| 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 wired when I used csv. If the csv module works fine in your environment, use it. The idea is, to retrieve each element of value in each row; we are interested in the 0th and 3rd columns.</p>
<p>In the following code, we maintain a dictionary, survival_map, and count the frequency of a particular age being associated with a 1.</p>
<pre><code>import operator
survival_map = {}
with open('Dataset.csv', 'rb') as in_f:
for row in in_f:
row = row.rstrip() #to remove the end line character
items = row.split(',') #I converted the tab space to a comma, had a problem otherwise
age = int(items[0])
survival_rate = int(items[3])
if survival_rate == 1:
if age in survival_map:
survival_map[age] += 1
else:
survival_map[age] = 1
</code></pre>
<p>Once we build the dictionary, {33: 2, 34: 5, 35: 2, 30: 3, 31: 2}, it is sorted in reverse by the key:</p>
<pre><code>sorted_survival_map = sorted(survival_map.items(), key=operator.itemgetter(1), reverse = True)
max_survival = sorted_survival_map[0]
</code></pre>
<p>UPDATE:</p>
<p>For a single max value, OP's suggestion (in a comment) is preferred. Posting it here:</p>
<pre><code>maximum = max(dict, key=dict.get)
print(maximum, dict[maximum])
</code></pre>
<p>For multiple max values</p>
<pre><code>max_keys = []
max_value = 0
for k,v in survival_map.items():
if v > max_value:
max_keys = [k]
max_value = v
elif v == max_value:
max_keys.append(k)
print [(x, max_value) for x in max_keys]
</code></pre>
<p>Of course, this could be achieved by a dictionary comprehension; however for readability, I am proposing this. Also, this is done through one pass through the objects in the dictionary without going through it multiple times. Therefore, the solution has O(n) time complexity and would be the fastest.</p>
| 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()
clock = task.Clock()
for ip in self.ips:
if self.factory.dictQueue.get(ip) is not None:
self.factory.dictQueue[ip].append(self)
else:
self.factory.dictQueue[ip] = deque([self])
# self.factory.dictQueue[ip].append(self)
log.msg("-----------------the queue after wait")
log.msg(self.factory.dictQueue)
###############################HERE, this does not work
self.dtime = task.deferLater(clock, 5, self.printData)
#############################
self.dtime.addCallback(self.cancelTest)
self.dtime.addErrback(log.err)
else:
self.cancelTimeOut()
d.addCallback(self.dispatch)
d.addErrback(log.err)
def sendBackIP(self):
self.ips.pop(0)
log.msg("the IPs: %s" % self.ips)
d = self.factory.service.checkResource(self.ips)
d.addCallback(self.diverge) ###invoke above function
log.msg("the result from checkResource: ")
log.msg()
</code></pre>
| 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.deferLater</code> implementation should also work. However without seeing more of your code I don't think I can help you more other than stating that it's strange :)</p>
<h1>References</h1>
<ul>
<li><a href="https://twistedmatrix.com/documents/current/core/howto/defer.html#callbacks" rel="nofollow">https://twistedmatrix.com/documents/current/core/howto/defer.html#callbacks</a>
<a href="http://twistedmatrix.com/documents/current/api/twisted.internet.base.ReactorBase.html#callLater" rel="nofollow">http://twistedmatrix.com/documents/current/api/twisted.internet.base.ReactorBase.html#callLater</a></li>
</ul>
| 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()
clock = task.Clock()
for ip in self.ips:
if self.factory.dictQueue.get(ip) is not None:
self.factory.dictQueue[ip].append(self)
else:
self.factory.dictQueue[ip] = deque([self])
# self.factory.dictQueue[ip].append(self)
log.msg("-----------------the queue after wait")
log.msg(self.factory.dictQueue)
###############################HERE, this does not work
self.dtime = task.deferLater(clock, 5, self.printData)
#############################
self.dtime.addCallback(self.cancelTest)
self.dtime.addErrback(log.err)
else:
self.cancelTimeOut()
d.addCallback(self.dispatch)
d.addErrback(log.err)
def sendBackIP(self):
self.ips.pop(0)
log.msg("the IPs: %s" % self.ips)
d = self.factory.service.checkResource(self.ips)
d.addCallback(self.diverge) ###invoke above function
log.msg("the result from checkResource: ")
log.msg()
</code></pre>
| 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 production.</p>
<p>So, what should you use in production? <strong>reactor</strong>! In fact, all production reactor implementations implement the IReactorTime interface.</p>
<p>Just use the following import and function call:</p>
<pre><code>from twisted.internet import reactor
# (omissis)
self.dtime = task.deferLater(reactor, 5, self.printData)
</code></pre>
<p>Just some sidenotes: </p>
<p>in your text above the snippet, you say that you want to invoke cancelTest after five seconds, but in the code you actually invoke printData; of course if printData just prints something, doesn't raise and returns an immediate value, this will cause the cancelTest function to be executed immediately after since it's a chained callcack; <strong>but if you want to actually be 100% sure, you should call cancelTest within deferLater, not printData</strong>.</p>
<p>Also, I don't understand if this is a kind of "timeout"; please be advised that such callback will be triggered in all situations, even if the tests take less than five seconds. If you need a cancelable task, you should use reactor.callLater directly; that will NOT return a deferred you can use, but will let you cancel the scheduled call.</p>
| 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 value of <code>True</code> is under it (<code>column1</code> and then for the next row <code>column2</code> and <code>column3</code>). In the code I have below, it's printing every column.</p>
<pre><code> with open(reportOut, 'r') as f:
reader = csv.reader(f, skipinitialspace=True)
header = next(reader)
for row in reader:
if 'True' in row:
print(header)
</code></pre>
| 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
if val == "True": # Check for the value
# Print the header according to the column number
print(row_number, headers[column])
</code></pre>
<p>Output:</p>
<pre><code>2 column1
3 column2
3 column3
</code></pre>
| 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) This security update
resolves a vulnerability in Microsoft Windows. The vulnerability could
allow Secure Boot security features to be bypassed if an attacker
installs an affected policy on a target device. An attacker must have
either administrative privileges or physical access to install a
policy and bypass Secure Boot.</p>
</blockquote>
<p>I've never experienced such weird behavior. Anybody have any suggestions?</p>
<p>This is the function I've written.</p>
<pre><code>def scrub(file_name):
try:
file = open(file_name,"r")
unscrubbed_string = file.read()
file.close()
cms = open("common_misspellings.csv","r")
for line in cms:
replacement = line.strip('\n').split(',')
while replacement[0] in unscrubbed_string:
unscrubbed_string = unscrubbed_string.replace(replacement[0],replacement[1])
cms.close()
special_chars = ['.',',',';',"'","\""]
for char in special_chars:
while char in unscrubbed_string:
unscrubbed_string = unscrubbed_string.replace(char,"")
unscrubbed_list = unscrubbed_string.split()
noise = open("noise.txt","r")
noise_list = []
for word in noise:
noise_list.append(word.strip('\n'))
noise.close()
for noise in noise_list:
while noise in unscrubbed_list:
unscrubbed_list.remove(noise)
return unscrubbed_list
except:
print("""[*] File not found.""")
</code></pre>
| 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 critical text, then the <code>while</code> loop will never finish. In fact, you don't need the <code>while</code> loop at allâa single <code>.replace()</code> call will replace all occurrences.</p>
<p>But that's only one example of the problems you'll encounter with your current approach of using a blanket <code>unscrubbed_string.replace(...)</code> You'll either need to use <em>regular expression</em> substitution (from the <code>re</code>) module, or break your string down into words yourself and work word-by-word instead. Why? Well, here's a simple example: <code>'Teh'</code> needs to be corrected to <code>'The'</code>âbut what if the document contains a reference to <code>'Tehran'</code>? Your "Secure Boot" text will contain an example analogous to this.</p>
<p>If you go the regular-expression route, the symbol <code>\b</code> solves this by matching word boundaries of any kind (start or end of string, spaces, punctuation). Here's a simplified example:</p>
<pre><code>import re
replacements = {
'Teh':'The',
}
unscrubbed = 'Teh capital of Iran is Tehran. Teh capital of France is Paris.'
better = unscrubbed
naive = unscrubbed
for target, replacement in replacements.items():
naive = naive.replace(target, replacement)
pattern = r'\b' + target + r'\b'
better = re.sub(pattern, replacement, better)
print(unscrubbed)
print(naive)
print(better)
</code></pre>
<p>Output, with mistakes emphasized:</p>
<blockquote>
<p><strong><em>Teh</em></strong> capital of Iran is Tehran. <strong><em>Teh</em></strong> capital of France is Paris. (<code>unscrubbed</code>)</p>
<p>The capital of Iran is <strong><em>Theran</em></strong>. The capital of France is Paris. (<code>naive</code>)</p>
<p>The capital of Iran is Tehran. The capital of France is Paris. (<code>better</code>)</p>
</blockquote>
| 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"] in an array
</code></pre>
<p>How do I do that?</p>
| 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/cluster/k_means_.py</a>. However, it's not listed in <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/__init__.py#L17" rel="nofollow">scikit-learn/blob/master/sklearn/cluster/__init__.py</a>. Is there any "nice" way to do that?</p>
| 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/cluster/k_means_.py</a>. However, it's not listed in <a href="https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/cluster/__init__.py#L17" rel="nofollow">scikit-learn/blob/master/sklearn/cluster/__init__.py</a>. Is there any "nice" way to do that?</p>
| 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(DeclarativeBase):
__tablename__ = 'questions'
id = Column(Integer, primary_key=True)
content = Column(Unicode(2500), nullable=False)
account_id = Column(Integer, ForeignKey(
'accounts.id', onupdate='CASCADE', ondelete='CASCADE'), nullable=False)
account = relationship('Account', backref=backref('questions'))
</code></pre>
<p>I got a method that returns a question in json format from the provided question ID.
when the method is like this below, it only returns the <code>id</code> the <code>content</code> and the <code>account_id</code> of the question.</p>
<pre><code> @expose('json')
def question(self, question_id):
return dict(questions=DBSession.query(Question).filter(Question.id == question_id).one())
</code></pre>
<p>but I need the user_name of Account to be included in the json response too. something weird (at least to me) is that I have to explicitly tell the method that the query result contains a relation to an Account and this way the account info will be included in the json response: I mean doing something like this</p>
<pre><code> @expose('json')
def question(self, question_id):
result = DBSession.query(Question).filter(Question.id == question_id).one()
weird_variable = result.account.user_name
return dict(question=result)
</code></pre>
<p>why do I have to do such thing? what is the reason behind this?</p>
| 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 relationship <em>account</em> does not actually load the account data when you fetch a <code>Question</code>, but when you access the <code>account</code> attribute of a <code>Question</code> instance. This behaviour can be controlled:</p>
<pre><code>from sqlalchemy.orm import joinedload
DBSession.query(Question).\
filter(Question.id == question_id).\
options(joinedload('account')).\
one()
</code></pre>
<p>Adding the <code>joinedload</code> option instructs the query to load the relationship at the same time with the parent, using a join. Other eager loading techniques are also available, their possible use cases and tradeoffs discussed under <a href="http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html#what-kind-of-loading-to-use" rel="nofollow">"What Kind of Loading to Use?"</a></p>
| 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 for loop but I guess there could be more direct way to doing so. The closest (wrong solution) i have is arr[:][-1] which gives me element of last row and arr[np.arange(len(arr)),-1] which throws an 'IndexError' error. </p>
<p>My desired output is:</p>
<pre><code>array([['orange','scooter','purple']], dtype=object)
</code></pre>
<p>I will appreciate any guidance. thank you.</p>
| 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 [car, bike, train, ship, plane, scooter]
2 [red, purple]
In [94]: df[0].str[-1]
Out[94]:
0 orange
1 scooter
2 purple
Name: 0, dtype: object
</code></pre>
<p>or as a NumPy array:</p>
<pre><code>In [95]: df[0].str[-1].values
Out[95]: array(['orange', 'scooter', 'purple'], dtype=object)
</code></pre>
| 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 for loop but I guess there could be more direct way to doing so. The closest (wrong solution) i have is arr[:][-1] which gives me element of last row and arr[np.arange(len(arr)),-1] which throws an 'IndexError' error. </p>
<p>My desired output is:</p>
<pre><code>array([['orange','scooter','purple']], dtype=object)
</code></pre>
<p>I will appreciate any guidance. thank you.</p>
| 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.html" rel="nofollow"><code>np.concatenate</code></a> to get a flattened version and then indexing into it with proper indices for the selection of final elements of each list -</p>
<pre><code>np.concatenate(arr)[np.cumsum(map(len,arr))-1]
</code></pre>
<p>There's an use of <code>map</code> operator, which doesn't look like a vectorized operation, but since we are using it to only get the lengths of the lists, that part should not be heavy on runtime. So, I guess it's an almost vectorized approach.</p>
<p>Sample run -</p>
<pre><code>In [166]: arr
Out[166]:
array([['apple', 'banana', 'orange'],
['car', 'bike', 'train', 'ship', 'plane', 'scooter'],
['red', 'purple']], dtype=object)
In [167]: np.concatenate(arr)[np.cumsum(map(len,arr))-1]
Out[167]:
array(['orange', 'scooter', 'purple'],
dtype='|S7')
</code></pre>
<p>Please note that if we want an object dtype array, we would need to convert to such dtype before indexing : <code>np.concatenate(arr).astype(object)</code>.</p>
| 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 for loop but I guess there could be more direct way to doing so. The closest (wrong solution) i have is arr[:][-1] which gives me element of last row and arr[np.arange(len(arr)),-1] which throws an 'IndexError' error. </p>
<p>My desired output is:</p>
<pre><code>array([['orange','scooter','purple']], dtype=object)
</code></pre>
<p>I will appreciate any guidance. thank you.</p>
| 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 [x[-1] for x in b] # 75.9 µs
f = np.frompyfunc(lambda x:x[-1], 1, 1)
%timeit f(b) # 165 µs
import cytoolz
%timeit list(cytoolz.pluck(-1, a)) # 42.7 µs
%timeit list(cytoolz.pluck(-1, b)) # 75.8 µs
import pandas as pd
s = pd.Series(a)
%timeit s.str[-1] # 965 µs
</code></pre>
<p>Even you have a DataFrame or Series object, you can convert it to a list first:</p>
<pre><code>%timeit s.tolist() #45.6 µs
</code></pre>
| 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 = ['62','68','93','75','89','85']
print grades [3]
def lettergrade (grades):
if grades >=90:
print('A')
elif grades >=80 and grades <90:
print('B')
elif grades >=70 and grades <80:
print('C')
elif grades >=60 and grades <70:
print('D')
else:
print('F')
print lettergrade (grades)
</code></pre>
| 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 <code>false</code>. The comparison that you are looking for is <code>if(grades[index]>= 90):</code> where <code>index</code> is whatever index you are looking at.</p>
<p>The <code>print()</code> statement inside <code>lettergrade()</code> will only print out the grade, so change each print statement to `print('LETTER:' + value).</p>
<p>In addition, the method <code>lettergrade()</code> will only print out one thing, so there needs to be a loop to call it multiple times, with multiple values:</p>
<pre><code>for value in grades:
lettergrade(value)
</code></pre>
| 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 = ['62','68','93','75','89','85']
print grades [3]
def lettergrade (grades):
if grades >=90:
print('A')
elif grades >=80 and grades <90:
print('B')
elif grades >=70 and grades <80:
print('C')
elif grades >=60 and grades <70:
print('D')
else:
print('F')
print lettergrade (grades)
</code></pre>
| 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:
return('C')
elif grades >=60 and grades <70:
return('D')
else:
return('F')
grades = ['62','68','93','75','89','85']
for grade in grades: # iterate in grades
# call to lettergrade function -> lettergrade(grade)
print(grade, ' equivalent ', lettergrade(grade))
</code></pre>
| 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 = ['62','68','93','75','89','85']
print grades [3]
def lettergrade (grades):
if grades >=90:
print('A')
elif grades >=80 and grades <90:
print('B')
elif grades >=70 and grades <80:
print('C')
elif grades >=60 and grades <70:
print('D')
else:
print('F')
print lettergrade (grades)
</code></pre>
| 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:
print('A', score)
elif grades >=80 and grades <90:
print('B', score)
elif grades >=70 and grades <80:
print('C', score)
elif grades >=60 and grades <70:
print('D', score)
else:
print('F', score)
except:
print "Error"
</code></pre>
| 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 = ['62','68','93','75','89','85']
print grades [3]
def lettergrade (grades):
if grades >=90:
print('A')
elif grades >=80 and grades <90:
print('B')
elif grades >=70 and grades <80:
print('C')
elif grades >=60 and grades <70:
print('D')
else:
print('F')
print lettergrade (grades)
</code></pre>
| 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, 'C']
elif grade >= 60 and grades < 70:
result = [grade, 'D']
else:
result = [grade, 'F']
return result
# call LetterGrade for each value in grades array
for grade in grades:
print(LetterGrade(grade))
</code></pre>
<p>You needed to loop for each value in the grades array. Also, try to get into the habit of following PEP 8 (Python style guide)</p>
| 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>import a</code> (from the appropriate directory), there is no error. Both packages have <code>__init__.py</code>s. <a href="http://stackoverflow.com/questions/6351805/cyclic-module-dependencies-and-relative-imports-in-python">This answer</a> explains why fairly well, but does not mention how to fix this. How can I fix this?</p>
<p>File structure:</p>
<pre><code>parent_directory
a
__init__.py
module_in_a.py
b
__init__.py
module_in_b.py (this imports a)
</code></pre>
| 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 packages <code>a</code> and <code>b</code>, you don't have a problem. Python's <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> can help with local installs that don't affect your system python modules. But you can also edit the <code>PYTHONPATH</code> environment variable to point to a place where you have installed <code>a</code> and <code>b</code> or you can change <code>sys.path</code> inside your program. For instance, </p>
<p>b/module_in_b.py</p>
<pre><code>import sys
import os
_my_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _my_path not in sys.path:
sys.path.append(_my_path)
del _my_path
import a
</code></pre>
| 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>I tried using:
conda install -c menpo enum=0.4.4
but it didn't work.</p>
<p>I also tried installing enum from this link - <a href="https://pypi.python.org/pypi/enum34#downloads" rel="nofollow">https://pypi.python.org/pypi/enum34#downloads</a></p>
<p>None of these solutions have worked for me so far. </p>
<p>Any help would be greatly appreciated. Thanks!</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)
IPv4Address('127.23.181.175')
</code></pre>
<p>Is there is an analogue for IPv6?</p>
| -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 address 0:0:0:0:0:0:0:1 is called the loopback address.
It may be used by a node to send an IPv6 packet to itself. It must
not be assigned to any physical interface. It is treated as having
Link-Local scope, and may be thought of as the Link-Local unicast
address of a virtual interface (typically called the "loopback
interface") to an imaginary link that goes nowhere.</p>
<p>The loopback address must not be used as the source address in IPv6
packets that are sent outside of a single node. An IPv6 packet with
a destination address of loopback must never be sent outside of a
single node and must never be forwarded by an IPv6 router. A packet
received on an interface with a destination address of loopback must
be dropped.</p>
</blockquote>
| 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 <code>Hello World</code>. How would I execute this file with arguments, using <code>import</code>?</p>
| 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-subprocess-module" rel="nofollow"><code>subprocess.run()</code></a>.</p>
<hr>
<p>In Python 2 you may use <a href="https://docs.python.org/2.7/library/subprocess.html#subprocess.call" rel="nofollow"><code>subprocess.call()</code></a> or <a href="https://docs.python.org/2.7/library/subprocess.html#subprocess.check_output" rel="nofollow"><code>subprocess.check_output()</code></a> if you need the programs output.</p>
| 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 <code>Hello World</code>. How would I execute this file with arguments, using <code>import</code>?</p>
| 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 more complex parsing.</p>
| 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? </p>
| 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 line:</p>
<pre><code>comm_ip_addr_one, comm_ip_addr_two, mac_addr_one, mac_addr_two = \
compute_ip_address()
</code></pre>
| 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 with are large (up to 1000x1000), so I'm looking for an efficient way to do this. This is my current solution:</p>
<pre><code>def weighted_mat_choice(prob_mat):
"""
Randomly select indices of the matrix according to the probabilities in prob_mat
:param prob_mat: Normalized probabilities to select each element
:return: indices (i, j) selected
"""
inds_mat = [[(i, j) for j in xrange(prob_mat.shape[1])] for i in xrange(prob_mat.shape[0])]
inds_list = [item for sublist in inds_mat for item in sublist]
inds_of_inds = xrange(len(inds_list))
prob_list = prob_mat.flatten()
pick_ind_of_ind = np.random.choice(inds_of_inds, p=prob_list)
pick_ind = inds_list[pick_ind_of_ind]
return pick_ind
</code></pre>
<p>which is definitely not efficient. (Basically, linearizing the matrix, creating a list of index tuples, and then picking accordingly.) Is there a better way to do this selection?</p>
| 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))
res = np.column_stack(
np.unravel_index(
np.random.choice(ind, p=p_flat, size=10000),
p.shape))
</code></pre>
<p>The result:</p>
<pre><code>array([[0, 2],
[2, 2],
[2, 1],
...,
[1, 0],
[0, 2],
[0, 0]], dtype=int64)
</code></pre>
| 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 commission:"))
#Calculations
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
#Output
print("Stock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
===============================OUTPUT===================================================
Enter stock name OR -999 to Quit:Google
Enter number of shares:10000
Enter purchase price:39.99
Enter selling price:35.99
Enter commission:0.04
Enter stock name OR -999 to Quit:Amazon
Enter number of shares:10000
Enter purchase price:15.99
Enter selling price:33.99
Enter commission:0.04
Enter stock name OR -999 to Quit:-999
Enter number of shares:10000
Enter purchase price:14.99
Enter selling price:49.99
Enter commission:0.04
Stock Name: -999
Amount paid for the stock: $ 149,900.00
Commission paid on the purchase: $ 5,996.00
Amount the stock sold for: $ 499,900.00
Commission paid on the sale: $ 19,996.00
Profit (or loss if negative): $ 324,008.00
</code></pre>
<p>As you can see I'm inputting stocks for Google and Amazon, but they're not being printed when I run the "-999" to break out of the while loop. Instead, it thinks that "-999" is a Stock name and quits when you enter fake numbers for it and prints those instead. I can't figure out what I'm doing wrong. </p>
| -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
test=input("Enter stock name OR -999 to Quit:")
if test=='-999': break
name=test
shares=int(input("Enter number of shares:"))
pp=float(input("Enter purchase price:"))
sp=float(input("Enter selling price:"))
commission=float(input("Enter commission:"))
#Calculations
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
#Output
result += """
Stock Name: {}
Amount paid for the stock: ${:06.2f}
Commission paid on the purchase: ${:06.2f}
Amount the stock sold for: ${:06.2f}
Commission paid on the sale: ${:06.2f}
Profit (or loss if negative): ${:06.2f}
""".format(name, amount_paid, commission_paid_purchase, amount_sold, commission_paid_sale, profit_loss)
print (result);
</code></pre>
<p>See it run on <a href="https://repl.it/Dg8d/1" rel="nofollow">repl.it</a></p>
| 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 commission:"))
#Calculations
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
#Output
print("Stock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
===============================OUTPUT===================================================
Enter stock name OR -999 to Quit:Google
Enter number of shares:10000
Enter purchase price:39.99
Enter selling price:35.99
Enter commission:0.04
Enter stock name OR -999 to Quit:Amazon
Enter number of shares:10000
Enter purchase price:15.99
Enter selling price:33.99
Enter commission:0.04
Enter stock name OR -999 to Quit:-999
Enter number of shares:10000
Enter purchase price:14.99
Enter selling price:49.99
Enter commission:0.04
Stock Name: -999
Amount paid for the stock: $ 149,900.00
Commission paid on the purchase: $ 5,996.00
Amount the stock sold for: $ 499,900.00
Commission paid on the sale: $ 19,996.00
Profit (or loss if negative): $ 324,008.00
</code></pre>
<p>As you can see I'm inputting stocks for Google and Amazon, but they're not being printed when I run the "-999" to break out of the while loop. Instead, it thinks that "-999" is a Stock name and quits when you enter fake numbers for it and prints those instead. I can't figure out what I'm doing wrong. </p>
| -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:"))
pp = float(input("Enter purchase price:"))
sp = float(input("Enter selling price:"))
commission = float(input("Enter commission:"))
</code></pre>
<p>That said, your script is only going to process the information for the <em>last</em> stock you enter; each iteration of the loop overwrites the previous value of <code>name</code>, <code>shares</code>, <code>pp</code>, <code>sp</code>, and <code>commission</code>. You want to either move the calculations inside the loop as well, or save <em>all</em> the data entered in a list or a dictionary so you can access it later.</p>
| 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 commission:"))
#Calculations
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
#Output
print("Stock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))
===============================OUTPUT===================================================
Enter stock name OR -999 to Quit:Google
Enter number of shares:10000
Enter purchase price:39.99
Enter selling price:35.99
Enter commission:0.04
Enter stock name OR -999 to Quit:Amazon
Enter number of shares:10000
Enter purchase price:15.99
Enter selling price:33.99
Enter commission:0.04
Enter stock name OR -999 to Quit:-999
Enter number of shares:10000
Enter purchase price:14.99
Enter selling price:49.99
Enter commission:0.04
Stock Name: -999
Amount paid for the stock: $ 149,900.00
Commission paid on the purchase: $ 5,996.00
Amount the stock sold for: $ 499,900.00
Commission paid on the sale: $ 19,996.00
Profit (or loss if negative): $ 324,008.00
</code></pre>
<p>As you can see I'm inputting stocks for Google and Amazon, but they're not being printed when I run the "-999" to break out of the while loop. Instead, it thinks that "-999" is a Stock name and quits when you enter fake numbers for it and prints those instead. I can't figure out what I'm doing wrong. </p>
| -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>control+c</code> to it ? I cannot find it by using <code>taskList</code> in windows command line.</p>
<pre><code> SHELLEXECUTEINFO processInfo;
processInfo.cbSize = sizeof(SHELLEXECUTEINFO);
processInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
processInfo.hwnd = NULL;
processInfo.lpVerb = NULL;
processInfo.lpFile = L"C:\\Users\\Li\\ddddp\\bin\\scripts\\dddpstart.pyc";
processInfo.lpParameters = L"--device-type --device-serial yyyyy --device-model TEST --debug --verbose";
processInfo.lpDirectory = NULL;
processInfo.nShow = SW_MAXIMIZE;
processInfo.hInstApp = NULL;
ShellExecuteEx(&processInfo);
TerminateProcess(processInfo.hProcess, 1);
</code></pre>
<p>Then a console pops up but it doesn't stop at the end of the code.</p>
| 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, get the PID, and then call kill() with the PID and the signal number - SIGKILL (9) should kill it off, but other signals, such SIGHUP and SIGQUIT are less draconian and your Python program can trap those and exit gracefully.</p>
<p>If you need example code, let me know, however, once you know the "how", this is pretty straightforward.</p>
| -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:
print i.knob("motionblur").value() #Transform nuke node class
print i.knob("samples").value() #ScanlineRender nuke node class
</code></pre>
<p>Thank you.</p>
| 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 node.</p>
<pre><code>for i in nuke.allNodes():
if i.Class() == "MotionBlur":
#DO SOMETHING
elif i.Class() == "Transform":
#DO SOMETHING
</code></pre>
<p>If you are doing the same thing to both types of nodes, you could merge two lists and iterate over it.</p>
<pre><code>n = nuke.allNodes("MotionBlur")
n.extend(nuke.allNodes("Transform"))
for i in n:
#DO SOMETHING TO BOTH TYPES
</code></pre>
<p>I don't know what you are specifically trying to achieve, so this may not be the most efficient method.</p>
| 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",
"http://pitchfork.com/reviews/best/reissues/?page=2",
"http://pitchfork.com/reviews/best/reissues/?page=3",
]
def parse(self, response):
for sel in response.xpath('//div[@class="album-artist"]'):
item = PitchforkItem()
item['artist'] = sel.xpath('//ul[@class="artist-list"]/li/text()').extract()
item['reissue'] = sel.xpath('//h2[@class="title"]/text()').extract()
return item
</code></pre>
<p>then I import the <code>module</code> where the <code>class</code> belongs:</p>
<pre><code>from blogs.spiders.pitchfork_reissues_feed import *
</code></pre>
<p>and try to call <code>parse()</code> in another context:</p>
<pre><code>def reissues(self):
pitchfork_reissues = PitchforkSpider()
reissues = pitchfork_reissues.parse('response')
print (reissues)
</code></pre>
<p>but I get the following error:</p>
<pre><code>pitchfork_reissues.parse('response')
File "/Users/vitorpatalano/Documents/Code/Soup/Apps/myapp/blogs/blogs/spiders/pitchfork_reissues_feed.py", line 21, in parse
for sel in response.xpath('//div[@class="album-artist"]'):
AttributeError: 'str' object has no attribute 'xpath'
</code></pre>
<p>what am I missing?</p>
| 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>parse</code> method requires an instance of <code>scrapy.http.Response</code> as it's first argument, not a string literal that contains the word 'response'.</p>
<p>I haven't used Scrapy myself, so I only know what I read in the documentation, but apparently such a Response instance is usually created by a 'Downloader'.</p>
<p>It seems that you're trying to call your Spider's <code>parse</code> method outside of Scrapy's usual workflow. In that case I think you're responsible for creating such a Response and passing it to your Spider when calling it's <code>parse</code> method.</p>
| 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 collected packages: lxml
Running setup.py install for lxml ... error
Complete output from command /usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-9YW4Cf/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-bin1bn-record/install-record.txt --single-version-externally-managed --compile:
Building lxml version 3.6.4.
Building without Cython.
Using build configuration of libxslt 1.1.26
Building against libxml2/libxslt in the following directory: /usr/lib64
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.6
creating build/lib.linux-x86_64-2.6/lxml
copying src/lxml/usedoctest.py -> build/lib.linux-x86_64-2.6/lxml
copying src/lxml/doctestcompare.py -> build/lib.linux-x86_64-2.6/lxml
copying src/lxml/ElementInclude.py -> build/lib.linux-x86_64-2.6/lxml
copying src/lxml/builder.py -> build/lib.linux-x86_64-2.6/lxml
copying src/lxml/pyclasslookup.py -> build/lib.linux-x86_64-2.6/lxml
copying src/lxml/_elementpath.py -> build/lib.linux-x86_64-2.6/lxml
copying src/lxml/cssselect.py -> build/lib.linux-x86_64-2.6/lxml
copying src/lxml/__init__.py -> build/lib.linux-x86_64-2.6/lxml
copying src/lxml/sax.py -> build/lib.linux-x86_64-2.6/lxml
creating build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/__init__.py -> build/lib.linux-x86_64-2.6/lxml/includes
creating build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/usedoctest.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/_setmixin.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/formfill.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/clean.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/soupparser.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/_html5builder.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/defs.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/builder.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/ElementSoup.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/diff.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/_diffcommand.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/__init__.py -> build/lib.linux-x86_64-2.6/lxml/html
copying src/lxml/html/html5parser.py -> build/lib.linux-x86_64-2.6/lxml/html
creating build/lib.linux-x86_64-2.6/lxml/isoschematron
copying src/lxml/isoschematron/__init__.py -> build/lib.linux-x86_64-2.6/lxml/isoschematron
copying src/lxml/lxml.etree.h -> build/lib.linux-x86_64-2.6/lxml
copying src/lxml/lxml.etree_api.h -> build/lib.linux-x86_64-2.6/lxml
copying src/lxml/includes/relaxng.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/tree.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/xpath.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/config.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/etreepublic.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/xinclude.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/uri.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/xmlparser.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/c14n.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/htmlparser.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/xslt.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/xmlschema.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/xmlerror.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/schematron.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/dtdvalid.pxd -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/lxml-version.h -> build/lib.linux-x86_64-2.6/lxml/includes
copying src/lxml/includes/etree_defs.h -> build/lib.linux-x86_64-2.6/lxml/includes
creating build/lib.linux-x86_64-2.6/lxml/isoschematron/resources
creating build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/rng
copying src/lxml/isoschematron/resources/rng/iso-schematron.rng -> build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/rng
creating build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/xsl
copying src/lxml/isoschematron/resources/xsl/XSD2Schtrn.xsl -> build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/xsl
copying src/lxml/isoschematron/resources/xsl/RNG2Schtrn.xsl -> build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/xsl
creating build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_svrl_for_xslt1.xsl -> build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_message.xsl -> build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_dsdl_include.xsl -> build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_schematron_skeleton_for_xslt1.xsl -> build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/iso_abstract_expand.xsl -> build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
copying src/lxml/isoschematron/resources/xsl/iso-schematron-xslt1/readme.txt -> build/lib.linux-x86_64-2.6/lxml/isoschematron/resources/xsl/iso-schematron-xslt1
running build_ext
building 'lxml.etree' extension
creating build/temp.linux-x86_64-2.6
creating build/temp.linux-x86_64-2.6/src
creating build/temp.linux-x86_64-2.6/src/lxml
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -I/usr/include/libxml2 -Isrc/lxml/includes -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-x86_64-2.6/src/lxml/lxml.etree.o -w
{standard input}: Assembler messages:
{standard input}:224305: Warning: end of file in string; '"' inserted
gcc: Internal error: Killed (program cc1)
Please submit a full bug report.
See <http://bugzilla.redhat.com/bugzilla> for instructions.
Compile failed: command 'gcc' failed with exit status 1
creating tmp
cc -I/usr/include/libxml2 -I/usr/include/libxml2 -c /tmp/xmlXPathInitDjSg3x.c -o tmp/xmlXPathInitDjSg3x.o
cc tmp/xmlXPathInitDjSg3x.o -L/usr/lib64 -lxml2 -o a.out
error: command 'gcc' failed with exit status 1
----------------------------------------
Command "/usr/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-9YW4Cf/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-bin1bn-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-9YW4Cf/lxml/
</code></pre>
| 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 write the directory name like this:</p>
<pre><code>open("/studentstories/Zorine.txt", "r")
</code></pre>
<p>Do I need to import sys and use sys.listdir or os.path? If so can you please give a quick little example how to do this? Thank you in advance.</p>
| 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['Content-Disposition'] = 'attachment;filename="somefilename.pdf"'
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
##################### 1. First and last name
first_last_name = "Barney Stinson"
can.drawString(63, 686, first_last_name)
#Saving
can.save()
#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file("fw9.pdf", "rb"))
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
page = existing_pdf.getPage(0)
page.mergePage(new_pdf.getPage(0))
output.addPage(page)
# finally, write "output" to a real file
#outputStream = file("output.pdf", "wb")
#output.write(outputStream)
response.write(output)
outputStream.close()
return response
</code></pre>
<p>It let's me download the pdf, but when I am trying to open it, I get the message, that the file is damaged or wasn't correctly decoded.</p>
<p>Does anyone know what am I don't wrong?</p>
<p>Thank you!</p>
| 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</code> object which would be something like:</p>
<pre><code><PyPDF2.pdf.PdfFileWriter object at 0x7f0e801ea090>
</code></pre>
<p>which is what you will find in the downloaded PDF file.</p>
| 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
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, black, [lead_x, lead_y, 10, 10])
pygame.display.update()
gameExit=False
while not gameExit:
for event in pygame.event.get():
print (event)
if (event.type == pygame.QUIT):
gameExit=True
if (event.type == pygame.KEYDOWN):
if event.key == pygame.K_LEFT:
lead_x -= 10
if event.key == pygame.K_RIGHT:
lead_x += 10
pygame.display.update()
</code></pre>
| -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 password is in the span tag. Here is the part of content fetched from gmail which is in the variable 'body':</p>
<pre><code>Helvetica;font-size: 14px;font-weight: normal;text-align: ce=
nter;"> <span style=3D"font-size:28px">orPYG$XV</span><!----></td> </tr> </=
tbody> </table> </td> </tr> </tbody> </table> <!--[if gte mso 9]></td>
</code></pre>
<p>The part of my python code to fetch :</p>
<pre><code>passwordd =re.findall(r'<span style=3D"font-size:28px">+.*</span>', str(body), re.I|re.M)
lookkk = re.findall(r'(?<![A-Za-z0-9]))', str(passwordd))
print(str(lookkk))
</code></pre>
<p>where:<br>
body: is the email content I fetched from the gmail inbox in HTML form<br>
passwordd: is a variable created to extract the content from the email text<br>
lookkk: is the final out I'm looking for that is the length 8 password</p>
<p>The passwordd is able to fetch the password including the <code><span...span></code>. I want to exclude the <code><span...span></code>. How can I do that? Also, is it possible to get the plain text from gmail instead of text in html form. I looked at many forums but couldn't do that.</p>
| 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 a more specific search matching exactly what the word is expected to be : <code>[@#$_!0-9a-zA-Z]{8}</code>, so only one expression is enough to find the word.</p>
<p>try <a href="https://regex101.com/r/oR7vX8/1" rel="nofollow">your example on regex101</a> </p>
| 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]: from hypothesis import find, strategies as st
In [2]: find(st.sampled_from(('ST', 'LT', 'TG', 'CT')), lambda x: True)
Out[2]: 'ST'
</code></pre>
<p>But, is there a way to have <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow"><code>random.sample()</code></a>-like strategy to produce subsequences of length N out of a sequence?</p>
<pre><code>In [3]: import random
In [4]: random.sample(('ST', 'LT', 'TG', 'CT'), 2)
Out[4]: ['CT', 'TG']
</code></pre>
| 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 seems to work.</p>
<pre><code>from random import sample
from hypothesis.searchstrategy.strategies import SearchStrategy
from hypothesis.strategies import defines_strategy
class SampleMultipleFromStrategy(SearchStrategy):
def __init__(self, elements, n):
super(SampleMultipleFromStrategy, self).__init__()
self.elements = tuple(elements)
if not self.elements:
raise ValueError
self.n = int(n)
def do_draw(self, data):
return sample(self.elements, self.n)
@defines_strategy
def sample_multiple_from(elements, n):
return SampleMultipleFromStrategy(elements, n)
</code></pre>
<p>Sample result:</p>
<pre><code>>>> find(sample_multiple_from([1, 2, 3, 4], 2), lambda x: True)
[4, 2]
</code></pre>
| 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]: from hypothesis import find, strategies as st
In [2]: find(st.sampled_from(('ST', 'LT', 'TG', 'CT')), lambda x: True)
Out[2]: 'ST'
</code></pre>
<p>But, is there a way to have <a href="https://docs.python.org/3/library/random.html#random.sample" rel="nofollow"><code>random.sample()</code></a>-like strategy to produce subsequences of length N out of a sequence?</p>
<pre><code>In [3]: import random
In [4]: random.sample(('ST', 'LT', 'TG', 'CT'), 2)
Out[4]: ['CT', 'TG']
</code></pre>
| 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')
</code></pre>
<p>what is this dtype and what does it mean?
Any help would be appreciated </p>
| 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, it is incompatible with the <code>'%.4f'</code> <a href="https://docs.python.org/2.4/lib/typesseq-strings.html" rel="nofollow">format specifier</a>. Instead, use something like <code>'%u'</code>.</p>
<pre><code>np.savetxt('data.csv', array, delimiter=',', fmt='%u')
</code></pre>
<p>If you really want your data formatted as floating point values in your csv, you can <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.astype.html" rel="nofollow">cast</a> the array to float like so:</p>
<pre><code>np.savetxt('data.csv', array.astype(float), delimiter=',', fmt='%.4f')
</code></pre>
| 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("opencv",img)
WaitKey(0)
</code></pre>
<p>The procedure I did was the following...</p>
<p>I downloaded the zip file from the main page of GitHub and while being in a destination directory I created, I built OpenCV using</p>
<p><code>cmake OpenCV_Source_Directory</code></p>
<p>Then on the destination directory I run</p>
<p><code>make</code></p>
<p><code>sudo make install</code></p>
| 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>cv2.cv</code> module doesn't exist.</p>
| 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("opencv",img)
WaitKey(0)
</code></pre>
<p>The procedure I did was the following...</p>
<p>I downloaded the zip file from the main page of GitHub and while being in a destination directory I created, I built OpenCV using</p>
<p><code>cmake OpenCV_Source_Directory</code></p>
<p>Then on the destination directory I run</p>
<p><code>make</code></p>
<p><code>sudo make install</code></p>
| 2 |
2016-09-23T23:30:49Z
| 39,677,259 |
<p>Presumable you did:</p>
<pre><code>git clone git@github.com: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-g7f14a27
</code></pre>
<p>That is, the default branch is OpenCV 3, which doesn't have the cv2.cv module.
Either change your code to work with the OpenCV 3 cv2 module.
Or downgrade to OpenCV2. You can do this by:</p>
<pre><code>cd opencv
git checkout 2.4.13.1
cd ../build && so on ...
</code></pre>
| 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("opencv",img)
WaitKey(0)
</code></pre>
<p>The procedure I did was the following...</p>
<p>I downloaded the zip file from the main page of GitHub and while being in a destination directory I created, I built OpenCV using</p>
<p><code>cmake OpenCV_Source_Directory</code></p>
<p>Then on the destination directory I run</p>
<p><code>make</code></p>
<p><code>sudo make install</code></p>
| 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)]
output = []
for delta in deltas:
for i in range(delta):
datum = next(iterator)
output.append(datum)
</code></pre>
<p>Are those two layers of loop necessary? Am I missing a trick with <code>itertools</code>?</p>
| 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 itertools.islice(iterator, max_index + 1)]
values = [data[i] for i in indices]
</code></pre>
| 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)]
output = []
for delta in deltas:
for i in range(delta):
datum = next(iterator)
output.append(datum)
</code></pre>
<p>Are those two layers of loop necessary? Am I missing a trick with <code>itertools</code>?</p>
| 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)
try:
index = next(it)
except StopIteration:
break
</code></pre>
<p>You can also do this in a list comprehension for very low number of indices as you incur overhead for the check (but avoid the <code>sort</code>):</p>
<pre><code>[datum for i, datum in enumerate(x) if i in indices]
</code></pre>
<p>You can reduce the cost of the check by converting <code>indices</code> to a <code>set</code>. I would be interested to see performance of <code>sort</code> over a <code>set</code> construction (set lookup is O(1)):</p>
<pre><code>indices = set(indices)
[datum for i, datum in enumerate(x) if i in indices]
</code></pre>
<p><strong>Update</strong>: First and third options are roughly equivalent in timing at just over 900 ms (slight edge to first) to choose 1000 random indices out of 10,000,000 items. The OP's code ran in about 1.2 s.</p>
| 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 the top right corner. Each subsequent image must be placed beneath the previous and wedged into the corner.</p>
<p>Here is my current function:</p>
<pre><code>def pyramid2img(pmd):
'''
Given a pre-constructed pyramid, this is a helper
function to display the pyramid in a single image.
'''
# orignal shape (pyramid goes from biggest to smallest)
org_img_shp = pmd[0].shape
# the output will have to have 1.5 times the width
out_shp = tuple(int(x*y) \
for (x,y) in zip(org_img_shp, (1, 1.5)))
new_img = np.zeros(out_shp, dtype=np.int8)
# i keep track of the top left corner of where I want to
# place the current image matrix
origin = [0, 0]
for lvl, img_mtx in enumerate(pmd):
# trying to specify the subset to place the next img_mtx in
sub = new_img[origin[0]:origin[0]+pmd[lvl].shape[0],
origin[1]:origin[1]+pmd[lvl].shape[1]]# = img_mtx
# some prints to see exactly whats being called above ^
print 'level {}, sub {}, mtx {}'.format(
lvl, sub.shape, img_mtx.shape)
print 'sub = new_img[{}:{}, {}:{}]'.format(
origin[0], origin[0]+pmd[lvl].shape[0],
origin[1], origin[1]+pmd[lvl].shape[1])
# first shift moves the origin to the right
if lvl == 0:
origin[0] += pmd[lvl].shape[0]
# the rest move the origin downward
else:
origin[1] += pmd[lvl].shape[1]
return new_img
</code></pre>
<p>OUTPUT FROM THE PRINT STATEMENTS:</p>
<pre><code>level 0, sub (256, 256), mtx (256, 256)
sub = new_img[0:256, 0:256]
level 1, sub (0, 128), mtx (128, 128)
sub = new_img[256:384, 0:128]
level 2, sub (0, 64), mtx (64, 64)
sub = new_img[256:320, 128:192]
level 3, sub (0, 32), mtx (32, 32)
sub = new_img[256:288, 192:224]
level 4, sub (0, 16), mtx (16, 16)
sub = new_img[256:272, 224:240]
level 5, sub (0, 8), mtx (8, 8)
sub = new_img[256:264, 240:248]
level 6, sub (0, 4), mtx (4, 4)
sub = new_img[256:260, 248:252]
</code></pre>
<p>If you look at the output, you can see that I am trying to reference a 2d-slice of the output image so that I can place the next level of the pyramid inside it.</p>
<p>The problem is that the slicing I am performing is not giving a 2d-array with the shape I expect it too. It thinks I am trying to put a (n,n) matrix into a (0, n) matrix.</p>
<p>How come when I specify a slice like <code>new_img[256:320, 128:192]</code>, it returns an object with shape <code>(0, 64)</code>, NOT <code>(64, 64)</code>?</p>
<p>Is there an easier way to do what I am trying to do?</p>
| 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 images:</p>
<pre><code>def align(size, width, loc):
if loc in ("left", "top"):
return 0
elif loc in ("right", "bottom"):
return size - width
elif loc == "center":
return (size - width) // 2
def resize_canvas(img, shape, loc, fill=255):
new_img = np.full(shape + img.shape[2:], fill, dtype=img.dtype)
y = align(shape[0], img.shape[0], loc[0])
x = align(shape[1], img.shape[1], loc[1])
new_img[y:y+img.shape[0], x:x+img.shape[1], ...] = img
return new_img
def vbox(imgs, align="right", fill=255):
width = max(img.shape[1] for img in imgs)
return np.concatenate([
resize_canvas(img, (img.shape[0], width), ("top", align), fill=fill)
for img in imgs
])
def hbox(imgs, align="top", fill=255):
height = max(img.shape[0] for img in imgs)
return np.concatenate([
resize_canvas(img, (height, img.shape[1]), (align, "left"), fill=fill)
for img in imgs
], axis=1)
</code></pre>
<p>the output of:</p>
<pre><code>pl.imshow(hbox([imgs[0], vbox(imgs[1:])]))
</code></pre>
<p><a href="http://i.stack.imgur.com/pCSVp.png" rel="nofollow"><img src="http://i.stack.imgur.com/pCSVp.png" alt="enter image description here"></a></p>
| 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
passenger on a vessel travelling from India to
Australia, that vessel ("the
Indian vessel") was intercepted by an Australian border protection vessel ("the
Commonwealth ship")
in Australia's contiguous
zone<span class="sup"><b><a name="fnB313" href="http://www.austlii.edu.au/au/cases/cth/HCA/2015/1.html#fn313">[313]</a></b></span>.
</li>
</code></pre>
<p>I have tried using the following <code>find_all</code> function, which returns an empty list.</p>
<pre><code>html.find_all('li', string='KEANE J.')
</code></pre>
<p>I have also tried the <code>find</code> function with regex, which returns a none object:</p>
<pre><code>html.find('li', string=re.compile(r'^KEANE\sJ\.\s'))
</code></pre>
<p>How would I find this element in the html document?</p>
| 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</code> paragraph</a>:</p>
<blockquote>
<p>If a tag contains more than one thing, then itâs not clear what <code>.string</code> should refer to, so <code>.string</code> is defined to be <code>None</code></p>
</blockquote>
<p>What you can do is to locate the <em>text node itself</em> and then get its parent:</p>
<pre><code>li = html.find(string=re.compile(r'^KEANE\sJ\.\s')).parent
print(li)
</code></pre>
| 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 value="Brea(Orange)">Brea</option>
</code></pre>
<p>So I try this: </p>
<pre><code>{%for area in areas%}
{% with area|add:"(Orange)" as area_county%}
<option value="{{area_county}}">{{area}}</option>
{% endwith %}
{%endfor%}
</code></pre>
<p>But the output is this:</p>
<pre><code><option value="">Anaheim</option>
<option value="">Westminster</option>
<option value="">Brea</option>
</code></pre>
<p>Where did I do wrong? </p>
<p>Thank you!</p>
| 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 value="Brea(Orange)">Brea</option>
</code></pre>
<p>So I try this: </p>
<pre><code>{%for area in areas%}
{% with area|add:"(Orange)" as area_county%}
<option value="{{area_county}}">{{area}}</option>
{% endwith %}
{%endfor%}
</code></pre>
<p>But the output is this:</p>
<pre><code><option value="">Anaheim</option>
<option value="">Westminster</option>
<option value="">Brea</option>
</code></pre>
<p>Where did I do wrong? </p>
<p>Thank you!</p>
| 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 against the original column. If any other language other than python is helpful in this case, I appreciate their suggestion too.<br>
I have written a pseudo python code for that:</p>
<pre><code> import pandas as pd
import numpy as np
from sys import argv
from pylab import *
import csv
script, filename = argv
# read flash.dat to a list of lists
datContent = [i.strip().split() for i in open("./flash.dat").readlines()]
# write it as a new CSV file
with open("./flash.dat", "wb") as f:
writer = csv.writer(f)
writer.writerows(datContent)
columns_to_keep = ['#time']
dataframe = pd.read_csv("./flash.csv", usecols=columns_to_keep)
df = pd.DataFrame({"#time"})
df["#time"] = df["#time"] + [pd.Timedelta(minutes=m) for m in np.random.choice(a=range(60), size=df.shape[0])]
df["value"] = np.random.normal(size=df.shape[0])
df["prev_time"] = [np.nan] + df.iloc[:-1]["#time"].tolist()
df["time_delta"] = df.time - df.prev_time
df
pd.set_option('display.height', 1000)
pd.set_option('display.max_rows', 1000)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
dataframe.plot(x='#time', y='time_delta', style='r')
print dataframe
show()
</code></pre>
<p>Updated my code, and i am also sharing the .dat file I am working on.
<a href="https://www.dropbox.com/s/w4jbxmln9e83355/flash.dat?dl=0" rel="nofollow">https://www.dropbox.com/s/w4jbxmln9e83355/flash.dat?dl=0</a></p>
| 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>import pandas as pd
import numpy as np
df = pd.DataFrame({"time": pd.date_range("24 sept 2016", periods=5*24, freq="1h")})
df["time"] = df["time"] + [pd.Timedelta(minutes=m) for m in np.random.choice(a=range(60), size=df.shape[0])]
df["value"] = np.random.normal(size=df.shape[0])
</code></pre>
<p><a href="http://i.stack.imgur.com/9yijZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/9yijZ.png" alt="enter image description here"></a></p>
<p>If you want to compute the time delta from the previous (or next, or whatever) row, you can simply copy the value from it, and then perform the subtraction: </p>
<pre><code>df["prev_time"] = [np.nan] + df.iloc[:-1]["time"].tolist()
df["time_delta"] = df.time - df.prev_time
df
</code></pre>
<p><a href="http://i.stack.imgur.com/YdqFO.png" rel="nofollow"><img src="http://i.stack.imgur.com/YdqFO.png" alt="enter image description here"></a></p>
| 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(Parent):
def __init__(self):
childclass.__init__(self)
self.childgreeting = "Hi I'm a Child Object!"
class ChildB(Parent):
pass
</code></pre>
<p>Now I have to write a parent object and the children objects which will print out their respective strings.<br>
That's where I'm getting confused: I already put in the strings that they are a child or parent object within their classes.<br>
But how do I get them to print as an object?</p>
<p>I've started out my code like this. </p>
<pre><code>class Parent(object):
class ChildA(object):
class ChildB(object):
</code></pre>
<p>How to get those strings to print is bugging me.<br>
And I have a feeling that my ChildA code for the class is not correct either.</p>
<p>Can anyone help me?</p>
| 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 self.greeting
p = Parent()
print(p)
c = Child()
print(c)
</code></pre>
<p>This method could help you to use 'print()' statement to print out greeting for individual class. But if you want to directly get self.greeting attribute you should use </p>
<pre><code>p = Parent()
print(p.greeting)
</code></pre>
<p>Hope I understood you since your questions seems to be not properly explained...</p>
| 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(Parent):
def __init__(self):
childclass.__init__(self)
self.childgreeting = "Hi I'm a Child Object!"
class ChildB(Parent):
pass
</code></pre>
<p>Now I have to write a parent object and the children objects which will print out their respective strings.<br>
That's where I'm getting confused: I already put in the strings that they are a child or parent object within their classes.<br>
But how do I get them to print as an object?</p>
<p>I've started out my code like this. </p>
<pre><code>class Parent(object):
class ChildA(object):
class ChildB(object):
</code></pre>
<p>How to get those strings to print is bugging me.<br>
And I have a feeling that my ChildA code for the class is not correct either.</p>
<p>Can anyone help me?</p>
| 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>
</blockquote>
<p>Okay... </p>
<pre><code>p = Parent()
child_a = ChildA()
print(p.greeting)
print(child_a.childgreeting)
</code></pre>
<p><strong>However</strong> - <code>ChildA()</code> won't work because <code>__init__</code> should look like this </p>
<pre><code>class ChildA(Parent):
def __init__(self):
super().__init__() # This calls the Parent __init__
self.childgreeting = "Hi I'm a Child Object!"
</code></pre>
<p>Now, the above code will work. </p>
<p>But, I assume you want the <code>greeting</code> attribute to be overwritten? Otherwise you get this</p>
<pre><code>print(child_a.greeting) # Hi I'm a Parent Object!
print(child_a.childgreeting) # Hi I'm a Child Object!
</code></pre>
<p>If that is the case, you simply change <code>childgreeting</code> to <code>greeting</code>. Then, from the first example</p>
<pre><code>print(p.greeting) # Hi I'm a Parent Object!
print(child_a.greeting) # Hi I'm a Child Object!
</code></pre>
<blockquote>
<p>how do I get them to print as an object?</p>
</blockquote>
<p>Not entirely sure what you mean by that, but if you define <code>__str__</code> to return <code>greeting</code></p>
<pre><code>class Parent:
"""Parent Object"""
def __init__(self):
self.greeting = "Hi I'm a Parent Object!"
def __str__(self):
return self.greeting
</code></pre>
<p>The example now becomes </p>
<pre><code>print(p) # Hi I'm a Parent Object!
print(child_a) # Hi I'm a Child Object!
</code></pre>
| 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' object has no attribute 'final_state'</code>. However, I am able to use <code>print("TEST", fsa.final_state)</code> without any error and the output is also correct. Please ask any part of the code you donât understand. Thanks.</p>
<p>Code:
<a href="https://repl.it/Dfey/7" rel="nofollow">https://repl.it/Dfey/7</a></p>
| 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> parameter is passed through to<code>loop()</code> and then <code>accept_state()</code> as <code>fsa</code> until you try to access one of it's properties, where the error occurs. </p>
<p>In short, your passing an <code>int</code> as fsa, not an actual <code>FSA</code> object. You'll have to create it and then pass that through as a parameter. </p>
<p><strong>EDIT:</strong></p>
<p>Around line 260 you write <code>days = 31</code> which overrides the days declaration from earlier in the program on line 72. You don't redefine <code>months</code> however, which is why it works for <code>months</code> but not for <code>days</code></p>
| 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 Value_Check():
Start_Hours = eval(Starting_Hours.get())
Start_Min = eval(Starting_Minutes.get())
End_Hours = eval(Ending_Hours.get())
End_Min = eval(Ending_Minutes.get())
Start_Time_Window = ((Start_Hours*60)+ Start_Min)
End_Time_Window = ((End_Hours*60)+ End_Min)
Total_Window = (Start_Time_Window - End_Time_Window)
Window_Hours = math.floor(Total_Window/60)
Window_Minutes = (Total_Window - Window_Hours)
print "You have a ", Window_Hours, "Hours and", Window_Minutes, "minute window to test"
Frame_Start_Window= Frame(Master)
Frame_Start_Window.pack()
#Setting the starting time of the testing window
Start_Time_Frame = Frame(Master)
Start_Time_Frame.pack( side = BOTTOM )
Starting_Title = Label(Frame_Start_Window, text = "When can you start testing? ")
Starting_Title.pack()
Starting_Hours = Spinbox(Frame_Start_Window, text = "Hour", from_ = 1, to = 24, wrap =True, width = 2, command = Value_Check)
Starting_Hours.pack(side = LEFT)
Collen_Title = Label(Frame_Start_Window, text = ":")
Collen_Title.pack(side = LEFT)
Starting_Minutes = Spinbox(Frame_Start_Window, text = "Minutes", from_ = 0, to = 59, wrap =True, width = 2, command = Value_Check)
Starting_Minutes.pack(side = LEFT)
#The end half of the testing window:
Frame_End_Window= Frame(Master)
Frame_End_Window.pack()
#Setting the starting time of the testing window:
End_Title = Label(Frame_End_Window, text = "What time do you HAVE to stop testing?")
End_Title.pack()
Ending_Hours = Spinbox(Frame_End_Window, text = "Hour", from_ = 1, to = 24, wrap =True, width = 2, command = Value_Check)
Ending_Hours.pack(side = LEFT)
Collen2_Title = Label(Frame_End_Window, text = ":")
Collen2_Title.pack(side = LEFT)
Ending_Minutes = Spinbox(Frame_End_Window, text = "Minutes", from_ = 0, to = 59, wrap =True, width = 2, command = Value_Check)
Ending_Minutes.pack(side = LEFT)
#Where the answer from the Test_Calculator button is displayed:
Results_Screen = Text(Master, height=2, width=65)
Results_Screen.pack()
Data_Reset = Button (Master, text = "Reset Values", command = Value_Check)
Data_Reset.pack()
mainloop()
</code></pre>
| 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 independent Spinbox widgets both using the <code>textvariable</code> of <code>Minute</code>. The <code>textvariable</code> setting tells the Spinbox to link the content of the Spinbox to the content of the named variable; any time the Spinbox changes, the named variable will change, and any time the named variable changes, the Spinbox will change. Thus, you change the value in one Spinbox, it updates the variable, which in turn updates the other Spinbox.</p>
| 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
A
b
B
</code></pre>
<p>How would I loop over it in a way that would print as many of each letter as there are? As in, 2 A's, 2 a's, 1 b, 1 B, 1 C.</p>
<p>Edit: apparently there is a method called elements() that serves this exact purpose.</p>
| 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
A
b
B
</code></pre>
<p>How would I loop over it in a way that would print as many of each letter as there are? As in, 2 A's, 2 a's, 1 b, 1 B, 1 C.</p>
<p>Edit: apparently there is a method called elements() that serves this exact purpose.</p>
| 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 counted, ignoring elements with counts<1</p>
<pre><code> for i in t.elements():
print(i)
</code></pre>
| 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 screen names (not ids). I would like their descriptions as well, but can do this in a separate step unless there is a suggestion for pulling both pieces of information. Below is the code that I am using:</p>
<pre><code>import time
import tweepy
import csv
#Twitter API credentials
consumer_key = ""
consumer_secret = ""
access_key = ""
access_secret = ""
auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
ids = []
for page in tweepy.Cursor(api.friends, screen_name="").pages():
ids.extend(page)
time.sleep(60)
print(len(ids))
users = api.lookup_users(user_ids=ids) #iterates through the list of users and prints them
for u in users:
print(u.screen_name)
</code></pre>
| 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_key = ""
access_secret = ""
auth = tweepy.auth.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_key, access_secret)
api = tweepy.API(auth)
ids = []
for page in tweepy.Cursor(api.friends, screen_name="").pages():
ids.extend(page)
time.sleep(60)
print(len(ids))
idChunks = [ids[i:i + 300] for i in range(0, len(ids), 300)]
users = []
for idChunk in idChunks:
try:
users.append(api.lookup_users(user_ids=idChunk))
except tweepy.error.RateLimitError:
print("RATE EXCEDED. SLEEPING FOR 16 MINUTES")
time.sleep(16*60)
users.append(api.lookup_users(user_ids=idChunk))
for u in users:
print(u.screen_name)
print(u.description)
</code></pre>
<p>This code has not been tested, and does not writes the CSV, but it should help you getting past that error you were having. The size of 300 for the chunks is completely arbitrary, adjust it if it is too small (or too big).</p>
| 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 laboratories. So my Subject class is like this:</p>
<pre><code>class Subject:
number = 0
name = ""
dummyData = []
even = {}
odd = {}
all = {}
type = ""
def __init__(self, name, number, type):
self.name = name
self.number = number
self.type = type
self.info = str(number) + " " + name + " " + type
</code></pre>
<p>Previously I had all days written in <code>even</code>, <code>odd</code>, and <code>all</code> dicts, like this:</p>
<pre><code>even = {"mon":"",
"tue":"",
"wed":"",
"thu":"",
"fri":"",
}
</code></pre>
<p>So I could add all the classes hours to specific day key. But, there was a problem. For example lets say Programming lecture is subject 1 and Programming laboratories are subject 2. Subject 1 is on Monday at 9.15. Subject 2 is on Monday as well, but at 17.05. So I have a function, which would check if the subject is on even/odd week or it is every week. And then I would assign f.e 9.15 to <code>even["mon"]</code> on subject 1. Then I would go for subject 2, and tried to add 17.05 to <code>even["mon"]</code>. Every subject was an other Subject class object stored in a list. But there was a mistake. When I tried to add 17.05 to subject 2s <code>even["mon"]</code> it added it, okay, but then <code>even["mon"]</code> should <code>="17.05"</code>, but it was <code>="9.15/17.05"</code>. I was trying to figure out whats wrong, and I finally did, by changing my class from:</p>
<pre><code>class Subject:
number = 0
name = ""
dummyData = []
even = {"mon":"",
"tue":"",
"wed":"",
"thu":"",
"fri":"",
}
...etc...
type = ""
def __init__(self, name, number, type):
self.name = name
self.number = number
self.type = type
self.info = str(number) + " " + name + " " + type
</code></pre>
<p>to:</p>
<pre><code>class Subject:
number = 0
name = ""
dummyData = []
even = {}
odd = {}
all = {}
type = ""
def __init__(self, name, number, type):
self.name = name
self.number = number
self.type = type
self.info = str(number) + " " + name + " " + type
self.even = {"mon":"",
"tue":"",
"wed":"",
"thu":"",
"fri":"",
}
</code></pre>
<p>+ odd and all. So why is Python like remembering whats been written into the first object attributes?</p>
| 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 = {}
self.type = type
</code></pre>
<p>Declaring the variables inside the class declaration makes them "class" members and not instance members. Declaring them in the <code>__init__</code> method makes ensures a new instance of the members is created every time you create a new instance of the object.</p>
| 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 = ax - mx
dy = ay - my
if dx < 2 or dy < 2:
if dx > 1:
y = my
for x in xrange(mx, ax-1):
grid[y][x] |= E
grid[y][x+1] |= W
</code></pre>
<p>what is |= mean? </p>
| -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 each tuple),..., (19, list(first item of each tuple))
</code></pre>
<p>Can someone help me out with how to map this?<br>
I'll appreciate that! </p>
| 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 itemgetter
rdd = sc.parallelize([(0, [(0,'a'), (1,'b'), (2,'c')]), (1, [(3,'x'), (5,'y'), (6,'z')])])
mapped = rdd.mapValues(lambda v: map(itemgetter(0), v))
</code></pre>
<p>Output</p>
<pre><code>mapped.collect()
[(0, [0, 1, 2]), (1, [3, 5, 6])]
</code></pre>
| 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 each tuple),..., (19, list(first item of each tuple))
</code></pre>
<p>Can someone help me out with how to map this?<br>
I'll appreciate that! </p>
| 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/" rel="nofollow">https://www.google.com/</a>. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '<a href="http://127.0.0.1:5000" rel="nofollow">http://127.0.0.1:5000</a>' is therefore not allowed
access</p>
</blockquote>
<p>I tried to use CORS as such:</p>
<pre><code>app = Flask(__name__)
CORS(app)
</code></pre>
<p>along with the @cross_origin() on my route. What is going wrong here? I was reading this may be a chrome bug when running locally?
.</p>
| 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 nginx.conf file</code> It basically makes it so that the web server accepts HTTP requests from places other than its own domain. The "real" way to fix it is by actually going into the web server (via ssh) and editing the applicable .conf to include this header. If you are on apache, you would add <code>Header set Access-Control-Allow-Origin "*"</code> at the top of the file. After you do this, restart apache in order to make sure that your changes are saved (<code>service httpd restart</code>). If you are on NGINX use this configuration:</p>
<pre><code> #
# Wide-open CORS config for nginx
#
location / {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
#
# Om nom nom cookies
#
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
if ($request_method = 'POST') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
if ($request_method = 'GET') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
}
}
</code></pre>
<p>Now, I imagine, given your example, that you don't have access to the web server (since you put google's url in the URL). This is where it gets tricky. </p>
<p>One of your options is to use <a href="http://www.whateverorigin.org/" rel="nofollow">http://www.whateverorigin.org/</a>. It bypasses CORS and retrieves the data effectively. In order to use it, you would run:</p>
<pre><code>$.getJSON('http://whateverorigin.org/get?url=' + encodeURIComponent('http://google.com') + '&callback=?', function(data){
alert(data.contents);
});
</code></pre>
<p>This retrieves the response regardless of the CORS present on the web server. </p>
<p>If you don't want to change any of your existing code and you are using Google Chrome, there is a way around this CORS issue. One thing that you can do is install this browser extension: <a href="https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=plus" rel="nofollow">https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=plus</a>
and you can bypass CORS and run your program. </p>
<p>Hope this works for you!</p>
| 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/" rel="nofollow">https://www.google.com/</a>. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin '<a href="http://127.0.0.1:5000" rel="nofollow">http://127.0.0.1:5000</a>' is therefore not allowed
access</p>
</blockquote>
<p>I tried to use CORS as such:</p>
<pre><code>app = Flask(__name__)
CORS(app)
</code></pre>
<p>along with the @cross_origin() on my route. What is going wrong here? I was reading this may be a chrome bug when running locally?
.</p>
| 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 = serverSentUrl;
</code></pre>
| 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 awesome"
if question() = "Yes":
print y
else:
print c
print "Blah"
if question() = "Yes":
print y
else:
print c
</code></pre>
| 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 question() = "Yes":
print y
y_counter = y_counter + 1
else:
print c
c_counter = c_counter + 1
print "y was used " + str(y_counter) + " times!"
print "c was used " + str(c_counter) + " times!"
</code></pre>
| 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 awesome"
if question() = "Yes":
print y
else:
print c
print "Blah"
if question() = "Yes":
print y
else:
print c
</code></pre>
| 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
else:
count+=1
print c
print "Blah"
if question() == "Yes":
print y
else:
count+=1
print c
print c
</code></pre>
| 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 awesome"
if question() = "Yes":
print y
else:
print c
print "Blah"
if question() = "Yes":
print y
else:
print c
</code></pre>
| 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":
print y
else:
print c
counter += 1
print "Blah"
if question() = "Yes":
print y
else:
print c
counter +=1
print counter
</code></pre>
| 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 awesome"
if question() = "Yes":
print y
else:
print c
print "Blah"
if question() = "Yes":
print y
else:
print c
</code></pre>
| 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):
self.y_count += 1
return 'Blah'
a = A()
print(a.y)
# Blah
print(a.y)
# Blah
print(a.y)
# Blah
print(a.y_count)
# 3
</code></pre>
| 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 some hash(some_item) --> key, and then list[key] and then add to the head of a LinkedList. This occurs in O(1) time</p>
<p>When removing a value from the linkedlist, in python we replace it with a placeholder because hashsets are not allowed to have Null/None values, correct?</p>
<p>When the list[] gets over a certain % of load/fullness, we copy it over to another list</p>
<p><strong>Regarding Time Complexity Confusion:</strong>
So one question is, why is Average search/access O(1) if there can be a list of N items at the linkedlist at a given index?</p>
<p><strong>Wouldnt the average case be the searchitem is in the middle of its indexed linkedlist so it should be O(n/2) -> O(n)?</strong></p>
<p>Also, when removing an item, if we are replacing it with a placeholder value, isn't this considered a waste of memory if the placeholder is never used?</p>
<p>And finally, what is the difference between this and a HashMap other than HashMaps can have nulls? And HashMaps are key/value while Hashsets are just value?</p>
| 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 elements collide is low. Under this assumption, it's possible to formally prove that the expected number of elements to check is O(1). If you search online for "universal family of hash functions," you'll probably find some good proofs of this result.</p>
<p>As for using placeholders - there are several different ways to implement a hash table. The approach you're using is called "closed addressing" or "hashing with chaining," and in that approach there's little reason to use placeholders. However, other hashing strategies exist as well. One common family of approaches is called "open addressing" (the most famous of which is linear probing hashing), and in those setups placeholder elements are necessary to avoid false negative lookups. Searching online for more details on this will likely give you a good explanation about why.</p>
<p>As for how this differs from HashMap, the HashMap is just one possible implementation of a map abstraction backed by a hash table. Java's HashMap does support nulls, while other approaches don't.</p>
| 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 some hash(some_item) --> key, and then list[key] and then add to the head of a LinkedList. This occurs in O(1) time</p>
<p>When removing a value from the linkedlist, in python we replace it with a placeholder because hashsets are not allowed to have Null/None values, correct?</p>
<p>When the list[] gets over a certain % of load/fullness, we copy it over to another list</p>
<p><strong>Regarding Time Complexity Confusion:</strong>
So one question is, why is Average search/access O(1) if there can be a list of N items at the linkedlist at a given index?</p>
<p><strong>Wouldnt the average case be the searchitem is in the middle of its indexed linkedlist so it should be O(n/2) -> O(n)?</strong></p>
<p>Also, when removing an item, if we are replacing it with a placeholder value, isn't this considered a waste of memory if the placeholder is never used?</p>
<p>And finally, what is the difference between this and a HashMap other than HashMaps can have nulls? And HashMaps are key/value while Hashsets are just value?</p>
| 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 resizing the hash table as needed. Along with a hash function that evenly distributes the values, this keeps the expected chain length bounded, giving constant time lookups.</p>
<p>The hash tables used by hashmaps and hashsets are the same except they store different values. A hashset will contain references to a single value, and a hashmap will contain references to a key and a value. Hashsets can be implemented by delegating to a hashmap where the keys and values are the same.</p>
| 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 some hash(some_item) --> key, and then list[key] and then add to the head of a LinkedList. This occurs in O(1) time</p>
<p>When removing a value from the linkedlist, in python we replace it with a placeholder because hashsets are not allowed to have Null/None values, correct?</p>
<p>When the list[] gets over a certain % of load/fullness, we copy it over to another list</p>
<p><strong>Regarding Time Complexity Confusion:</strong>
So one question is, why is Average search/access O(1) if there can be a list of N items at the linkedlist at a given index?</p>
<p><strong>Wouldnt the average case be the searchitem is in the middle of its indexed linkedlist so it should be O(n/2) -> O(n)?</strong></p>
<p>Also, when removing an item, if we are replacing it with a placeholder value, isn't this considered a waste of memory if the placeholder is never used?</p>
<p>And finally, what is the difference between this and a HashMap other than HashMaps can have nulls? And HashMaps are key/value while Hashsets are just value?</p>
| 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>amortized</em> O(1) time for insert because the table needs to be reorganized periodically as it grows. </p>
<p>(Some may opt to reorganize on delete, also, to shrink the table when the load factor reaches some bottom threshold, gut this only affect space, not asymptotic run time.)</p>
<p>Reorganization means increasing (or decreasing) the number of buckets and re-assigning all elements into their new bucket locations. There are schemes, e.g. <em>extensible hashing</em>, to make this a bit cheaper. But in general it means touching each element in the table.</p>
<p>Reorganization, then, is O(n). How can insert be O(1) when any given one may incur this cost? The secret is amortization and the power of powers. When the table is grown, it <em>must</em> be grown by a <em>factor</em> greater than one, two being most common. If the table starts with 1 bucket and doubles each time the load factor reaches F, then the cost of N reorganizations is</p>
<pre><code>F + 2F + 4F + 8F ... (2^(N-1))F = (2^N - 1)F
</code></pre>
<p>At this point the table contains <code>(2^(N-1))F</code> elements, the number in the table during the last reorganization. I.e. we have done <code>(2^(N-1))F</code> inserts, and the total cost of reorganization is as shown on the right. The interesting part is the <em>average</em> cost per element in the table (or insert, take your pick):</p>
<pre><code>(2^N - 1)F 2^N
---------- ~= ------- = 2
(2^(N-1))F 2^(N-1)
</code></pre>
<p><em>That's</em> where the amortized O(1) comes from.</p>
<p>One additional point is that for modern processors, linked lists aren't a great idea for the bucket lists. With 8-byte pointers, the overhead is meaningful. More importantly, heap-allocated nodes in a single list will almost never be contiguous in memory. Traversing such a list kills cache performance, which can slow things down by orders of magnitude. </p>
<p>Arrays (with an integer count for number of data-containing elements) are likely to work out better. If the load factor is small enough, just allocate an array equal in size to the load factor at the time the first element is inserted in the bucket. Otherwise, grow these element arrays by factors the same way as the bucket array! Everything will still amortize to O(1).</p>
<p>To delete an item from such a bucket, don't mark it deleted. Just copy the last array element to the location of the deleted one and decrement the element count. Of course this won't work if you allow external pointers into the hash buckets, but that's a bad idea anyway.</p>
| 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 = [[],[]...[]]</code><br>
When addEntry is executed the first time, <code>hashBucket</code> is just an empty list, so I expect <code>hashBucket[i][0]</code> will generate an indexing error, but the program actually works, why? Thank you very much for your help.</p>
<p>Here is the program</p>
<pre><code>class intDict(object):
"""A dictionary with integer keys"""
def __init__(self, numBuckets):
"""Create an empty dictionary"""
self.buckets = []
self.numBuckets = numBuckets
for i in range(numBuckets):
self.buckets.append([])
def addEntry(self, dictKey, dictVal):
"""Assumes dictKey an int. Adds an entry"""
hashBucket = self.buckets[dictKey%self.numBuckets]
for i in range(len(hashBucket)):
if hashBucket[i][0] == dictKey:
hashBucket[i] = (dictKey, dictVal)
return
hashBucket.append((dictKey, dictVal))
def getValue(self, dictKey):
"""Assumes dictKey an int. Returns entry associated with the key dictKey"""
hashBucket = self.buckets[dictKey%self.numBumBuckets]
for e in hashBucket:
if e[0] == dictKay:
return e[1]
return None
def __str__(self):
result = '{'
for b in self.buckets:
for e in b:
result = result + str(e[0]) + ":" + str(e[1]) + ','
return result[:-1] + '}' # result[:-1] omits the last coma
</code></pre>
| 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 = [[],[]...[]]</code><br>
When addEntry is executed the first time, <code>hashBucket</code> is just an empty list, so I expect <code>hashBucket[i][0]</code> will generate an indexing error, but the program actually works, why? Thank you very much for your help.</p>
<p>Here is the program</p>
<pre><code>class intDict(object):
"""A dictionary with integer keys"""
def __init__(self, numBuckets):
"""Create an empty dictionary"""
self.buckets = []
self.numBuckets = numBuckets
for i in range(numBuckets):
self.buckets.append([])
def addEntry(self, dictKey, dictVal):
"""Assumes dictKey an int. Adds an entry"""
hashBucket = self.buckets[dictKey%self.numBuckets]
for i in range(len(hashBucket)):
if hashBucket[i][0] == dictKey:
hashBucket[i] = (dictKey, dictVal)
return
hashBucket.append((dictKey, dictVal))
def getValue(self, dictKey):
"""Assumes dictKey an int. Returns entry associated with the key dictKey"""
hashBucket = self.buckets[dictKey%self.numBumBuckets]
for e in hashBucket:
if e[0] == dictKay:
return e[1]
return None
def __str__(self):
result = '{'
for b in self.buckets:
for e in b:
result = result + str(e[0]) + ":" + str(e[1]) + ','
return result[:-1] + '}' # result[:-1] omits the last coma
</code></pre>
| 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 the for loop will never get executed</p>
<pre><code>def addEntry(self, dictKey, dictVal):
"""Assumes dictKey an int. Adds an entry"""
hashBucket = self.buckets[dictKey%self.numBuckets]
for i in range(len(hashBucket)):
# This is never executed if hashBucket is empty
if hashBucket[i][0] == dictKey:
hashBucket[i] = (dictKey, dictVal)
return
hashBucket.append((dictKey, dictVal))
</code></pre>
| 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 = [[],[]...[]]</code><br>
When addEntry is executed the first time, <code>hashBucket</code> is just an empty list, so I expect <code>hashBucket[i][0]</code> will generate an indexing error, but the program actually works, why? Thank you very much for your help.</p>
<p>Here is the program</p>
<pre><code>class intDict(object):
"""A dictionary with integer keys"""
def __init__(self, numBuckets):
"""Create an empty dictionary"""
self.buckets = []
self.numBuckets = numBuckets
for i in range(numBuckets):
self.buckets.append([])
def addEntry(self, dictKey, dictVal):
"""Assumes dictKey an int. Adds an entry"""
hashBucket = self.buckets[dictKey%self.numBuckets]
for i in range(len(hashBucket)):
if hashBucket[i][0] == dictKey:
hashBucket[i] = (dictKey, dictVal)
return
hashBucket.append((dictKey, dictVal))
def getValue(self, dictKey):
"""Assumes dictKey an int. Returns entry associated with the key dictKey"""
hashBucket = self.buckets[dictKey%self.numBumBuckets]
for e in hashBucket:
if e[0] == dictKay:
return e[1]
return None
def __str__(self):
result = '{'
for b in self.buckets:
for e in b:
result = result + str(e[0]) + ":" + str(e[1]) + ','
return result[:-1] + '}' # result[:-1] omits the last coma
</code></pre>
| 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>:</p>
<pre><code>@api_view(['POST'])
@permission_classes((AllowAny,))
def say_hello(request):
return Response("hello")
</code></pre>
<p>As you can see, I'm using Token Authentication to protect my other API's by default, but <strong>when I add a token header</strong> in <code>say_hello</code>, Django Rest Framework will also check if the token is valid or not, even when i add <code>AllowAny</code> permission class.</p>
<p><strong>My question is</strong> how to make Django Rest Framework ignore checking the token if the token header is present in the <code>say_hello</code>?
and are there any security considerations for making this?</p>
<p>Thanks.</p>
| 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 should keep the default in place for other views while treating this one differently.</p>
| 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>:</p>
<pre><code>@api_view(['POST'])
@permission_classes((AllowAny,))
def say_hello(request):
return Response("hello")
</code></pre>
<p>As you can see, I'm using Token Authentication to protect my other API's by default, but <strong>when I add a token header</strong> in <code>say_hello</code>, Django Rest Framework will also check if the token is valid or not, even when i add <code>AllowAny</code> permission class.</p>
<p><strong>My question is</strong> how to make Django Rest Framework ignore checking the token if the token header is present in the <code>say_hello</code>?
and are there any security considerations for making this?</p>
<p>Thanks.</p>
| 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 adding also to your view another decorator, to bypass the <code>TokenAuthentication</code>:</p>
<pre><code>@authentication_classes([])
</code></pre>
<p>Note that if you put this on a <code>POST</code> endpoint, your app is now vulnerable to nasty stuff like Cross-Site Request Forgery. </p>
| 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 this moment this code show me the result of the plus oh the all values in a for loop but how can I get the result?</p>
<p>I mean the last value.</p>
<p>This is my code:</p>
<pre><code>def fun(*args):
valores = args
print valores
if len(valores) >= 3:
print 'es mayor'
suma = 0
for n in valores:
suma += n
print suma
#at this line it works fine, the problem is when I want to get the las value of the for loop
print suma[3]
else:
print 'es menor'
fun(10,10,10,10)
</code></pre>
<p>Thank you for the orientation.</p>
| -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,10,10,10)
</code></pre>
| 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
repeat this process for suppose 10 times and finally print the names of the link connected</p>
<p>i am using this code
urlllib is working only once</p>
<pre><code>import urllib
from bs4 import *
url = raw_input('enter url:')
count = raw_input('enter count:')
position = raw_input('enter position:')
count = int(count)
position = int(position)
l = list()
p = 0
for _ in xrange(0,count):
print 'retrieving:' + url
html = urllib.urlopen(url).read()
s = BeautifulSoup(html)
tags = s.findAll('a')
for tag in tags:
w = tag.get('href')
p = p + 1
if p == position:
url = "'" + w + "'"
l.append(tag.contents[0])
print l
</code></pre>
| 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://example.com/link.php" rel="nofollow">http://example.com/link.php</a> and urllib wouldn't know what to do with that. If you expect all the links you could be interested in to be relative then you'd need to add the base url before appending the new link for it follow.</p>
| 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.