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 |
---|---|---|---|---|---|---|---|---|---|
tensorflow placeholder in function
| 39,549,472 |
<p>Now, I have a bit of code like below:</p>
<pre><code>import tensorflow as tf
x = tf.placeholder(tf.float32, [1, 3])
y = x * 2
with tf.Session() as sess:
result = sess.run(y, feed_dict={x: [2, 4, 6]})
print(result)
</code></pre>
<p>I want to feed values to a function.</p>
<p>Below is an obvious wrong.
How do I suppose to do that?</p>
<pre><code>import tensorflow as tf
def place_func():
x = tf.placeholder(tf.float32, [1, 3])
y = x * 2
with tf.Session() as sess:
result = sess.run(y, feed_dict={x: [2, 4, 6]})
print(result)
</code></pre>
| 0 |
2016-09-17T17:00:59Z
| 39,549,778 |
<p>One option is to run a session inside of function just as follows: </p>
<pre><code>import tensorflow as tf
def my_func(data):
x = tf.placeholder(tf.float32, [1, 3])
y = x * 2
return sess.run(y, feed_dict = {x: data})
with tf.Session() as sess:
result = my_func([[2, 4, 6]])
print(result)
</code></pre>
<p>You could also create a class and let x to be a field of that class. </p>
| 1 |
2016-09-17T17:30:01Z
|
[
"python",
"tensorflow",
"placeholder"
] |
Why is this implementation of the conditional logit gradient failing?
| 39,549,482 |
<p>I've written a very simple implementation of the likelihood/gradient for the conditional logit model (explained <a href="http://data.princeton.edu/wws509/notes/c6s3.html" rel="nofollow">here</a>) - the likelihood works fine, but the gradient isn't correct. My two questions are: is my derivation of the gradient correct, and if so, is my implementation in Python correct? If this is better asked in the Math forum, feel free to move.</p>
<p>Model: <a href="http://i.stack.imgur.com/uyW2a.gif" rel="nofollow"><img src="http://i.stack.imgur.com/uyW2a.gif" alt="enter image description here"></a></p>
<p>Log likelihood: <a href="http://i.stack.imgur.com/SM5wj.gif" rel="nofollow"><img src="http://i.stack.imgur.com/SM5wj.gif" alt="enter image description here"></a></p>
<p>Finally, the gradient:<a href="http://i.stack.imgur.com/TTe3g.gif" rel="nofollow"><img src="http://i.stack.imgur.com/TTe3g.gif" alt="enter image description here"></a></p>
<p>Here, i is each observation, j is an alternative within observation i, c is the chosen alternative in observation i, Xij is the feature vector for choice j in i and B are the corresponding coefficients. <em>The likelihood formula should have the feature vector multiplied by the coefficient vector. My mistake</em></p>
<p>My implementation for the likelihood and gradients are as follows: </p>
<p>Likelihood:</p>
<pre><code>def log_likelihood(coefs, observations, config, lasso):
def func(grp):
mtrx = grp.as_matrix(config.features)
dp = np.dot(mtrx, coefs)
sub = np.log(np.exp(dp).sum())
inc = (dp * grp['choice']).sum()
return inc - sub
ll = observations.groupby(['observation_id']).apply(func).sum()
if lasso is not None:
ll -= (np.abs(coefs).sum() * lasso)
neg_log = ll * -1
return neg_log
</code></pre>
<p>Gradient:</p>
<pre><code>def gradient(coefs, observations, config, lasso):
def func(grp):
mtrx = grp.as_matrix([config.features])
tmtrx = mtrx.transpose()
tmp = np.exp(tmtrx * coefs[:, np.newaxis])
sub = (tmp * tmtrx).sum(1) / tmp.sum(1)
inc = (mtrx * grp['choice'][:, np.newaxis]).sum(0)
ret = inc - sub
return ret
return -1 * observations.groupby(['observation_id']).apply(func).sum()
</code></pre>
<p>Here, coefs is a numpy array containing the coefficients, observations is a dataframe where each row represents an alternative within in an observation and the columns are a choice column indicating 0/1 for the choice within a column and an observation_id column where all alternatives within an observation have the same id, and finally config is a dict containing a member 'features' which is the list of columns in the observations df containing the features. <em>Note I'm testing without using the lasso parameter</em>. Example below of what the data looks like.</p>
<p>I've verified the likelihood is correct; however, the error for the gradient is very large when using scipy.optimize.check_grad. I'm also able to solve for B when not passing the gradient to scipy.optimize.minimize. The gradient evaluates as I'd expect, so at this point I can only think that my derivation is incorrect, but I'm not sure why.</p>
<pre><code>In [27]: df.head(14)
Out[27]:
x1 x2 x3 observation_id choice
0 0.187785 0.435922 -0.475349 211 1
1 -0.935956 -0.405833 -1.753128 211 0
2 0.210424 0.141579 0.415933 211 0
3 0.507025 0.307965 -0.198089 211 0
4 0.080658 -0.125473 -0.592301 211 0
5 0.605302 0.239491 0.287094 293 1
6 0.259580 0.415388 -0.396969 293 0
7 -0.637267 -0.984442 -1.376066 293 0
8 0.241874 0.435922 0.855742 293 0
9 0.831534 0.650425 0.930592 293 0
10 -1.682565 0.435922 -2.517229 293 0
11 -0.149186 0.300299 0.494513 293 0
12 -1.918179 -9.967421 -2.774450 293 0
13 -1.185817 0.295601 -1.974923 293 0
</code></pre>
| 0 |
2016-09-17T17:02:17Z
| 39,565,675 |
<p>The derivation was incorrect. In the exponentiation I was only including the feature and coefficient for the partial derivative of the given coefficient. Rather, it should have been e to the dot product of all features and coefficients. </p>
| 0 |
2016-09-19T05:00:40Z
|
[
"python",
"scipy",
"statistics",
"mathematical-optimization"
] |
Trying to install mathplot.lib for python 2.7.11. But Cannot find a suitable process. Have tried various ways from Youtube Tutorials, but invain
| 39,549,494 |
<p>I have installed matplotlib-1.5.0.win-amd64-py2.7 from sourcefourge.net after downloading and installing numpy using commandprompt by using pip: pip install numpy. But when I write the following code it Gives me error. Help me out.
Code:</p>
<pre><code>from matplotlib.pylab import *
pylab.plot([1,2,3,4],[1,2,3,4])
pylab.show()
</code></pre>
<p>It gives me following error message:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python27\Lib\idlelib\1.py", line 1, in <module>
from matplotlib.pylab import *
File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 124, in <module>
from matplotlib.rcsetup import (defaultParams,
File "C:\Python27\lib\site-packages\matplotlib\rcsetup.py", line 25, in <module>
from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
File "C:\Python27\lib\site-packages\matplotlib\fontconfig_pattern.py", line 25, in <module>
from pyparsing import Literal, ZeroOrMore, \
ImportError: No module named pyparsing
</code></pre>
| 2 |
2016-09-17T17:03:16Z
| 39,549,700 |
<p>There is an easy and complete guide on the <a href="http://matplotlib.org/users/installing.html" rel="nofollow">Matplotlib Website</a>.
Try and follow this one.</p>
| 3 |
2016-09-17T17:21:47Z
|
[
"python",
"numpy",
"matplotlib"
] |
Trying to install mathplot.lib for python 2.7.11. But Cannot find a suitable process. Have tried various ways from Youtube Tutorials, but invain
| 39,549,494 |
<p>I have installed matplotlib-1.5.0.win-amd64-py2.7 from sourcefourge.net after downloading and installing numpy using commandprompt by using pip: pip install numpy. But when I write the following code it Gives me error. Help me out.
Code:</p>
<pre><code>from matplotlib.pylab import *
pylab.plot([1,2,3,4],[1,2,3,4])
pylab.show()
</code></pre>
<p>It gives me following error message:</p>
<pre><code>Traceback (most recent call last):
File "C:\Python27\Lib\idlelib\1.py", line 1, in <module>
from matplotlib.pylab import *
File "C:\Python27\lib\site-packages\matplotlib\__init__.py", line 124, in <module>
from matplotlib.rcsetup import (defaultParams,
File "C:\Python27\lib\site-packages\matplotlib\rcsetup.py", line 25, in <module>
from matplotlib.fontconfig_pattern import parse_fontconfig_pattern
File "C:\Python27\lib\site-packages\matplotlib\fontconfig_pattern.py", line 25, in <module>
from pyparsing import Literal, ZeroOrMore, \
ImportError: No module named pyparsing
</code></pre>
| 2 |
2016-09-17T17:03:16Z
| 39,550,167 |
<p>refer to this answer of mine
<a href="http://stackoverflow.com/a/38618044/5334188">http://stackoverflow.com/a/38618044/5334188</a></p>
<p>install numpy</p>
<p><code>pip install numpy</code></p>
<p>If you face installation issues for numpy, get the pre-built windows installers from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a> for your python version (python version is different from windows version).</p>
<p>numpy 32-bit: numpy-1.11.1+mkl-cp27-cp27m-win32.whl</p>
<p>numpy 64-bit: numpy-1.11.1+mkl-cp27-cp27m-win_amd64.whl</p>
<p>Later you require VC++ 9.0, then please get it from below link Microsoft Visual C++ 9.0 is required. Get it from <a href="http://aka.ms/vcpython27" rel="nofollow">http://aka.ms/vcpython27</a></p>
<p>Then install matplotlib using</p>
<p><code>pip install matplotlib</code></p>
<p>If you face errors, please download below from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a>, which will do the rest. </p>
<p>32-bit: matplotlib-1.5.3-cp27-cp27m-win32.whl</p>
<p>64-bit: matplotlib-1.5.3-cp27-cp27m-win_amd64.whl</p>
<p>works like charm</p>
| 1 |
2016-09-17T18:12:59Z
|
[
"python",
"numpy",
"matplotlib"
] |
Run python script from PHP in windows
| 39,549,846 |
<p>I want to run <code>python</code> script from <code>php</code>. I am on <code>python 3.5 , 64 bit</code> .I have read <a href="http://stackoverflow.com/questions/9283065/run-a-python-script-from-the-prompt-in-windows">StackQ1</a> and <a href="http://stackoverflow.com/questions/28622526/how-to-correctly-run-python-script-from-php">StackQ2</a>. No one was helpful. I am running this code </p>
<pre><code><?php
$py = exec("D:/pythonFolder/python C:/wamp64/www/python.py");
echo $py;
?>
</code></pre>
<p><code>D:/pythonFolder/python</code> is the path to <code>python.exe</code>. On running the above code, nothing happens. I also tried with this <code>$py = shell_exec("python C:/wamp64/www/python.py");</code> and this <code>$py = exec("python C:/wamp64/www/python.py");</code> but no success.
Any help will be appreciative.</p>
| 0 |
2016-09-17T17:37:55Z
| 39,549,884 |
<p>If you want to capture any output from the python script, you need to use shell_exec. Otherwise you're just running the script and the output isn't going anywhere. There are different commands for different purposes. Exec only runs a command, doesn't care about any potential return values.</p>
<p><a href="http://php.net/manual/en/book.exec.php" rel="nofollow">http://php.net/manual/en/book.exec.php</a></p>
| 0 |
2016-09-17T17:41:46Z
|
[
"php",
"python"
] |
Plot multiple series with non-overlapping x-axis
| 39,549,856 |
<p>I have two dataframes, one contains a subset of samples of the other.</p>
<pre><code>df = pd.DataFrame(data= {'A' : [1,2,3,4,3,2,1]}
,index = [1,2,3,4,5,6,7])
df2 = pd.DataFrame(data = {'B' : [0.7, 1.4]}
,index = [2,6])
</code></pre>
<p>I'd like to plot these such that the complete dataset is a line plot, while the other is a bar plot.</p>
<p>But trying</p>
<pre><code>ax = df.plot()
df2.plot(kind='bar', ax=ax)
</code></pre>
<p>Gives me</p>
<p><a href="http://i.stack.imgur.com/JO73q.png" rel="nofollow"><img src="http://i.stack.imgur.com/JO73q.png" alt="My ugly graph"></a></p>
<p>What am I missing?</p>
<p><strong>Edit</strong></p>
<p>I just discovered this works</p>
<pre><code>plt.plot(df.index, df['A'])
plt.bar(df2.index, df2['B'])
</code></pre>
<p>What's the functional difference / what fundamentals should I go read about?</p>
| 0 |
2016-09-17T17:38:43Z
| 39,550,600 |
<p>You should do it the following way. </p>
<pre><code>import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('ggplot')
df = pd.DataFrame(data= {'A' : [1,2,3,4,3,2,1]}
,index = [1,2,3,4,5,6,7])
df2 = pd.DataFrame(data = {'B' : [0.7, 1.4]}
,index = [2,6])
df_final = pd.concat([df,df2], axis=2)
plt.figure()
ax = df_final['A'].plot(kind='line', color='y', legend='A')
df_final['B'].plot(kind='bar', color='r', legend='B')
plt.show()
</code></pre>
<p>In your previous method, you miss following points :</p>
<ul>
<li>An index(passed as a number) does not have a numerical significance in terms of ordering. Hence when you have two dataframes separated, and then plot them one after the other, there will be no way for Pandas to know how to align the plots together.</li>
<li>If you used strings as indices, in that case also Pandas would not have automatically aligned the plots together and filled in for the missing values. This is a sensible and expected behavior because different plots with different meanings and contexts might have similar indices. What you see in your original result, is just an overlap of two plots on the same figure with no regard for any kind of alignment.</li>
</ul>
<p>Always align different dataframes together when you want to plot them at the same time in the same figure and upon the same set of axes.</p>
<p><strong>EDITED :
I saw the edit in your question later on and hence adding this.</strong></p>
<p>Your edited one works because now you do not use the Pandas wrapper and directly use matplotlib. Pandas <code>plot()</code> is just a wrapper around matplotlib. In this case, matplotlib does not make any assumption since it is not specifically careful about datasets, and just aligns your column values alongside the appropriate indices. However I would recommend using Pandas for significant plotting applications involving datasets.
See <a href="http://pandas.pydata.org/pandas-docs/stable/visualization.html" rel="nofollow" title="Pandas Documentation">Pandas documentation on visualization</a></p>
| 1 |
2016-09-17T18:57:08Z
|
[
"python",
"pandas",
"plot"
] |
Need to edit subset of rows from MySQL table using Pandas Dataframe
| 39,549,887 |
<p>I'm in the process of trying to alter a table in my database. However I am finding it difficult using the to_sql method provided by Pandas. My <code>price_data</code> Dataframe looks something like this:</p>
<h2>Initial Dataframe (as rows in the database):</h2>
<p><a href="http://i.stack.imgur.com/5sPFo.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/5sPFo.jpg" alt="enter image description here"></a></p>
<h2>Code used to alter data:</h2>
<pre><code>with con:
price_data.to_sql(con=con, name='clean_prices2', if_exists='append', index=False, flavor='mysql')
</code></pre>
<p>The ultimate goal here is to modify the initial dataframe (converting zero values into Nan's, then interpolate them), and saving it back in the database. The results should look like this (except with the same <code>id</code>):</p>
<h2>Desired Output:</h2>
<p><a href="http://i.stack.imgur.com/qCSw4.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/qCSw4.jpg" alt="enter image description here"></a></p>
<p>If you look specifically at the <code>close_price</code> column you can see the 0 value was assigned 90.7350</p>
<p>My current solution is appending the datarows, which results in duplicate enteries like this:</p>
<h2>Actual Output:</h2>
<p><a href="http://i.stack.imgur.com/b5NQ7.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/b5NQ7.jpg" alt="enter image description here"></a></p>
<p>Finally, I would have to perform another query to remove the duplicate rows (based on price_date)</p>
<p>I know I could change the <code>if_exists</code> parameter to <strong>replace</strong> but that would remove the rest of my database table. Basically I want to perform this query multiple times on different <code>symbol_id</code>'s</p>
<p>Is there anyway to modify a subset (in the case, just the 3 rows) without removing the rest of the data in my table? The solution can either modify the existing rows (keeping the same <code>id</code>) or delete the old rows, and create the new ones without zeroes. I am just trying to accomplish this without the additional delete duplicate query.</p>
| 0 |
2016-09-17T17:41:55Z
| 39,551,237 |
<p>Consider a temp table with exact structure as final table but regularly replaced and will then be used to update existing final table. Try using <a href="http://docs.sqlalchemy.org/en/latest/core/connections.html" rel="nofollow">sqlalchemy engine</a> for both operations. </p>
<p>Specifically, for the latter SQL you would use an <a href="http://www.mysqltutorial.org/mysql-update-join/" rel="nofollow">UPDATE JOIN</a> query between temp and final table. Below assumes you use <code>pymysql</code> module (adjust as needed):</p>
<pre><code>import pymysql
from sqlalchemy import create_engine
...
engine = create_engine("mysql+pymysql://user:password@hostname:port/database")
# PANDAS UPLOAD
price_data.to_sql(name='clean_prices_temp', con=engine, if_exists='replace', index=False)
# SQL UPDATE (USING TRANSACTION)
with engine.begin() as conn:
conn.execute("UPDATE clean_prices_final f" +
" INNER JOIN clean_prices_temp t" +
" ON f.symbol_id = t.symbol_id" +
" AND f.price_date = t.price_date" +
" SET f.open_price = t.open_price," +
" f.high_price = t.high_price," +
" f.low_price = t.low_price," +
" f.close_price = t.close_price," +
" f.adj_close_price = t.adj_close_price;")
engine.dispose()
</code></pre>
| 0 |
2016-09-17T20:10:14Z
|
[
"python",
"mysql",
"pandas",
"pandasql"
] |
Copying set of specific columns between Pandas dfs where specific values match
| 39,549,889 |
<p>I am sure this is going to be a 'doh' moment, but I am having a difficult time trying to copy a set of columns between dataframes where the value of a specific column in df1 is also found in df2.</p>
<p>A simplified version of df1 looks like this:
<a href="http://i.stack.imgur.com/oVzMm.png" rel="nofollow"><img src="http://i.stack.imgur.com/oVzMm.png" alt="df1"></a></p>
<p>A simplified version of df2 looks like this:
<a href="http://i.stack.imgur.com/mSycT.png" rel="nofollow"><img src="http://i.stack.imgur.com/mSycT.png" alt="df2"></a></p>
<p>From here I'm building a list of columns (cols) that does not include the 'p_people_id' field from df1 and creating those fields in df2 and assigning a nan value.
cols=<a href="http://i.stack.imgur.com/zVeq9.png" rel="nofollow"><img src="http://i.stack.imgur.com/zVeq9.png" alt="columns from df1 != p_people_id"></a>
After which df2 looks like this:
<a href="http://i.stack.imgur.com/PrtY7.png" rel="nofollow"><img src="http://i.stack.imgur.com/PrtY7.png" alt="df2 w appended cols"></a>
Working with these dfs I'm trying to look find all instances where df2.a_people_id == df1.p_people_id and assign the values of df1[cols] to the df2 instance.</p>
<p>Finding the instance using .loc is simple enough. I've managed to be able to select the cols I want to target using .loc as well </p>
<pre><code>df2.loc[df2['a_people_id']==df1['p_people_id'][0],np.array(cols)]
</code></pre>
<p>This works fine and returns: <a href="http://i.stack.imgur.com/dBis5.png" rel="nofollow"><img src="http://i.stack.imgur.com/dBis5.png" alt="enter image description here"></a> </p>
<p>But, if I try something like this to set/assign those specific columns where the id field in df1 matches the id field in df2: </p>
<pre><code>df2.loc[df2['a_people_id']==df1['p_people_id'][0],np.array(cols)]=df1.loc[df1['p_people_id']==df1['p_people_id'][0],np.array(cols)]
</code></pre>
<p>Nothing happens and I'm not sure why. <a href="http://i.stack.imgur.com/NYVTM.png" rel="nofollow"><img src="http://i.stack.imgur.com/NYVTM.png" alt="df2 assignment results"></a></p>
<p>I've attempted to utilize .ix, .loc, .iloc, .where, .select, .set in various ways, but this has to be one of those areas where I'm "just not doin it right." I can post other examples where I've managed to get the syntax right to find [cols] where the specific id matches and no error or 'view vs copy' warning is printed, but no assignment happens either. Where am I going wrong here?</p>
| 0 |
2016-09-17T17:41:59Z
| 39,550,218 |
<p>If I'm not mistaken, I think you're looking for a join operation. </p>
<p>In particular, this statement in your description: </p>
<pre><code>df2.loc[df2['a_people_id']==df1['p_people_id'][0],np.array(cols)]
</code></pre>
<p>Means "look in <code>df2</code> for all rows where <code>p_people_id</code> matches the first <code>p_people_id</code> and for those rows, select the <code>cols</code> columns. </p>
<p>This produces a set of rows and a columns (6 in your example, all containing NA's) and, if I get things correctly, you then want to put those 6 lines together with the corresponding line in df1, plus do that for all <code>p_people_id</code> in <code>df1</code>. </p>
<p>If my assumption above is correct, then this can be done with a simple join. Like so: </p>
<pre><code>pd.merge(left=df1, left_on="p_people_id",
right=df2, right_on="p_people_id")
</code></pre>
<p>If there are 1000 different p_people_id in df1 and each of them had 6 lines in df2, the above statement would produce a dataframe with 6000 rows.</p>
<p>You can then select the desired columns in the result. </p>
| 1 |
2016-09-17T18:18:08Z
|
[
"python",
"pandas",
"dataframe"
] |
Bit shifting of negative integer?
| 39,549,971 |
<p>I am trying to understand the bit shift operation <code>>></code> on a negative integer.</p>
<pre><code>-2 >> 1 # -1
-3 >> 1 # -2
-5 >> 1 # -3
-7 >> 1 # -4
</code></pre>
<p>Can someone explain how this is done? I know it is related to Two's complement, but I can't related that to the shifting operation.</p>
| 1 |
2016-09-17T17:50:33Z
| 39,550,074 |
<p>The full explanation is provided <a href="https://wiki.python.org/moin/BitwiseOperators" rel="nofollow">here</a></p>
<blockquote>
<p>Two's Complement binary for Negative Integers:</p>
<p>Negative numbers are written with a leading one instead of a leading
zero. So if you are using only 8 bits for your twos-complement
numbers, then you treat patterns from "00000000" to "01111111" as the
whole numbers from 0 to 127, and reserve "1xxxxxxx" for writing
negative numbers. A negative number, -x, is written using the bit
pattern for (x-1) with all of the bits complemented (switched from 1
to 0 or 0 to 1). So -1 is complement(1 - 1) = complement(0) =
"11111111", and -10 is complement(10 - 1) = complement(9) =
complement("00001001") = "11110110". This means that negative numbers
go all the way down to -128 ("10000000").</p>
<p>Of course, Python doesn't use 8-bit numbers. It USED to use however
many bits were native to your machine, but since that was
non-portable, it has recently switched to using an INFINITE number of
bits. Thus the number -5 is treated by bitwise operators as if it were
written "...1111111111111111111011".</p>
</blockquote>
<p>So, the explanation for shift operator:</p>
<blockquote>
<p>x >> y Returns x with the bits shifted to the right by y places. This
is the same as //'ing x by 2**y.</p>
</blockquote>
<p>In order to understand the above explanation you can check it out with something like this:</p>
<pre><code>def twos_comp(val, nbits):
"""Compute the 2's complement of int value val"""
if val < 0:
val = (1 << nbits) + val
else:
if (val & (1 << (nbits - 1))) != 0:
# If sign bit is set.
# compute negative value.
val = val - (1 << nbits)
return val
def foo(a,b):
print("{0:b} >> {1:b} = {2:b} <==> {3:b} >> {4:b} = {5:b}".format(
a,b,a>>b,
twos_comp(a,8),b, twos_comp(a>>b,8)
))
foo(-2, 1)
foo(-3, 1)
foo(-5, 1)
foo(-7, 1)
</code></pre>
<p>Which outputs:</p>
<pre><code>-10 >> 1 = -1 <==> 11111110 >> 1 = 11111111
-11 >> 1 = -10 <==> 11111101 >> 1 = 11111110
-101 >> 1 = -11 <==> 11111011 >> 1 = 11111101
-111 >> 1 = -100 <==> 11111001 >> 1 = 11111100
</code></pre>
<p>As you can see, the two's complement of the number will extend the sign.</p>
| 2 |
2016-09-17T18:02:12Z
|
[
"python",
"bit-manipulation"
] |
Convert Pandas Dataframe from Row based to Columnar
| 39,550,147 |
<p>My Dataframe (df) looks like this:</p>
<pre><code>Date FieldA ValueA ValueB
09-02-2016 TypeA 3 5
09-02-2016 TypeB 6 7
</code></pre>
<p>I want the dataframe to look like below:</p>
<pre><code>Date TypeA_ValueA TypeA_ValueB TypeB_ValueA TypeB_ValueB
09-02-2016 3 5 6 7
</code></pre>
<p>I tired the df.pivot in pandas where I can provide single Value column. It doesnt take more than one. When I provide more than one i get below exception. <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="nofollow">pandas_pivot</a></p>
<pre><code>Exception: Data must be 1-dimensional
</code></pre>
| 0 |
2016-09-17T18:10:13Z
| 39,550,196 |
<pre><code>df1 = df.set_index(['Date', 'FieldA']).unstack()
df1.columns = df1.columns.map('_'.join)
df1.reset_index()
</code></pre>
<p><a href="http://i.stack.imgur.com/Q583z.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q583z.png" alt="enter image description here"></a></p>
<hr>
<h3>Setup Reference</h3>
<pre><code>from StringIO import StringIO
import pandas as pd
text = """Date FieldA ValueA ValueB
09-02-2016 TypeA 3 5
09-02-2016 TypeB 6 7"""
df = pd.read_csv(StringIO(text), delim_whitespace=True)
df
</code></pre>
<p><a href="http://i.stack.imgur.com/U3AXF.png" rel="nofollow"><img src="http://i.stack.imgur.com/U3AXF.png" alt="enter image description here"></a></p>
| 2 |
2016-09-17T18:15:39Z
|
[
"python",
"sql",
"pandas",
"pyspark",
"spark-dataframe"
] |
Convert Pandas Dataframe from Row based to Columnar
| 39,550,147 |
<p>My Dataframe (df) looks like this:</p>
<pre><code>Date FieldA ValueA ValueB
09-02-2016 TypeA 3 5
09-02-2016 TypeB 6 7
</code></pre>
<p>I want the dataframe to look like below:</p>
<pre><code>Date TypeA_ValueA TypeA_ValueB TypeB_ValueA TypeB_ValueB
09-02-2016 3 5 6 7
</code></pre>
<p>I tired the df.pivot in pandas where I can provide single Value column. It doesnt take more than one. When I provide more than one i get below exception. <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="nofollow">pandas_pivot</a></p>
<pre><code>Exception: Data must be 1-dimensional
</code></pre>
| 0 |
2016-09-17T18:10:13Z
| 39,551,015 |
<pre><code>In [36]: df
Out[36]:
Date FieldA ValueA ValueB
0 2016-09-02 TypeA 3 5
1 2016-09-02 TypeB 6 7
2 2016-09-03 TypeA 4 8
3 2016-09-03 TypeB 3 9
In [37]: v_cols = df.columns.difference(['FieldA', 'Date'])
In [38]: def func(x):
...: d = {'_'.join([t, c]): x[x['FieldA'] == t][c].iloc[0] for t in x.FieldA for c in v_cols}
...: for k, v in d.iteritems():
...: x[k] = v
...: return x
...:
In [39]: newdf = df.groupby('Date').apply(func)
In [40]: newdf.drop(v_cols.tolist() + ['FieldA'], axis=1).drop_duplicates()
Out[340]:
Date TypeA_ValueA TypeA_ValueB TypeB_ValueA TypeB_ValueB
0 2016-09-02 3 5 6 7
2 2016-09-03 4 8 3 9
</code></pre>
| 0 |
2016-09-17T19:43:23Z
|
[
"python",
"sql",
"pandas",
"pyspark",
"spark-dataframe"
] |
Convert Pandas Dataframe from Row based to Columnar
| 39,550,147 |
<p>My Dataframe (df) looks like this:</p>
<pre><code>Date FieldA ValueA ValueB
09-02-2016 TypeA 3 5
09-02-2016 TypeB 6 7
</code></pre>
<p>I want the dataframe to look like below:</p>
<pre><code>Date TypeA_ValueA TypeA_ValueB TypeB_ValueA TypeB_ValueB
09-02-2016 3 5 6 7
</code></pre>
<p>I tired the df.pivot in pandas where I can provide single Value column. It doesnt take more than one. When I provide more than one i get below exception. <a href="http://pandas.pydata.org/pandas-docs/stable/reshaping.html" rel="nofollow">pandas_pivot</a></p>
<pre><code>Exception: Data must be 1-dimensional
</code></pre>
| 0 |
2016-09-17T18:10:13Z
| 39,552,056 |
<p>Use <code>pd.pivot_table</code>.</p>
<pre><code>In [1]: pd.pivot_table(df, index='Date', columns='FieldA', values=['ValueA', 'ValueB'])
Out[1]:
ValueA ValueB
FieldA TypeA TypeB TypeA TypeB
Date
09-02-2016 3 6 5 7
</code></pre>
<p>As a result, you'll get a DataFrame with MultiIndex. If you want to flatten it and have <code>_</code> as separator in the column name, you can just do:</p>
<pre><code>In [1]: df = pd.pivot_table(df, index='Date', columns='FieldA', values=['ValueA', 'ValueB'])
In [2]: df.columns = [ '{}_{}'.format(cat, val) for val, cat in df.columns ]
In [3]: df
Out[3]:
TypeA_ValueA TypeB_ValueA TypeA_ValueB TypeB_ValueB
Date
09-02-2016 3 6 5 7
</code></pre>
| 0 |
2016-09-17T21:47:41Z
|
[
"python",
"sql",
"pandas",
"pyspark",
"spark-dataframe"
] |
Error in parsing strings to ints
| 39,550,210 |
<p>I have these two and it seems that bytes2integer is wrong, but I eliminated all the other issues. What is wrong? <a href="https://github.com/construct/construct/blob/master/construct/lib/py3compat.py" rel="nofollow">p3compat</a> provides some helper functions. On side note, <code>-int(data[1:], 2)</code> also doesnt work but that isnt necessary for correctness. Code is both PY2 and PY3.</p>
<pre><code>def bits2integer(data, signed=False):
data = "".join("01"[b & 1] for b in iterateints(data))
if signed and data[0] == "1":
# return -int(data[1:], 2)
data = data[1:]
bias = 1 << len(data)
return int(data, 2) - bias
else:
return int(data, 2)
def bytes2integer(data, signed=False):
number = 0
for b in iterateints(data[::-1]):
number = (number << 8) | b
if signed and byte2int(bytes2bits(data[0:1])[0:1]):
# data = data[1:]
bias = 1 << (len(data)*8 -1)
return number - bias
else:
return number
</code></pre>
<p><a href="https://github.com/construct/construct/blob/add-binary/tests/test_lib.py#L33" rel="nofollow">Tests</a> returned these errors:</p>
<pre><code>returned 6124614018247163903, expected -300
returned -9079256848778919937, expected -255
returned 2089670227099910143, expected -100
returned 9223372036854775807, expected -1
returned 72057594037927936, expected 1
returned 7205759403792793600, expected 100
returned 18374686479671623680, expected 255
returned 3170815612645539840, expected 300
</code></pre>
| 2 |
2016-09-17T18:17:28Z
| 39,550,811 |
<p>Bytes were reversed wrongly, and then it parsed the sign bit into number. Two bugs fixed.</p>
<pre><code>def onebit2integer(b):
if b in (b"0", b"\x00"):
return 0
if b in (b"1", b"\x01"):
return 1
raise ValueError(r"bit was not recognized as one of: 0 1 \x00 \x01")
def bits2integer(data, signed=False):
number = 0
for b in iteratebytes(data):
number = (number << 1) | onebit2integer(b)
if signed and onebit2integer(data[0:1]):
bias = 1 << (len(data) -1)
return number - bias*2
else:
return number
def bytes2integer(data, signed=False):
number = 0
for b in iterateints(data):
number = (number << 8) | b
if signed and byte2int(bytes2bits(data[0:1])[0:1]):
bias = 1 << (len(data)*8 -1)
return number - bias*2
else:
return number
</code></pre>
| 0 |
2016-09-17T19:20:47Z
|
[
"python",
"parsing"
] |
PANDAS Combine Rows And Preserve Column Order
| 39,550,212 |
<p>I have a "long" format pandas dataframe of the following general structure:</p>
<pre><code>id,date,color,size,density
1,201201,val1,val2,val3
1,201301,val1,val2,val3
1,201301,val1,val2,val3
2,201201,val1,val2,val3
2,201202,val1,val2,val3
</code></pre>
<p>The new "wide" format I am looking to create is this:</p>
<pre><code>id,color_1,size_1,density_1,color_2,size_2,density_2,color_3,size_3,density_3
1,val1,val2,val3,val1,val2,val3,val1,val2,val3
2,val1,val2,val3,val1,val2,val3
</code></pre>
<p>Where the original row order of columns are preserved but they are now put in order of ascending date in single rows by id. When I try pd.pivot variations it does not preserve the column order. Perhaps a concat approach? Any advice is welcome.</p>
<p><strong>UPDATE:</strong></p>
<p>I've made some progress on this so here is my new base dataframe:</p>
<pre><code>id, date, feature_vector (parens for clarity, not in data, comma seperated string field)
1,2012-01-01,(0,1,0,0,0,1)
1,2013-01-01,(0,0,1,0,0,1)
1,2013-01-02,(0,1,0,1,0,1)
2,2012-01-11,(0,1,0,0,1,1)
2,2012-02-11,(0,1,1,0,0,1)
</code></pre>
<p>I'm trying to create the following:</p>
<pre><code>id, feature_vector
1,(0,1,0,0,0,1,0,0,1,0,0,1,0,1,0,1,0,1)
2,(0,1,0,0,1,1,0,1,1,0,0,1)
</code></pre>
<p>I'm just trying to concatenate the feature vectors in date order now.</p>
| 1 |
2016-09-17T18:17:30Z
| 39,550,921 |
<p>You could use the concat method, but I tried making your long dataframe and found it unwieldy and fragile even in your toy example. I would suggest using the groupby method.</p>
<pre><code>grouped = df.sort('date', ascending=True).groupby('id')
</code></pre>
<p>If you need the concatenated version, try this:</p>
<pre><code>columns = ['date', 'color', 'size', 'density']
first = grouped.nth(0)
first = first[columns]
first.rename(columns=lambda x: '{}_1'.format(x), inplace=True)
second = grouped.nth(1)
second = second[columns]
second.rename(columns=lambda x: '{}_2'.format(x), inplace=True)
new_df = pd.concat([first, second], axis=1)
</code></pre>
| 1 |
2016-09-17T19:32:32Z
|
[
"python",
"pandas"
] |
How can I apply a function to a single row or column of a matrix using numpy and python
| 39,550,238 |
<p>I am learning numpy and using python and asking for help. I would like to sort a SINGLE row or column as a learning experience. Looking through their docs i see apply_along_axis but there isnt a parameter in their docs on how to indicate a splice/selector in choosing which rows or columns to apply it to.</p>
<p>I only want the second row to be sorted.
Here is my code so far...</p>
<pre><code>import numpy as np
A = [29,-11,10,-160,61,-55,55,-21,19]
A = np.asarray(A)
A = np.reshape(A, (3,-1))
np.apply_along_axis(func1d=sorted, axis=1, arr=A) #this line is not correct
</code></pre>
<p>Starting with the following array...</p>
<pre><code>array([[ 29, -11, 10],
[-160, 61, -55],
[ 55, -21, 19]])
</code></pre>
<p>I would like to see the following output...</p>
<pre><code>array([[ 29, -11, 10],
[-160, -55, 61],
[ 55, -21, 19]])
</code></pre>
| 2 |
2016-09-17T18:20:37Z
| 39,550,499 |
<p>There's an inplace sort method.</p>
<pre><code>In [75]: A=np.array(A).reshape(3,-1)
In [76]: A
Out[76]:
array([[ 29, -11, 10],
[-160, 61, -55],
[ 55, -21, 19]])
In [77]: A[1,:].sort()
In [78]: A
Out[78]:
array([[ 29, -11, 10],
[-160, -55, 61],
[ 55, -21, 19]])
</code></pre>
<p>I just took a guess that it would work on a single row of the array, and tried. It appears to work. (I overlooked Divakar's comment).</p>
<p><code>apply_along...</code> and <code>apply_over...</code> are convenience functions that make it easier (not faster) to iterate over one or more dimensions, and over kill in a case like this.</p>
<p>It may be easier to understand this with the <code>np.sort</code> function:</p>
<pre><code>In [85]: np.sort(A[1,:])
Out[85]: array([-160, -55, 61])
</code></pre>
<p>the function returns a copy of the row that is sorted; we can then write it back to <code>A</code> with:</p>
<pre><code>In [86]: A[1,:]=np.sort(A[1,:])
</code></pre>
<p><code>numpy</code> has its own sorting methods, so usually we don't need to use the general Python list versions, such as <code>sorted</code>. However this works: <code>A[1,:]=sorted(A[1,:])</code>.</p>
| 4 |
2016-09-17T18:46:41Z
|
[
"python",
"numpy"
] |
How would a parent class call its own method within itself in Python
| 39,550,288 |
<p>I am trying to create the concrete class <code>Val15</code> class with the Mixins, <code>MyCollection</code>, <code>Val5</code>, <code>Val10</code>. <code>Val15</code> is trying to inherit <code>values</code> from <code>MyCollection</code>. When <code>Val15</code> is instantiated, I am trying to call both <code>Val10</code>'s and <code>Val5</code>'s <code>value</code> and add them to <code>Val15</code>, <code>values</code>. </p>
<p>However, it turns out that <code>Val15</code> will inherit only <code>Val10</code>'s value and all the classes will call <code>Val10</code>'s value. How exactly can you overturn this problem?</p>
<pre><code>class MyCollection(object):
def __init__(self):
super().__init__()
self.values = []
class MyMessage(object):
def __init__(self):
super().__init__()
def message(self):
print('Hello World')
class Val10(object):
def __init__(self):
super().__init__()
print('Call 10')
self.values.append(self.value())
def value(self):
print('Value 10')
return 10
class Val5(object):
def __init__(self):
super().__init__()
print('Call 5')
self.values.append(self.value())
def value(self):
print('Value 5')
return 5
class Val15(Val10, Val5, MyMessage, MyCollection):
def __init__(self):
super().__init__()
def my_sum(self):
return sum(self.values)
val15 = Val15()
val15.my_sum()
val15.message()
# Result:
# Call 5
# Value 10
# Call 10
# Value 10
# Hello World
</code></pre>
| 0 |
2016-09-17T18:26:06Z
| 39,551,113 |
<p>This is the interesting part:</p>
<pre><code>class Val10(object):
def value(self):
return 10
class Val5(object):
def value(self):
return 5
</code></pre>
<p>To get the sum of parents' values, you have to call each of them:</p>
<pre><code>class Val15(Val10, Val5):
def value(self):
return Val10.value(self) + Val5.value(self)
</code></pre>
<h2>Alternative solution</h2>
<p>Another approach is to define that <code>value</code> always returns the sum of all inherited values, whatever they may be, without knowing which parent classes' <code>value</code> to call:</p>
<pre><code>class Val10:
def value(self):
previous = getattr(super(), 'value', lambda: 0)()
return previous + 10
class Val5:
def value(self):
previous = getattr(super(), 'value', lambda: 0)()
return previous + 5
class Val15(Val10, Val5):
def value(self):
return getattr(super(), 'value', lambda: 0)()
Val15().value() # 15
</code></pre>
<p>This solution does not make any assumptions about the way inheritance is going to be configured.</p>
<p><strong>Remarks:</strong></p>
<ul>
<li>The answer assumes that this is Python 3, because of the <code>super()</code> syntax</li>
<li><code>getattr(super(), 'value', lambda: 0)</code> returns the bound <code>value</code> method of the parent class, if such exists, or defaults to a function which returns 0.</li>
</ul>
| 1 |
2016-09-17T19:55:03Z
|
[
"python",
"inheritance",
"mixins"
] |
TypeError: both int and float
| 39,550,293 |
<pre><code>class Account(object):
def __init__(self,holder, number, balance, credit_line = 1500):
self.holder = holder
self.number = number
self.balance = balance
self.credit_line = credit_line
def deposit(self, amount):
self.balance = amount
def withdraw(self, amount):
if(self.balance - amount < -self.credit_line):
return False
else:
self.balance -= amount
return True
def balance(self):
return self.balance
def holder(self):
return self.holder
def transfer(self, target, amount):
if(self.balance - amount < -self.credit_line):
#coverage insufficient
return False
else:
self.balance -= amount
target.balance += amount
return True
Guido = Account("Guido", 10 ,1000.50)
Guido.balance()
-------------------------------------------------------------------------
Traceback (most recent call last):
File "Account.py", line 31, in <module>
Guido.balance()
TypeError: 'float' object is not callable
</code></pre>
| -2 |
2016-09-17T18:26:41Z
| 39,550,328 |
<p>You are overriding method <code>balance</code> in your <code>__init__</code> method. You could either change the field name to <code>_balance</code> or just remove <code>balance</code> method and use <code>Guido.balance</code>.</p>
<p>Also note, that you should name your variables starting with lowercase character (i.e. <code>guido = Account(...)</code>, not <code>Guido</code>)</p>
| 1 |
2016-09-17T18:31:00Z
|
[
"python",
"python-2.7"
] |
TypeError: both int and float
| 39,550,293 |
<pre><code>class Account(object):
def __init__(self,holder, number, balance, credit_line = 1500):
self.holder = holder
self.number = number
self.balance = balance
self.credit_line = credit_line
def deposit(self, amount):
self.balance = amount
def withdraw(self, amount):
if(self.balance - amount < -self.credit_line):
return False
else:
self.balance -= amount
return True
def balance(self):
return self.balance
def holder(self):
return self.holder
def transfer(self, target, amount):
if(self.balance - amount < -self.credit_line):
#coverage insufficient
return False
else:
self.balance -= amount
target.balance += amount
return True
Guido = Account("Guido", 10 ,1000.50)
Guido.balance()
-------------------------------------------------------------------------
Traceback (most recent call last):
File "Account.py", line 31, in <module>
Guido.balance()
TypeError: 'float' object is not callable
</code></pre>
| -2 |
2016-09-17T18:26:41Z
| 39,555,750 |
<pre><code>class Account(object):
def __init__(self,holder, number, balance, credit_line = 1500):
self.holder = holder
self.number = number
self.balance = balance
self.credit_line = credit_line
def deposit(self, amount):
self.balance = amount
def withdraw(self, amount):
if amount > self.balance:
print "Amount greater than available balance"
else:
self.balance -= amount
return True
def bala_nce(self):
return self.balance
def hold_er(self):
return self.holder
def num(self):
return self.number
def transfer(self, target, amount):
if(self.balance - amount < -self.credit_line):
#coverage insufficient
return False
else:
self.balance -= amount
target.balance += amount
return True
guido = Account("Guido", 10 ,10000.100)
guido.withdraw(2300.100)
print "Account name: " ,guido.hold_er()
print "available balance: $",guido.bala_nce()
</code></pre>
<p>thanx to you soon............... its working now</p>
| 0 |
2016-09-18T08:45:34Z
|
[
"python",
"python-2.7"
] |
urllib read() changing attributes
| 39,550,348 |
<p>I have a basic script, which is requesting websites to get the html source code.
while crawling several websites I figured out that different attributes in the source code are being represented wrong.</p>
<p>Example:</p>
<pre><code>from urllib import request
opener = request.build_opener()
with opener.open("https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2") as response:
html = response.read()
print(html)
</code></pre>
<p>I compared the results (<code>html</code> var) with the source code being represented by Chrome and Firefox.</p>
<p>I saw differences like these:</p>
<pre><code>Browser Urllib
href='rfc2616.html' href=\'rfc2616.html\'
rev='Section' rev=\'Section\'
rel='xref' rel=\'xref\'
id='sec4.5' id=\'sec4.4\'
</code></pre>
<p>It looks like <code>urllib</code> is putting backslashes here to escape code.</p>
<p>Is this a bug deep inside <code>urllib</code> or is there any way to fix this problem?</p>
<p>Thanks in advance.</p>
| 0 |
2016-09-17T18:32:45Z
| 39,550,415 |
<p><code>responce.read()</code> will return a <code>bytes</code> object, when printed its escape sequences don't get interpreted, see:</p>
<pre><code>print(b'hello\nworld') # prints b'hello\nworld'
</code></pre>
<p>You'll need to <code>decode</code> it to <code>str</code> which, when printed, evaluates the escapes correctly:</p>
<pre><code>print(html.decode())
</code></pre>
| 0 |
2016-09-17T18:38:25Z
|
[
"python",
"python-3.x",
"urllib"
] |
Is there a way to avoid a new line while using `end=`
| 39,550,446 |
<p>I've just started using python and I'm creating a simple program that will ask whoever the user is a question and then from the text file I will extract a specific line and print that line and along with the line - at the end I will add their answer. here's the code.</p>
<pre><code> question = input("do you want to print the line")
if "yes" in question:
print(open("tp.txt").readlines()[:10][-1],end=question)
</code></pre>
<p>The issue is that <code>,end=question)</code> puts the users answer on a new line. I know that <code>end=</code> is the same as <code>\n</code>. So I'm just wondering is there a way or an alternative to stop 'end=' from automatically creating a new line?</p>
<pre><code> print(open("tp.txt").readlines()[:10][-1],
</code></pre>
<p>is the way I open and read a specific line from the file
since its a 'nice' shortcut to do than rather do<code>with open (filename.txt,'r') as f:</code></p>
| -1 |
2016-09-17T18:41:45Z
| 39,550,524 |
<p>Have you tried simply omitting the "end="?
I don't think it's necessary you put it there.</p>
| 0 |
2016-09-17T18:48:51Z
|
[
"python",
"python-3.5"
] |
Is there a way to avoid a new line while using `end=`
| 39,550,446 |
<p>I've just started using python and I'm creating a simple program that will ask whoever the user is a question and then from the text file I will extract a specific line and print that line and along with the line - at the end I will add their answer. here's the code.</p>
<pre><code> question = input("do you want to print the line")
if "yes" in question:
print(open("tp.txt").readlines()[:10][-1],end=question)
</code></pre>
<p>The issue is that <code>,end=question)</code> puts the users answer on a new line. I know that <code>end=</code> is the same as <code>\n</code>. So I'm just wondering is there a way or an alternative to stop 'end=' from automatically creating a new line?</p>
<pre><code> print(open("tp.txt").readlines()[:10][-1],
</code></pre>
<p>is the way I open and read a specific line from the file
since its a 'nice' shortcut to do than rather do<code>with open (filename.txt,'r') as f:</code></p>
| -1 |
2016-09-17T18:41:45Z
| 39,550,589 |
<p>The problem is that the lines returned by <code>readlines()</code> contain the ending newline:</p>
<pre><code>$ echo 'a
> b
> c
> ' > test_file.txt
$ python3
Python 3.5.2 (default, Jul 5 2016, 12:43:10)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> with open('test_file.txt') as f:
... print(f.readlines())
...
['a\n', 'b\n', 'c\n', '\n']
</code></pre>
<p>See the <code>\n</code>? Note the difference bewteen:</p>
<pre><code>>>> print('a\n')
a
>>>
</code></pre>
<p>And:</p>
<pre><code>>>> print('a')
a
>>>
</code></pre>
<p>So you want to remove that:</p>
<pre><code>>>> with open('test_file.txt') as f:
... for line in f:
... print(line.rstrip('\n'), end='<something>')
...
a<something>b<something>c<something><something>>>>
</code></pre>
| 0 |
2016-09-17T18:56:19Z
|
[
"python",
"python-3.5"
] |
Selenium returns wrong element when search by class/xpath/css
| 39,550,448 |
<p>I'm trying to make simple python script that finds non-faded elements on site and click them.</p>
<p>My code:</p>
<pre><code>from selenium import webdriver
ffprofile = webdriver.FirefoxProfile(r"C:/Users/Dan/AppData/Roaming/Mozilla/Firefox/Profiles/q3fhuchn.QAtest")
driver = webdriver.Firefox(ffprofile)
driver.get("https://www.steamgifts.com/giveaways/search?page=1&type=wishlist")
element = driver.find_element_by_class_name("giveaway__row-inner-wrap")
element.find_element_by_class_name("giveaway__heading__name").click()
</code></pre>
<p>In this script Selenium returns wrong element with the similar class name - "giveaway__row-inner-wrap is-faded".</p>
<p>I've tried xpath and css selectors, but result was the same.
It looks like Selenium searches not the exact class name, but the one which contains search query.</p>
<p>Also script works fine with the following expression:</p>
<pre><code>driver.find_element_by_xpath("//div[@class='giveaway__row-inââner-wrap']//a[@classââ='giveaway__heading_ââ_name']").click()
</code></pre>
<p>But I need list of all elements to be able to iterate them.</p>
<p>Here is example of both types of HTML elements:</p>
<pre><code> <div class="giveaway__row-outer-wrap" data-game-id="707524220">
<div class="giveaway__row-inner-wrap is-faded">
<div class="giveaway__summary">
<h2 class="giveaway__heading">
<a class="giveaway__heading__name" href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack">Call of Duty: Black Ops III - Multiplaye...</a><span class="giveaway__heading__thin">(15P)</span><a class="giveaway__icon" rel="nofollow" target="_blank" href="http://store.steampowered.com/app/437350/"><i class="fa fa-steam"></i></a><i data-popup="popup--hide-games" class="giveaway__icon giveaway__hide trigger-popup fa fa-eye-slash"></i>
</h2>
<div class="giveaway__columns">
<div><i class="fa fa-clock-o"></i> <span title="Tomorrow, 4:59am">7 hours remaining</span></div><div class="giveaway__column--width-fill text-right"><span title="September 12, 2016, 4:01am">5 days ago</span> by <a class="giveaway__username" href="/user/Clockknight">Clockknight</a></div></div>
<div class="giveaway__links">
<a href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack/entries"><i class="fa fa-tag"></i> <span>2,552 entries</span></a>
<a href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack/comments"><i class="fa fa-comment"></i> <span>25 comments</span></a>
</div>
</div><a href="/user/Clockknight" class="global__image-outer-wrap global__image-outer-wrap--avatar-small"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/51/5127d377a5bb8ee65356bcd81e44873824a2e7b5_medium.jpg);"></div></a><a class="global__image-outer-wrap global__image-outer-wrap--game-medium" href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steam/apps/437350/capsule_184x69.jpg);"></div>
</a>
</div>
</div>
<div class="giveaway__row-outer-wrap" data-game-id="8668">
<div class="giveaway__row-inner-wrap">
<div class="giveaway__summary">
<h2 class="giveaway__heading">
<a class="giveaway__heading__name" href="/giveaway/MsP6N/chaos-on-deponia">Chaos on Deponia</a><span class="giveaway__heading__thin">(100P)</span><a class="giveaway__icon" rel="nofollow" target="_blank" href="http://store.steampowered.com/app/220740/"><i class="fa fa-steam"></i></a><i data-popup="popup--hide-games" class="giveaway__icon giveaway__hide trigger-popup fa fa-eye-slash"></i>
</h2>
<div class="giveaway__columns">
<div><i class="fa fa-clock-o"></i> <span title="Tomorrow, 7:00am">9 hours remaining</span></div><div class="giveaway__column--width-fill text-right"><span title="Today, 5:03pm">4 hours ago</span> by <a class="giveaway__username" href="/user/JsxfT">JsxfT</a></div></div>
<div class="giveaway__links">
<a href="/giveaway/MsP6N/chaos-on-deponia/entries"><i class="fa fa-tag"></i> <span>84 entries</span></a>
<a href="/giveaway/MsP6N/chaos-on-deponia/comments"><i class="fa fa-comment"></i> <span>0 comments</span></a>
</div>
</div><a href="/user/JsxfT" class="global__image-outer-wrap global__image-outer-wrap--avatar-small"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/90/90b441d2627716a1a4c6be1f8fb375bea590c763_medium.jpg);"></div></a><a class="global__image-outer-wrap global__image-outer-wrap--game-medium" href="/giveaway/MsP6N/chaos-on-deponia"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steam/apps/220740/capsule_184x69.jpg);"></div>
</a>
</div>
</div>
</code></pre>
<p>I would be appreciate if someone can help me with this!</p>
| 0 |
2016-09-17T18:41:52Z
| 39,550,550 |
<p>You can try to click on required element using <code>XPath</code>:</p>
<pre><code>driver.find_element_by_xpath('//a[@class="giveaway__heading__name"]').click()
</code></pre>
| 0 |
2016-09-17T18:51:47Z
|
[
"python",
"html",
"selenium"
] |
Selenium returns wrong element when search by class/xpath/css
| 39,550,448 |
<p>I'm trying to make simple python script that finds non-faded elements on site and click them.</p>
<p>My code:</p>
<pre><code>from selenium import webdriver
ffprofile = webdriver.FirefoxProfile(r"C:/Users/Dan/AppData/Roaming/Mozilla/Firefox/Profiles/q3fhuchn.QAtest")
driver = webdriver.Firefox(ffprofile)
driver.get("https://www.steamgifts.com/giveaways/search?page=1&type=wishlist")
element = driver.find_element_by_class_name("giveaway__row-inner-wrap")
element.find_element_by_class_name("giveaway__heading__name").click()
</code></pre>
<p>In this script Selenium returns wrong element with the similar class name - "giveaway__row-inner-wrap is-faded".</p>
<p>I've tried xpath and css selectors, but result was the same.
It looks like Selenium searches not the exact class name, but the one which contains search query.</p>
<p>Also script works fine with the following expression:</p>
<pre><code>driver.find_element_by_xpath("//div[@class='giveaway__row-inââner-wrap']//a[@classââ='giveaway__heading_ââ_name']").click()
</code></pre>
<p>But I need list of all elements to be able to iterate them.</p>
<p>Here is example of both types of HTML elements:</p>
<pre><code> <div class="giveaway__row-outer-wrap" data-game-id="707524220">
<div class="giveaway__row-inner-wrap is-faded">
<div class="giveaway__summary">
<h2 class="giveaway__heading">
<a class="giveaway__heading__name" href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack">Call of Duty: Black Ops III - Multiplaye...</a><span class="giveaway__heading__thin">(15P)</span><a class="giveaway__icon" rel="nofollow" target="_blank" href="http://store.steampowered.com/app/437350/"><i class="fa fa-steam"></i></a><i data-popup="popup--hide-games" class="giveaway__icon giveaway__hide trigger-popup fa fa-eye-slash"></i>
</h2>
<div class="giveaway__columns">
<div><i class="fa fa-clock-o"></i> <span title="Tomorrow, 4:59am">7 hours remaining</span></div><div class="giveaway__column--width-fill text-right"><span title="September 12, 2016, 4:01am">5 days ago</span> by <a class="giveaway__username" href="/user/Clockknight">Clockknight</a></div></div>
<div class="giveaway__links">
<a href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack/entries"><i class="fa fa-tag"></i> <span>2,552 entries</span></a>
<a href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack/comments"><i class="fa fa-comment"></i> <span>25 comments</span></a>
</div>
</div><a href="/user/Clockknight" class="global__image-outer-wrap global__image-outer-wrap--avatar-small"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/51/5127d377a5bb8ee65356bcd81e44873824a2e7b5_medium.jpg);"></div></a><a class="global__image-outer-wrap global__image-outer-wrap--game-medium" href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steam/apps/437350/capsule_184x69.jpg);"></div>
</a>
</div>
</div>
<div class="giveaway__row-outer-wrap" data-game-id="8668">
<div class="giveaway__row-inner-wrap">
<div class="giveaway__summary">
<h2 class="giveaway__heading">
<a class="giveaway__heading__name" href="/giveaway/MsP6N/chaos-on-deponia">Chaos on Deponia</a><span class="giveaway__heading__thin">(100P)</span><a class="giveaway__icon" rel="nofollow" target="_blank" href="http://store.steampowered.com/app/220740/"><i class="fa fa-steam"></i></a><i data-popup="popup--hide-games" class="giveaway__icon giveaway__hide trigger-popup fa fa-eye-slash"></i>
</h2>
<div class="giveaway__columns">
<div><i class="fa fa-clock-o"></i> <span title="Tomorrow, 7:00am">9 hours remaining</span></div><div class="giveaway__column--width-fill text-right"><span title="Today, 5:03pm">4 hours ago</span> by <a class="giveaway__username" href="/user/JsxfT">JsxfT</a></div></div>
<div class="giveaway__links">
<a href="/giveaway/MsP6N/chaos-on-deponia/entries"><i class="fa fa-tag"></i> <span>84 entries</span></a>
<a href="/giveaway/MsP6N/chaos-on-deponia/comments"><i class="fa fa-comment"></i> <span>0 comments</span></a>
</div>
</div><a href="/user/JsxfT" class="global__image-outer-wrap global__image-outer-wrap--avatar-small"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/90/90b441d2627716a1a4c6be1f8fb375bea590c763_medium.jpg);"></div></a><a class="global__image-outer-wrap global__image-outer-wrap--game-medium" href="/giveaway/MsP6N/chaos-on-deponia"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steam/apps/220740/capsule_184x69.jpg);"></div>
</a>
</div>
</div>
</code></pre>
<p>I would be appreciate if someone can help me with this!</p>
| 0 |
2016-09-17T18:41:52Z
| 39,550,576 |
<p>What you're seeing is correct. The element</p>
<pre><code><div class="giveaway__row-inner-wrap is-faded">
</code></pre>
<p>has in fact two classes: <code>giveaway__row-inner-wrap</code> and <code>is-faded</code> therefore it's correct that Selenium returns it. I suspect that you have two elements in that list, you just need to iterate it and locate the one element that does <em>not</em> also have the <code>is-faded</code> class.</p>
| 0 |
2016-09-17T18:55:02Z
|
[
"python",
"html",
"selenium"
] |
Selenium returns wrong element when search by class/xpath/css
| 39,550,448 |
<p>I'm trying to make simple python script that finds non-faded elements on site and click them.</p>
<p>My code:</p>
<pre><code>from selenium import webdriver
ffprofile = webdriver.FirefoxProfile(r"C:/Users/Dan/AppData/Roaming/Mozilla/Firefox/Profiles/q3fhuchn.QAtest")
driver = webdriver.Firefox(ffprofile)
driver.get("https://www.steamgifts.com/giveaways/search?page=1&type=wishlist")
element = driver.find_element_by_class_name("giveaway__row-inner-wrap")
element.find_element_by_class_name("giveaway__heading__name").click()
</code></pre>
<p>In this script Selenium returns wrong element with the similar class name - "giveaway__row-inner-wrap is-faded".</p>
<p>I've tried xpath and css selectors, but result was the same.
It looks like Selenium searches not the exact class name, but the one which contains search query.</p>
<p>Also script works fine with the following expression:</p>
<pre><code>driver.find_element_by_xpath("//div[@class='giveaway__row-inââner-wrap']//a[@classââ='giveaway__heading_ââ_name']").click()
</code></pre>
<p>But I need list of all elements to be able to iterate them.</p>
<p>Here is example of both types of HTML elements:</p>
<pre><code> <div class="giveaway__row-outer-wrap" data-game-id="707524220">
<div class="giveaway__row-inner-wrap is-faded">
<div class="giveaway__summary">
<h2 class="giveaway__heading">
<a class="giveaway__heading__name" href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack">Call of Duty: Black Ops III - Multiplaye...</a><span class="giveaway__heading__thin">(15P)</span><a class="giveaway__icon" rel="nofollow" target="_blank" href="http://store.steampowered.com/app/437350/"><i class="fa fa-steam"></i></a><i data-popup="popup--hide-games" class="giveaway__icon giveaway__hide trigger-popup fa fa-eye-slash"></i>
</h2>
<div class="giveaway__columns">
<div><i class="fa fa-clock-o"></i> <span title="Tomorrow, 4:59am">7 hours remaining</span></div><div class="giveaway__column--width-fill text-right"><span title="September 12, 2016, 4:01am">5 days ago</span> by <a class="giveaway__username" href="/user/Clockknight">Clockknight</a></div></div>
<div class="giveaway__links">
<a href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack/entries"><i class="fa fa-tag"></i> <span>2,552 entries</span></a>
<a href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack/comments"><i class="fa fa-comment"></i> <span>25 comments</span></a>
</div>
</div><a href="/user/Clockknight" class="global__image-outer-wrap global__image-outer-wrap--avatar-small"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/51/5127d377a5bb8ee65356bcd81e44873824a2e7b5_medium.jpg);"></div></a><a class="global__image-outer-wrap global__image-outer-wrap--game-medium" href="/giveaway/FFdQd/call-of-duty-black-ops-iii-multiplayer-starter-pack"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steam/apps/437350/capsule_184x69.jpg);"></div>
</a>
</div>
</div>
<div class="giveaway__row-outer-wrap" data-game-id="8668">
<div class="giveaway__row-inner-wrap">
<div class="giveaway__summary">
<h2 class="giveaway__heading">
<a class="giveaway__heading__name" href="/giveaway/MsP6N/chaos-on-deponia">Chaos on Deponia</a><span class="giveaway__heading__thin">(100P)</span><a class="giveaway__icon" rel="nofollow" target="_blank" href="http://store.steampowered.com/app/220740/"><i class="fa fa-steam"></i></a><i data-popup="popup--hide-games" class="giveaway__icon giveaway__hide trigger-popup fa fa-eye-slash"></i>
</h2>
<div class="giveaway__columns">
<div><i class="fa fa-clock-o"></i> <span title="Tomorrow, 7:00am">9 hours remaining</span></div><div class="giveaway__column--width-fill text-right"><span title="Today, 5:03pm">4 hours ago</span> by <a class="giveaway__username" href="/user/JsxfT">JsxfT</a></div></div>
<div class="giveaway__links">
<a href="/giveaway/MsP6N/chaos-on-deponia/entries"><i class="fa fa-tag"></i> <span>84 entries</span></a>
<a href="/giveaway/MsP6N/chaos-on-deponia/comments"><i class="fa fa-comment"></i> <span>0 comments</span></a>
</div>
</div><a href="/user/JsxfT" class="global__image-outer-wrap global__image-outer-wrap--avatar-small"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/90/90b441d2627716a1a4c6be1f8fb375bea590c763_medium.jpg);"></div></a><a class="global__image-outer-wrap global__image-outer-wrap--game-medium" href="/giveaway/MsP6N/chaos-on-deponia"><div class="global__image-inner-wrap" style="background-image:url(https://steamcdn-a.akamaihd.net/steam/apps/220740/capsule_184x69.jpg);"></div>
</a>
</div>
</div>
</code></pre>
<p>I would be appreciate if someone can help me with this!</p>
| 0 |
2016-09-17T18:41:52Z
| 39,551,520 |
<p>I don't know why, but this string works perfectly for my scenario, so I use it to create a list of non-faded elements:</p>
<pre><code>elements = driver.find_elements_by_xpath("//div[@class='giveaway__row-inner-wrap']//a[@class='giveaway__heading__name']")
elements[x].click()
</code></pre>
| 0 |
2016-09-17T20:40:54Z
|
[
"python",
"html",
"selenium"
] |
Python version of Java regular expression?
| 39,550,452 |
<p>I am a Java developer, and new to Python. I would like to define a regex accepting all the alphabetic characters except for some of them. I want to exclude just the vowels and the character 'y', be it in upper- or lowercase. </p>
<p>The regex in Java for it would be as follows:</p>
<pre><code> "[a-zA-Z&&[^aeiouyAEIOUY]]"
</code></pre>
<p>How can I (re)define it as in Python? The above doesn't work for Python, obviously. And I also would <strong>NOT</strong> like the following pattern to be suggested:</p>
<pre><code>"[bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ]"
</code></pre>
| 0 |
2016-09-17T18:42:07Z
| 39,550,636 |
<p>Like <code>(?i)[b-df-hj-np-tv-xz]</code> or <code>(?i)\w(?<![_aeiouy\d])</code>. Test <a href="https://regex101.com/#python" rel="nofollow">here</a>.</p>
| 0 |
2016-09-17T19:01:12Z
|
[
"python",
"regex"
] |
Python version of Java regular expression?
| 39,550,452 |
<p>I am a Java developer, and new to Python. I would like to define a regex accepting all the alphabetic characters except for some of them. I want to exclude just the vowels and the character 'y', be it in upper- or lowercase. </p>
<p>The regex in Java for it would be as follows:</p>
<pre><code> "[a-zA-Z&&[^aeiouyAEIOUY]]"
</code></pre>
<p>How can I (re)define it as in Python? The above doesn't work for Python, obviously. And I also would <strong>NOT</strong> like the following pattern to be suggested:</p>
<pre><code>"[bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ]"
</code></pre>
| 0 |
2016-09-17T18:42:07Z
| 39,550,784 |
<blockquote>
<p><strong>(?=...)</strong> Positive lookahead assertion. This succeeds if the contained
regular expression, represented here by ..., successfully matches at
the current location, and fails otherwise. But, once the contained
expression has been tried, the matching engine doesnât advance at all;
the rest of the pattern is tried right where the assertion started.</p>
<p><strong>(?!...)</strong> Negative lookahead assertion. This is the opposite of the
positive assertion; it succeeds if the contained expression doesnât
match at the current position in the string.</p>
</blockquote>
<pre><code>r"(?![aeiouyAEIOUY])[a-zA-Z])"
</code></pre>
| 0 |
2016-09-17T19:18:11Z
|
[
"python",
"regex"
] |
Python version of Java regular expression?
| 39,550,452 |
<p>I am a Java developer, and new to Python. I would like to define a regex accepting all the alphabetic characters except for some of them. I want to exclude just the vowels and the character 'y', be it in upper- or lowercase. </p>
<p>The regex in Java for it would be as follows:</p>
<pre><code> "[a-zA-Z&&[^aeiouyAEIOUY]]"
</code></pre>
<p>How can I (re)define it as in Python? The above doesn't work for Python, obviously. And I also would <strong>NOT</strong> like the following pattern to be suggested:</p>
<pre><code>"[bcdfghjklmnpqrstvwxzBCDFGHJKLMNPQRSTVWXZ]"
</code></pre>
| 0 |
2016-09-17T18:42:07Z
| 39,550,987 |
<p>I don't think the current python regular expression module has exactly what you're looking for. The eventual replacement <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><code>regex</code></a> does have what you need, and you can install it should you wish.</p>
<p>Other than that, a negation might be the way to go. Basically, define all the characters you don't want and then invert that. Sounds labourious, but the "not-word" shorthand (<code>\W</code>) can help us out. <code>\w</code> means <code>a-zA-Z0-9_</code> (for ASCII matches), and <code>\W</code> means the opposite (<code>[^\w]</code>). Thus, <code>[aeiouyAEIOUY\W\d_]</code> means every character which you are not looking for, and so <code>[^aeiouyAEIOUY\W\d_]</code> means every character you are looking for. eg.</p>
<pre><code>>>> import re
>>> s = "xyz_ d10 word"
>>> pattern = "[^aeiouyAEIOUY\W\d_]+"
>>> re.findall(pattern, s)
['x', 'z', 'd', 'w', 'rd']
</code></pre>
<p>If you are strictly after only ASCII characters then you can use the <code>ASCII</code> flag. eg.</p>
<pre><code>>>> s = "Español"
>>> re.findall(pattern, s)
['sp', 'ñ', 'l']
>>> re.findall(pattern, s, re.ASCII)
['sp', 'l']
</code></pre>
| 2 |
2016-09-17T19:40:58Z
|
[
"python",
"regex"
] |
Dealing with QVariants in a settings-module with python 2.7.6 / PyQt4
| 39,550,456 |
<p>I have previously read several topics on this site and other platforms, but my code does still not work as desired. I seem not to be able to put all the puzzle pieces together and need someone to look over my code. </p>
<p>I'm writing a plugin for the program QtiPlot. Im using Python 2.7.6 and PyQt4. I created the Plugin GUI with QT Designer. I'm also new to Python. Im using these "old" resources because my predecessor has used them.</p>
<p>My current task is to develop the settings, i.e. being able to save and restore parameters.
I found a template on this site for this purpose: <a href="http://stackoverflow.com/questions/23279125/python-pyqt4-functions-to-save-and-restore-ui-widget-values">Python PyQt4 functions to save and restore UI widget values?</a></p>
<p>I want to save parameters to an Ini-File.
However I have problems with the QVariants. Instead of the strings I inserted in the plugin, the expression "PyQt4.QtCore.QVariant object at 0x08667FB0" is being saved. I already know that this is an issue due to the fact that the QVariants are not correcly converted back to Python objects. </p>
<p>So, in order to convert the QVariants back manually, I added the phrase "toString()" to the value assignment of QLineEdit-Objects in the restore function(the line commented out is the previous version). But then my QLineEdit-Blocks in the plugin are empty, which confuses me. I read in the documentation that an empty string is returned if the QVariant does not consist of one of the preset types, including string. But this happens although I entered a string before.</p>
<p>Does this mean that the strings are not correctly saved in the first place? Or else what does it mean, what do I miss or what am I doing wrong?</p>
<p>I also noticed that no values are stored in the Ini-File, so that part of the code is also still buggy. But I'm not sure if this due to the fact that the save-function doesn't work or because the Ini-construction is wrong itself.</p>
<p>Further, I tried to use the SIP-Module at the head of the configuration file to fix my problem(it is commented out, too, because it didn't work for me so far). But although I placed this at the head of the code, I then get the error "API 'QVariant' has already been set to version 1". I don't understand why or from what the SIP-instruction is overridden. Is there any way to fix this?</p>
<p>My Configuration program looks like this:</p>
<pre><code>#import sip
#sip.setapi('QVariant', 2)
#sip.setapi('QString', 2)
import inspect
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
sys.path.append("C:\\Program Files (x86)\\QtiPlot\\app\\02 Python Packages")
import PyQt4_Save_Restore_UI_Widget_Values
class app_conf(QtGui.QWidget):
def __init__(self):
super(self.__class__, self).__init__()
self.version = 1.0
QtCore.QCoreApplication.setOrganizationName("Organization")
QtCore.QCoreApplication.setApplicationName("Application")
QtCore.QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, "C:\\Program Files (x86)\\QtiPlot\\app\\02 Python Packages\\saved.ini")
self.settings = QtCore.QSettings("C:\\Program Files (x86)\\QtiPlot\\app\\02 Python Packages\\saved.ini", QSettings.IniFormat)
from PyQt4 import uic
self.ui = uic.loadUi(r"C:\Program Files (x86)/QtiPlot/app/03 UI Files/Config.ui")
PyQt4_Save_Restore_UI_Widget_Values.gui_restore_settings(self.ui, self.settings)
self.ui.closeEvent = self.closeEvent
self.ui.show()
def closeEvent(self, event):
PyQt4_Save_Restore_UI_Widget_Values.gui_save_settings(self.ui, self.settings)
window = app_conf()
</code></pre>
<p>And my settings module(PyQt4_Save_Restore_UI_Widget_Values.py) looks like this:</p>
<pre><code>#===================================================================
# Module with functions to save & restore qt widget values
# Written by: Alan Lilly
# Website: http://panofish.net
#===================================================================
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import inspect
def gui_save_settings(ui, settings):
#for child in ui.children(): # works like getmembers, but because it traverses the hierarachy, you would have to call guisave recursively to traverse down the tree
for name, obj in inspect.getmembers(ui):
#if type(obj) is QComboBox: # this works similar to isinstance, but missed some field... not sure why?
if isinstance(obj, QComboBox):
name = obj.objectName() # get combobox name
index = obj.currentIndex() # get current index from combobox
text = obj.itemText(index) # get the text for current index
settings.setValue(name, text) # save combobox selection to registry
if isinstance(obj, QLineEdit):
name = obj.objectName()
value = obj.text()
settings.setValue(name, value) # save ui values, so they can be restored next time
if isinstance(obj, QCheckBox):
name = obj.objectName()
state = obj.checkState()
settings.setValue(name, state)
def gui_restore_settings(ui, settings):
for name, obj in inspect.getmembers(ui):
if isinstance(obj, QComboBox):
index = obj.currentIndex() # get current region from combobox
#text = obj.itemText(index) # get the text for new selected index
name = obj.objectName()
value = unicode(settings.value(name))
if value == "":
continue
index = obj.findText(value) # get the corresponding index for specified string in combobox
if index == -1: # add to list if not found
obj.insertItems(0,[value])
index = obj.findText(value)
obj.setCurrentIndex(index)
else:
obj.setCurrentIndex(index) # preselect a combobox value by index
if isinstance(obj, QLineEdit):
name = obj.objectName()
#value = unicode(settings.value(name)) # get stored value from registry
value = settings.value(name).toString()
obj.setText(value) # restore lineEditFile
if isinstance(obj, QCheckBox):
name = obj.objectName()
value = settings.value(name) # get stored value from registry
if value != None:
obj.setCheckState(value.toBool()) # restore checkbox
################################################################
if __name__ == "__main__":
# execute when run directly, but not when called as a module.
# therefore this section allows for testing this module!
#print "running directly, not as a module!"
sys.exit()
</code></pre>
| 2 |
2016-09-17T18:42:36Z
| 39,551,768 |
<p>The best solution is to use <code>sip.setapi</code>. But to get it to work properly, it <strong>must</strong> be invoked before the <em>first</em> import of PyQt in your application. So it needs to go in the main script, not the config module:</p>
<pre><code>#===================================================================
# Module with functions to save & restore qt widget values
# Written by: Alan Lilly
# Website: http://panofish.net
#===================================================================
import sys
import sip
sip.setapi('QVariant', 2)
sip.setapi('QString', 2)
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import inspect
</code></pre>
<p>This will ensure <code>QVariant</code> and <code>QString</code> are always automatically converted to ordinary python types - so no need to use <code>unicode()</code>, <code>toString()</code>, <code>toBool()</code>, etc.</p>
| 1 |
2016-09-17T21:07:33Z
|
[
"python",
"pyqt4"
] |
Dealing with QVariants in a settings-module with python 2.7.6 / PyQt4
| 39,550,456 |
<p>I have previously read several topics on this site and other platforms, but my code does still not work as desired. I seem not to be able to put all the puzzle pieces together and need someone to look over my code. </p>
<p>I'm writing a plugin for the program QtiPlot. Im using Python 2.7.6 and PyQt4. I created the Plugin GUI with QT Designer. I'm also new to Python. Im using these "old" resources because my predecessor has used them.</p>
<p>My current task is to develop the settings, i.e. being able to save and restore parameters.
I found a template on this site for this purpose: <a href="http://stackoverflow.com/questions/23279125/python-pyqt4-functions-to-save-and-restore-ui-widget-values">Python PyQt4 functions to save and restore UI widget values?</a></p>
<p>I want to save parameters to an Ini-File.
However I have problems with the QVariants. Instead of the strings I inserted in the plugin, the expression "PyQt4.QtCore.QVariant object at 0x08667FB0" is being saved. I already know that this is an issue due to the fact that the QVariants are not correcly converted back to Python objects. </p>
<p>So, in order to convert the QVariants back manually, I added the phrase "toString()" to the value assignment of QLineEdit-Objects in the restore function(the line commented out is the previous version). But then my QLineEdit-Blocks in the plugin are empty, which confuses me. I read in the documentation that an empty string is returned if the QVariant does not consist of one of the preset types, including string. But this happens although I entered a string before.</p>
<p>Does this mean that the strings are not correctly saved in the first place? Or else what does it mean, what do I miss or what am I doing wrong?</p>
<p>I also noticed that no values are stored in the Ini-File, so that part of the code is also still buggy. But I'm not sure if this due to the fact that the save-function doesn't work or because the Ini-construction is wrong itself.</p>
<p>Further, I tried to use the SIP-Module at the head of the configuration file to fix my problem(it is commented out, too, because it didn't work for me so far). But although I placed this at the head of the code, I then get the error "API 'QVariant' has already been set to version 1". I don't understand why or from what the SIP-instruction is overridden. Is there any way to fix this?</p>
<p>My Configuration program looks like this:</p>
<pre><code>#import sip
#sip.setapi('QVariant', 2)
#sip.setapi('QString', 2)
import inspect
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
sys.path.append("C:\\Program Files (x86)\\QtiPlot\\app\\02 Python Packages")
import PyQt4_Save_Restore_UI_Widget_Values
class app_conf(QtGui.QWidget):
def __init__(self):
super(self.__class__, self).__init__()
self.version = 1.0
QtCore.QCoreApplication.setOrganizationName("Organization")
QtCore.QCoreApplication.setApplicationName("Application")
QtCore.QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, "C:\\Program Files (x86)\\QtiPlot\\app\\02 Python Packages\\saved.ini")
self.settings = QtCore.QSettings("C:\\Program Files (x86)\\QtiPlot\\app\\02 Python Packages\\saved.ini", QSettings.IniFormat)
from PyQt4 import uic
self.ui = uic.loadUi(r"C:\Program Files (x86)/QtiPlot/app/03 UI Files/Config.ui")
PyQt4_Save_Restore_UI_Widget_Values.gui_restore_settings(self.ui, self.settings)
self.ui.closeEvent = self.closeEvent
self.ui.show()
def closeEvent(self, event):
PyQt4_Save_Restore_UI_Widget_Values.gui_save_settings(self.ui, self.settings)
window = app_conf()
</code></pre>
<p>And my settings module(PyQt4_Save_Restore_UI_Widget_Values.py) looks like this:</p>
<pre><code>#===================================================================
# Module with functions to save & restore qt widget values
# Written by: Alan Lilly
# Website: http://panofish.net
#===================================================================
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import inspect
def gui_save_settings(ui, settings):
#for child in ui.children(): # works like getmembers, but because it traverses the hierarachy, you would have to call guisave recursively to traverse down the tree
for name, obj in inspect.getmembers(ui):
#if type(obj) is QComboBox: # this works similar to isinstance, but missed some field... not sure why?
if isinstance(obj, QComboBox):
name = obj.objectName() # get combobox name
index = obj.currentIndex() # get current index from combobox
text = obj.itemText(index) # get the text for current index
settings.setValue(name, text) # save combobox selection to registry
if isinstance(obj, QLineEdit):
name = obj.objectName()
value = obj.text()
settings.setValue(name, value) # save ui values, so they can be restored next time
if isinstance(obj, QCheckBox):
name = obj.objectName()
state = obj.checkState()
settings.setValue(name, state)
def gui_restore_settings(ui, settings):
for name, obj in inspect.getmembers(ui):
if isinstance(obj, QComboBox):
index = obj.currentIndex() # get current region from combobox
#text = obj.itemText(index) # get the text for new selected index
name = obj.objectName()
value = unicode(settings.value(name))
if value == "":
continue
index = obj.findText(value) # get the corresponding index for specified string in combobox
if index == -1: # add to list if not found
obj.insertItems(0,[value])
index = obj.findText(value)
obj.setCurrentIndex(index)
else:
obj.setCurrentIndex(index) # preselect a combobox value by index
if isinstance(obj, QLineEdit):
name = obj.objectName()
#value = unicode(settings.value(name)) # get stored value from registry
value = settings.value(name).toString()
obj.setText(value) # restore lineEditFile
if isinstance(obj, QCheckBox):
name = obj.objectName()
value = settings.value(name) # get stored value from registry
if value != None:
obj.setCheckState(value.toBool()) # restore checkbox
################################################################
if __name__ == "__main__":
# execute when run directly, but not when called as a module.
# therefore this section allows for testing this module!
#print "running directly, not as a module!"
sys.exit()
</code></pre>
| 2 |
2016-09-17T18:42:36Z
| 39,574,513 |
<p>As in Python 2 and with SIP old API, <code>toString()</code> will return a <code>QString</code>. You have to force it to a Python string with <code>str</code> for both the <code>get</code> and the <code>set</code> methods. Concerning the <code>QCheckBox</code>, I used the <code>toInt</code> method instead of the <code>toBool</code> one (which works fine for me).</p>
<p>Here is a modified version of your save and restore functions:</p>
<pre><code>def gui_save_settings(ui, settings):
for _, obj in inspect.getmembers(ui):
name = obj.objectName()
# Set QComboBox setting
if isinstance(obj, QComboBox):
value = str(obj.currentText()) # get current text from combobox
settings.setValue(name, value) # save combobox selection to registry
# Set QLineEdit setting
if isinstance(obj, QLineEdit):
value = str(obj.text())
settings.setValue(name, value) # save ui values, so they can be restored next time
# Set QCheckBox setting
if isinstance(obj, QCheckBox):
value = int(checkbox.isChecked())
settings.setValue(name, value)
def gui_restore_settings(ui, settings):
for _, obj in inspect.getmembers(ui):
name = obj.objectName()
# Get QComboBox setting
if isinstance(obj, QComboBox):
value = str(settings.value(name).toString())
if value == "":
continue
index = obj.findText(value) # get the corresponding index for specified string in combobox
if index == -1: # add to list if not found
obj.addItem(value)
index = obj.findText(value)
obj.setCurrentIndex(index) # preselect a combobox value by index
continue
# Get QLineEdit setting
if isinstance(obj, QLineEdit):
value = str(settings.value(name).toString())
obj.setText(value) # restore lineEditFile
continue
# Get QCheckBox setting
if isinstance(obj, QCheckBox):
value, res = settings.value(key).toInt() # get stored value from registry
if res:
obj.setCheckState(value) # restore checkbox
continue
</code></pre>
| 1 |
2016-09-19T13:32:24Z
|
[
"python",
"pyqt4"
] |
Scrapy - send form data with multiple options
| 39,550,477 |
<p>I'm using scrapy to parse a website that has the following form:</p>
<pre><code><form id="form1"...>
<select name="codes" multiple="multiple"...>
<option value="0">Option one</option>
<option value="1">Option two</option>
<option value="2">Option three</option>
....
</select>
</form>
</code></pre>
<p>I'm filling and submitting the form with the following code:</p>
<pre><code>submit_form = FormRequest.from_response(response,
formxpath="//form[@id='form1']",
formdata={'codes': '0'},
callback=self.parse_table)
yield submit_form
</code></pre>
<p>How can I submit multiple codes in the form data? I've tried:</p>
<pre><code>formdata={'codes': '["0", "1", "2"]'},
formdata={'codes': ['0', '1', '2']},
</code></pre>
<p>Without any luck.</p>
<p><strong>EDIT:</strong></p>
<p>The form has additional input controls, some of them hidden, that are correctly passed in the form. What I'm seeing after the form submit is like the server is returning to the same page with the form, when I'm expecting a new page with a table that actually has the data that I want to retrieve.</p>
<p>I don't know a lot about the server backend more than that it was built with .NET 2.0. It is a very old site from a goverment dependency.</p>
<p>Thanks.</p>
| 0 |
2016-09-17T18:45:18Z
| 39,557,714 |
<p>to send form with multiple options, you should try passing formdata in following format</p>
<pre><code>formdata = {}
formdata['codes[]'] = ["0","1","2","3"]
yield scrapy.FormRequest.from_response(
response=response,
formid='UserLoginForm',
formdata=formdata,
callback=self.search_result,
)
</code></pre>
<p>to verify that codes value is submitted in required format, here is the output of request_body</p>
<pre><code>codes%5B%5D=0&codes%5B%5D=1&codes%5B%5D=2&codes%5B%5D=3
</code></pre>
<p>unquote</p>
<pre><code>codes[]=0&codes[]=1&codes[]=2&codes[]=3
</code></pre>
<p>split on &</p>
<pre><code>codes[]=0
codes[]=1
codes[]=2
codes[]=3
</code></pre>
| 0 |
2016-09-18T12:39:06Z
|
[
"python",
"forms",
"scrapy"
] |
How to use 'saveas' function to send a pdf file to client side? Openerp | Odoo
| 39,550,479 |
<p>I wrote a module to consume a .wsdl webservice, using python suds library, this service returns a PDF file in base64, I'm able to save this file in a binary fild, so I want a button to download this file on client side, How can I do that? I was reading that I can use 'saveas' method available on '/web/controllers/main.py' but It's a contoller method, How can I call it by a button action? I couldn't figure out! I would appreciate any help you can give me! Thanks!</p>
| 0 |
2016-09-17T18:45:27Z
| 39,552,496 |
<p>If you are adding a button in the backend that you wish to download your pdf. You won't have access to template structures. You can get around this using a technique like this example.</p>
<p>You need a link, which you can wrap around a button (which does nothing) and you can use javascript if you need to manipulate the href (to add a query_string or to pass any data to your controller. Because you define your link as <code>target=_blank</code> and provide a download name whatever you get as a response from your controller function your browser will try to download. </p>
<pre><code><a id="pdf_download_link" href="/controller/url/path" target="_blank" download='my_pdf_file.pdf'>
<button class="oe_stat_button"
type="action"
icon="fa-print"
name="print_pdf_function"
string="Download PDF"
help="Download PDF File"/>
</a>
<script>
$(document).ready(function(){
var controller_url = ...
$("#pdf_download_link").attr("href", controller_url);
});
</script>
</code></pre>
<p>Your model does not need an action function <code>print_pdf</code>_function. In Odoo8 (not sure about Odoo9) the button will click but it just will not find the action function however the url will trigger the response from your controller.</p>
<p>Your controller.py file</p>
<pre><code>@http.route('/controller/url/path', auth='user', website=True)
def download_pdf_method(self, **kwargs):
your_method = ...
return file
</code></pre>
<p>In your controller you will need to access your binary file from your model and return it in the response to the link's request.</p>
<p>I use this in a module of my own. I use javascript to manipulate my link href so that I am passing the appropriate record it to my controllers. However you may be able to interrogate the request object and determine the record id or any other relevant data that you need. Also wrapping the button in the link is not really necessary however the buttons look much nicer than a plain text link.</p>
<p>I know this is not a conventional approach. Your other option is to just save it as a binary file and make the file available on your form. When a binary field has data the normal function of Odoo's backend form is to provide a download link.</p>
| 0 |
2016-09-17T22:54:36Z
|
[
"python",
"pdf",
"openerp",
"odoo-8",
"openerp-7"
] |
parsing and inserting raw text data into mysql database using python or shell
| 39,550,534 |
<p>I have a text file which has data in the following format:
these are 2 lines from the text file which is ncdc raw weather data:
The highlighted part is the air temperature which will be (Degree Celsius *100) Thats just one of the columns that i need to insert into database.
The temperature position always remains the same.</p>
<p>0029227070999991901122820004+62167+030650FM-12+010299999V0200501N003119999999N0000001N9-<strong>01561</strong>+99999100061ADDGF108991999999999999999999</p>
<p>0029227070999991901122906004+62167+030650FM-12+010299999V0200901N003119999999N0000001N9-<strong>01501</strong>+99999100181ADDGF108991999999999999999999</p>
<p>How do i read this text file either in Python or Bash and insert into a table in mysql database:
<strong>mysql Ver 14.14 Distrib 5.5.52, for debian-linux-gnu (x86_64) using readline 6.3</strong>
<strong>Python 2.7.6</strong>
I'm running a vagrant ubuntu virtual machine and working on it!</p>
<p>for example the table name is myweatherdata</p>
<p>Thanks!</p>
| 0 |
2016-09-17T18:50:31Z
| 39,551,665 |
<p>In python you could do something like:</p>
<pre><code>f = open("data.txt", "r") #assuming this is your file
data = f.read()
f.close()
for line in data.split("\n"): #split all data in lines
print line[88:93]
</code></pre>
<p>Last step would be inserting it in the DB instead of just printing it, eg:</p>
<pre><code>INSERT INTO myweatherdata (temperature)
VALUES (temperature_1)
</code></pre>
| 1 |
2016-09-17T20:57:19Z
|
[
"python",
"mysql",
"bash"
] |
Django: View didn't return an HttpResponse object. It returned None instead
| 39,550,577 |
<p>Basically I would like a user to input a number in a field and the fibonacci result to be printed but once the input is inserted into the input field I recieve that it returned None instead of an object</p>
<p>I have this code over here for my html form:</p>
<pre><code>{% block content %}
<form method="POST" action=".">{% csrf_token %}
<input type="text" name="fcal" value="{{F}}" />
<p>
<input type="submit" name="fibo" value="Fibonacci" />
</p>
</form>
{% if cal %}
Your Fibonacci answer is {{cal}}
{% endif %}
{% endblock %}
</code></pre>
<p>The content of my views.py is this one:</p>
<pre><code>from django.shortcuts import render_to_response, get_object_or_404, render
from django.forms import ModelForm
from django.http import HttpResponse, Http404, HttpResponseRedirect, HttpResponseNotFound
import fibonacci
def fibocal(request):
if request.method == 'POST':
fb = request.POST['fcal']
cal = fibonacci.fibo(fb)
return render(request, 'fibb/fibb.html', {'cal': cal})
else:
return render(request, 'fibb/fibb.html', {})
</code></pre>
<p>And my fibonacci function is this one: </p>
<pre><code>def fibo(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
result = fibo(n - 1) + fibo(n - 2)
return result
</code></pre>
<p>I would like to know where the error is caused as I've looked again and again and I can see that I am returning a render not None</p>
<p>Full traceback include:</p>
<pre><code>Traceback:
File "C:\python35\lib\site-packages\django\core\handlers\base.py" in get_response
158. % (callback.__module__, view_name))
Exception Type: ValueError at /fibb/
Exception Value: The view fibb.views.fibb didn't return an HttpResponse object. It returned None instead.
</code></pre>
| 0 |
2016-09-17T18:55:08Z
| 39,550,753 |
<p>In your <em>views.py</em> file, is there any <em>fibb</em> function that return a HTTPResponse? In the error trace, Django cannot find that response in <em>fibb</em> function in <em>fibb.views</em>. You can check the url directed to <em>fibb</em> function. Maybe it should be directed to <em>fibocal</em> function as you mentioned above.</p>
| 0 |
2016-09-17T19:14:26Z
|
[
"python",
"django"
] |
Hexadecimal file is loading with 2 back slashes before each byte instead of one
| 39,550,744 |
<p>I have a hex file in this format: <code>\xda\xd8\xb8\x7d</code></p>
<p>When I load the file with Python, it loads with two back slashes instead of one.</p>
<pre><code>with open('shellcode.txt', 'r') as file:
shellcode = file.read().replace('\n', '')
</code></pre>
<p>Like this: <code>\\xda\\xd8\\xb8\\x7d</code></p>
<p>I've tried using <code>hex.replace("\\", "\")</code>, but I'm getting an error</p>
<blockquote>
<p>EOL while scanning string literal</p>
</blockquote>
<p>What is the proper way to replace <code>\\</code> with <code>\</code>?</p>
| 0 |
2016-09-17T19:13:32Z
| 39,550,787 |
<p>Here is an example </p>
<pre><code>>>> h = "\\x123"
>>> h
'\\x123'
>>> print h
\x123
>>>
</code></pre>
<p>The two backslashes are needed because \ is an escape character, and so it needs to be escaped. When you print h, it shows what you want</p>
| 1 |
2016-09-17T19:18:50Z
|
[
"python",
"escaping",
"hex"
] |
Hexadecimal file is loading with 2 back slashes before each byte instead of one
| 39,550,744 |
<p>I have a hex file in this format: <code>\xda\xd8\xb8\x7d</code></p>
<p>When I load the file with Python, it loads with two back slashes instead of one.</p>
<pre><code>with open('shellcode.txt', 'r') as file:
shellcode = file.read().replace('\n', '')
</code></pre>
<p>Like this: <code>\\xda\\xd8\\xb8\\x7d</code></p>
<p>I've tried using <code>hex.replace("\\", "\")</code>, but I'm getting an error</p>
<blockquote>
<p>EOL while scanning string literal</p>
</blockquote>
<p>What is the proper way to replace <code>\\</code> with <code>\</code>?</p>
| 0 |
2016-09-17T19:13:32Z
| 39,550,982 |
<p>Backshlash (<code>\</code>) is an escape character. It is used for changing the meaning of the character(s) following it.</p>
<p>For example, if you want to create a string which contains a quote, you have to escape it:</p>
<pre><code>s = "abc\"def"
print s # prints: abc"def
</code></pre>
<p>If there was no backslash, the first quote would be interpreted as the end of the string.</p>
<p>Now, if you really wanted that backslash in the string, you would have to escape the bacsklash using another backslash:</p>
<pre><code>s = "abc\\def"
print s # prints: abc\def
</code></pre>
<p>However, if you look at the representation of the string, it will be shown with the escape characters:</p>
<pre><code>print repr(s) # prints: 'abc\\def'
</code></pre>
<p>Therefore, this line should include escapes for each backslash:</p>
<pre><code>hex.replace("\\", "\") # wrong
hex.replace("\\\\", "\\") # correct
</code></pre>
<p>But that is not the solution to the problem!</p>
<p>There is no way that <code>file.read().replace('\n', '')</code> introduced additional backslashes. What probably happened is that OP printed the representation of the string with backslashes (<code>\</code>) which ended up printing escaped backslashes (<code>\\</code>).</p>
| 0 |
2016-09-17T19:40:13Z
|
[
"python",
"escaping",
"hex"
] |
Hexadecimal file is loading with 2 back slashes before each byte instead of one
| 39,550,744 |
<p>I have a hex file in this format: <code>\xda\xd8\xb8\x7d</code></p>
<p>When I load the file with Python, it loads with two back slashes instead of one.</p>
<pre><code>with open('shellcode.txt', 'r') as file:
shellcode = file.read().replace('\n', '')
</code></pre>
<p>Like this: <code>\\xda\\xd8\\xb8\\x7d</code></p>
<p>I've tried using <code>hex.replace("\\", "\")</code>, but I'm getting an error</p>
<blockquote>
<p>EOL while scanning string literal</p>
</blockquote>
<p>What is the proper way to replace <code>\\</code> with <code>\</code>?</p>
| 0 |
2016-09-17T19:13:32Z
| 39,551,396 |
<p>You can make a <code>bytes</code> object with a <code>utf-8</code> encoding, and then decode as <code>unicode-escape</code>.</p>
<pre><code>>>> x = "\\x61\\x62\\x63"
>>> y = bytes(x, "utf-8").decode("unicode-escape")
>>> print(x)
\x61\x62\x63
>>> print(y)
abc
</code></pre>
| 0 |
2016-09-17T20:27:21Z
|
[
"python",
"escaping",
"hex"
] |
NumPy MemoryError when using array constructors
| 39,550,796 |
<p>I'm creating a couple of arrays using numpy and list constructors, and I can't figure out why this is failing. My code is:</p>
<pre><code>import numpy as np
A = np.ndarray( [i for i in range(10)] ) # works fine
B = np.ndarray( [i**2 for i in range(10)] ) # fails, with MemoryError
</code></pre>
<p>I've also tried just <code>B = [i**2 for i in range(10)]</code> which works, but I need it to be an ndarray. I don't see why the normal constructor would work but calling a function wouldn't. As far as I understand, the ndarray constructor shouldn't even see the inside of that, it should get a length 10 list with ints in it for both.</p>
| 0 |
2016-09-17T19:19:28Z
| 39,550,955 |
<p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html</a> is a low-level method that we normally don't use. Its first argument is the <code>shape</code>.</p>
<pre><code>In [98]: np.ndarray([x for x in range(3)])
Out[98]: array([], shape=(0, 1, 2), dtype=float64)
In [99]: np.ndarray([x**2 for x in range(3)])
Out[99]: array([], shape=(0, 1, 4), dtype=float64)
</code></pre>
<p>Normally use <code>zeros</code> or <code>ones</code> to construct a blank array of a given shape:</p>
<pre><code>In [100]: np.zeros([x**2 for x in range(3)])
Out[100]: array([], shape=(0, 1, 4), dtype=float64)
</code></pre>
<p>Use <code>np.array</code> if you want to turn a list into an array:</p>
<pre><code>In [101]: np.array([x for x in range(3)])
Out[101]: array([0, 1, 2])
In [102]: np.array([x**2 for x in range(3)])
Out[102]: array([0, 1, 4])
</code></pre>
<p>You can generate the range numbers, and then perform the math on the whole array (without iteration):</p>
<pre><code>In [103]: np.arange(3)**2
Out[103]: array([0, 1, 4])
</code></pre>
| 2 |
2016-09-17T19:36:18Z
|
[
"python",
"arrays",
"list",
"numpy",
"constructor"
] |
How to extract data from complex Json using python
| 39,550,808 |
<pre><code>{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4224484,
"lng" : -122.0843249
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4237973802915,
"lng" : -122.0829759197085
},
"southwest" : {
"lat" : 37.4210994197085,
"lng" : -122.0856738802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
</code></pre>
<p>How can i retrieve <code>formatted_address</code>,<code>Lat</code> and <code>Long</code> under <code>geometry>Location</code> etc. from json. Most of the json tutorials are explained with simple json file.
Kindly help me on this and help me find some good tutorials</p>
| 0 |
2016-09-17T19:20:29Z
| 39,550,839 |
<p>You can follow the documentation for json library from the links: <a href="https://docs.python.org/2/library/json.html" rel="nofollow">python2</a> or <a href="https://docs.python.org/3/library/json.html" rel="nofollow">python3</a>
If you have any spesific questions, you can define traces or code parts to find correct answers.</p>
| 0 |
2016-09-17T19:23:43Z
|
[
"python",
"json"
] |
How to extract data from complex Json using python
| 39,550,808 |
<pre><code>{
"results" : [
{
"address_components" : [
{
"long_name" : "1600",
"short_name" : "1600",
"types" : [ "street_number" ]
},
{
"long_name" : "Amphitheatre Parkway",
"short_name" : "Amphitheatre Pkwy",
"types" : [ "route" ]
},
{
"long_name" : "Mountain View",
"short_name" : "Mountain View",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Santa Clara County",
"short_name" : "Santa Clara County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "94043",
"short_name" : "94043",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
"geometry" : {
"location" : {
"lat" : 37.4224484,
"lng" : -122.0843249
},
"location_type" : "ROOFTOP",
"viewport" : {
"northeast" : {
"lat" : 37.4237973802915,
"lng" : -122.0829759197085
},
"southwest" : {
"lat" : 37.4210994197085,
"lng" : -122.0856738802915
}
}
},
"place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
"types" : [ "street_address" ]
}
],
"status" : "OK"
}
</code></pre>
<p>How can i retrieve <code>formatted_address</code>,<code>Lat</code> and <code>Long</code> under <code>geometry>Location</code> etc. from json. Most of the json tutorials are explained with simple json file.
Kindly help me on this and help me find some good tutorials</p>
| 0 |
2016-09-17T19:20:29Z
| 39,550,853 |
<p>Actually, simple JSONs and complex JSONs are not that different. You can say that a <em>complex JSON</em> has many <em>simpler JSONs</em> inside, so if you know how to get data from simple ones, you end up knowing how to get data from complexes </p>
<p>Anyway, think of JSON objects as <code>dictionaries</code> and JSON arrays as <code>lists</code>. To get data from dicts, use the <code>key</code> for a value. To get data from lists, use the <code>index</code> (position) of a value.</p>
<p>So, in your case:</p>
<pre><code>lat = json["results"][0]["geometry"]["location"]["lat"]
long = json["results"][0]["geometry"]["location"]["lng"]
</code></pre>
<p>and</p>
<pre><code>formatted_address = json["results"][0]["formatted_address"]
</code></pre>
<p>Notice how the navigation through keys occur, and how you get deeper as you retrieve values from its keys</p>
| 3 |
2016-09-17T19:24:44Z
|
[
"python",
"json"
] |
How to program 'Sunfounder sensor kit V1.0' for Raspberry Pi
| 39,550,838 |
<p>I am an beginner programmer and I purchased the above kit to learn how to program in Python. (Unfortunately, the included instructions were written in C and I'm very new to Python)</p>
<p>All I want to do is plug the sensor into my breadboard and run a script to see the results.</p>
<p>Sensors include: Humiture sensor, Tempurature sensor, Buzzer, light etc...</p>
<p>Thank you in advance.</p>
<p>Chris</p>
| -1 |
2016-09-17T19:23:39Z
| 39,650,182 |
<p>The SunFounder kit includes a lot of different sensors, so you'll have to look up how to use each one individually. You should probably start by looking at the tutorials available at the SunFounder Tutorial <a href="https://www.sunfounder.com/learn" rel="nofollow" title="SunFounder tutorial">https://www.sunfounder.com/learn</a> site.</p>
| 0 |
2016-09-22T23:08:28Z
|
[
"python",
"sensor",
"raspberry-pi3"
] |
Splitting stacked dataframe in pandas
| 39,550,927 |
<p>I have a dataframe like</p>
<pre><code> age sex values
time
2015 10 F 589628.0
2015 10 M 458390.0
2015 11 F 108018.0
2015 11 M 764350.0
....
2000 60 M 34676.0
2000 60 F 45488.0
</code></pre>
<p>I would like to create data frame like</p>
<pre><code> age F M
time
2015 10 589628.0 458390.0
2015 11
....
2000 60 45488.0 34676.0
</code></pre>
<p>reducing the rows by half and adding a column. I have tried to do this with pivot, but no avail.</p>
<pre><code>df.pivot(columns='sex', values='values')
</code></pre>
<p>but this returns</p>
<pre><code>Index contains duplicate entries, cannot reshape
</code></pre>
<p>Any ideas how can I cleanly split the dataframe without writing a tedious function to do it?</p>
<p>Cheers, Mike</p>
| 1 |
2016-09-17T19:33:04Z
| 39,551,188 |
<p>Using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow">pivot_table</a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow">reset_index</a>:</p>
<pre><code>In [17]: df
Out[17]:
age sex values
time
2015 10 F 589628.0
2015 10 M 458390.0
2015 11 F 108018.0
2015 11 M 764350.0
In [18]: newdf = df.reset_index().pivot_table('values', ['time', 'age'], 'sex').reset_index()
In [19]: newdf.columns.name = None
In [20]: newdf = newdf.set_index(['time'])
In [21]: newdf
Out[21]:
age F M
time
2015 10 589628.0 458390.0
2015 11 108018.0 764350.0
</code></pre>
| 1 |
2016-09-17T20:04:05Z
|
[
"python",
"pandas",
"dataframe"
] |
Splitting stacked dataframe in pandas
| 39,550,927 |
<p>I have a dataframe like</p>
<pre><code> age sex values
time
2015 10 F 589628.0
2015 10 M 458390.0
2015 11 F 108018.0
2015 11 M 764350.0
....
2000 60 M 34676.0
2000 60 F 45488.0
</code></pre>
<p>I would like to create data frame like</p>
<pre><code> age F M
time
2015 10 589628.0 458390.0
2015 11
....
2000 60 45488.0 34676.0
</code></pre>
<p>reducing the rows by half and adding a column. I have tried to do this with pivot, but no avail.</p>
<pre><code>df.pivot(columns='sex', values='values')
</code></pre>
<p>but this returns</p>
<pre><code>Index contains duplicate entries, cannot reshape
</code></pre>
<p>Any ideas how can I cleanly split the dataframe without writing a tedious function to do it?</p>
<p>Cheers, Mike</p>
| 1 |
2016-09-17T19:33:04Z
| 39,551,368 |
<p>I can't confirm this but it should be</p>
<pre><code>df.set_index(['age', 'sex'], append=True)['values'].unstack().reset_index('age')
</code></pre>
| 2 |
2016-09-17T20:23:48Z
|
[
"python",
"pandas",
"dataframe"
] |
Django queryset order_by dates near today
| 39,550,997 |
<p>I want to show the records near to today's date at top and then all records in the past at bottom:</p>
<p>Today<br>
Tomorrow<br>
Tomorrow + 1<br>
.<br>
.<br>
.<br>
Yesterday<br>
Yesterday -1 </p>
| 0 |
2016-09-17T19:41:58Z
| 39,551,190 |
<p>Yes you can, what you want is the descending behavior of the <strong><a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.query.QuerySet.order_by" rel="nofollow">order_by</a></strong>.</p>
<p><strong>Oldest items first.</strong></p>
<pre><code>Model.objects.order_by('creation_time')
</code></pre>
<p><strong>Newest items first.</strong> (what you want)</p>
<pre><code>Model.objects.order_by('-creation_time')
</code></pre>
<p><strong>For Your Edit</strong></p>
<p>You have to make two queries and then evaluate them to lists to do what you wat, you can't do such thing with django ORM's queries.</p>
<p>In fact, combining queries using the <strong>|</strong> operator wouldn't preserve the order you want, so you can't do this with 2 django queries.</p>
<pre><code>qset = Model.objects.all()
result = qset.filter(creation=today) | qset.filter(creation_gte=today) | qset.filter(creation_lt=today)
</code></pre>
<p>The following <code>result</code> would contain all items you'd want, but won't preserve single queryset ordering. So, not gonna do what you want from it.</p>
<p>So in summary, you have to evaluate the querysets, and add them together as lists to achieve what you want.</p>
<pre><code>qset = Model.objects.all()
result = list(qset.filter(creation=today)) + list(qset.filter(creation_gte=today)) + list(qset.filter(creation_lt=today))
</code></pre>
<p>or in a nicer fashion:</p>
<pre><code>import itertools
result = list(itertools.chain(qset.filter(creation=today), qset.filter(creation_gte=today), qset.filter(creation_lt=today)))
</code></pre>
<p>Don't forget to do the <code>order_by</code>s in each queryset to order each part of the result as you want, for brevity of codes, I didn't write them here.</p>
| 0 |
2016-09-17T20:04:33Z
|
[
"python",
"django",
"sorting",
"sql-order-by"
] |
How to use flask flash messages in 2 different app.route
| 39,551,157 |
<p>I'm fresh developer in flask framework, and I got stuck on these methods for showing error message, and I don't understand how to use flask flash message. I was thinking about it for 3 or 4 days and I got some idea how to handle this problem. so my plan is simple, I make some authentication login in my viewer. If it results output with value false, it will produce error code and that's error code will be showed in my login page. here is how I've implemented my idea.</p>
<pre><code>@app.route('/login/process', methods = ['POST'])
def loginprocess():
username = request.form.get('user_name')
passwd = request.form.get('user_passwd')
userAdminAuth = userLogin.checkUserAdmin(username, passwd)
userMemberAuth = userLogin.checkUserMember(username, passwd)
if userAdminAuth == True and userMemberAuth == False:
session['logged_in'] = True
session['username'] = username
return redirect(url_for('admin'))
elif userAdminAuth == False and userMemberAuth == True:
session['logged_in'] = True
session['username'] = username
return redirect(url_for('member'))
else:
error = 'Invalid username or password'
return redirect(url_for('login'))
@app.route('/login')
def login():
return render_template('login.html')
</code></pre>
<p>And in the html code I have this one</p>
<pre><code>{% if error %}
<div class="alert alert-danger" role="alert">
<span class="glyphicon glyphicon-exclamation-sign"></span>
<span class="sr-only">Error</span>
{{ error }}
</div>
{% endif %}
</code></pre>
<p>The question is how can I pass variable </p>
<pre><code>error = 'Invalid username or password'
</code></pre>
<p>In url route</p>
<pre><code>@app.route('/login/process', methods=['POST'])
</code></pre>
<p>To url route</p>
<pre><code>@app.route('/login')
</code></pre>
<p>Oh anyway you should know this one</p>
<pre><code><form action="/login/process" method="post">
<div class="form-group">
<div class="input-group">
<div class="input-group-addon icon-custumized"><span class="glyphicon glyphicon-user"></span></div>
<input type="text" name="user_name" class="form-control form-costumized" placeholder="Username">
</div>
</div>
<div class="form-group">
<div class="input-group">
<div class="input-group-addon icon-custumized"><span class="glyphicon glyphicon-lock"></span></div>
<input type="password" name="user_passwd" class="form-control form-costumized" placeholder="Password">
</div>
</div>
<div class="btn-toolbar" role="toolbar" aria-label="action">
<div class="btn-group" role="group" aria-label="action">
<a class="btn btn-default btn-customized" href="#"><span class="glyphicon glyphicon-list-alt"></span> <span class="textsize">Register</span></a>
<button type="submit" class="btn btn-default btn-customized"><span class="textsize">Login</span> <span class="glyphicon glyphicon-menu-right"></span></button>
</div>
</div>
</form>
</code></pre>
| -1 |
2016-09-17T19:59:43Z
| 39,551,224 |
<p>In Python, you have to call:</p>
<pre><code>flask.flash('This is the message')
</code></pre>
<p>Then, in the template use <code>get_flashed_messages</code> to get the flashed messages and display them, e.g.:</p>
<pre><code>{% with messages = get_flashed_messages(with_categories=True) %}
{% for category, message in messages %}
<div class="flash {{category}}">{{message}}</div>
{% endfor %}
{% endwith%}
</code></pre>
<p><a href="http://flask.pocoo.org/docs/0.11/patterns/flashing/" rel="nofollow">Flask documentation</a> has a very simple and nice example.</p>
<p>The fact that the message is flashed in one route and displayed in another is not a problem. That is exactly the use case <code>flask.flash</code> was designed for!</p>
| 1 |
2016-09-17T20:08:14Z
|
[
"python",
"python-3.x",
"flask",
"flash-message"
] |
Interpret serialdata in python
| 39,551,238 |
<p>I'm currently struggling with an issue. I have an arduino sending serialdata to my raspberry pi. The raspberry pi reads the data and stores it in a database. What i'm struggling with is to get data in the correct order. If i start the script at the correct time, the values get read properly. If i don't they get mixed up.</p>
<p>I have a headerByte sent from the arduino, this value is 999 and it is the first value to be sent each time. Is there a way in python to make 999 the marker for the beginning of every read? My variables will never exceed 999 so this will not be a problem.</p>
<p>Python code:</p>
<pre><code>import serial
import time
values = []
serialArduino = serial.Serial('/dev/ttyACM0', baudrate=9600, timeout=1)
voltageRead = serialArduino.readline()
currentRead = serialArduino.readline()
while True:
voltageRead = serialArduino.readline()
currentRead = serialArduino.readline()
print"V=", voltageRead, "A=", currentRead
</code></pre>
<p>Arduino Code:</p>
<pre><code>void loop() {
float voltageRead = analogRead(A0);
float ampsRead = analogRead(A1);
float calculatedVoltage = voltageRead / 103;
float calculatedCurrent = ampsRead / 1;
int headerByte = 999;
Serial.println(headerByte);
Serial.println(calculatedVoltage);
Serial.println(calculatedCurrent);
delay(1000);
}
</code></pre>
| 0 |
2016-09-17T20:10:22Z
| 39,552,807 |
<p>Your method isn't particularly efficient; you could send everything as a struct from the Arduino (header + data) and parse it on the RPi side with the <code>struct</code> module though your way does have the advantage of simplicity. But, if 999 is the highest value you expect in your readings, then it makes more sense to use a number <em>greater</em> than 999 like 1000. And 999 isn't really a byte.</p>
<p>That said, if "1000" is your header, you can simply check for the header's presence like this:</p>
<pre><code>HEADER = "1000"
serialArduino = serial.Serial('/dev/ttyACM0', baudrate=9600, timeout=1)
while True:
if serialArduino.readline().rstrip() == HEADER: # check for header
voltageRead = serialArduino.readline() # read two lines
currentRead = serialArduino.readline()
print"V=", voltageRead, "A=", currentRead
</code></pre>
| 0 |
2016-09-17T23:51:48Z
|
[
"python",
"arduino",
"serial-port",
"raspberry-pi3"
] |
Creating output variables and copying attributes in python xarray netcdf4
| 39,551,245 |
<p>I can create variables and copy over attributes in netcdf4 like this:</p>
<pre><code>out_var = hndl_out_nc.createVariable(name_var, var.datatype, var.dimensions)
out_var.setncatts({k: var.getncattr(k) for k in var.ncattrs()})
</code></pre>
<p>What is the corresponding version for xarray?</p>
| 0 |
2016-09-17T20:10:53Z
| 39,562,266 |
<p>If <code>var</code> is an <code>xarray.DataArray</code>, you can put it (along with attributes) into a new <code>xarray.Dataset</code> simply by writing <code>ds[name_] = var</code>. Or you can construct a new DataArray piece by piece with <code>xarray.DataArray(var.data, var.coords, var.dims, var.attrs)</code>.</p>
| 1 |
2016-09-18T20:18:18Z
|
[
"python",
"python-xarray",
"netcdf4"
] |
sklearn SVM performing awfully poor
| 39,551,264 |
<p>I have 9164 points, where 4303 are labeled as the class I want to predict and 4861 are labeled as not that class. They are no duplicate points.</p>
<p>Following <a href="http://stackoverflow.com/questions/39500894/how-to-split-into-train-test-and-evaluation-sets-in-sklearn">How to split into train, test and evaluation sets in sklearn?</a>, and since my <code>dataset</code> is a tuple of 3 items (id, vector, label), I do:</p>
<pre><code>df = pd.DataFrame(dataset)
train, validate, test = np.split(df.sample(frac=1), [int(.6*len(df)), int(.8*len(df))])
train_labels = construct_labels(train)
train_data = construct_data(train)
test_labels = construct_labels(test)
test_data = construct_data(test)
def predict_labels(test_data, classifier):
labels = []
for test_d in test_data:
labels.append(classifier.predict([test_d]))
return np.array(labels)
def construct_labels(df):
labels = []
for index, row in df.iterrows():
if row[2] == 'Trump':
labels.append('Atomium')
else:
labels.append('Not Trump')
return np.array(labels)
def construct_data(df):
first_row = df.iloc[0]
data = np.array([first_row[1]])
for index, row in df.iterrows():
if first_row[0] != row[0]:
data = np.concatenate((data, np.array([row[1]])), axis=0)
return data
</code></pre>
<p>and then:</p>
<pre><code>>>> classifier = SVC(verbose=True)
>>> classifier.fit(train_data, train_labels)
[LibSVM].......*..*
optimization finished, #iter = 9565
obj = -2718.376533, rho = 0.132062
nSV = 5497, nBSV = 2550
Total nSV = 5497
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=True)
>>> predicted_labels = predict_labels(test_data, classifier)
>>> for p, t in zip(predicted_labels, test_labels):
... if p == t:
... correct = correct + 1
</code></pre>
<p>and I get correct only 943 labels out of 1833 (=len(test_labels)) -> (943*100/1843 = 51.4%)</p>
<hr>
<p>I am suspecting I am missing something big time here, maybe I should set a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html" rel="nofollow">parameter</a> to the classifier to do more refined work or something?</p>
<p>Note: First time using SVMs here, so anything you might get for granted, I might have not even imagine...</p>
<hr>
<p>Attempt:</p>
<p>I went ahed and decreased the number of negative examples to 4303 (same number as positive examples). This slightly improved accuracy.</p>
<hr>
<p>Edit after the answer:</p>
<pre><code>>>> print(clf.best_estimator_)
SVC(C=1000.0, cache_size=200, class_weight='balanced', coef0=0.0,
decision_function_shape=None, degree=3, gamma=0.0001, kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
>>> classifier = SVC(C=1000.0, cache_size=200, class_weight='balanced', coef0=0.0,
... decision_function_shape=None, degree=3, gamma=0.0001, kernel='rbf',
... max_iter=-1, probability=False, random_state=None, shrinking=True,
... tol=0.001, verbose=False)
>>> classifier.fit(train_data, train_labels)
SVC(C=1000.0, cache_size=200, class_weight='balanced', coef0=0.0,
decision_function_shape=None, degree=3, gamma=0.0001, kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
</code></pre>
<p>Also I tried <code>clf.fit(train_data, train_labels)</code>, which performed the same.</p>
<hr>
<p>Edit with data (the data are not random):</p>
<pre><code>>>> train_data[0]
array([ 20.21062112, 27.924016 , 137.13815308, 130.97432804,
... # there are 256 coordinates in total
67.76352596, 56.67798138, 104.89566517, 10.02616417])
>>> train_labels[0]
'Not Trump'
>>> train_labels[1]
'Trump'
</code></pre>
| 0 |
2016-09-17T20:13:00Z
| 39,551,445 |
<p>Most estimators in scikit-learn such as SVC are initiated with a number of input parameters, also known as hyper parameters. Depending on your data, you will have to figure out what to pass as inputs to the estimator during initialization. If you look at the SVC documentation in scikit-learn, you see that it can be initialized using several different input parameters.</p>
<p>For simplicity, let's consider kernel which can be 'rbf' or âlinearâ (among a few other choices); and C which is a penalty parameter, and you want to try values 0.01, 0.1, 1, 10, 100 for C. That will lead to 10 different possible models to create and evaluate. </p>
<p>One simple solution is to write two nested for-loops one for kernel and the other for C and create the 10 possible models and see which one is the best model amongst others. However, if you have several hyper parameters to tune, then you have to write several nested for loops which can be tedious.</p>
<p>Luckily, scikit learn has a better way to create different models based on different combinations of values for your hyper model and choose the best one. For that, you use GridSearchCV. GridSearchCV is initialized using two things: an instance of an estimator, and a dictionary of hyper parameters and the desired values to examine. It will then run and create all possible models given the choices of hyperparameters and finds the best one, hence you need not to write any nested for-loops. Here is an example:</p>
<pre><code>from sklearn.grid_search import GridSearchCV
print("Fitting the classifier to the training set")
param_grid = {'C': [0.01, 0.1, 1, 10, 100], 'kernel': ['rbf', 'linear']}
clf = GridSearchCV(SVC(class_weight='balanced'), param_grid)
clf = clf.fit(train_data, train_labels)
print("Best estimator found by grid search:")
print(clf.best_estimator_)
</code></pre>
<p>You will need to use something similar to this example, and play with different hyperparameters. If you have a good variety of values for your hyperparameters, there is a very good chance you will find a much better model this way.</p>
<p>It is however possible for GridSearchCV to take a very long time to create all these models to find the best one. A more practical approach is to use RandomizedSearchCV instead, which creates a subset of all possible models (using the hyperparameters) at random. It should run much faster if you have a lot of hyperparameters, and its best model is usually pretty good.</p>
| 3 |
2016-09-17T20:32:10Z
|
[
"python",
"pandas",
"machine-learning",
"scikit-learn",
"classification"
] |
sklearn SVM performing awfully poor
| 39,551,264 |
<p>I have 9164 points, where 4303 are labeled as the class I want to predict and 4861 are labeled as not that class. They are no duplicate points.</p>
<p>Following <a href="http://stackoverflow.com/questions/39500894/how-to-split-into-train-test-and-evaluation-sets-in-sklearn">How to split into train, test and evaluation sets in sklearn?</a>, and since my <code>dataset</code> is a tuple of 3 items (id, vector, label), I do:</p>
<pre><code>df = pd.DataFrame(dataset)
train, validate, test = np.split(df.sample(frac=1), [int(.6*len(df)), int(.8*len(df))])
train_labels = construct_labels(train)
train_data = construct_data(train)
test_labels = construct_labels(test)
test_data = construct_data(test)
def predict_labels(test_data, classifier):
labels = []
for test_d in test_data:
labels.append(classifier.predict([test_d]))
return np.array(labels)
def construct_labels(df):
labels = []
for index, row in df.iterrows():
if row[2] == 'Trump':
labels.append('Atomium')
else:
labels.append('Not Trump')
return np.array(labels)
def construct_data(df):
first_row = df.iloc[0]
data = np.array([first_row[1]])
for index, row in df.iterrows():
if first_row[0] != row[0]:
data = np.concatenate((data, np.array([row[1]])), axis=0)
return data
</code></pre>
<p>and then:</p>
<pre><code>>>> classifier = SVC(verbose=True)
>>> classifier.fit(train_data, train_labels)
[LibSVM].......*..*
optimization finished, #iter = 9565
obj = -2718.376533, rho = 0.132062
nSV = 5497, nBSV = 2550
Total nSV = 5497
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=True)
>>> predicted_labels = predict_labels(test_data, classifier)
>>> for p, t in zip(predicted_labels, test_labels):
... if p == t:
... correct = correct + 1
</code></pre>
<p>and I get correct only 943 labels out of 1833 (=len(test_labels)) -> (943*100/1843 = 51.4%)</p>
<hr>
<p>I am suspecting I am missing something big time here, maybe I should set a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html" rel="nofollow">parameter</a> to the classifier to do more refined work or something?</p>
<p>Note: First time using SVMs here, so anything you might get for granted, I might have not even imagine...</p>
<hr>
<p>Attempt:</p>
<p>I went ahed and decreased the number of negative examples to 4303 (same number as positive examples). This slightly improved accuracy.</p>
<hr>
<p>Edit after the answer:</p>
<pre><code>>>> print(clf.best_estimator_)
SVC(C=1000.0, cache_size=200, class_weight='balanced', coef0=0.0,
decision_function_shape=None, degree=3, gamma=0.0001, kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
>>> classifier = SVC(C=1000.0, cache_size=200, class_weight='balanced', coef0=0.0,
... decision_function_shape=None, degree=3, gamma=0.0001, kernel='rbf',
... max_iter=-1, probability=False, random_state=None, shrinking=True,
... tol=0.001, verbose=False)
>>> classifier.fit(train_data, train_labels)
SVC(C=1000.0, cache_size=200, class_weight='balanced', coef0=0.0,
decision_function_shape=None, degree=3, gamma=0.0001, kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
</code></pre>
<p>Also I tried <code>clf.fit(train_data, train_labels)</code>, which performed the same.</p>
<hr>
<p>Edit with data (the data are not random):</p>
<pre><code>>>> train_data[0]
array([ 20.21062112, 27.924016 , 137.13815308, 130.97432804,
... # there are 256 coordinates in total
67.76352596, 56.67798138, 104.89566517, 10.02616417])
>>> train_labels[0]
'Not Trump'
>>> train_labels[1]
'Trump'
</code></pre>
| 0 |
2016-09-17T20:13:00Z
| 39,584,093 |
<p>After the comments of sascha and the answer of shahins, I did this eventually:</p>
<pre><code>df = pd.DataFrame(dataset)
train, validate, test = np.split(df.sample(frac=1), [int(.6*len(df)), int(.8*len(df))])
train_labels = construct_labels(train)
train_data = construct_data(train)
test_labels = construct_labels(test)
test_data = construct_data(test)
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
train_data = scaler.fit_transform(train_data)
from sklearn.svm import SVC
# Classifier found with shahins' answer
classifier = SVC(C=10, cache_size=200, class_weight='balanced', coef0=0.0,
decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
classifier = classifier.fit(train_data, train_labels)
test_data = scaler.fit_transform(test_data)
predicted_labels = predict_labels(test_data, classifier)
</code></pre>
<p>and got:</p>
<pre><code>>>> correct_labels = count_correct_labels(predicted_labels, test_labels)
>>> print_stats(correct_labels, len(test_labels))
Correct labels = 1624
Accuracy = 88.5979268958
</code></pre>
<p>with these methods:</p>
<pre><code>def count_correct_labels(predicted_labels, test_labels):
correct = 0
for p, t in zip(predicted_labels, test_labels):
if p[0] == t:
correct = correct + 1
return correct
def print_stats(correct_labels, len_test_labels):
print "Correct labels = " + str(correct_labels)
print "Accuracy = " + str((correct_labels * 100 / float(len_test_labels)))
</code></pre>
<p>I was able to optimize more with more hyper parameter tuning!</p>
<p>Helpful link: <a href="http://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html" rel="nofollow">RBF SVM parameters</a></p>
<hr>
<p>Note: If I don't transform the <code>test_data</code>, accuracy is 52.7%.</p>
| 0 |
2016-09-20T00:47:08Z
|
[
"python",
"pandas",
"machine-learning",
"scikit-learn",
"classification"
] |
Python - download video from indirect url
| 39,551,320 |
<p>I have a link like this</p>
<pre><code>https://r9---sn-4g57knle.googlevideo.com/videoplayback?id=10bc30daeba89d81&itag=22&source=picasa&begin=0&requiressl=yes&mm=30&mn=sn-4g57knle&ms=nxu&mv=m&nh=IgpwcjA0LmZyYTE2KgkxMjcuMC4wLjE&pl=19&sc=yes&mime=video/mp4&lmt=1439597374686662&mt=1474140191&ip=84.56.35.53&ipbits=8&expire=1474169270&sparams=ip,ipbits,expire,id,itag,source,requiressl,mm,mn,ms,mv,nh,pl,sc,mime,lmt&signature=6EF8ABF841EA789F5314FC52C3C3EA8698A587C9.9297433E91BB6CBCBAE29548978D35CDE30C19EC&key=ck2
</code></pre>
<p>which is a temporary generated redirect from (a link like) this link:
<a href="https://2.bp.blogspot.com/bO0q678cHRVZqTDclb33qGUXve_X1CRTgHMVz9NUgA=m22" rel="nofollow">https://2.bp.blogspot.com/bO0q678cHRVZqTDclb33qGUXve_X1CRTgHMVz9NUgA=m22</a></p>
<p>(so the first link won't work in a couple of hours)</p>
<p>How can I download the video from the <em>googlevideo</em> site with Python?
I already tried youtube-dl because of <a href="http://stackoverflow.com/a/33818090/5635812">this</a> answer, but it isn't working for me.</p>
<p>The direct URL would already help me a lot!</p>
| -5 |
2016-09-17T20:19:11Z
| 39,551,444 |
<p>You can use <a href="http://pycurl.io/docs/latest/quickstart.html" rel="nofollow">pycurl</a></p>
<pre><code>#!/bin/usr/env python
import sys
import pycurl
c = pycurl.Curl()
c.setopt(c.FOLLOWLOCATION, 1)
c.setopt(c.URL, sys.argv[1])
with open(sys.argv[2], 'w') as f:
c.setopt(c.WRITEFUNCTION, f.write)
c.perform()
</code></pre>
<p>Usage:</p>
<pre><code>$ chmod +x a.py
$ ./a.py "https://2.bp.blogspot.com/bO0q678cHRVZqTDclb33qGUXve_X1CRTgHMVz9NUgA=m22" output.mp4
$ file output.mp4
output.mp4: ISO Media, MP4 v2 [ISO 14496-14]
</code></pre>
| 0 |
2016-09-17T20:32:01Z
|
[
"python",
"url",
"video",
"web-scraping"
] |
Why isn't this regex matching a string with percentage symbol?
| 39,551,333 |
<p>I have a file which has the following input : </p>
<pre><code>xa%1bc
ba%1bc
.
.
</code></pre>
<p>and so on. I want to use <code>match</code> and <code>regex</code> to identify the lines which have <code>a%1b</code>in them.
I am using </p>
<pre><code> import re
p1 = re.compile(r'\ba%1b\b', flags=re.I)
if re.match(p1,linefromfile):
continue
</code></pre>
<p>It doesnt seem to detect the line with %1. What is the issue? Thanks</p>
| -1 |
2016-09-17T20:20:50Z
| 39,551,391 |
<p>You can try</p>
<pre><code>if 'a%1b' in linefromfile:
</code></pre>
<p><strong>OR</strong></p>
<p>if you need regex</p>
<pre><code>if re.match('a%1b', linefromfile):
</code></pre>
| 0 |
2016-09-17T20:27:00Z
|
[
"python",
"regex",
"string",
"match",
"word-boundary"
] |
Why isn't this regex matching a string with percentage symbol?
| 39,551,333 |
<p>I have a file which has the following input : </p>
<pre><code>xa%1bc
ba%1bc
.
.
</code></pre>
<p>and so on. I want to use <code>match</code> and <code>regex</code> to identify the lines which have <code>a%1b</code>in them.
I am using </p>
<pre><code> import re
p1 = re.compile(r'\ba%1b\b', flags=re.I)
if re.match(p1,linefromfile):
continue
</code></pre>
<p>It doesnt seem to detect the line with %1. What is the issue? Thanks</p>
| -1 |
2016-09-17T20:20:50Z
| 39,551,422 |
<p><code>match</code> only search the pattern at the beginning of the string, if you want to find out if a string contains a pattern, use <code>search</code> instead. Besides you don't need the word boundary, <code>\b</code>:</p>
<blockquote>
<p>re.search(pattern, string, flags=0) </p>
<p>Scan through string looking for
the first location where the regular expression pattern produces a
match, and return a corresponding match object. Return None if no
position in the string matches the pattern; note that this is
different from finding a zero-length match at some point in the
string.</p>
<p>re.match(pattern, string, flags=0) </p>
<p>If zero or more characters at the
beginning of string match the regular expression pattern, return a
corresponding match object. Return None if the string does not match
the pattern; note that this is different from a zero-length match.</p>
</blockquote>
<pre><code>import re
if re.search(r"a%1b", "xa%1bc"):
print("hello")
# hello
</code></pre>
| 1 |
2016-09-17T20:30:15Z
|
[
"python",
"regex",
"string",
"match",
"word-boundary"
] |
Receiving intermittent error when querying BigQuery database from Django App hosted on Apache2 Server
| 39,551,379 |
<p>Not sure if I'm allowed, but for the sake of those who wants to see my issue first hand, I am adding url of my development environment (www.blesque.tv). Issue is easily reproducible by reloading that page multiple times.</p>
<p>I switched the home page of my site to query data from my BigQuery database. When I am reloading the page, 2 times out of 3 approximately, I receive error as on the attached image below. Not sure what is happening. When content loads, it loads very quickly (the main reason I am switching to BQ), but then next time reloading the page, error is thrown. I tried to look through Google's API reference thinking maybe DB connection needs to be closed explicitly after each time I query it, but could not find anything about it. Need help from StackOverflow community. Thank you.</p>
<p><em>This is the Google's API I am using:
<a href="https://cloud.google.com/bigquery/docs/reference/v2/" rel="nofollow">https://cloud.google.com/bigquery/docs/reference/v2/</a></em></p>
<p><strong>Error message:</strong></p>
<p>Error at /</p>
<p>[('rsa routines', 'RSA_setup_blinding', 'BN lib'), ('rsa routines', 'RSA_EAY_PRIVATE_ENCRYPT', 'internal error')]</p>
<p>Request Method: GET
Request URL: <a href="http://www.blesque.tv/" rel="nofollow">http://www.blesque.tv/</a>
Django Version: 1.9.8
Exception Type: Error
Exception Value: </p>
<p>[('rsa routines', 'RSA_setup_blinding', 'BN lib'), ('rsa routines', 'RSA_EAY_PRIVATE_ENCRYPT', 'internal error')]</p>
<p>Exception Location: /home/businessai/lib/python2.7/OpenSSL/_util.py in exception_from_error_queue, line 48
Python Executable: /usr/local/bin/python
Python Version: 2.7.5</p>
<p><strong>Code of my BigQuery controller</strong></p>
<pre><code>class BQController():
def __init__(self):
configFile = "pass_to_config_file_containing_p12_key_client_email_and_project_id"
#Authorizing connection
with open(configFile, "r") as conConf:
filedata = conConf.read()
jsonData = self.getJsonContent(filedata)
KEY_FILE = jsonData["signin_credentials"]["key_file"]
self.PROJECT_ID = jsonData["signin_credentials"]["project_id"]
CLIENT_EMAIL = jsonData["signin_credentials"]["client_email"]
scopes = ['https://www.googleapis.com/auth/bigquery']
credentials = ServiceAccountCredentials.from_p12_keyfile(
CLIENT_EMAIL, KEY_FILE, scopes=scopes)
http_auth = credentials.authorize(Http())
self.bigquery = build('bigquery', 'v2', http=http_auth)
#Method that I run to select data.
def runQuery(self, queryStr):
try:
query_request = self.bigquery.jobs()
query_data = {
'query': (
queryStr)
}
query_response = query_request.query(
projectId=self.PROJECT_ID,
body=query_data).execute()
queryset = query_response['rows']
except HttpError as err:
queryset = []
print('Error: {}'.format(err.content))
raise err
return queryset
</code></pre>
<p><strong>Screenshot of the error:</strong></p>
<p><a href="http://i.stack.imgur.com/ShwF1.png" rel="nofollow"><img src="http://i.stack.imgur.com/ShwF1.png" alt="enter image description here"></a></p>
<p><strong>My second implementation based on the suggestion from Thang. Still produces the same errors.</strong> It is interesting because when python script is executed on it's own on back end, it works fine all the time, but as soon as I plug it into the Django, I start seeing these issues.</p>
<pre><code>from gcloud import bigquery
class GcloudController():
def __init__(self):
self.client = bigquery.Client.from_service_account_json('/keys/client_secrets.json','project_name')
def runSelectQuery(self, query, maxResults):
query_results = self.client.run_sync_query(query)
# Use standard SQL syntax for queries.
# See: https://cloud.google.com/bigquery/sql-reference/
query_results.use_legacy_sql = False
query_results.run()
# Drain the query results by requesting a page at a time.
page_token = None
while True:
rows, total_rows, page_token = query_results.fetch_data(
max_results=maxResults,
page_token=page_token)
return rows
if not page_token:
break
</code></pre>
| 0 |
2016-09-17T20:24:43Z
| 39,559,348 |
<p>Have you considered using the <a href="https://googlecloudplatform.github.io/google-cloud-python/" rel="nofollow">Python API client</a> to query BQ?</p>
<p>There's a code sample <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/bigquery/cloud-client/sync_query.py" rel="nofollow">here</a> you can check out to get an idea of how to use it. While this may not directly solve your issue, the Python client may give a more verbose error. </p>
| 0 |
2016-09-18T15:27:12Z
|
[
"python",
"django",
"apache",
"google-bigquery"
] |
Receiving intermittent error when querying BigQuery database from Django App hosted on Apache2 Server
| 39,551,379 |
<p>Not sure if I'm allowed, but for the sake of those who wants to see my issue first hand, I am adding url of my development environment (www.blesque.tv). Issue is easily reproducible by reloading that page multiple times.</p>
<p>I switched the home page of my site to query data from my BigQuery database. When I am reloading the page, 2 times out of 3 approximately, I receive error as on the attached image below. Not sure what is happening. When content loads, it loads very quickly (the main reason I am switching to BQ), but then next time reloading the page, error is thrown. I tried to look through Google's API reference thinking maybe DB connection needs to be closed explicitly after each time I query it, but could not find anything about it. Need help from StackOverflow community. Thank you.</p>
<p><em>This is the Google's API I am using:
<a href="https://cloud.google.com/bigquery/docs/reference/v2/" rel="nofollow">https://cloud.google.com/bigquery/docs/reference/v2/</a></em></p>
<p><strong>Error message:</strong></p>
<p>Error at /</p>
<p>[('rsa routines', 'RSA_setup_blinding', 'BN lib'), ('rsa routines', 'RSA_EAY_PRIVATE_ENCRYPT', 'internal error')]</p>
<p>Request Method: GET
Request URL: <a href="http://www.blesque.tv/" rel="nofollow">http://www.blesque.tv/</a>
Django Version: 1.9.8
Exception Type: Error
Exception Value: </p>
<p>[('rsa routines', 'RSA_setup_blinding', 'BN lib'), ('rsa routines', 'RSA_EAY_PRIVATE_ENCRYPT', 'internal error')]</p>
<p>Exception Location: /home/businessai/lib/python2.7/OpenSSL/_util.py in exception_from_error_queue, line 48
Python Executable: /usr/local/bin/python
Python Version: 2.7.5</p>
<p><strong>Code of my BigQuery controller</strong></p>
<pre><code>class BQController():
def __init__(self):
configFile = "pass_to_config_file_containing_p12_key_client_email_and_project_id"
#Authorizing connection
with open(configFile, "r") as conConf:
filedata = conConf.read()
jsonData = self.getJsonContent(filedata)
KEY_FILE = jsonData["signin_credentials"]["key_file"]
self.PROJECT_ID = jsonData["signin_credentials"]["project_id"]
CLIENT_EMAIL = jsonData["signin_credentials"]["client_email"]
scopes = ['https://www.googleapis.com/auth/bigquery']
credentials = ServiceAccountCredentials.from_p12_keyfile(
CLIENT_EMAIL, KEY_FILE, scopes=scopes)
http_auth = credentials.authorize(Http())
self.bigquery = build('bigquery', 'v2', http=http_auth)
#Method that I run to select data.
def runQuery(self, queryStr):
try:
query_request = self.bigquery.jobs()
query_data = {
'query': (
queryStr)
}
query_response = query_request.query(
projectId=self.PROJECT_ID,
body=query_data).execute()
queryset = query_response['rows']
except HttpError as err:
queryset = []
print('Error: {}'.format(err.content))
raise err
return queryset
</code></pre>
<p><strong>Screenshot of the error:</strong></p>
<p><a href="http://i.stack.imgur.com/ShwF1.png" rel="nofollow"><img src="http://i.stack.imgur.com/ShwF1.png" alt="enter image description here"></a></p>
<p><strong>My second implementation based on the suggestion from Thang. Still produces the same errors.</strong> It is interesting because when python script is executed on it's own on back end, it works fine all the time, but as soon as I plug it into the Django, I start seeing these issues.</p>
<pre><code>from gcloud import bigquery
class GcloudController():
def __init__(self):
self.client = bigquery.Client.from_service_account_json('/keys/client_secrets.json','project_name')
def runSelectQuery(self, query, maxResults):
query_results = self.client.run_sync_query(query)
# Use standard SQL syntax for queries.
# See: https://cloud.google.com/bigquery/sql-reference/
query_results.use_legacy_sql = False
query_results.run()
# Drain the query results by requesting a page at a time.
page_token = None
while True:
rows, total_rows, page_token = query_results.fetch_data(
max_results=maxResults,
page_token=page_token)
return rows
if not page_token:
break
</code></pre>
| 0 |
2016-09-17T20:24:43Z
| 39,604,562 |
<p>After trying many different methods to make a workaround for this issue, I ended up developing a hack that works for now I guess. But I really think there is a bug in Google API's Authentication. I mean if you want to test it out, visit www.blesque.tv. You can see that now it works good. Slower than if I was hitting Google's API directly, but works. I really didn't change anything in my BigQuery Controller's Authentication. I simply started executing it through a "subprocess" and then read the results of a query from "stdout". But that's not the fix, it is a hack. Google needs to fix the bug that is blocking me and I bet many others from being able to use Bigquery API the correct way. Code to my fix is below. Feel free to comment. I mean maybe someone still knows better way to fix this issue and I hope in the future Google will fix their API Authentication bugs. There is some conflict when authenticating from within the application running on Django platform when it tries to create a new token or acquire existing one. Bug basically that Google needs to fix.</p>
<p><strong>My BigQuery Controller:</strong></p>
<pre><code>__author__ = 'igor_vishnevskiy'
#Gogle's API Refference page:
#https://cloud.google.com/bigquery/docs/reference/v2/jobs#configuration.query
#https://cloud.google.com/bigquery/docs/reference/v2/tables
from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http
from apiclient.discovery import build
import os
from googleapiclient.errors import HttpError
import random
import json
import sys
class BQController():
def __init__(self):
self.authenticate_one()
query = sys.argv[1]
print self.runQuery(query)
def authenticate_one(self):
configFile = "pass_to_config_file_containing_p12_key_client_email_and_project_id"
#Authorizing connection
with open(configFile, "r") as conConf:
filedata = conConf.read()
jsonData = self.getJsonContent(filedata)
KEY_FILE = jsonData["signin_credentials"]["key_file"]
self.PROJECT_ID = jsonData["signin_credentials"]["project_id"]
CLIENT_EMAIL = jsonData["signin_credentials"]["client_email"]
scopes = ['https://www.googleapis.com/auth/bigquery']
self.credentials = ServiceAccountCredentials.from_p12_keyfile(
CLIENT_EMAIL, KEY_FILE, scopes=scopes)
self.http_auth = self.credentials.authorize(Http())#ca_certs=os.environ['REQUESTS_CA_BUNDLE']))
self.credentials.refresh(self.http_auth)
self.bigquery = build('bigquery', 'v2', http=self.http_auth)
def runQuery(self, queryStr):
try:
query_request = self.bigquery.jobs()
query_data = {
'query': (
queryStr)
}
try:
query_response = query_request.query(
projectId=self.PROJECT_ID,
body=query_data).execute()
queryset = query_response['rows']
return queryset
except:
self.credentials.refresh(self.http_auth)
self.runQuery(queryStr)
except HttpError as err:
queryset = []
print('Error: {}'.format(err.content))
raise err
return queryset
def getJsonContent(self, jsonStr):
jsonData = json.loads(jsonStr)
return jsonData
BQController()
</code></pre>
<p>Code that I used to convert stdout of BQController() into a queryset object that then I pass to my Django template:</p>
<pre><code>def my_view(request):
subProcessResponse = runShellCommandWithLogReturnedAsString("cd /home/businessai/webapps/blesque_tv/trydjango19/product_upload/controllers/; python bigquery_run.py 'SELECT product_id as id, supplier_name as db_name, image_file as image_url, title, description as clean_content, msrp as marked_up_price, product_sku, price, ship_cost, drop_ship_fee, condition FROM products.doba_inventory LIMIT 10'")
queryset = eval(subProcessResponse)
context = {
"object_list" : queryset,
}
return render(request, "template.html", context)
def runShellCommandWithLogReturnedAsString(commandAsStr):
logToReturn = ""
try:
popen = subprocess.Popen(commandAsStr, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
lines_iterator = iter(popen.stdout.readline, b"")
for line in lines_iterator:
logToReturn = logToReturn + str(line)
except Exception,e:
print e
return logToReturn
</code></pre>
| 0 |
2016-09-20T22:13:52Z
|
[
"python",
"django",
"apache",
"google-bigquery"
] |
How to separately use the encoder of an Autoencoder in keras?
| 39,551,478 |
<p>I have trained the following autoencoder model:</p>
<pre><code>input_img = Input(shape=(1, 32, 32))
x = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(input_img)
x = MaxPooling2D((2, 2), border_mode='same')(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
x = MaxPooling2D((2, 2), border_mode='same')(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
encoded = MaxPooling2D((2, 2), border_mode='same')(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(encoded)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)
x = UpSampling2D((2, 2))(x)
x = Convolution2D(16, 3, 3, activation='relu',border_mode='same')(x)
x = UpSampling2D((2, 2))(x)
decoded = Convolution2D(1, 3, 3, activation='sigmoid', border_mode='same')(x)
autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='RMSprop', loss='binary_crossentropy')
autoencoder.fit(X_train, X_train,
nb_epoch=1,
batch_size=128,
shuffle=True,
validation_data=(X_test, X_test)]
)
</code></pre>
<p>After training this autoencoder i want to use the trained encoder for a supervised line. How can i extract only the trained encoder part of this autoencoder model ? </p>
| 1 |
2016-09-17T20:34:56Z
| 39,552,164 |
<p>You can just create a model after training that only uses the encoder:</p>
<pre><code>autoencoder = Model(input_img, encoded)
</code></pre>
<p>If you want to add further layers after the encoded portion, you can do that as well:</p>
<pre><code>classifier = Dense(nb_classes, activation='softmax')(encoded)
model = Model(input_img, classifier)
</code></pre>
| 1 |
2016-09-17T22:07:57Z
|
[
"python",
"neural-network",
"deep-learning",
"keras",
"autoencoder"
] |
Python POST request error "image format unsupported" using Microsoft Face API
| 39,551,502 |
<p>I'm trying to send a binary image file to test the Microsoft Face API. Using POSTMAN works perfectly and I get back a <code>faceId</code> as expected. However, I try to transition that to Python code and it's currently giving me this error: </p>
<pre><code>{"error": {"code": "InvalidImage", "message": "Decoding error, image format unsupported."}}
</code></pre>
<p>I read this <a href="http://stackoverflow.com/questions/36120746/decoding-error-image-format-unsupported-in-microsoft-face-api">SO post</a> but it doesn't help. Here's my code for sending requests. I'm trying to mimic what POSTMAN is doing such as labeling it with the header <code>application/octet-stream</code> but it's not working. Any ideas?</p>
<pre><code>url = "https://api.projectoxford.ai/face/v1.0/detect"
headers = {
'ocp-apim-subscription-key': "<key>",
'content-type': "application/octet-stream",
'cache-control': "no-cache",
}
data = open('IMG_0670.jpg', 'rb')
files = {'IMG_0670.jpg': ('IMG_0670.jpg', data, 'application/octet-stream')}
response = requests.post(url, headers=headers, files=files)
print(response.text)
</code></pre>
| 0 |
2016-09-17T20:38:16Z
| 39,552,568 |
<p>So the API endpoint takes a byte array but also requires the input body param as <code>data</code>, not <code>files</code>. Anyway, this code below works for me. </p>
<pre><code>url = "https://api.projectoxford.ai/face/v1.0/detect"
headers = {
'ocp-apim-subscription-key': "<key>",
'Content-Type': "application/octet-stream",
'cache-control': "no-cache",
}
data = open('IMG_0670.jpg', 'rb').read()
response = requests.post(url, headers=headers, data=data)
print(response.text)
</code></pre>
| 3 |
2016-09-17T23:07:21Z
|
[
"python",
"azure",
"python-requests",
"azure-api-apps",
"microsoft-cognitive"
] |
Why is the network not learning as effective (Tensorflow - LSTMs for text generation)?
| 39,551,564 |
<p>So my query is this: when I initially ran a 2 LSTM network (each 512 units) on the Shakespeare corpus, I got a pretty decent output after 2 epochs of training (where each epoch = one cycle through the dataset).
Here it is: </p>
<p><em>best ward of mine</em>
<em>him that you a man of make the pein to the noble from his day?</em></p>
<p><em>DUKE VINGEN:
So that man be, mure the this more to the part that the tongue were an one shall you an every wall.</em></p>
<p><em>HALLES:</em>
<em>Why, your hall thou to the good word to my sole mister of the men and the twouse to your ever and me the appice to be a forting would the crease.</em></p>
<p><em>HARLET:</em>
<em>I would not the ching and not the good souls as be be he of the seement that is dead mone stains to me the ufber me do and with the sures and to conforn the tre</em></p>
<p>It was still learning, with loss of 1.73 and the graph of loss was not levelling off. However, in all subsequent runs (10) it has not been able to achieve anywhere as near as good results - after 6 epochs, for example, in my best run subsequently it had a loss of 2.43 and was levelling off -
this is the output:</p>
<p><em>friar?
How doth my l mo toee or inrou
o inain me c ahes oisteese an th thet ot spr h
sat t heooi to yerton dhe tha dou tr hum es teride t an Mose lhre moud wilh the will add toe exereaasne op ther sa e and ho m reevion
hatd tik t e thane ofore te,t
hhe serined o chane the ertrs aine thele aelt To tee g te
ou so yos we tiie be rere th livt hir but at jnt hu
As ehmug te to fare t ce
To tha mhn hi did r t ter oe hir rat ft thr ionyoee wh eoo that e cade tientta To
tike a r hee ta t he</em></p>
<p>This is similar to the outputs after 4, 5, 6 epochs. Most commonly, in the runs subsequent to the initial run, the network would level off learning after a loss of 2.70.</p>
<p><a href="http://i.stack.imgur.com/BoUzy.png" rel="nofollow">This is the graph of the loss</a>
and I have also posted the code:</p>
<pre><code>from __future__ import absolute_import, division, print_function
import os
import numpy as np
import tflearn
from tflearn.data_utils import *
from tflearn.layers.estimator import regression
inputs, targets, char_dict = \
textfile_to_semi_redundant_sequences("shakespeare_input.txt", seq_maxlen=20) #helper - vectorises text
LSTM = tflearn.input_data([None, 20, len(char_dict)])
LSTM = tflearn.lstm(LSTM, 512, return_seq=True, restore=True, dropout = 0.5)
LSTM = tflearn.lstm(LSTM, 512, restore=True, dropout = 0.5)
LSTM = tflearn.fully_connected(LSTM, len(char_dict), activation='softmax')
LSTM = tflearn.regression(LSTM, optimizer= 'adam', loss='categorical_crossentropy',
learning_rate=0.001)
LSTMmodel = tflearn.SequenceGenerator(LSTM, dictionary=char_dict,
seq_maxlen=20,
clip_gradients=5.0, tensorboard_verbose=0,tensorboard_dir='pathfile/logs')
#LSTMmodel.load('/pathfile/LSTMmodel.tfl')
for i in range(10):
print("-- TESTING...")
starting = random_sequence_from_textfile("shakespeare_input.txt", 20)
output_path = 'pathfile/epoch_' + str(i) + '_output.txt'
generated_output = LSTMmodel.generate(500, temperature=1.0, seq_seed=starting)
text_file = open(output_path, "w") #save the outputs to a text file - allows us to view progress of model
text_file.write("With temperature 1.0: \n \n \n") #two different temperatures - higher temp = more novel
text_file.write(generated_output)
generated_output = LSTMmodel.generate(500, temperature=0.5, seq_seed=starting) #lower temp = more accurate to original text
text_file.write("\n \n \n With temperature 0.5: \n \n \n")
text_file.write(generated_output)
text_file.close()
print("-- TRAINING...")
LSTMmodel.fit(inputs, targets, batch_size=200, n_epoch=1, run_id='Shakespeare_Generator',shuffle = True)
print("-- SAVING MODEL...")
if (i%2==0):
LSTMmodel.save("pathfile/LSTMmodel.tfl")
else:
LSTMmodel.save("pathfile//LSTMmodel2.tfl")
print("-- EPOCH " + str(i+1) +" COMPLETE...")
</code></pre>
<p>Since I am running this on an old dual core i3 with 4gb of RAM, the network takes 6 hr 45 mins to go through one epoch. And of course, it will take at least two epochs to see results. So unfortunately, I cannot keep tweaking the code and running and re-running. I am also limited by the memory of my computer, as 1gb of the 4 is allocated to Ubuntu - the other 3 allocated to Windows. Therefore, I can only train a small network.</p>
<p>I would really appreciate if someone could provide an answer that is tested and known to work. Sorry if this sounds like an unreasonable request - I do not wish to come across as demanding. </p>
| 1 |
2016-09-17T20:45:50Z
| 39,577,340 |
<p>I don't have an answer for this model, but have you tried starting with an existing example for a Shakespeare-generating LSTM, like this one?</p>
<p><a href="https://github.com/sherjilozair/char-rnn-tensorflow" rel="nofollow">https://github.com/sherjilozair/char-rnn-tensorflow</a></p>
<p>It should be a bit quicker to train, and if you're starting from a working example it might be easier to debug where it's going wrong.</p>
| 1 |
2016-09-19T15:59:01Z
|
[
"python",
"tensorflow",
"deep-learning",
"lstm"
] |
Create a set from a series in pandas
| 39,551,566 |
<p>I have a dataframe extracted from Kaggle's San Fransico Salaries: <a href="https://www.kaggle.com/kaggle/sf-salaries" rel="nofollow">https://www.kaggle.com/kaggle/sf-salaries</a>
and I wish to create a set of the values of a column, for instance 'Status'.</p>
<p>This is what I have tried but it brings a list of all the records instead of the set (sf is how I name the data frame).</p>
<pre><code>a=set(sf['Status'])
print a
</code></pre>
<p>According to this webpage, this should work.
<a href="http://stackoverflow.com/questions/15768757/how-to-construct-a-set-out-of-list-items">How to construct a set out of list items?</a></p>
| 0 |
2016-09-17T20:46:07Z
| 39,551,952 |
<p>If you only need to get list of unique values, you can just use <code>unique</code> method.
If you want to have Python's set, then do <code>set(some_series)</code></p>
<pre><code>In [1]: s = pd.Series([1, 2, 3, 1, 1, 4])
In [2]: s.unique()
Out[2]: array([1, 2, 3, 4])
In [3]: set(s)
Out[3]: {1, 2, 3, 4}
</code></pre>
<p>However, if you have DataFrame, just select series out of it ( <code>some_data_frame['<col_name>']</code> ).</p>
| 1 |
2016-09-17T21:33:14Z
|
[
"python",
"pandas",
"dataframe",
"series"
] |
Failing to update pygame surfaces
| 39,551,648 |
<p>I'm making a pygame game. I have 3 surfaces: <code>gameDisplay</code> (where the character and background is directly rendered to), <code>guiSurf</code> and <code>invSurf</code>
I have a clock made in core pyhon which displays the game time with the pygame font. I blit the clock to <code>guiSurf</code> and then in my gameloop I blit <code>guiSurf</code> and <code>invSurf</code> to <code>gameDisplay</code>. My problem is that the clock leaves a mark from where it was. IE when it changes from '07:00' to '07:01', the '01' is ontop of the '00' which shouldn't be there. I would post the code but theres like 400 lines. Does anyone have any idea what I may of done wrong. <a href="http://gyazo.com/5716aeda3a5769aac7af985db6907caa.png" rel="nofollow">Link to a picture of the clock</a></p>
| 1 |
2016-09-17T20:54:27Z
| 39,551,817 |
<p>Make sure you 'clear' the area of where the time is being printed by blitting another image over the spot where the text is. When you draw your surfaces to the screen it simply becomes one 'surface' that is always drawn until overwritten by something else. You need to clear this surface before you blit something else to it, otherwise you get the effect you see. By simple calling display_name.fill((0,0,0)) at the beginning of every game tick you will 'clear' the screen and then redraw your text onto it without the spillover effect. Of course you will have to reblit everything to the screen every tick, but this should not be a problem unless you need to blit thousands of items. If you do not wish to redraw everything, then blit a small rectangle over the text and then redraw it, and your issues should be solved.</p>
<p>I hope this helps you with your issue and happy coding!</p>
| 0 |
2016-09-17T21:14:24Z
|
[
"python",
"python-3.x",
"pygame",
"python-3.5",
"pygame-surface"
] |
Failing to update pygame surfaces
| 39,551,648 |
<p>I'm making a pygame game. I have 3 surfaces: <code>gameDisplay</code> (where the character and background is directly rendered to), <code>guiSurf</code> and <code>invSurf</code>
I have a clock made in core pyhon which displays the game time with the pygame font. I blit the clock to <code>guiSurf</code> and then in my gameloop I blit <code>guiSurf</code> and <code>invSurf</code> to <code>gameDisplay</code>. My problem is that the clock leaves a mark from where it was. IE when it changes from '07:00' to '07:01', the '01' is ontop of the '00' which shouldn't be there. I would post the code but theres like 400 lines. Does anyone have any idea what I may of done wrong. <a href="http://gyazo.com/5716aeda3a5769aac7af985db6907caa.png" rel="nofollow">Link to a picture of the clock</a></p>
| 1 |
2016-09-17T20:54:27Z
| 39,551,840 |
<p>Visibly, the clock is blitted twice on the guiSurf. And I guess it keeps stacking the previous image of time (7:00, then 7:01, then 7.02 and so on). You need to clear the surface holding the clock before drawing time into it : <code>clock_surf.fill(clearcolor, clock_surf.get_rect())</code>.</p>
| 0 |
2016-09-17T21:18:04Z
|
[
"python",
"python-3.x",
"pygame",
"python-3.5",
"pygame-surface"
] |
Incomplete reads from file written by Popen()-based subprocess
| 39,551,660 |
<p>i'm trying to read the output from one function into another one.</p>
<p>if i break things down into two steps, call the first function(journal.py) from the command line, and then call the second(ip_list.py) i get the results that i'm looking for.</p>
<p>if i try to import the first and run it in the second the resulting list is empty.</p>
<pre><code>import re
import journal
journal.journal()
ip_list = []
with open('Invalid_names_file') as file1:
print(file1)
a = [re.search(r'((\d+\.)+\d+)', line).group() for line in file1]
print(a)
for x in a:
if x not in ip_list:
ip_list.append(x)
print(ip_list)
</code></pre>
<p>output -></p>
<pre><code><_io.TextIOWrapper name='Invalid_names_file' mode='r' encoding='UTF-8'>
[]
[]
</code></pre>
<p>when called in this manner, the file that i'm opening is there (once the script is done running), with what i'm expecting, yet i can't get it to read from it when i try to include it with the import.</p>
<p>i have the print()s so that i can try to understand what's happening, yet can't get my head around it.</p>
<p>journal.py is a Popen command that writes the file.</p>
<p>edit for chris</p>
<p>journal.py</p>
<pre><code>from subprocess import Popen
import os
def journal():
with open('Invalid_names_file', 'w') as Invalid_names_file:
Popen('journalctl -u sshd.service --no-pager --since -168hours\
--until today | grep Invalid', stdout=Invalid_names_file,\
universal_newlines=True, bufsize=1, shell=True)
if os.stat('Invalid_names_file').st_size == 0:
Popen('journalctl -u ssh.service --no-pager --since -168hours\
--until today | grep Invalid', stdout=Invalid_names_file,\
universal_newlines=True, bufsize=1, shell=True)
Invalid_names_file.close()
</code></pre>
| 1 |
2016-09-17T20:56:32Z
| 39,552,417 |
<p>You should wait for <code>Popen()</code> to finish.
Assign its return value to a variable and call <code>wait()</code> on it:</p>
<pre><code>p = Popen('journalctl ...')
p.wait()
</code></pre>
<p>When you run the journal script separately, the parent process will only return when all of its children have terminated.
However, <code>Popen()</code> doesn't wait â unless you tell it to.
Thus, in your case, the <code>journal()</code> function exits immediately after starting the subprocess, so by the time you're reading the target file, it is still empty or incomplete.</p>
| 1 |
2016-09-17T22:44:26Z
|
[
"python",
"file-io",
"popen"
] |
Docker : How to export/save classifying results outside a Docker (tensorflow) box?
| 39,551,771 |
<p>I just followed this tutorial to easily train an image classifier with tensorflow :</p>
<p><a href="https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/" rel="nofollow">https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/</a></p>
<p>I now have a Docker box on my Ubuntu laptop, I managed to train the image classifier, and IT WORKS. Now I want to classify a batch of new images and <strong>store results (i.e. probabilities) on my laptop</strong>.</p>
<p>My objective is to save on my laptop the following results in an "output.csv" file like this:</p>
<pre><code>pic1 0.95 0.05
pic2 0.94 0.06
pic3 0.97 0.03
pic4 0.09 0.91
</code></pre>
<p>I put new images in a "tested" folder and I run the following python code, trying to write in an output file.</p>
<p>Inside Docker terminal I run:</p>
<pre><code>python /tf_files/label_batch_images.py /tf_files/tested
</code></pre>
<p>where label_batch_images.py code is:</p>
<pre><code>import tensorflow as tf, sys
import glob
folder_path = sys.argv[1]
# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
in tf.gfile.GFile("/tf_files/retrained_labels.txt")]
# Unpersists graph from file
with tf.gfile.FastGFile("/tf_files/retrained_graph.pb", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
with tf.Session() as sess:
out = open('output.csv', 'a')
for image_path in glob.glob(folder_path+'/*'):
# Read in the image_data
image_data = tf.gfile.FastGFile(image_path, 'rb').read()
# Feed the image_data as input to the graph and get first prediction
softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
predictions = sess.run(softmax_tensor, \
{'DecodeJpeg/contents:0': image_data})
print("%s\t%s\t%s\n" % (image_path,predictions[0][1],predictions[0][0]))
#THIS ACTUALLY WORKS, I see in my terminal "/tf_files/tested/pic1.jpg 0.00442768 0.995572"
out.write("%s\t%s\t%s\n" % (image_path,predictions[0][1],predictions[0][0]))
#This does not work, because output.csv is not modified
out.close()
</code></pre>
<p>While it works - I see the expected results for each image in my Docker terminal - how to save it on a file on my laptop ?</p>
| 1 |
2016-09-17T21:07:55Z
| 39,558,966 |
<h2>use volumes</h2>
<p>Share a so called host volume with your host, laptop, to write down the results directly on the host. e.g when starting your image</p>
<p><code>docker run -v /home/me/docker/results:/data/results <image></code></p>
<p>In your container, when you write on /data/results, all files will be synced back / placed on the host under /home/me/docker/results</p>
<p>You can of course adjust both, the host or the container path</p>
<h2>user docker cp</h2>
<p>You can easily copy file from a docker container ( or to a docker container ) user <code>docker cp</code></p>
<p>so </p>
<pre><code>docker cp <yourimageid>:/path/to/the/file/on/the/container /home/me/docker/results
</code></pre>
<p>Do this, before you shutdown the container</p>
| 0 |
2016-09-18T14:50:38Z
|
[
"python",
"csv",
"docker",
"tensorflow"
] |
Detecting `<Enter>` and `<Leave>` events for a frame in tkinter
| 39,551,850 |
<p>I have a menu which when the user moves their mouse off I want to disappear. The menu consists of a <code>Frame</code> packed with several <code>Label</code>/<code>Button</code> widgets. I can detect the user moving their mouse off a <code>Label</code>/<code>Button</code> with simply binding to the <code><Enter></code>/<code><Leave</code> events for those. But binding to the same events for the frame never triggers - I guess because the widgets on top cover up the frame so the mouse never enters it?</p>
<p>Is their a way to make the events propagate down to the containing <code>Frame</code>? </p>
<pre><code>window=tkinter.Tk()
menu_frm = tkinter.Frame(window, name="menu_frm")
lbl_1 = tkinter.Label(menu_frm, text="Label", name="lbl_1")
lbl_1.pack()
lbl_2 = tkinter.Label(menu_frm, text="Label", name="lbl_2")
lbl_2.pack()
menu_frm.pack()
# These two (per label and the number of labels is likely to grow) events fire
lbl_1.bind("<Enter>", lambda _: stayopenfunction())
lbl_1.bind("<Leave>", lambda _: closefunction())
lbl_2.bind("<Enter>", lambda _: stayopenfunction())
lbl_2.bind("<Leave>", lambda _: closefunction())
# These two events do not fire
menu_frm.bind("<Enter>", lambda _: stayopenfunction())
menu_frm.bind("<Leave>", lambda _: closefunction())
</code></pre>
| -1 |
2016-09-17T21:19:39Z
| 39,556,152 |
<p>If you're just trying to simplify maintenance of the callbacks on the widgets, then I don't think binding events to the containing frame is the best approach. (I guess it's possible to generate virtual events in the callbacks on the buttons and labels, and bind the virtual event to the frame, but it seems rather complicated. Maybe that's just because I have no experience with virtual events.)</p>
<p>Why not just subclass the label and button widgets? Look at the "Instance and Class Bindings" heading at <a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow">http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm</a> Then you'd just have two class binding to maintain, one for the labels and one for the buttons. This seems cleaner to me; it's just vanilla OOP.</p>
<p>Hope this helps.</p>
| 0 |
2016-09-18T09:34:25Z
|
[
"python",
"tkinter"
] |
How do I copy values from one dictionary to a second dictionary with new keys?
| 39,551,853 |
<p>I am trying to make weapons in my game exclusive to certain classes. I have an item database in form:</p>
<pre><code>itemsList = {
1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "light"},
2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "light"},
3: {"name": "Studded Leather Armor", "armor": 3, "value": 25, "class": "light"},
...
19: {"name": "Dagger", "damage" : int(random.randrange(1, 4)), "value": 2, "Type": "Dagger"},
20: {"name": "Dagger + 1", "damage" : int(random.randrange(1, 4) + 1), "value": 200, "Type": "Dagger"},
21: {"name": "Dagger + 2", "damage" : int(random.randrange(1, 4) + 2), "value": 750, "Type": "Dagger"},
22: {"name": "Dagger + 3", "damage" : int(random.randrange(1, 4) + 3), "value": 2000, "Type": "Dagger"}
}
</code></pre>
<p>I am going to import, if a class can equip a certain weapon, to a new dictionary, </p>
<pre><code>character.canEquipWeapon = {}
</code></pre>
<p>I would like to assign the name, damage, value, and type to a new set of keys in the dictionary, only, I would like to add only certain subsets (daggers, maces, swords) to certain classes. </p>
<p>I have tried </p>
<pre><code>character.canEquipWeapon.update(itemsList[5])
</code></pre>
<p>and that just overwrites the dictionary with each new value. How do I go about doing this?</p>
| 1 |
2016-09-17T21:19:58Z
| 39,551,994 |
<p>How do you feel about making <code>itemsList</code> an array instead of a dict? Seems like you're using it as an array anyhow. That way, you could do something like</p>
<pre><code>itemsList2 = [weapon for weapon in itemsList if weapon.type == "dagger"]
</code></pre>
<p>or if the weapon types are stored in, say, <code>character.weaponTypes</code></p>
<pre><code>itemsList2 = [weapon for weapon in itemsList if weapon.type in character.weaponTypes]
</code></pre>
| 0 |
2016-09-17T21:38:42Z
|
[
"python",
"dictionary",
"key"
] |
How do I copy values from one dictionary to a second dictionary with new keys?
| 39,551,853 |
<p>I am trying to make weapons in my game exclusive to certain classes. I have an item database in form:</p>
<pre><code>itemsList = {
1: {"name": "Padded Armor", "armor": 1, "value": 5, "class": "light"},
2: {"name": "Leather Armor", "armor": 2, "value": 10, "class": "light"},
3: {"name": "Studded Leather Armor", "armor": 3, "value": 25, "class": "light"},
...
19: {"name": "Dagger", "damage" : int(random.randrange(1, 4)), "value": 2, "Type": "Dagger"},
20: {"name": "Dagger + 1", "damage" : int(random.randrange(1, 4) + 1), "value": 200, "Type": "Dagger"},
21: {"name": "Dagger + 2", "damage" : int(random.randrange(1, 4) + 2), "value": 750, "Type": "Dagger"},
22: {"name": "Dagger + 3", "damage" : int(random.randrange(1, 4) + 3), "value": 2000, "Type": "Dagger"}
}
</code></pre>
<p>I am going to import, if a class can equip a certain weapon, to a new dictionary, </p>
<pre><code>character.canEquipWeapon = {}
</code></pre>
<p>I would like to assign the name, damage, value, and type to a new set of keys in the dictionary, only, I would like to add only certain subsets (daggers, maces, swords) to certain classes. </p>
<p>I have tried </p>
<pre><code>character.canEquipWeapon.update(itemsList[5])
</code></pre>
<p>and that just overwrites the dictionary with each new value. How do I go about doing this?</p>
| 1 |
2016-09-17T21:19:58Z
| 39,552,123 |
<p>You could create a dict with usable items by class, so that for a given class, you have the list of the IDs it can equip as such :</p>
<pre><code>classItem = {
'rogue' : [1,2,3,12,13,14,15],
'mage' : [13,15,16,18],
'soldier' : [1,2,3,4,5,6,7],
}
</code></pre>
<p>Then to get the list of items usable by the rogue for instance :</p>
<pre><code>rogueItems = [v for k,v in itemsList.items() if k in classItem['rogue']]
</code></pre>
<p>Note that with python2 you'd have to use <code>itemsList.iteritems()</code> instead of <code>itemsList.items()</code></p>
| 0 |
2016-09-17T22:00:23Z
|
[
"python",
"dictionary",
"key"
] |
How to make loop repeat until the sum is a single digit?
| 39,551,886 |
<p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p>
<p>This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another <code>while</code> statement</p>
<pre><code>n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
</code></pre>
<p>this is a sample output of the code</p>
<p>Input an integer: 98765678912398</p>
<p>8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88</p>
<p>8 + 8 = 16</p>
<p>1 + 6 = 7</p>
| 2 |
2016-09-17T21:24:34Z
| 39,551,939 |
<p>You don't need to convert your integer to a float here; just use the <a href="https://docs.python.org/3/library/functions.html#divmod" rel="nofollow"><code>divmod()</code> function</a> in a loop:</p>
<pre><code>def sum_digits(n):
newnum = 0
while n:
n, digit = divmod(n, 10)
newnum += digit
return newnum
</code></pre>
<p>By making it a function you can more easily use it to repeatedly apply this to a number until it is smaller than 10:</p>
<pre><code>n = int(input("Input an integer:"))
while n > 9:
n = sum_digits(n)
print(n)
</code></pre>
| 1 |
2016-09-17T21:31:30Z
|
[
"python"
] |
How to make loop repeat until the sum is a single digit?
| 39,551,886 |
<p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p>
<p>This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another <code>while</code> statement</p>
<pre><code>n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
</code></pre>
<p>this is a sample output of the code</p>
<p>Input an integer: 98765678912398</p>
<p>8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88</p>
<p>8 + 8 = 16</p>
<p>1 + 6 = 7</p>
| 2 |
2016-09-17T21:24:34Z
| 39,551,949 |
<p>You could utilize recursion.</p>
<p>Try this:</p>
<pre><code>def sum_of_digits(n):
s = 0
while n:
s += n % 10
n //= 10
if s > 9:
return sum_of_digits(s)
return s
n = int(input("Enter an integer: "))
print(sum_of_digits(n))
</code></pre>
| 1 |
2016-09-17T21:32:56Z
|
[
"python"
] |
How to make loop repeat until the sum is a single digit?
| 39,551,886 |
<p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p>
<p>This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another <code>while</code> statement</p>
<pre><code>n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
</code></pre>
<p>this is a sample output of the code</p>
<p>Input an integer: 98765678912398</p>
<p>8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88</p>
<p>8 + 8 = 16</p>
<p>1 + 6 = 7</p>
| 2 |
2016-09-17T21:24:34Z
| 39,551,970 |
<p>This should work, no division involved.</p>
<pre><code>n = int(input("Input an integer:"))
while n > 9:
n = sum([int(i) for i in str(n)])
print(n)
</code></pre>
<p>It basically converts the integer to a string, then sums over the digits using a list comprehension and continues until the number is no greater than 9.</p>
| 3 |
2016-09-17T21:35:04Z
|
[
"python"
] |
How to make loop repeat until the sum is a single digit?
| 39,551,886 |
<p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p>
<p>This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another <code>while</code> statement</p>
<pre><code>n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
</code></pre>
<p>this is a sample output of the code</p>
<p>Input an integer: 98765678912398</p>
<p>8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88</p>
<p>8 + 8 = 16</p>
<p>1 + 6 = 7</p>
| 2 |
2016-09-17T21:24:34Z
| 39,552,059 |
<p>I'm not sure if it's anti-practice in Python because I know nothing about the language, but here is my solution.</p>
<pre><code>n = int(input("Input an integer:"))
def sum_int(num):
numArr = map(int,str(num))
number = sum(numArr)
if number < 10:
print(number)
else:
sum_int(number)
sum_int(n)
</code></pre>
<p>Again I am unsure about the recursion within a function in Python, but hey, it works :)</p>
| 0 |
2016-09-17T21:48:12Z
|
[
"python"
] |
How to make loop repeat until the sum is a single digit?
| 39,551,886 |
<p>Prompt: Write a program that adds all the digits in an integer. If the resulting sum is more than one digit, keep repeating until the sum is one digit. For example, the number 2345 has the sum <code>2+3+4+5 = 14</code> which is not a single digit so repeat with <code>1+4 = 5</code> which is a single digit.</p>
<p>This is the code I have so far. It works out for the first part, but I can't figure out how to make it repeat until the sum is a single digit. I'm pretty sure I'm supposed to nest the code I already have with another <code>while</code> statement</p>
<pre><code>n = int(input("Input an integer:"))
sum_int=0
while float(n)/10 >= .1:
r= n%10
sum_int += r
n= n//10
if float(n)/10 > .1: print(r, end= " + ")
else: print(r,"=",sum_int)
</code></pre>
<p>this is a sample output of the code</p>
<p>Input an integer: 98765678912398</p>
<p>8 + 9 + 3 + 2 + 1 + 9 + 8 + 7 + 6 + 5 + 6 + 7 + 8 + 9 = 88</p>
<p>8 + 8 = 16</p>
<p>1 + 6 = 7</p>
| 2 |
2016-09-17T21:24:34Z
| 39,552,332 |
<p>If you like <strong>recursion</strong>, and you must:</p>
<pre><code>>>> def sum_digits_rec(integ):
if integ <= 9:
return integ
res = sum(divmod(integ, 10))
return sum_digits(res)
>>> print(sum_digits_rec(98765678912398))
7
</code></pre>
| 0 |
2016-09-17T22:32:41Z
|
[
"python"
] |
My celery redis task isn't working in my django app on heroku server
| 39,551,927 |
<p>I have a task that was working fine on my local server but when I pushed it to Heroku, nothing happens. there are no error messages. I am a newbie when it comes to this and locally I would start the worker by doing </p>
<pre><code>celery worker -A blog -l info.
</code></pre>
<p>So I'm guessing that's the issue may have to do with that. because I don't know to do this. I doubt I'm supposed to do this in my app. heres my code</p>
<p>celery.py</p>
<pre><code>import os
from celery import Celery
from django.conf import settings
# set the default Django settings module for the 'celery' program.
os.environ.setdefault(
'DJANGO_SETTINGS_MODULE', 'gettingstarted.settings'
)
app = Celery('blog')
# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
</code></pre>
<p>my tasks.py</p>
<pre><code>import requests
import random
import os
from bs4 import BeautifulSoup
from .celery import app
from .models import Post
from django.contrib.auth.models import User
@app.task
def the_star():
def swappo():
user_one = ' "Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0" '
user_two = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)" '
user_thr = ' "Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko" '
user_for = ' "Mozilla/5.0 (Macintosh; Intel Mac OS X x.y; rv:10.0) Gecko/20100101 Firefox/10.0" '
agent_list = [user_one, user_two, user_thr, user_for]
a = random.choice(agent_list)
return a
headers = {
"user-agent": swappo(),
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"accept-charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
"accept-encoding": "gzip,deflate,sdch",
"accept-language": "en-US,en;q=0.8",
}
# scraping from worldstar
url_to = 'http://www.worldstarhiphop.com'
html = requests.get(url_to, headers=headers)
soup = BeautifulSoup(html.text, 'html5lib')
titles = soup.find_all('section', 'box')
name = 'World Star'
if os.getenv('_system_name') == 'OSX':
author = User.objects.get(id=2)
else:
author = User.objects.get(id=3)
def make_soup(url):
the_comments_page = requests.get(url, headers=headers)
soupdata = BeautifulSoup(the_comments_page.text, 'html5lib')
comment = soupdata.find('div')
para = comment.find_all('p')
kids = [child.text for child in para]
blu = str(kids).strip('[]')
return blu
cleaned_titles = [title for title in titles if title.a.get('href') != 'vsubmit.php']
world_entries = [{'href': url_to + box.a.get('href'),
'src': box.img.get('src'),
'text': box.strong.a.text,
'comments': make_soup(url_to + box.a.get('href')),
'name': name,
'url': url_to + box.a.get('href'),
'embed': None,
'author': None,
'video': False
} for box in cleaned_titles][:10] # The count
for entry in world_entries:
post = Post()
post.title = entry['text']
title = post.title
if not Post.objects.filter(title=title):
post.title = entry['text']
post.name = entry['name']
post.url = entry['url']
post.body = entry['comments']
post.image_url = entry['src']
post.video_path = entry['embed']
post.author = entry['author']
post.video = entry['video']
post.status = 'draft'
post.save()
post.tags.add("video", "Musica")
return world_entries
</code></pre>
<p>my views.py</p>
<pre><code>def shopan(request):
the_star.delay()
return redirect('/')
</code></pre>
<p>I have multiple instances of REDIS_URL</p>
<p>soI ran</p>
<pre><code>heroku redis:promote REDIS_URL
</code></pre>
<p>and that's what I use in my environment variable which you can see above. How can i make this work?</p>
| 0 |
2016-09-17T21:30:08Z
| 39,552,041 |
<p>You need to add an entry in your Procfile to tell Heroku to start the Celery worker:</p>
<pre><code>worker:celery worker -A blog -l info
</code></pre>
| 1 |
2016-09-17T21:45:36Z
|
[
"python",
"django",
"heroku",
"deployment",
"redis"
] |
Python Twitter API Stream tweepy trying to save data to a CSV file
| 39,551,928 |
<pre><code>from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
ckey = 'hidden due to question'
csecret = 'hidden due to question'
atoken = 'hidden due to question'
asecret = 'hidden due to question'
class listener(StreamListener):
def on_data(self, data):
try:
print (data)
saveFile = open('TwitterAPI.csv','a')
saveFile.write(data)
saveFile.Write('\n')
saveFIle.close()
return (True)
def on_error(self, status):
print (status)
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["car"])
</code></pre>
<p>The problem with the code above is the fact that it keeps on coming up with an error message stating that there is an unexpected unindent at the //def on_error// row</p>
| 1 |
2016-09-17T21:30:09Z
| 39,551,969 |
<p>You open a <code>try</code> block without catching the exception.</p>
<p><a href="https://docs.python.org/3/tutorial/errors.html" rel="nofollow">https://docs.python.org/3/tutorial/errors.html</a></p>
<p>Also be careful, python is case sensitive, so <code>saveFile</code> is not <code>saveFIle</code>, nor <code>saveFile.write()</code> is <code>saveFile.Write()</code>...</p>
<p>Editing your <code>on_data()</code> handler as follow should make it work :</p>
<pre><code>def on_data(self, data):
try:
print(data)
with open('TwitterAPI.csv','a') as f:
f.write(data)
except Exception as e: # here catch whatever exception you may have.
print('[!] Error : %s' % e)
</code></pre>
<p><strong>Edit :</strong> Below is your full code reworked :</p>
<pre><code>from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
ckey = 'hidden due to question'
csecret = 'hidden due to question'
atoken = 'hidden due to question'
asecret = 'hidden due to question'
class listener(StreamListener):
def on_data(self, data):
try:
print(data)
with open('TwitterAPI.csv','a') as f:
f.write(data)
except:
pass
def on_error(self, status):
print (status)
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track=["car"])
</code></pre>
| 0 |
2016-09-17T21:35:01Z
|
[
"python",
"api",
"csv",
"twitter"
] |
Apply a weight formula over a Dataframe using Numpy
| 39,552,158 |
<p>I have a Dataframe and am looking to divide the float value of a cell by the sum of the row where it resides. For this I use a numpy formula. This therefore would give me a weight for that cell for that row. I have this dataframe <code>df1</code>:</p>
<pre class="lang-none prettyprint-override"><code> AA AB AC AD
2005-01-02 23:55:00 "EQUITY" "EQUITY" "EQUITY" "EQUITY"
2005-01-03 00:00:00 32.32 19.5299 32.32 31.0455
2005-01-04 00:00:00 31.9075 19.4487 31.9075 30.3755
2005-01-05 00:00:00 31.6151 19.5799 31.6151 29.971
2005-01-06 00:00:00 31.1426 19.7174 31.1426 29.9647
</code></pre>
<p>I have tried the following so far:</p>
<pre><code>import numpy as np
def foo_bar(x):
if type(x) is not str:
return x / np.sum(df1, axis=1)
else:
return
df = df_numeric.apply(np.vectorize(foo_bar))
</code></pre>
<p>It seems the sum part of my formula is not properly written as I get the following error:</p>
<pre class="lang-none prettyprint-override"><code> AA AB AC AD
ValueError: ('setting an array element with a sequence.', 'occurred at index AA')
</code></pre>
| 0 |
2016-09-17T22:07:04Z
| 39,552,360 |
<p>The message error is quite informative in this case: <strong>you are trying to set an array element (<em>x</em>) with a sequence.</strong></p>
<p>Try to load your dataframe <code>df1</code> in a Python prompt and print the expression <code>np.sum(df1,axis=1)</code>: it returns a sequence -a vector- containing the sums of each row. You would need to select the element of this sequence which corresponds to the appropriate row in each case.</p>
<p>You can <strong>try the following</strong>, as explained <a href="http://stackoverflow.com/questions/18594469/normalizing-a-pandas-dataframe-by-row">here</a>:</p>
<p><code>df1.div(df1.sum(axis=1), axis=0)</code></p>
<p><code>div</code> will apply element-wise division in your dataframe.</p>
<p>From your <code>df1</code> snippet it seems that you have rows with strings (<code>"EQUITY"</code>) alternated with rows with numbers, those will give you problems. I suggest you take out any string rows and leave only a dataframe with numbers. You can use the column titles to give significant names to the columns in your dataframe.</p>
| 4 |
2016-09-17T22:37:08Z
|
[
"python",
"pandas",
"numpy",
"dataframe"
] |
Apply a weight formula over a Dataframe using Numpy
| 39,552,158 |
<p>I have a Dataframe and am looking to divide the float value of a cell by the sum of the row where it resides. For this I use a numpy formula. This therefore would give me a weight for that cell for that row. I have this dataframe <code>df1</code>:</p>
<pre class="lang-none prettyprint-override"><code> AA AB AC AD
2005-01-02 23:55:00 "EQUITY" "EQUITY" "EQUITY" "EQUITY"
2005-01-03 00:00:00 32.32 19.5299 32.32 31.0455
2005-01-04 00:00:00 31.9075 19.4487 31.9075 30.3755
2005-01-05 00:00:00 31.6151 19.5799 31.6151 29.971
2005-01-06 00:00:00 31.1426 19.7174 31.1426 29.9647
</code></pre>
<p>I have tried the following so far:</p>
<pre><code>import numpy as np
def foo_bar(x):
if type(x) is not str:
return x / np.sum(df1, axis=1)
else:
return
df = df_numeric.apply(np.vectorize(foo_bar))
</code></pre>
<p>It seems the sum part of my formula is not properly written as I get the following error:</p>
<pre class="lang-none prettyprint-override"><code> AA AB AC AD
ValueError: ('setting an array element with a sequence.', 'occurred at index AA')
</code></pre>
| 0 |
2016-09-17T22:07:04Z
| 39,554,468 |
<p>Try the following bit of code, which uses pandas features instead of an explicit function.</p>
<p>The function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow">div</a> performs an element wise division. You feed the total sums as a series to that function, and use the row index of your original element to select the appropriate value for division.</p>
<pre><code>import numpy as np
import pandas as pd
data = pd.DataFrame(np.arange(12).reshape((3, 4)),columns=['A', 'B', 'C', 'D'])
data['Total'] = data.sum(axis=1)
data_new= data.iloc[:, :-1].div(data["Total"], axis=0)
print data
print data_new
</code></pre>
<p>Result:</p>
<pre><code> A B C D Total
0 0 1 2 3 6
1 4 5 6 7 22
2 8 9 10 11 38
A B C D
0 0.000000 0.166667 0.333333 0.500000
1 0.181818 0.227273 0.272727 0.318182
2 0.210526 0.236842 0.263158 0.289474
</code></pre>
| 1 |
2016-09-18T05:35:21Z
|
[
"python",
"pandas",
"numpy",
"dataframe"
] |
Loading multiple PNGs in pyglet window
| 39,552,160 |
<p>If I loaded two partially transparent PNGs in succession (onDraw), would I still be able to see the first image if the second image was transparent in that area? These images would be drawn into a window. I would use Sprites but I couldn't get them to work. Thanks!</p>
| 0 |
2016-09-17T22:07:18Z
| 39,744,446 |
<p>There's no code in your question and quite frankly there's so many solutions to what I think is your problem that you could have at least 10 different answers here.</p>
<p>I'll vote to close this question but seeing as these are so rare and they usually don't get much response on either closing requests or down votes enough for people to care.. I'll give a example snippet of code that might get you on your way towards a working solution:</p>
<pre><code>import pyglet
from pyglet.gl import *
class main(pyglet.window.Window):
def __init__ (self):
super(main, self).__init__(300, 300, fullscreen = False)
self.alive = 1
self.image_one = pyglet.sprite.Sprite(pyglet.image.load('./image_one.png'))
self.image_two = pyglet.sprite.Sprite(pyglet.image.load('./image_two.png'))
self.image_one.x = 100
self.image_one.y = 100
self.image_two.x = 70
self.image_two.y = 80
def on_draw(self):
self.render()
def on_close(self):
self.alive = 0
def render(self):
self.clear()
self.image_one.draw()
self.image_two.draw()
self.flip()
def run(self):
while self.alive == 1:
self.render()
# -----------> This is key <----------
# This is what replaces pyglet.app.run()
# but is required for the GUI to not freeze
#
event = self.dispatch_events()
x = main()
x.run()
</code></pre>
<p>I used these two images:</p>
<ol>
<li><p><a href="http://i.stack.imgur.com/tW3Dz.png" rel="nofollow"><img src="http://i.stack.imgur.com/tW3Dz.png" alt="enter image description here"></a></p></li>
<li><p><a href="http://i.stack.imgur.com/SuQRp.png" rel="nofollow"><img src="http://i.stack.imgur.com/SuQRp.png" alt="enter image description here"></a></p></li>
</ol>
<p>Nothing fancy but it will give you an example of how to render two images using the <a href="http://pyglet.readthedocs.io/en/pyglet-1.2-maintenance/api/pyglet/pyglet.sprite.html" rel="nofollow">Sprite</a> class.</p>
| 0 |
2016-09-28T10:11:11Z
|
[
"python",
"pyglet"
] |
Functions and List Index Out Of Range
| 39,552,170 |
<p>I'm working on a simple yahtzee style dice game for class but I keep running into issues. Namely right now I'm having an issue with lists. I keep getting </p>
<pre><code> File "C:/Users/u1069284/Desktop/HW3_LandonShoaf.py", line 90, in scoring
counts[value] = counts[value] + 1
IndexError: list index out of range
</code></pre>
<p>when I run my program. I'm not sure please help?</p>
<pre><code> from math import *
from random import *
global PlayerScore
PlayerScore = 100
def firstroll():
global dice
dice = [0,0,0,0,0]
print(dice)
for Index in range(5):
dice[Index] = randint(1,6)
print(dice)
return(dice)
def reroll():
rerollstring = input("Which die/dice do you want to reroll?: ")
print(rerollstring)
rerolllist = rerollstring.split()
print(rerolllist)
for i in rerolllist:
dice[int(i) - 1] = randint(1,6)
print(dice)
return(dice)
def scoring():
global dice
counts = [] * 7
for value in dice:
counts[value] = counts[value] + 1
if 5 in counts:
message = "Five Of A Kind! +30 Points!"
score = 30
elif 4 in counts:
message = "Four Of A Kind! +25 Points!"
score = 25
elif (3 in counts) and (2 in counts):
message = "FULL HOUSE! +15 Points!"
score = 15
elif 3 in counts:
message = "Three Of A Kind! +10 Points!"
score = 10
elif counts.count(2) == 2:
message = "Two Pairs! +5 Points"
score = 5
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
message = "Straight! +20 Points!"
score = 20
else:
message = "NO POINTS!"
score = 0
return(score)
print(message)
def PlayerScoring():
PlayerScore == PlayerScore - 10
PlayerScore == PlayerScore + score
return(PlayerScore)
print(PlayerScore)
def want2play():
play = input("Play the dice game? (y for yes): ")
return play
def main():
while True:
if int(PlayerScore) > 0:
playround = want2play()
if playround == 'y':
firstroll()
reroll()
scoring()
PlayerScoring()
else:
print("Game Over")
break
else:
print("Your Are Out Of Points!")
print("GAME OVER")
main()
</code></pre>
| 0 |
2016-09-17T22:08:39Z
| 39,552,212 |
<p>Try this : </p>
<pre><code>counts = [0]*7
for value in dice:
counts[value] += 1
</code></pre>
| 0 |
2016-09-17T22:14:40Z
|
[
"python"
] |
Functions and List Index Out Of Range
| 39,552,170 |
<p>I'm working on a simple yahtzee style dice game for class but I keep running into issues. Namely right now I'm having an issue with lists. I keep getting </p>
<pre><code> File "C:/Users/u1069284/Desktop/HW3_LandonShoaf.py", line 90, in scoring
counts[value] = counts[value] + 1
IndexError: list index out of range
</code></pre>
<p>when I run my program. I'm not sure please help?</p>
<pre><code> from math import *
from random import *
global PlayerScore
PlayerScore = 100
def firstroll():
global dice
dice = [0,0,0,0,0]
print(dice)
for Index in range(5):
dice[Index] = randint(1,6)
print(dice)
return(dice)
def reroll():
rerollstring = input("Which die/dice do you want to reroll?: ")
print(rerollstring)
rerolllist = rerollstring.split()
print(rerolllist)
for i in rerolllist:
dice[int(i) - 1] = randint(1,6)
print(dice)
return(dice)
def scoring():
global dice
counts = [] * 7
for value in dice:
counts[value] = counts[value] + 1
if 5 in counts:
message = "Five Of A Kind! +30 Points!"
score = 30
elif 4 in counts:
message = "Four Of A Kind! +25 Points!"
score = 25
elif (3 in counts) and (2 in counts):
message = "FULL HOUSE! +15 Points!"
score = 15
elif 3 in counts:
message = "Three Of A Kind! +10 Points!"
score = 10
elif counts.count(2) == 2:
message = "Two Pairs! +5 Points"
score = 5
elif not (2 in counts) and (counts[1] == 0 or counts[6] == 0):
message = "Straight! +20 Points!"
score = 20
else:
message = "NO POINTS!"
score = 0
return(score)
print(message)
def PlayerScoring():
PlayerScore == PlayerScore - 10
PlayerScore == PlayerScore + score
return(PlayerScore)
print(PlayerScore)
def want2play():
play = input("Play the dice game? (y for yes): ")
return play
def main():
while True:
if int(PlayerScore) > 0:
playround = want2play()
if playround == 'y':
firstroll()
reroll()
scoring()
PlayerScoring()
else:
print("Game Over")
break
else:
print("Your Are Out Of Points!")
print("GAME OVER")
main()
</code></pre>
| 0 |
2016-09-17T22:08:39Z
| 39,552,215 |
<p>This:</p>
<pre><code>counts = [] * 7
for value in dice:
counts[value] = counts[value] + 1
</code></pre>
<p>Is not a valid way to initialize a list of <code>0</code> values, as you are expecting. Simply print out <code>[] * 7</code> at an interpreter, and you will see that your assumption was incorrect. It produces an empty list. I don't know what led you to believe that your code would produce a list of <code>0</code>s.</p>
<p>Instead, replace <code>counts = [] * 7</code> with <code>counts = [0 for _ in range(6)]</code>, and then keep in mind that it's zero-indexed. This allows you to avoid a redundant first element in the list.</p>
<pre><code>counts = [0 for _ in range(6)]
for value in dice:
counts[value-1] += 1
</code></pre>
| 0 |
2016-09-17T22:15:18Z
|
[
"python"
] |
Generator expression evaluation with several ... for ... in ... parts
| 39,552,213 |
<p><strong>Question</strong>: What does Python do under the hood when it sees this kind of expression? </p>
<pre><code>sum(sum(i) for j in arr for i in j)
</code></pre>
<hr>
<p><strong>My thoughts</strong>: <em>The above expression works.</em> But as it is written in <a href="https://docs.python.org/3.5/reference/executionmodel.html#resolution-of-names" rel="nofollow">Python's docs</a>:</p>
<blockquote>
<p>generator expressions are implemented using a function scope</p>
</blockquote>
<p>Not to be verbose :) I have an array with the following layout (<em>as an example</em>): </p>
<pre><code>>>> arr = [
[[1,2,3], [4,5,6]],
[[7,8,9],[10,11,12]]
]
</code></pre>
<p>At first, I try to sum all elements of <code>arr</code> with the following expression:</p>
<pre><code>>>> sum(sum(i) for i in j for j in arr)
NameError: name 'j' is not defined
</code></pre>
<p>It raises <code>NameError</code>, but why not <code>UnboundLocalError: local variable 'j' referenced before assignment</code> if it is implemented using a function scope, what is evaluation rules for <code>for ... in ...</code> from left-to-right or from right-to-left? And what is an equivalent generator function for this generator expression?</p>
<hr>
<p><strong>EDIT</strong>:</p>
<p>I catch the idea. Thanks @vaultah for some insight. In this case <code>j</code> is the argument that is send to generator expression:</p>
<pre><code>>>> sum(sum(i) for i in j for j in arr) # NameError
</code></pre>
<p>that's why I get this weird <code>NameError</code>. </p>
<hr>
<p><a href="http://stackoverflow.com/a/39552690/6793085">@Eric answer</a> shows that generator expression:</p>
<pre><code>>>> sum(sum(i) for j in arr for i in j)
</code></pre>
<p>is equivalent to: </p>
<pre><code>>>> def __gen(arr):
for j in arr:
for i in j:
yield sum(i)
>>> sum(__gen(arr))
</code></pre>
<hr>
| 0 |
2016-09-17T22:14:44Z
| 39,552,306 |
<p>Whether it is a generator or a list comprehension, the comprehension nesting is the same. It is easier to see what is going on with a list comprehension and that is what I will use in the examples below.</p>
<p>Given:</p>
<pre><code>>>> arr
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
</code></pre>
<p>You can flatten the List of Lists of Ints by 1 level using a nested list comprehension (or generator):</p>
<pre><code>>>> [e for sl in arr for e in sl]
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
</code></pre>
<p>You can flatten completely, given that structure, by nesting again (example only; there are better ways to flatten a deeply nested list):</p>
<pre><code>>>> [e2 for sl2 in [e for sl in arr for e in sl] for e2 in sl2]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
</code></pre>
<p>Since <code>sum</code> takes an iterable, the second flattening is not necessary in your example:</p>
<pre><code>>>> [sum(e) for sl in arr for e in sl]
[6, 15, 24, 33] # sum of those is 78...
</code></pre>
<hr>
<p>The general form of a comprehension is:</p>
<pre><code>[ expression for a_variable in a_DEFINED_sequence optional_predicate ]
</code></pre>
<p>You can get the same <code>NameError</code> you are seeing on your nested comprehension by using a non defined name:</p>
<pre><code>>>> [c for c in not_defined]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'not_defined' is not defined
</code></pre>
<p>So the error you see on <code>sum(sum(i) for i in j for j in arr)</code> is because <code>j</code> has not been defined yet. Comprehensions are evaluated left to right, inner to outer. The definition of <code>j</code> as a sequence is to the right of its attempted use. </p>
<p>To unroll the list comprehension into nested loops, the <em>inner</em> (or left hand) section becomes the <em>outer</em> loop:</p>
<pre><code>for sl in arr:
for sl2 in sl:
for e in sl2:
# now you have each int in the LoLoInts...
# you could use yield e for a generator here
</code></pre>
<hr>
<p>Your final question: Why do you get a <code>TypeError</code> with <code>gen = (j for j in arr)</code>?</p>
<p>That generator expression does nothing. Example:</p>
<pre><code>>>> [j for j in arr]
[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
>>> [j for j in arr] == arr
True
</code></pre>
<p>So the expression <code>(j for j in arr)</code> just returns a generator over <code>arr</code>. </p>
<p>And <code>sum</code> does not know how to add that or arr either:</p>
<pre><code>>>> sum(arr)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'list'
</code></pre>
<p>Since <code>gen</code> in your example is returning the same data structure, that is your error. </p>
<p>To fix it:</p>
<pre><code>>>> gen=(e for sl in arr for e in sl)
>>> sum(sum(li) for li in gen)
78
</code></pre>
| 1 |
2016-09-17T22:29:59Z
|
[
"python",
"python-3.x",
"scope",
"nested",
"generator"
] |
Generator expression evaluation with several ... for ... in ... parts
| 39,552,213 |
<p><strong>Question</strong>: What does Python do under the hood when it sees this kind of expression? </p>
<pre><code>sum(sum(i) for j in arr for i in j)
</code></pre>
<hr>
<p><strong>My thoughts</strong>: <em>The above expression works.</em> But as it is written in <a href="https://docs.python.org/3.5/reference/executionmodel.html#resolution-of-names" rel="nofollow">Python's docs</a>:</p>
<blockquote>
<p>generator expressions are implemented using a function scope</p>
</blockquote>
<p>Not to be verbose :) I have an array with the following layout (<em>as an example</em>): </p>
<pre><code>>>> arr = [
[[1,2,3], [4,5,6]],
[[7,8,9],[10,11,12]]
]
</code></pre>
<p>At first, I try to sum all elements of <code>arr</code> with the following expression:</p>
<pre><code>>>> sum(sum(i) for i in j for j in arr)
NameError: name 'j' is not defined
</code></pre>
<p>It raises <code>NameError</code>, but why not <code>UnboundLocalError: local variable 'j' referenced before assignment</code> if it is implemented using a function scope, what is evaluation rules for <code>for ... in ...</code> from left-to-right or from right-to-left? And what is an equivalent generator function for this generator expression?</p>
<hr>
<p><strong>EDIT</strong>:</p>
<p>I catch the idea. Thanks @vaultah for some insight. In this case <code>j</code> is the argument that is send to generator expression:</p>
<pre><code>>>> sum(sum(i) for i in j for j in arr) # NameError
</code></pre>
<p>that's why I get this weird <code>NameError</code>. </p>
<hr>
<p><a href="http://stackoverflow.com/a/39552690/6793085">@Eric answer</a> shows that generator expression:</p>
<pre><code>>>> sum(sum(i) for j in arr for i in j)
</code></pre>
<p>is equivalent to: </p>
<pre><code>>>> def __gen(arr):
for j in arr:
for i in j:
yield sum(i)
>>> sum(__gen(arr))
</code></pre>
<hr>
| 0 |
2016-09-17T22:14:44Z
| 39,552,690 |
<blockquote>
<p>What does Python do under the hood when it sees this kind of expression?</p>
<pre><code> sum(sum(i) for j in array for i in j)
</code></pre>
</blockquote>
<p>It becomes something equivalent to:</p>
<pre><code>def __gen(it):
# "it" is actually in locals() as ".0"
for j in it:
for i in j:
yield sum(i)
sum(__gen(iter(arr)))
</code></pre>
<p>Note that both <code>__iter__</code> and the name resolution happen outside the function scope. This only applies to the first <code>for</code> loop</p>
<p><a href="https://www.python.org/dev/peps/pep-0289/#the-details" rel="nofollow">PEP 0289</a> explains this in more detail</p>
| 2 |
2016-09-17T23:29:53Z
|
[
"python",
"python-3.x",
"scope",
"nested",
"generator"
] |
Loading local file in sc.textFile
| 39,552,235 |
<p>I try to load a local file as below</p>
<pre><code>File = sc.textFile('file:///D:/Python/files/tit.csv')
File.count()
</code></pre>
<p>Full traceback</p>
<pre><code>IllegalArgumentException Traceback (most recent call last)
<ipython-input-72-a84ae28a29dc> in <module>()
----> 1 File.count()
/databricks/spark/python/pyspark/rdd.pyc in count(self)
1002 3
1003 """
-> 1004 return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum()
1005
1006 def stats(self):
/databricks/spark/python/pyspark/rdd.pyc in sum(self)
993 6.0
994 """
--> 995 return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add)
996
997 def count(self):
/databricks/spark/python/pyspark/rdd.pyc in fold(self, zeroValue, op)
867 # zeroValue provided to each partition is unique from the one provided
868 # to the final reduce call
--> 869 vals = self.mapPartitions(func).collect()
870 return reduce(op, vals, zeroValue)
871
/databricks/spark/python/pyspark/rdd.pyc in collect(self)
769 """
770 with SCCallSiteSync(self.context) as css:
--> 771 port = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
772 return list(_load_from_socket(port, self._jrdd_deserializer))
773
/databricks/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py in __call__(self, *args)
811 answer = self.gateway_client.send_command(command)
812 return_value = get_return_value(
--> 813 answer, self.gateway_client, self.target_id, self.name)
814
815 for temp_arg in temp_args:
/databricks/spark/python/pyspark/sql/utils.pyc in deco(*a, **kw)
51 raise AnalysisException(s.split(': ', 1)[1], stackTrace)
52 if s.startswith('java.lang.IllegalArgumentException: '):
---> 53 raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace)
54 raise
55 return deco
IllegalArgumentException: u'java.net.URISyntaxException: Expected scheme-specific part at index 2: D:'
</code></pre>
<p>what's wrong? I do usual way
for example
<a href="http://stackoverflow.com/questions/32064280/load-a-local-file-to-spark-using-sc-textfile">load a local file to spark using sc.textFile()</a>
or
<a href="http://stackoverflow.com/questions/27299923/how-to-load-local-file-in-sc-textfile-instead-of-hdfs">How to load local file in sc.textFile, instead of HDFS</a>
These examles are for scala but for python is thr same way if i don't mind</p>
<p>but </p>
<pre><code>val File = 'D:\\\Python\\files\\tit.csv'
SyntaxError: invalid syntax
File "<ipython-input-132-2a3878e0290d>", line 1
val File = 'D:\\\Python\\files\\tit.csv'
^
SyntaxError: invalid syntax
</code></pre>
| 1 |
2016-09-17T22:19:06Z
| 39,557,033 |
<p>Update:
There seems to be an issue with ":" in hadoop...</p>
<pre><code>filenames with ':' colon throws java.lang.IllegalArgumentException
</code></pre>
<p><a href="https://issues.apache.org/jira/browse/HDFS-13" rel="nofollow">https://issues.apache.org/jira/browse/HDFS-13</a></p>
<p>and </p>
<pre><code>Path should handle all characters
</code></pre>
<p><a href="https://issues.apache.org/jira/browse/HADOOP-3257" rel="nofollow">https://issues.apache.org/jira/browse/HADOOP-3257</a></p>
<p>In this Q&A someone manage to overcome it with spark 2.0</p>
<p><a href="http://stackoverflow.com/questions/38669206/spark-2-0-relative-path-in-absolute-uri-spark-warehouse">Spark 2.0: Relative path in absolute URI (spark-warehouse)</a></p>
<hr>
<p>There are several issues in the question:</p>
<p>1) python access to local files in windows </p>
<pre><code>File = sc.textFile('file:///D:/Python/files/tit.csv')
File.count()
</code></pre>
<p>Can you please try:</p>
<pre><code>import os
inputfile = sc.textFile(os.path.normpath("file://D:/Python/files/tit.csv"))
inputfile.count()
</code></pre>
<p>os.path.normpath(path)</p>
<p>Normalize a pathname by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. This string manipulation may change the meaning of a path that contains symbolic links. On Windows, it converts forward slashes to backward slashes. To normalize case, use normcase().</p>
<p><a href="https://docs.python.org/2/library/os.path.html#os.path.normpath" rel="nofollow">https://docs.python.org/2/library/os.path.html#os.path.normpath</a></p>
<p>The output is:</p>
<pre><code>>>> os.path.normpath("file://D:/Python/files/tit.csv")
'file:\\D:\\Python\\files\\tit.csv'
</code></pre>
<p>2) scala code tested in python:</p>
<pre><code>val File = 'D:\\\Python\\files\\tit.csv'
SyntaxError: invalid syntax
</code></pre>
<p>This code doesn't run in python as it is scala code.</p>
| 1 |
2016-09-18T11:13:40Z
|
[
"python",
"apache-spark"
] |
Loading local file in sc.textFile
| 39,552,235 |
<p>I try to load a local file as below</p>
<pre><code>File = sc.textFile('file:///D:/Python/files/tit.csv')
File.count()
</code></pre>
<p>Full traceback</p>
<pre><code>IllegalArgumentException Traceback (most recent call last)
<ipython-input-72-a84ae28a29dc> in <module>()
----> 1 File.count()
/databricks/spark/python/pyspark/rdd.pyc in count(self)
1002 3
1003 """
-> 1004 return self.mapPartitions(lambda i: [sum(1 for _ in i)]).sum()
1005
1006 def stats(self):
/databricks/spark/python/pyspark/rdd.pyc in sum(self)
993 6.0
994 """
--> 995 return self.mapPartitions(lambda x: [sum(x)]).fold(0, operator.add)
996
997 def count(self):
/databricks/spark/python/pyspark/rdd.pyc in fold(self, zeroValue, op)
867 # zeroValue provided to each partition is unique from the one provided
868 # to the final reduce call
--> 869 vals = self.mapPartitions(func).collect()
870 return reduce(op, vals, zeroValue)
871
/databricks/spark/python/pyspark/rdd.pyc in collect(self)
769 """
770 with SCCallSiteSync(self.context) as css:
--> 771 port = self.ctx._jvm.PythonRDD.collectAndServe(self._jrdd.rdd())
772 return list(_load_from_socket(port, self._jrdd_deserializer))
773
/databricks/spark/python/lib/py4j-0.9-src.zip/py4j/java_gateway.py in __call__(self, *args)
811 answer = self.gateway_client.send_command(command)
812 return_value = get_return_value(
--> 813 answer, self.gateway_client, self.target_id, self.name)
814
815 for temp_arg in temp_args:
/databricks/spark/python/pyspark/sql/utils.pyc in deco(*a, **kw)
51 raise AnalysisException(s.split(': ', 1)[1], stackTrace)
52 if s.startswith('java.lang.IllegalArgumentException: '):
---> 53 raise IllegalArgumentException(s.split(': ', 1)[1], stackTrace)
54 raise
55 return deco
IllegalArgumentException: u'java.net.URISyntaxException: Expected scheme-specific part at index 2: D:'
</code></pre>
<p>what's wrong? I do usual way
for example
<a href="http://stackoverflow.com/questions/32064280/load-a-local-file-to-spark-using-sc-textfile">load a local file to spark using sc.textFile()</a>
or
<a href="http://stackoverflow.com/questions/27299923/how-to-load-local-file-in-sc-textfile-instead-of-hdfs">How to load local file in sc.textFile, instead of HDFS</a>
These examles are for scala but for python is thr same way if i don't mind</p>
<p>but </p>
<pre><code>val File = 'D:\\\Python\\files\\tit.csv'
SyntaxError: invalid syntax
File "<ipython-input-132-2a3878e0290d>", line 1
val File = 'D:\\\Python\\files\\tit.csv'
^
SyntaxError: invalid syntax
</code></pre>
| 1 |
2016-09-17T22:19:06Z
| 39,557,162 |
<p>I've done</p>
<pre><code>import os
os.path.normpath("file:///D:/Python/files/tit.csv")
Out[131]: 'file:/D:/Python/files/tit.csv'
</code></pre>
<p>then</p>
<pre><code>inputfile = sc.textFile(os.path.normpath("file:/D:/Python/files/tit.csv"))
inputfile.count()
IllegalArgumentException: u'java.net.URISyntaxException: Expected scheme-specific part at index 2: D:'
</code></pre>
<p>if i do like this</p>
<pre><code>inputfile = sc.textFile(os.path.normpath("file:\\D:\\Python\\files\\tit.csv"))
inputfile.count()
IllegalArgumentException: u'java.net.URISyntaxException: Relative path in absolute URI: file:%5CD:%5CPython%5Cfiles%5Ctit.csv'
</code></pre>
<p>and i did like this</p>
<pre><code>os.path.normcase("file:///D:/Python/files/tit.csv")
Out[136]: 'file:///D:/Python/files/tit.csv'
inputfile = sc.textFile(os.path.normpath("file:///D:/Python/files/tit.csv"))
inputfile.count()
IllegalArgumentException: u'java.net.URISyntaxException: Expected scheme-specific part at index 2: D:'
</code></pre>
| 0 |
2016-09-18T11:29:41Z
|
[
"python",
"apache-spark"
] |
Installing Python packages in command prompt not working well
| 39,552,257 |
<p>First, I'm very new to Python, and am having trouble getting any installs to work properly in command prompt. Here is the most recent example where, at the suggestion in the command prompt, I tried to upgrade to 'pip version 8.1.2', but got the messages indicated in the picture.</p>
<p><a href="http://i.stack.imgur.com/hqYyv.png" rel="nofollow">enter image description here</a></p>
| -1 |
2016-09-17T22:22:20Z
| 39,552,264 |
<p>As your Python is installed in Program Files (a protected directory), you'll need to run command prompt as an administrator.</p>
| 0 |
2016-09-17T22:23:35Z
|
[
"python"
] |
Unable to print wanted item from json api
| 39,552,276 |
<p>I'm trying to print the 'temp' item from a json urlfile. The problem is, I can't just type in <code>print(item['temp']</code>
If i do I get this error: </p>
<blockquote>
<p>TypeError: string indices must be integers</p>
</blockquote>
<p>So I figured I had to use an integer instead, which is what I did. But when it
prints out the result I got this:</p>
<p>"f
c"</p>
<p>This doesn't make any sense, doesn't matter what number I type in I get a result in the form of 2 letters.</p>
<p>Here's the code:</p>
<pre><code>import urllib.request
import json
url = urllib.request.urlopen("http://www.myweather2.com/developer/forecast.ashx?uac=fRnJKj3Xpi&output=json&query=SW1")
readurl = url.read()
json_obj = str(readurl, "utf-8")
data = json.loads(json_obj)
for item in data['weather']:
print(item[0])
</code></pre>
| -1 |
2016-09-17T22:25:31Z
| 39,552,456 |
<p><code>data['weather']</code> is a <em>dictionary</em>, and looping directly over a dictionary produces the keys in that dictionary. Here each key is a string; either <code>'curren_weather'</code> or <code>'forecast'</code>. As such, <code>item[0]</code> takes the first letter of each of these keys, so you end up printing <code>f</code> and <code>c</code>:</p>
<pre><code>>>> for item in data['weather']:
... print(item)
...
curren_weather
forecast
>>> for item in data['weather']:
... print(item[0])
...
c
f
</code></pre>
<p>I take it you want to print the <code>'temp'</code> key of the list of dictionaries in the list referenced by <code>curren_weather</code> instead:</p>
<pre><code>for curr in data['weather']['curren_weather']:
print(curr['temp'] + curr['temp_unit'])
</code></pre>
<p>I added the <code>temp_unit</code> value too; the above outputs:</p>
<pre><code>15c
</code></pre>
| 0 |
2016-09-17T22:49:22Z
|
[
"python",
"json",
"api",
"python-3.x",
"urllib"
] |
PyCharm ImportError: No module named googleapiclient
| 39,552,299 |
<p>I'm new to PyCharm and am trying to build/deploy a simple app to AppEngine. I've gone to PyCharm-->Preferences, clicked the Project Interpreter, and installed google-api-python-client which includes googleapiclient. However, when I run this app and load the page, it dies on this line:</p>
<pre><code>from googleapiclient import discovery
</code></pre>
<p>with this error:</p>
<pre><code>ImportError: No module named googleapiclient
</code></pre>
<p>I've dropped to PyCharm's CLI interpreter and run the same command where it runs fine, only when running as web app does it fail.</p>
<p>Have looked through the other folks having the same problem, and all the solutions talk about installing the package in the project interpreter, which I've already done, but it's still failing. Any help is appreciated.</p>
| 0 |
2016-09-17T22:29:10Z
| 39,558,553 |
<p>From the client library's <a href="https://developers.google.com/api-client-library/python/guide/google_app_engine#installation" rel="nofollow">Installation instructions</a>:</p>
<blockquote>
<p>For information on installing the source for the library into your App
Engine project, see the <a href="https://developers.google.com/api-client-library/python/start/installation#appengine" rel="nofollow">App Engine specific installation
instructions</a>.</p>
</blockquote>
<p>Which states:</p>
<blockquote>
<p>Because the Python client libraries are not installed in the <a href="https://cloud.google.com/appengine/docs/python/" rel="nofollow">App
Engine Python runtime environment</a>, they must be <a href="https://cloud.google.com/appengine/docs/python/tools/libraries27#vendoring" rel="nofollow">vendored into
your application</a> just like third-party libraries.</p>
</blockquote>
<p>The role of these instructions is to make the app itself self-contained and keep the dev server happy - they do not know (and should not need to know) how to read pycharm configs to run the code.</p>
| 0 |
2016-09-18T14:12:44Z
|
[
"python",
"google-app-engine",
"pycharm",
"google-api-client"
] |
Can't install pyethereum module
| 39,552,333 |
<p>I'm new in Ethereum, so probably that's a silly question.</p>
<p>Now I'm trying to install serpent and pyethereum according to this <a href="https://github.com/ethereum/wiki/wiki/Serpent" rel="nofollow">tutorial</a>. Everything works well, but when I'm launching Python's code:</p>
<pre><code>import serpent
import pyethereum
</code></pre>
<p>There is an error: <code>No module named pyethereum</code></p>
<p>How can I solve it?</p>
| 1 |
2016-09-17T22:32:45Z
| 39,552,445 |
<p>Follow the installation instructions from <a href="https://github.com/ethereum/pyethereum" rel="nofollow">Pytherium's Readme</a>, which read:</p>
<pre><code>git clone https://github.com/ethereum/pyethereum/
cd pyethereum
python setup.py install
</code></pre>
<p>In the tutorial's instructions, <code>develop</code> branch is used, which seems to be failing according to the continuous integration badges.</p>
| 1 |
2016-09-17T22:48:13Z
|
[
"python",
"ubuntu",
"ethereum"
] |
Can't install pyethereum module
| 39,552,333 |
<p>I'm new in Ethereum, so probably that's a silly question.</p>
<p>Now I'm trying to install serpent and pyethereum according to this <a href="https://github.com/ethereum/wiki/wiki/Serpent" rel="nofollow">tutorial</a>. Everything works well, but when I'm launching Python's code:</p>
<pre><code>import serpent
import pyethereum
</code></pre>
<p>There is an error: <code>No module named pyethereum</code></p>
<p>How can I solve it?</p>
| 1 |
2016-09-17T22:32:45Z
| 39,553,016 |
<p>The module's name is <code>ethereum</code>, not <code>pyethereum</code>. Using the following:</p>
<pre><code>import serpent
import ethereum
</code></pre>
<p>should work just fine.</p>
| 1 |
2016-09-18T00:34:54Z
|
[
"python",
"ubuntu",
"ethereum"
] |
How do I upload files to a specific folder in Django?
| 39,552,338 |
<p>After the user uploads 2 .ini files, I would like it to save both files inside the following folder.</p>
<p>MEDIA/uploadedconfigs/Printer/Plastic/</p>
<p>However, it's currently saving to the address below.</p>
<p>MEDIA/uploadedconfigs/None/</p>
<p><br></p>
<p>Below is the code that uploads the files. <br>
models.py</p>
<pre><code>def UploadedConfigPath(instance, filename):
return os.path.join('uploadedconfigs', str(instance.id), filename)
class ConfigFiles(models.Model):
Printer = models.CharField(_('Printer Model'),
max_length=100, blank=True, null=True, unique=False)
Plastic = models.CharField(_('Plastic'),
max_length=40, blank=True, null=True, unique=False)
creator = models.CharField(_('Creator'),
max_length=40, blank=True, null=True, unique=False)
HDConfig = models.FileField(_('High Detail'),
upload_to=UploadedConfigPath)
LDConfig = models.FileField(_('Low Detail'),
upload_to=UploadedConfigPath)
pub_date = models.DateTimeField(_('date_joined'),
default=timezone.now)
</code></pre>
<p>I'm not what "instance" is doing, but I was told it's what is spitting out the "None" folder name. I was also told I may need to place the files in a temporary folder but I'm not sure what that would entail. Any help would be appreciated! </p>
| 1 |
2016-09-17T22:33:55Z
| 39,552,420 |
<p>You could replace the function <code>UploadedConfigPath</code> with this :</p>
<pre><code>def UploadedConfigPath(instance, filename):
return os.path.join('uploadedconfigs', 'Printer', 'Plastic', filename)
</code></pre>
<p><strong>Edit :</strong></p>
<p>This should do it :</p>
<pre><code>def UploadedConfigPath(instance, filename):
return os.path.join('uploadedconfigs', instance.Printer, instance.Plastic, filename)
</code></pre>
| 1 |
2016-09-17T22:45:09Z
|
[
"python",
"django"
] |
How do I upload files to a specific folder in Django?
| 39,552,338 |
<p>After the user uploads 2 .ini files, I would like it to save both files inside the following folder.</p>
<p>MEDIA/uploadedconfigs/Printer/Plastic/</p>
<p>However, it's currently saving to the address below.</p>
<p>MEDIA/uploadedconfigs/None/</p>
<p><br></p>
<p>Below is the code that uploads the files. <br>
models.py</p>
<pre><code>def UploadedConfigPath(instance, filename):
return os.path.join('uploadedconfigs', str(instance.id), filename)
class ConfigFiles(models.Model):
Printer = models.CharField(_('Printer Model'),
max_length=100, blank=True, null=True, unique=False)
Plastic = models.CharField(_('Plastic'),
max_length=40, blank=True, null=True, unique=False)
creator = models.CharField(_('Creator'),
max_length=40, blank=True, null=True, unique=False)
HDConfig = models.FileField(_('High Detail'),
upload_to=UploadedConfigPath)
LDConfig = models.FileField(_('Low Detail'),
upload_to=UploadedConfigPath)
pub_date = models.DateTimeField(_('date_joined'),
default=timezone.now)
</code></pre>
<p>I'm not what "instance" is doing, but I was told it's what is spitting out the "None" folder name. I was also told I may need to place the files in a temporary folder but I'm not sure what that would entail. Any help would be appreciated! </p>
| 1 |
2016-09-17T22:33:55Z
| 39,552,422 |
<p>try to use original approach by setting parameter in settings.py</p>
<pre><code> MEDIA_ROOT = join(PROJECT_ROOT, '../media/')"
MEDIA_URL = '/media/'
</code></pre>
<p>In your file:</p>
<pre><code>def UploadedConfigPath(instance, filename):
return os.path.join(settings.MEDIA_ROOT, 'uploadedconfigs/', str(instance.id), '/', filename)
</code></pre>
| 2 |
2016-09-17T22:45:18Z
|
[
"python",
"django"
] |
Python sum() has a different result after importing numpy
| 39,552,458 |
<p>I came across this problem by Jake VanderPlas and I am not sure if my understanding of why the result differs after importing the numpy module is entirely correct.</p>
<pre><code>>>print(sum(range(5),-1)
>> 9
>> from numpy import *
>> print(sum(range(5),-1))
>> 10
</code></pre>
<p>It seems like in the first scenario the sum function calculates the sum over the iterable and then subtracts the second args value from the sum.</p>
<p>In the second scenario, after importing numpy, the behavior of the function seems to have modified as the second arg is used to specify the axis along which the sum should be performed.</p>
<p>Exercise number (24)
Source - <a href="http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html" rel="nofollow">http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html</a> </p>
| 2 |
2016-09-17T22:49:36Z
| 39,552,503 |
<p><em>"the behavior of the function seems to have modified as the second arg is used to specify the axis along which the sum should be performed."</em></p>
<p>You have basically answered your own question!</p>
<p>It is not technically correct to say that the behavior of the function has been <em>modified</em>. <code>from numpy import *</code> results in "shadowing" the <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow">builtin <code>sum</code> function</a> with the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sum.html" rel="nofollow">numpy <code>sum</code> function</a>, so when you use the name <code>sum</code>, Python finds the numpy version instead of the builtin version (see @godaygo's answer for more details). These are <em>different</em> functions, with different arguments. It is generally a bad idea to use <code>from somelib import *</code>, for exactly this reason. Instead, use <code>import numpy as np</code>, and then use <code>np.sum</code> when you want the numpy function, and plain <code>sum</code> when you want the Python builtin function.</p>
| 10 |
2016-09-17T22:55:55Z
|
[
"python",
"numpy",
"sum"
] |
Python sum() has a different result after importing numpy
| 39,552,458 |
<p>I came across this problem by Jake VanderPlas and I am not sure if my understanding of why the result differs after importing the numpy module is entirely correct.</p>
<pre><code>>>print(sum(range(5),-1)
>> 9
>> from numpy import *
>> print(sum(range(5),-1))
>> 10
</code></pre>
<p>It seems like in the first scenario the sum function calculates the sum over the iterable and then subtracts the second args value from the sum.</p>
<p>In the second scenario, after importing numpy, the behavior of the function seems to have modified as the second arg is used to specify the axis along which the sum should be performed.</p>
<p>Exercise number (24)
Source - <a href="http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html" rel="nofollow">http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html</a> </p>
| 2 |
2016-09-17T22:49:36Z
| 39,552,721 |
<p>Only to add my 5 pedantic coins to <a href="http://stackoverflow.com/a/39552503/6793085">@Warren Weckesser</a> answer. Really <code>from numpy import *</code> <strong>does not overwrite</strong> the <code>builtins</code> <code>sum</code> function, it only <strong>shadows</strong> <code>__builtins__.sum</code>, because <code>from ... import *</code> statement binds all names defined in the imported module, except those beginning with an underscore, to your current <code>global</code> namespace. And according to Python's name resolution rule (unofficialy <a href="http://stackoverflow.com/questions/291978/short-description-of-python-scoping-rules">LEGB</a> rule), the <code>global</code> namespace is looked up before <code>__builtins__</code> namespace. So if Python finds desired name, in your case <code>sum</code>, it returns you the binded object and does not look further.</p>
<p><strong>EDIT</strong>:
To show you what is going on:</p>
<pre><code> In[1]: print(sum, ' from ', sum.__module__) # here you see the standard `sum` function
Out[1]: <built-in function sum> from builtins
In[2]: from numpy import * # from here it is shadowed
print(sum, ' from ', sum.__module__)
Out[2]: <function sum at 0x00000229B30E2730> from numpy.core.fromnumeric
In[3]: del sum # here you restore things back
print(sum, ' from ', sum.__module__)
Out[3]: <built-in function sum> from builtins
</code></pre>
<p><strong><em>First note</em></strong>: <code>del</code> does not delete objects, it is a task of garbage collector, it only "dereference" the name-bindings and delete names from current namespace. </p>
<p><strong><em>Second note</em></strong>: the signature of built-in <code>sum</code> function is <code>sum(iterable[, start])</code>:</p>
<blockquote>
<p>Sums <code>start</code> and the items of an <code>iterable</code> from left to right and returns the total. <code>start</code> defaults to <code>0</code>. The iterableâs items are normally numbers, and the start value is not allowed to be a string.</p>
</blockquote>
<p>I your case <code>print(sum(range(5),-1)</code> for built-in <code>sum</code> summation starts with -1. So technically, your phrase <s>the sum over the iterable and then subtracts the second args value from the sum</s> isn't correct. For numbers it's really does not matter to <em>start with</em> or <em>add/subtract</em> later. But for lists it does (<em>silly example only to show the idea</em>):</p>
<pre><code> In[1]: sum([[1], [2], [3]], [4])
Out[1]: [4, 1, 2, 3] # not [1, 2, 3, 4]
</code></pre>
<p>Hope this will clarify your thoughts :)</p>
| 6 |
2016-09-17T23:36:44Z
|
[
"python",
"numpy",
"sum"
] |
Exercise python: how to group element in a list?
| 39,552,491 |
<p>I've tried to solve the following exercise, without using datetime!</p>
<p>Exercise:</p>
<blockquote>
<p>Given a list of int, such that the First three int represent a date,
the second three elementi represent a date etc..modify lst by grouping
every triple in One string with the numbers separeted by "/".</p>
</blockquote>
<p>Example:</p>
<pre><code>lst = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000]
groupd(lst)
lst
['1/2/2013', '23/9/2011', '10/11/2000']
</code></pre>
<p>My attempt:</p>
<pre><code>lst = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000].
stri = str(lst).
def groupd(lst):.
cont = 1.
a = (stri.replace(',', '/')).
for x in lst:.
if len[x]>2:.
lst.insert(lst[0],a )].
print(a).
print(groupd(lst)).
</code></pre>
<p>PS: sorry for my english!! Thank you all!</p>
| -1 |
2016-09-17T22:53:51Z
| 39,552,518 |
<p>You can use <code>zip</code> to create tuples and then format them to your strings:</p>
<pre><code>>>> ['%d/%d/%d' % parts for parts in zip(lst[::3], lst[1::3], lst[2::3])]
['1/2/2013', '23/9/2011', '10/11/2000']
</code></pre>
<p>Starting from an offset (first argument to slicing) while skipping items (third argument to slicing) allows for windowing behavior.</p>
<p>More generically:</p>
<pre><code>>>> N = 3
>>> ['/'.join(['%d'] * N) % parts for parts in zip(*[lst[start::N] for start in range(N)])]
['1/2/2013', '23/9/2011', '10/11/2000']
</code></pre>
| 2 |
2016-09-17T22:58:53Z
|
[
"python",
"list"
] |
Exercise python: how to group element in a list?
| 39,552,491 |
<p>I've tried to solve the following exercise, without using datetime!</p>
<p>Exercise:</p>
<blockquote>
<p>Given a list of int, such that the First three int represent a date,
the second three elementi represent a date etc..modify lst by grouping
every triple in One string with the numbers separeted by "/".</p>
</blockquote>
<p>Example:</p>
<pre><code>lst = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000]
groupd(lst)
lst
['1/2/2013', '23/9/2011', '10/11/2000']
</code></pre>
<p>My attempt:</p>
<pre><code>lst = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000].
stri = str(lst).
def groupd(lst):.
cont = 1.
a = (stri.replace(',', '/')).
for x in lst:.
if len[x]>2:.
lst.insert(lst[0],a )].
print(a).
print(groupd(lst)).
</code></pre>
<p>PS: sorry for my english!! Thank you all!</p>
| -1 |
2016-09-17T22:53:51Z
| 39,552,542 |
<p>You can group the list by it's index using <code>groupby</code> from <code>itertools</code>:</p>
<pre><code>from itertools import groupby
['/'.join(str(i[1]) for i in g) for _, g in groupby(enumerate(lst), key = lambda x: x[0]/3)]
# ['1/2/2013', '23/9/2011', '10/11/2000']
</code></pre>
| 1 |
2016-09-17T23:03:07Z
|
[
"python",
"list"
] |
Exercise python: how to group element in a list?
| 39,552,491 |
<p>I've tried to solve the following exercise, without using datetime!</p>
<p>Exercise:</p>
<blockquote>
<p>Given a list of int, such that the First three int represent a date,
the second three elementi represent a date etc..modify lst by grouping
every triple in One string with the numbers separeted by "/".</p>
</blockquote>
<p>Example:</p>
<pre><code>lst = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000]
groupd(lst)
lst
['1/2/2013', '23/9/2011', '10/11/2000']
</code></pre>
<p>My attempt:</p>
<pre><code>lst = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000].
stri = str(lst).
def groupd(lst):.
cont = 1.
a = (stri.replace(',', '/')).
for x in lst:.
if len[x]>2:.
lst.insert(lst[0],a )].
print(a).
print(groupd(lst)).
</code></pre>
<p>PS: sorry for my english!! Thank you all!</p>
| -1 |
2016-09-17T22:53:51Z
| 39,552,592 |
<p>This is more of a functional approach where the answer is passed around with the recursive function. </p>
<pre><code>lst1 = [1, 2, 2013, 23, 9, 2011, 10, 11, 2000]
lst2 = []
lst3 = [1,2, 2015]
lst4 = [1,2]
lst5 = [1]
lst6 = [1,2,2013, 23, 9]
def groupToDate(lst, acc):
if len(lst) < 3:
return acc
else:
# take first elements in list
day = lst[0]
month = lst[1]
year = lst[2]
acc.append(str(day) + '/' + str(month) + '/' + str(year))
return groupToDate(lst[3:len(lst)], acc)
print(groupToDate(lst1, []))
print(groupToDate(lst2, []))
print(groupToDate(lst3, []))
print(groupToDate(lst4, []))
print(groupToDate(lst5, []))
print(groupToDate(lst6, []))
</code></pre>
<p>It's also the basic approach of solving such problem if you don't want to use list comprehensions or groupby</p>
| 0 |
2016-09-17T23:11:25Z
|
[
"python",
"list"
] |
16 bit hex into 14 bit signed int python?
| 39,552,549 |
<p>I get a 16 bit Hex number (so 4 digits) from a sensor and want to convert it into a signed integer so I can actually use it.
There are plenty of codes on the internet that get the job done, but with this sensor it is a bit more arkward.</p>
<p>In fact, the number has only 14 bit, the first two (from the left) are irrelevant.
I tried to do it (in Python 3) but failed pretty hard.
Any suggestions how to "cut" the first two digits of the number and then make the rest a signed integer?
The Datasheet says, that E002 should be -8190 ane 1FFE should be +8190.</p>
<p>Thanks a lot!</p>
| 0 |
2016-09-17T23:04:40Z
| 39,552,600 |
<p>There is a general algorithm for sign-extending a two's-complement integer value <code>val</code> whose number of bits is <code>nbits</code> (so that the top-most of those bits is the sign bit).</p>
<p>That algorithm is:</p>
<ol>
<li>treat the value as a non-negative number, and if needed, mask off additional bits</li>
<li>invert the sign bit, still treating the result as a non-negative number</li>
<li>subtract the numeric value of the sign bit considered as a non-negative number, producing as a result, a <em>signed</em> number.</li>
</ol>
<p>Expressing this algorithm in Python produces:</p>
<pre><code>from __future__ import print_function
def sext(val, nbits):
assert nbits > 0
signbit = 1 << (nbits - 1)
mask = (1 << nbits) - 1
return ((val & mask) ^ signbit) - signbit
if __name__ == '__main__':
print('sext(0xe002, 14) =', sext(0xe002, 14))
print('sext(0x1ffe, 14) =', sext(0x1ffe, 14))
</code></pre>
<p>which when run shows the desired results:</p>
<pre><code>sext(0xe002, 14) = -8190
sext(0x1ffe, 14) = 8190
</code></pre>
| 1 |
2016-09-17T23:12:48Z
|
[
"python",
"cut",
"bits",
"data-conversion"
] |
16 bit hex into 14 bit signed int python?
| 39,552,549 |
<p>I get a 16 bit Hex number (so 4 digits) from a sensor and want to convert it into a signed integer so I can actually use it.
There are plenty of codes on the internet that get the job done, but with this sensor it is a bit more arkward.</p>
<p>In fact, the number has only 14 bit, the first two (from the left) are irrelevant.
I tried to do it (in Python 3) but failed pretty hard.
Any suggestions how to "cut" the first two digits of the number and then make the rest a signed integer?
The Datasheet says, that E002 should be -8190 ane 1FFE should be +8190.</p>
<p>Thanks a lot!</p>
| 0 |
2016-09-17T23:04:40Z
| 39,552,656 |
<p>Let's define a conversion function:</p>
<pre><code>>>> def f(x):
... r = int(x, 16)
... return r if r < 2**15 else r - 2**16
...
</code></pre>
<p>Now, let's test the function against the values that the datahsheet provided:</p>
<pre><code>>>> f('1FFE')
8190
>>> f('E002')
-8190
</code></pre>
<p>The usual convention for signed numbers is that a number is negative if the high bit is set and positive if it isn't. Following this convention, '0000' is zero and 'FFFF' is -1. The issue is that <code>int</code> assumes that a number is positive and we have to correct for that:</p>
<ul>
<li><p>For any number equal to or less than <code>0x7FFF</code>, then high bit is unset and the number is positive. Thus we return <code>r=int(x,16)</code> if r<2**15.</p></li>
<li><p>For any number <code>r-int(x,16)</code> that is equal to or greater than <code>0x8000</code>, we return <code>r - 2**16</code>.</p></li>
<li><p>While your sensor may only produce 14-bin data, the manufacturer is following the standard convention for 16-bit integers.</p></li>
</ul>
<h3>Alternative</h3>
<p>Instead of converting <code>x</code> to <code>r</code> and testing the value of <code>r</code>, we can directly test whether the high bit in <code>x</code> is set:</p>
<pre><code>>>> def g(x):
... return int(x, 16) if x[0] in '01234567' else int(x, 16) - 2**16
...
>>> g('1FFE')
8190
>>> g('E002')
-8190
</code></pre>
<h3>Ignoring the upper bits</h3>
<p>Let's suppose that the manufacturer is not following standard conventions and that the upper 2-bits are unreliable. In this case, we can use modulo, <code>%</code>, to remove them and, after adjusting the other constants as appropriate for 14-bit integers, we have:</p>
<pre><code>>>> def h(x):
... r = int(x, 16) % 2**14
... return r if r < 2**13 else r - 2**14
...
>>> h('1FFE')
8190
>>> h('E002')
-8190
</code></pre>
| 2 |
2016-09-17T23:23:26Z
|
[
"python",
"cut",
"bits",
"data-conversion"
] |
Extract multiple substrings from a file and list them in another place using python/shell
| 39,552,662 |
<p>I've got a log file similar to below:</p>
<pre><code>/* BUG: axiom too complex: SubClassOf(ObjectOneOf([NamedIndividual(http://www.sem.org/sina/onto/2015/7/TSB-GCL#t_Xi_xi)]),DataHasValue(DataProperty(http://www.code.org/onto/ont.owl#XoX_type),^^(periodic,http://www.mdos.org/1956/21/2-rdf-syntax-ns#PlainLiteral))) */
/* BUG: axiom too complex: SubClassOf(ObjectOneOf([NamedIndividual(http://www.sem.org/sina/onto/2015/7/TSB-GCL#t_Ziz)]),DataHasValue(DataProperty(http://www.co-ode.org/ontologies/ont.owl#YoY_type),^^(latency,http://www.w3.org/1956/01/11-rdf-syntax-ns#PlainLiteral))) */
....
</code></pre>
<p>I want to extract the fields of <em>t_Xi_xi</em>, <em>t_Ziz</em> ,<em>XoX_type</em> and <em>YoY_type</em> and also the values after <em>^^(</em> which in this case are <em>latency</em> and <em>periodic</em>.</p>
<p>Note: There are different alphabetic values for each <em>X</em> and <em>Y</em> in the file (e.g. X="sina" Y="Boom" so --> t_Xi_xi ~ t_Sina_sina) so I guess using the regex would be a better choice.</p>
<p>So the final result must be something like below:</p>
<pre><code>t_Xi_xi XoX_type periodic
t_Ziz YoY_type latency
</code></pre>
<p>I've tried the regex below to extract them and hopefully to be able to replace the rest of it to " " in the file with the help of <em>sed</em> in shell, but I failed.</p>
<pre><code>([a-zA-Z]_[a-zA-Z]*_[a-zA-Z]*)|(\#[a-zA-Z]*_[a-zA-Z]*)|(\^\([a-zA-Z]*)+
</code></pre>
<p>Any kind of help is appreciated on how to do this in Python (or even shell itself).</p>
| 0 |
2016-09-17T23:24:46Z
| 39,552,763 |
<pre><code>$ awk -F'#|\\^\\^\\(' '{for (i=2; i<NF; i++) printf "%s%s", gensub(/[^[:alnum:]_].*/,"",1,$i), (i<(NF-1) ? OFS : ORS) }' file
t_Xi_xi XoX_type periodic
t_Ziz YoY_type latency
</code></pre>
<p>The above uses GNU awk for gensub(), with other awks you'd use sub() and a separate printf statement.</p>
| 1 |
2016-09-17T23:44:04Z
|
[
"python",
"string",
"shell",
"sed",
"substring"
] |
threading.Lock() performance issues
| 39,552,670 |
<p>I have multiple threads:</p>
<pre><code>dispQ = Queue.Queue()
stop_thr_event = threading.Event()
def worker (stop_event):
while not stop_event.wait(0):
try:
job = dispQ.get(timeout=1)
job.waitcount -= 1
dispQ.task_done()
except Queue.Empty, msg:
continue
# create job objects and put into dispQ here
for j in range(NUM_OF_JOBS):
j = Job()
dispQ.put(j)
# NUM_OF_THREADS could be 10-20 ish
running_threads = []
for t in range(NUM_OF_THREADS):
t1 = threading.Thread( target=worker, args=(stop_thr_event,) )
t1.daemon = True
t1.start()
running_threads.append(t1)
stop_thr_event.set()
for t in running_threads:
t.join()
</code></pre>
<p>The code above was giving me some very strange behavior.
I've ended up finding out that it was due to decrementing waitcount with out a lock</p>
<p>I 've added an attribute to Job class <code>self.thr_lock = threading.Lock()</code>
Then I've changed it to</p>
<pre><code>with job.thr_lock:
job.waitcount -= 1
</code></pre>
<p>This seems to fix the strange behavior but it looks like it has degraded in performance.</p>
<p>Is this expected? is there way to optimize locking?<br>
Would it be better to have one global lock rather than one lock per job object?</p>
| 0 |
2016-09-17T23:25:39Z
| 39,552,982 |
<p>About the only way to "optimize" threading would be to break the processing down in blocks or chunks of work that can be performed at the same time. This mostly means doing input or output (I/O) because that is the only time the interpreter will release the Global Interpreter Lock, aka the GIL.</p>
<p>In actuality there is often no gain or even a net slow-down when threading is added due to the overhead of using it unless the above condition is met.</p>
<p>It would probably be worse if you used a single global lock for all the shared resources because it would make parts of the program wait when they really didn't need to do so since it wouldn't distinguish what resource was needed so unnecessary waiting would occur.</p>
<p>You might find the PyCon 2015 talk David Beasley gave titled <a href="https://www.youtube.com/watch?v=MCs5OvhV9S4" rel="nofollow"><em>Python Concurrency From the Ground Up</em></a> of interest. It covers threads, event loops, and coroutines.</p>
| 1 |
2016-09-18T00:25:13Z
|
[
"python",
"multithreading"
] |
threading.Lock() performance issues
| 39,552,670 |
<p>I have multiple threads:</p>
<pre><code>dispQ = Queue.Queue()
stop_thr_event = threading.Event()
def worker (stop_event):
while not stop_event.wait(0):
try:
job = dispQ.get(timeout=1)
job.waitcount -= 1
dispQ.task_done()
except Queue.Empty, msg:
continue
# create job objects and put into dispQ here
for j in range(NUM_OF_JOBS):
j = Job()
dispQ.put(j)
# NUM_OF_THREADS could be 10-20 ish
running_threads = []
for t in range(NUM_OF_THREADS):
t1 = threading.Thread( target=worker, args=(stop_thr_event,) )
t1.daemon = True
t1.start()
running_threads.append(t1)
stop_thr_event.set()
for t in running_threads:
t.join()
</code></pre>
<p>The code above was giving me some very strange behavior.
I've ended up finding out that it was due to decrementing waitcount with out a lock</p>
<p>I 've added an attribute to Job class <code>self.thr_lock = threading.Lock()</code>
Then I've changed it to</p>
<pre><code>with job.thr_lock:
job.waitcount -= 1
</code></pre>
<p>This seems to fix the strange behavior but it looks like it has degraded in performance.</p>
<p>Is this expected? is there way to optimize locking?<br>
Would it be better to have one global lock rather than one lock per job object?</p>
| 0 |
2016-09-17T23:25:39Z
| 39,564,266 |
<p>It's hard to answer your question based on your code. Locks do have some inherent cost, nothing is free, but normally it is quite small. If your jobs are very small, you might want to consider "chunking" them, that way you have many fewer acquire/release calls relative to the amount of work being done by each thread.</p>
<p>A related but separate issue is one of threads blocking each other. You might notice large performance issues if many threads are waiting on the same lock(s). Here your threads are sitting idle waiting on each other. In some cases this cannot be avoided because there is a shared resource which is a performance bottlenecking. In other cases you can re-organize your code to avoid this performance penalty.</p>
<p>There are some things in your example code that make me thing that it might be very different from actual application. First, your example code doesn't share job objects between threads. If you're not sharing job objects you shouldn't need locks on them. Second, as written your example code might not empty the queue before finishing. It will exit as soon as you hit <code>stop_thr_event.set()</code> leaving any remaining jobs in queue, is this by design?</p>
| 1 |
2016-09-19T01:42:26Z
|
[
"python",
"multithreading"
] |
Printing a X using * in Python
| 39,552,673 |
<p>I have to write a python program which allows a user to input an odd integer, n, greater than or equal to three. The program outputs an x with n rows and n columns. *My professor said using nested for loops would be ideal for this. The X is printed using *'s *</p>
<p>I have been experimenting over the past couple days and have had little success.
This is my starting code for the program and after that it's just blank, like my mind. If you could provide some explanation as to how the code works that would be amazing. </p>
<p><code>num=int(input("Please type in an odd integer."))
if num%2==0:
print("Your number is incorrect")</code></p>
| 1 |
2016-09-17T23:26:07Z
| 39,552,715 |
<p>I'll give you a hint :</p>
<pre><code>n = int(input("Please type in an odd integer."))
for i in range(n):
print('x', end='')
print()
</code></pre>
<p>This prints a x, n times on the same line and then go back to next line.</p>
<p>I'll let you figure out how you print this same line n times.</p>
| 0 |
2016-09-17T23:35:35Z
|
[
"python",
"for-loop",
"nested-loops"
] |
Printing a X using * in Python
| 39,552,673 |
<p>I have to write a python program which allows a user to input an odd integer, n, greater than or equal to three. The program outputs an x with n rows and n columns. *My professor said using nested for loops would be ideal for this. The X is printed using *'s *</p>
<p>I have been experimenting over the past couple days and have had little success.
This is my starting code for the program and after that it's just blank, like my mind. If you could provide some explanation as to how the code works that would be amazing. </p>
<p><code>num=int(input("Please type in an odd integer."))
if num%2==0:
print("Your number is incorrect")</code></p>
| 1 |
2016-09-17T23:26:07Z
| 39,552,934 |
<p>This should do it:</p>
<p><strong>Python 2</strong></p>
<pre><code>N = 5
for i in range(N):
for j in range(N):
if (i == j) or ((N - j -1) == i):
print '*',
else:
print ' ',
print ''
</code></pre>
<p><strong>Python 3</strong></p>
<pre><code>N = 5
for i in range(N):
for j in range(N):
if (i == j) or ((N - j -1) == i):
print('*', end = '')
else:
print(' ', end = '')
print('')
</code></pre>
<p>(thanks to Blckknght for Python 3 knowledge)</p>
<p>You're looping through all the rows in the outer loop, then all the columns or cells in the inner. The if clause checks whether you're on a diagonal. The comma after the print statement ensures you don't get a new line every print. The 3rd print gives you a new line once you're finished with that row.</p>
<p>If this is helpful / works for you; try making a Y using the same approach and post your code in the comments below. That way you could develop your understanding a bit more. </p>
| 0 |
2016-09-18T00:16:50Z
|
[
"python",
"for-loop",
"nested-loops"
] |
Printing a X using * in Python
| 39,552,673 |
<p>I have to write a python program which allows a user to input an odd integer, n, greater than or equal to three. The program outputs an x with n rows and n columns. *My professor said using nested for loops would be ideal for this. The X is printed using *'s *</p>
<p>I have been experimenting over the past couple days and have had little success.
This is my starting code for the program and after that it's just blank, like my mind. If you could provide some explanation as to how the code works that would be amazing. </p>
<p><code>num=int(input("Please type in an odd integer."))
if num%2==0:
print("Your number is incorrect")</code></p>
| 1 |
2016-09-17T23:26:07Z
| 39,554,568 |
<p>Using single for loop:</p>
<pre><code>for i in range(num):
a = [' '] * num
a[i] = '*'
a[num-i-1] = '*'
print(''.join(a))
</code></pre>
<p>Using nested for loops:</p>
<pre><code>for i in range(num):
s = ''
for j in range(num):
if j in [i, num-i-1]:
s += '*'
else:
s += ' '
print(s)
</code></pre>
| 0 |
2016-09-18T05:50:22Z
|
[
"python",
"for-loop",
"nested-loops"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.