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 |
---|---|---|---|---|---|---|---|---|---|
Using logistic regression to predict the parameter value
| 39,444,955 |
<p>I have written vary basic sklearn code using logistic regression to predict the value. </p>
<p>Training data looks like - </p>
<p><a href="https://gist.github.com/anonymous/563591e0395e8d988277d3ce63d7438f" rel="nofollow">https://gist.github.com/anonymous/563591e0395e8d988277d3ce63d7438f</a></p>
<pre><code>date hr_of_day vals
01/05/2014 9 929
01/05/2014 10 942
01/05/2014 11 968
01/05/2014 12 856
01/05/2014 13 835
01/05/2014 14 885
01/05/2014 15 945
01/05/2014 16 924
01/05/2014 17 914
01/05/2014 18 744
01/05/2014 19 377
01/05/2014 20 219
01/05/2014 21 106
</code></pre>
<p>and I have selected first 8 items from training data to just validate the classifier which is </p>
<p>I want to predict the value of <code>vals</code>, in testing data, I have put it as <code>0</code>. Is that correct?</p>
<pre><code>date hr_of_day vals
2014-05-01 0 0
2014-05-01 1 0
2014-05-01 2 0
2014-05-01 3 0
2014-05-01 4 0
2014-05-01 5 0
2014-05-01 6 0
2014-05-01 7 0
</code></pre>
<p>My model code, works fine. But my result looks trange. I was expecting value of <code>vals</code> in result. Rather then that, I am getting large matrix with all element value as <code>0.00030676</code>.</p>
<p>I appreciate if someone can give details or help me to play better with this result.</p>
<pre><code>import pandas as pd
from sklearn import datasets
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from datetime import datetime, date, timedelta
Train = pd.read_csv("data_scientist_assignment.tsv", sep='\t', parse_dates=['date'])
Train['timestamp'] = Train.date.values.astype(pd.np.int64)
x1=["timestamp", "hr_of_day"]
test=pd.read_csv("test.tsv", sep='\t', parse_dates=['date'])
test['timestamp'] = test.date.values.astype(pd.np.int64)
print(Train.columns)
print(test.columns)
model = LogisticRegression()
model.fit(Train[x1], Train["vals"])
print(model)
print model.score(Train[x1], Train["vals"])
print model.predict_proba(test[x1])
</code></pre>
<p>results looks like this:</p>
<pre><code>In [92]: print(model)
LogisticRegression(C=1.0, class_weight=None, dual=False, fit_intercept=True,
intercept_scaling=1, max_iter=100, multi_class='ovr', n_jobs=1,
penalty='l2', random_state=None, solver='liblinear', tol=0.0001,
verbose=0, warm_start=False)
In [93]: print model.score(Train[x1], Train["vals"])
0.00520833333333
In [94]:
In [94]: print model.predict_proba(test[x1])
[[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]
[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]
[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]
...,
[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]
[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]
[ 0.00030676 0.00030676 0.00030676 ..., 0.00030889 0.00030885
0.00030902]]
</code></pre>
| 0 |
2016-09-12T07:05:21Z
| 39,469,278 |
<p>Use following code to get predicted labels:</p>
<pre><code>predicted_labels= model.predict(test[x1])
</code></pre>
<p>Also try following example to understand logistic regression in sklearn:</p>
<pre><code># Logistic Regression
from sklearn import datasets
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
# load the iris datasets
dataset = datasets.load_iris()
# fit a logistic regression model to the data
model = LogisticRegression()
model.fit(dataset.data, dataset.target)
print(model)
# make predictions
expected = dataset.target
predicted = model.predict(dataset.data)
# summarize the fit of the model
print(metrics.classification_report(expected, predicted))
print(metrics.confusion_matrix(expected, predicted))
</code></pre>
<p>Example source: <a href="http://machinelearningmastery.com/get-your-hands-dirty-with-scikit-learn-now/" rel="nofollow">http://machinelearningmastery.com/get-your-hands-dirty-with-scikit-learn-now/</a></p>
| 1 |
2016-09-13T11:47:22Z
|
[
"python",
"machine-learning",
"scikit-learn",
"classification",
"logistic-regression"
] |
Python Tkinter in Docker .TclError: couldn't connect to display
| 39,445,047 |
<p>I am new to python and am trying to build a small app. It needs to be a GUI app and I was wanting to containerise it with docker. I am getting the following error and can not find a solution</p>
<pre><code>No protocol specified
No protocol specified
Traceback (most recent call last):
File "tkinker.py", line 7, in <module>
tinker = Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1818, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display ":0.0"
</code></pre>
<p>It starts locally but wont start in docker. My OS is Xubuntu.</p>
<p>I have created a sample app (below), see run-test.sh <a href="https://github.com/jeremysells/test/tree/master/docker-tkinter" rel="nofollow">https://github.com/jeremysells/test/tree/master/docker-tkinter</a></p>
| 2 |
2016-09-12T07:11:56Z
| 39,445,113 |
<p>As <a href="https://hub.docker.com/r/dorakorpar/nsgui/" rel="nofollow">described here</a>, you would need an X11 graphic layer.<br>
But since you are already on an '(X)Ubuntu, setting the DISPLAY should be enough:</p>
<pre><code>export DISPLAY=127.0.0.1:0.0
docker run -it -e DISPLAY=$DISPLAY -v /tmp/.X11-unix:/tmp/.X11-unix yourImage
</code></pre>
<p>Check also <a href="http://stackoverflow.com/a/25280523/6309">XAuthority</a>.</p>
| 1 |
2016-09-12T07:16:20Z
|
[
"python",
"ubuntu",
"docker",
"tkinter",
"xfce"
] |
Python Tkinter in Docker .TclError: couldn't connect to display
| 39,445,047 |
<p>I am new to python and am trying to build a small app. It needs to be a GUI app and I was wanting to containerise it with docker. I am getting the following error and can not find a solution</p>
<pre><code>No protocol specified
No protocol specified
Traceback (most recent call last):
File "tkinker.py", line 7, in <module>
tinker = Tk()
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1818, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: couldn't connect to display ":0.0"
</code></pre>
<p>It starts locally but wont start in docker. My OS is Xubuntu.</p>
<p>I have created a sample app (below), see run-test.sh <a href="https://github.com/jeremysells/test/tree/master/docker-tkinter" rel="nofollow">https://github.com/jeremysells/test/tree/master/docker-tkinter</a></p>
| 2 |
2016-09-12T07:11:56Z
| 39,445,114 |
<p>You'll have to set DISPLAY in the container. You can add it as an argument to the docker run command like this:</p>
<pre><code>docker run -ti -e DISPLAY=$DISPLAY blah-image blah-command
</code></pre>
<p>DISPLAY should be set in the Xubuntu shell you are running the command from.</p>
| 1 |
2016-09-12T07:16:29Z
|
[
"python",
"ubuntu",
"docker",
"tkinter",
"xfce"
] |
How do I properly combine numerical features with text (bag of words) in scikit-learn?
| 39,445,051 |
<p>I am writing a classifier for web pages, so I have a mixture of numerical features, and I also want to classify the text. I am using the bag-of-words approach to transform the text into a (large) numerical vector. The code ends up being like this:</p>
<pre><code>from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
import numpy as np
numerical_features = [
[1, 0],
[1, 1],
[0, 0],
[0, 1]
]
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one',
'Is this the first document?',
]
bag_of_words_vectorizer = CountVectorizer(min_df=1)
X = bag_of_words_vectorizer.fit_transform(corpus)
words_counts = X.toarray()
tfidf_transformer = TfidfTransformer()
tfidf = tfidf_transformer.fit_transform(words_counts)
bag_of_words_vectorizer.get_feature_names()
combinedFeatures = np.hstack([numerical_features, tfidf.toarray()])
</code></pre>
<p>This works, but I'm concerned about the accuracy. Notice that there are 4 objects, and only two numerical features. Even the simplest text results in a vector with nine features (because there are nine distinct words in the corpus). Obviously, with real text, there will be hundreds, or thousands of distinct words, so the final feature vector would be < 10 numerical features but > 1000 words based ones.</p>
<p>Because of this, won't the classifier (SVM) be heavily weighting the words over the numerical features by a factor of 100 to 1? If so, how can I compensate to make sure the bag of words is weighted equally against the numerical features?</p>
| 0 |
2016-09-12T07:12:03Z
| 39,446,018 |
<p>You can weight the counts by using the <a href="http://scikit-learn.org/stable/modules/feature_extraction.html#tfidf-term-weighting" rel="nofollow">Tfâidf</a>:</p>
<pre><code>import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
np.set_printoptions(linewidth=200)
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one',
'Is this the first document?',
]
vectorizer = CountVectorizer(min_df=1)
X = vectorizer.fit_transform(corpus)
words = vectorizer.get_feature_names()
print(words)
words_counts = X.toarray()
print(words_counts)
transformer = TfidfTransformer()
tfidf = transformer.fit_transform(words_counts)
print(tfidf.toarray())
</code></pre>
<p>The output is this:</p>
<pre><code># words
[u'and', u'document', u'first', u'is', u'one', u'second', u'the', u'third', u'this']
# words_counts
[[0 1 1 1 0 0 1 0 1]
[0 1 0 1 0 2 1 0 1]
[1 0 0 0 1 0 1 1 0]
[0 1 1 1 0 0 1 0 1]]
# tfidf transformation
[[ 0. 0.43877674 0.54197657 0.43877674 0. 0. 0.35872874 0. 0.43877674]
[ 0. 0.27230147 0. 0.27230147 0. 0.85322574 0.22262429 0. 0.27230147]
[ 0.55280532 0. 0. 0. 0.55280532 0. 0.28847675 0.55280532 0. ]
[ 0. 0.43877674 0.54197657 0.43877674 0. 0. 0.35872874 0. 0.43877674]]
</code></pre>
<p>With this representation you should be able to merge further binary features to train a <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html" rel="nofollow">SVC</a>.</p>
| 0 |
2016-09-12T08:19:35Z
|
[
"python",
"scikit-learn",
"classification",
"text-classification"
] |
Pandas INT column datatype changes depending on how the data is called (BUG?)
| 39,445,080 |
<p>I have a dataframe <code>XY</code> with two columns, one is an integer column, the other one a float column.</p>
<p>The integer column is called <code>Count</code> (with a capital C to avoid problems) and its unique values are these:</p>
<pre><code>XY["Count"].unique()
array([ 38, 7, 1, 13, 3, 28, 5, 6, 4, 11, 9, 2, 8,
22, 12, 15, 20, 17, 18, 10, 40, 14, 16, 24, 25, 39,
81, 19, 21, 110, 88, 23, 29, 46, 26, 32, 36, 43, 96,
34, 47, 61, 35, 56, 41, 33, 30, 53, 27, 54, 37, 65,
31, 52, 42, 93, 76, 57, 49, 71, 48, 77, 50, 84, 44,
69, 75, 58, 60, 55, 72, 536, 67, 80, 64, 82, 101, 99,
104, 68, 45, 66, 87, 90, 78, 74, 62, 73, 63, 86, 108,
105, 197, 118, 209, 70, 59, 98, 97, 94, 79, 89, 51, 83,
85, 221, 322, 164, 116, 103, 107, 102, 143, 91, 95, 92, 120,
188, 148, 106, 179, 124, 165, 122, 113, 119, 169, 109, 138, 123,
121, 125, 129, 177, 137, 206, 127, 115, 111, 131, 117, 128, 100,
126, 163, 133, 186, 114, 203, 135, 141, 227, 162], dtype=int64)
</code></pre>
<p>As you can see it's only integers and <code>numpy</code> interprets it correctly as <code>int64</code>.</p>
<p>Now lets look at extracting a single value:</p>
<pre><code>XY["Count"][0]
38
XY["Count"][0].dtype
numpy.int32
XY.ix[0,"Count"]
38
XY.ix[0,"Count"].dtype
numpy.int32
</code></pre>
<p>So direct indexing and <code>ix</code> with column label give back <code>int32</code>.</p>
<pre><code>XY.loc[0,"Count"]
38.0
XY.loc[0,"Count"].dtype
numpy.float64
XY.ix[0,0]
38.0
XY.ix[0,0].dtype
numpy.float64
XY.iloc[0,0]
38.0
XY.iloc[0,0].dtype
numpy.float64
</code></pre>
<p>But <code>loc</code>, <code>iloc</code>, and index-based <code>ix</code> report the format as <code>float64</code>.</p>
<p>Now when I'm directly extracting the values from the internal <code>numpy</code> array, it's also a <code>float64</code>. Remember that my second column is a float column.</p>
<pre><code>XY.values[0,0]
38.0
XY.values[0,0].dtype
numpy.float64
</code></pre>
<p>I don't know if I'm missing something, but this is really inconsistent and causes problems since I need to specifically return the data in integer format. I presume it's a bug.</p>
<p>EDIT 1:</p>
<p>When testing with a dataframe that has ONLY the integer column every method returned <code>int32</code>, so it seems the problem comes from the second column and inconsistent internal data conversion.</p>
| 1 |
2016-09-12T07:14:02Z
| 39,446,361 |
<p>I think you get back a float because each row of your dataframe contains a mix of integer and float types. Upon selecting a row index with <code>ix</code> or <code>loc</code>, integers are being converted to floats. To get around this, you could use loc to select from just the required column and not the whole dataframe: </p>
<pre><code>XY['Count'].loc[4]
</code></pre>
| 0 |
2016-09-12T08:41:05Z
|
[
"python",
"pandas",
"numpy"
] |
How to sum values of a row of a pandas dataframe efficiently
| 39,445,111 |
<p>I have a <code>python dataframe</code> with 1.5 million rows and 8 columns. I want combine few columns and create a new column. I know how to do this but wanted to know which one is faster and efficient. I am reproducing my code here </p>
<pre><code>import pandas as pd
import numpy as np
df=pd.Dataframe(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]])
</code></pre>
<p>Now here is what I want to achieve </p>
<pre><code>df['D']=0.5*df['A']+0.3*df['B']+0.2*df['C']
</code></pre>
<p>The other alternative is to use the <code>apply functionality</code> of pandas</p>
<pre><code>df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'])
</code></pre>
<p>I wanted to know which method takes less time when we have 1.5 millon rows and have to combine 8 columns</p>
| 2 |
2016-09-12T07:16:09Z
| 39,445,186 |
<p>First method is faster, because is vectorized:</p>
<pre><code>df=pd.DataFrame(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]])
print (df)
#[30000 rows x 3 columns]
df = pd.concat([df]*10000).reset_index(drop=True)
df['D1']=0.5*df['A']+0.3*df['B']+0.2*df['C']
#similar timings with mul function
#df['D1']=df['A'].mul(0.5)+df['B'].mul(0.3)+df['C'].mul(0.2)
df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'], axis=1)
print (df)
In [54]: %timeit df['D2']=df['A'].mul(0.5)+df['B'].mul(0.3)+df['C'].mul(0.2)
The slowest run took 10.84 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 950 µs per loop
In [55]: %timeit df['D1']=0.5*df['A']+0.3*df['B']+0.2*df['C']
The slowest run took 4.76 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 1.2 ms per loop
In [56]: %timeit df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'], axis=1)
1 loop, best of 3: 928 ms per loop
</code></pre>
<p>Another testing in <code>1.5M</code> size <code>DataFrame</code>, <code>apply</code> method is very slow:</p>
<pre><code>#[1500000 rows x 6 columns]
df = pd.concat([df]*500000).reset_index(drop=True)
In [62]: %timeit df['D2']=df['A'].mul(0.5)+df['B'].mul(0.3)+df['C'].mul(0.2)
10 loops, best of 3: 34.8 ms per loop
In [63]: %timeit df['D1']=0.5*df['A']+0.3*df['B']+0.2*df['C']
10 loops, best of 3: 31.5 ms per loop
In [64]: %timeit df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'], axis=1)
1 loop, best of 3: 47.3 s per loop
</code></pre>
| 3 |
2016-09-12T07:21:06Z
|
[
"python",
"performance",
"pandas",
"numpy",
"vectorization"
] |
How to sum values of a row of a pandas dataframe efficiently
| 39,445,111 |
<p>I have a <code>python dataframe</code> with 1.5 million rows and 8 columns. I want combine few columns and create a new column. I know how to do this but wanted to know which one is faster and efficient. I am reproducing my code here </p>
<pre><code>import pandas as pd
import numpy as np
df=pd.Dataframe(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]])
</code></pre>
<p>Now here is what I want to achieve </p>
<pre><code>df['D']=0.5*df['A']+0.3*df['B']+0.2*df['C']
</code></pre>
<p>The other alternative is to use the <code>apply functionality</code> of pandas</p>
<pre><code>df['D']=df.apply(lambda row: 0.5*row['A']+0.3*row['B']+0.2*row['C'])
</code></pre>
<p>I wanted to know which method takes less time when we have 1.5 millon rows and have to combine 8 columns</p>
| 2 |
2016-09-12T07:16:09Z
| 39,446,173 |
<p>Using @jezrael's setup</p>
<pre><code>df=pd.DataFrame(columns=['A','B','C'],data=[[1,2,3],[4,5,6],[7,8,9]])
df = pd.concat([df]*30000).reset_index(drop=True)
</code></pre>
<p>Far more efficient to use a <code>dot</code> product.</p>
<pre><code>np.array([[.5, .3, .2]]).dot(df.values.T).T
</code></pre>
<hr>
<h3>Timing</h3>
<p><a href="http://i.stack.imgur.com/MGbsy.png" rel="nofollow"><img src="http://i.stack.imgur.com/MGbsy.png" alt="enter image description here"></a></p>
| 3 |
2016-09-12T08:28:45Z
|
[
"python",
"performance",
"pandas",
"numpy",
"vectorization"
] |
Does SQLAlchemy's expire_all actually expire cached data?
| 39,445,203 |
<p>So, I've read a lot of conflicting reports on how sqlalchemy works. I've read that it doesn't cache queries, etc. None of it seems to match my experience.</p>
<p>I'll give an example:</p>
<pre><code> >>> x = Session.query(statusStorage).all()
>>> for i in x:
... print i.id
...
1
... - records omitted
100000
>>> Session.expire_all()
>>> x = Session.query(statusStorage).all()
>>> for i in x:
... print i.id
...
1
... - records omitted
100000
>>> Session.commit()
>>> x = Session.query(statusStorage).all()
>>> for i in x:
... print i.id
...
1
... - records omitted
100001
</code></pre>
<p>So this thread is querying a MySQL database, to get all the items of a class, then printing a field. After running the first query, I run the same query in another python process, and change the ID of the last item by adding 1.</p>
<p>When I run the next request, after expire_all, it returns the same results, and the id is still unchanged. I've had this happen in code I've developed, where the search is filtered.</p>
<p>Both rollback and commit will fix the problem, both expire(object) and expire_all() fail to expire the sqlalchemy cache.</p>
<p>Am I failing to understand something implicit in sqlalchemy? Shouldn't I be able to clear the contents of the cache, without either rollback or commit? I'm running 1.0.9 on python 2.7.</p>
| -1 |
2016-09-12T07:22:15Z
| 39,445,445 |
<p>I answered this on IRC, but the issue is simply that InnoDB's default transaction isolation level is "REPEATABLE READ", which means the second and third query are not permitted (by the database) to see your change.</p>
| 3 |
2016-09-12T07:39:20Z
|
[
"python",
"sqlalchemy"
] |
Running R script with subprocess on Windows, subprocess seems missing
| 39,445,422 |
<p>I am using python on windows.
I want to call an R script in my python code.</p>
<p>My script R is :</p>
<pre><code>c <- 3
print(paste("hello", c))
</code></pre>
<p>My python code calls the Rscript like this:</p>
<pre><code>import subprocess
subprocess.call(['Rscript', "sb.R"])
</code></pre>
<p>Unfortunately I have this error message :</p>
<pre><code>File "C:\Users\[...]\Local\Programs\Python\Python35-32\lib\subproce
ss.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Users\[...]\Local\Programs\Python\Python35-32\lib\subproce
ss.py", line 947, in __init__
restore_signals, start_new_session)
File "C:\Users\[...]\Local\Programs\Python\Python35-32\lib\subproce
ss.py", line 1224, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The file is not found
</code></pre>
<p>I have checked the following:</p>
<p>1) under powershell, when I enter <code>Rscript .\sb.R</code> it works.</p>
<p>2) in the python code I tried </p>
<pre><code>theproc = subprocess.Popen([sys.executable, "sbpy.py"])
theproc.communicate()
</code></pre>
<p>where sbpy.py contains <code>print("hello py")</code>. This works as well. So I assume that the library subprocess do work.</p>
<p>3) I tried the following code :</p>
<pre><code>cmd = ['Rscript', 'sb.R']
x = subprocess.check_output(cmd, shell=True)
</code></pre>
<p>I have then the following error :</p>
<pre><code>...
File "C:\Users\[...]\Local\Programs\Python\Python35-32\lib\subproce
ss.py", line 708, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['Rscript', 'sb.R']' returned non-zero e
xit status 1
</code></pre>
<p>4) As for the path, I have checked and yes R folder is in my path.</p>
<p>I newly installed python35 on my windows machine, is it a file missing in the lib subprocess, or is it something I have missed?</p>
| 1 |
2016-09-12T07:38:03Z
| 39,447,359 |
<p>Check your python script and Rscript in are the same file location.</p>
<p>Example:
Create a file named sb.R and subprocess_demo.py under Desktop location.
Change directory to Desktop in command prompt and run following command
<strong>python subprocess_demo.py</strong></p>
<p><strong><em>sb.R</em></strong></p>
<pre><code>c <- 3
print(paste("hello", c))
</code></pre>
<p><strong><em>subprocess_demo.py</em></strong></p>
<pre><code>import subprocess
subprocess.call(['Rscript', "sb.R"])
</code></pre>
| 0 |
2016-09-12T09:36:26Z
|
[
"python",
"windows",
"powershell",
"subprocess"
] |
trouble finding the right django queryset for this
| 39,445,579 |
<p>I have two models like this:</p>
<pre><code>class Foo():
name = CharField
frequency = IntegerField
class Bar():
thing = ForeignKey(Foo)
content = TextField
</code></pre>
<p>I want to get a queryset that will be <code>Bar</code> objects sorted by a range of <code>Foo</code> objects. It obviously doesn't work, but it illustrates what I need.</p>
<pre><code>Foo.objects.order_by('-frequency')[0:10].bar_set.all()
</code></pre>
| 0 |
2016-09-12T07:47:37Z
| 39,447,904 |
<p>if I am getting right what would you like to achieve, try this:</p>
<pre><code>objs = Bar.objects.filter(thing__pk__in=Foo.objects.all().order_by('-frequency').values_list('pk', flat=True)[:10])
</code></pre>
| 1 |
2016-09-12T10:07:51Z
|
[
"python",
"django"
] |
JAVA interaction with CPython
| 39,445,593 |
<p><strong>My Objective:</strong></p>
<p>When I run Python (CPython) from command line (not Jython since it does not support some packages like NumPy) I can interactively write lines of code and see results from its output.</p>
<p>My objective is to do this programmatically in JAVA. Here is my attempt to do so:</p>
<p><strong>Code:</strong></p>
<pre><code>import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class PythonProcess {
private Process proc;
private BufferedReader stdInput;
private BufferedReader stdError;
private BufferedWriter stdOutput;
public PythonProcess() {
Runtime rt = Runtime.getRuntime();
String[] commands = { "python.exe" };
try {
proc = rt.exec(commands);
stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
stdOutput = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
private String executeCommand(String command) throws IOException {
stdOutput.write(command + "\n");
stdOutput.newLine();
String s = null;
StringBuffer str = new StringBuffer();
while ((s = stdInput.readLine()) != null) {
str.append(s);
}
return str.toString();
}
public void initialize() throws IOException {
// will create a file - if correctly executed in python
stdOutput.write("f = open('c:/downloads/deleteme.txt','w')");
stdOutput.newLine();
stdOutput.write("f.write('hi there, I am Python \n')");
stdOutput.newLine();
stdOutput.write("f.close()");
stdOutput.newLine();
stdOutput.flush();
}
public static void main(String[] args) throws IOException {
PythonProcess proc = new PythonProcess();
proc.initialize(); // time demanding initialization
for (int i = 0; i < 10; i++) {
String out = proc.executeCommand("print \"Hello from command line #"+i+"\"");
System.out.println("Output: " + out);
}
}
}
</code></pre>
<p><strong>Problem:</strong></p>
<p>It seems that the code passed by <em>stdOutput</em> in initialize() method is not executed by Python at all since the file c:/downloads/deleteme.txt was not created. Later on I am also unable to read any output from the <em>stdInput</em> when calling <em>executeCommand</em> method.</p>
<p><strong>Questions:</strong></p>
<ol>
<li>Is there any simple way how to fix the code?</li>
<li>Can anyone point me to some example how can I interact with python e.g. by client - server way</li>
<li>or Any other idea?</li>
</ol>
<hr>
<p>BTW1: Jython is not the way to go since I need to execute CPython directives that are not supported by python.</p>
<hr>
<p>BTW2: I know that I can execute the python script in noninteractive way by String[] commands = { "python.exe" "script.py"};. The issue is when the initilaization takes significant time it would mean significant performance issue.</p>
| 0 |
2016-09-12T07:49:01Z
| 39,449,515 |
<p>Direct interaction with Python process is unfortunately not possible. Instead of it is a solution using TCP sockets:</p>
<p><strong>PythonServer.java</strong></p>
<pre><code>package pythonexample;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class PythonServer {
public static void main(String[] args) throws IOException, InterruptedException {
ProcessBuilder ps=new ProcessBuilder("python.exe","tcpServer.py");
ps.redirectErrorStream(true);
System.out.println("Starting Python server.");
Process pr = ps.start();
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
pr.waitFor();
in.close();
System.exit(0);
}
}
</code></pre>
<p><strong>tcpServer.py</strong></p>
<pre><code>import socket
# DO INITIALIZATION
TCP_IP = '127.0.0.1'
TCP_PORT = 5006
BUFFER_SIZE = 20 # Normally 1024, shorter if we want fast response
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
while 1:
print 'Waiting for connection'
conn, addr = s.accept()
print 'Connection address:', addr
if addr[0] == '127.0.0.1': # security - only local processes can connect
data = conn.recv(BUFFER_SIZE)
print "received data:", data
res = eval(data)
print "Sending result:", res
conn.send("This is reply from Python " + str(res) + "\n")
conn.close()
</code></pre>
<p><strong>PythonClient.java</strong></p>
<pre><code>package pythonexample;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class PythonClient {
public static void main(String[] args) throws IOException {
String serverAddress = "127.0.0.1";
Socket s = new Socket(serverAddress, 5006);
// do this in loop if needed
String result = sendCommand(s, "1+1 \n");
System.out.println("Received result: "+result);
// closing socket
s.close();
}
private static String sendCommand(Socket s, String command) throws IOException {
BufferedWriter ouput = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
ouput.write(command);
ouput.flush();
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
return answer;
}
}
</code></pre>
<p>First of all execute PythonServer class, which initializes the server. Than execute PythonClient which sends data to servers and gets result. </p>
<p>Of course all the features like NumPy and other which are not supported by e.g. Jython are now available.</p>
| 0 |
2016-09-12T11:42:22Z
|
[
"java",
"python",
"process",
"cpython"
] |
Softlayer API: How to do image capture with specify certain data disk?
| 39,445,620 |
<p>I have a vm with disk 1,2,3,4, I want to do some image operations: </p>
<ul>
<li>Q1: How can i capture the image only contain system disk and disk 3?</li>
<li>Q2: If I achieve the image production described in Q1, can I use this
image install or reload a vm? How SL api to do with the disk 3 in the
image ?</li>
<li>Q3: Can I make a snapshot image only for disk 3?</li>
<li>Q4: If I achieve the image described in Q3, how can I use this
snapshot to init a disk ?</li>
</ul>
| 0 |
2016-09-12T07:50:16Z
| 39,451,323 |
<p>at moment to create the image template you can specify the block devices that you want in the image template you can do that using the API and the portal.</p>
<p>this is an example using the API</p>
<pre><code>"""
Create image template.
The script creates a standard image template, it makes
a call to the SoftLayer_Virtual_Guest::createArchiveTransaction method
sending the IDs of the disks in the request.
For more information please see below.
Important manual pages:
https://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest
https://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/createArchiveTransaction
https://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest_Block_Device
License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""
import SoftLayer
# Your SoftLayer API username and key.
USERNAME = 'set me'
API_KEY = 'set me'
# The virtual guest ID you want to create a template
virtualGuestId = 4058502
# The name of the image template
groupName = 'my image name'
# An optional note for the image template
note = 'an optional note'
"""
Build a skeleton SoftLayer_Virtual_Guest_Block_Device object
containing the disks you want to the image.
In this case we are going take an image template of 2 disks
from the virtual machine.
"""
blockDevices = [
{
"id": 4667098,
"complexType": "SoftLayer_Virtual_Guest_Block_Device"
},
{
"id": 4667094,
"complexType": "SoftLayer_Virtual_Guest_Block_Device"
}
]
# Declare a new API service object
client = SoftLayer.Client(username=USERNAME, api_key=API_KEY)
try:
# Creating the transaction for the image template
response = client['SoftLayer_Virtual_Guest'].createArchiveTransaction(groupName, blockDevices, note, id=virtualGuestId)
print(response)
except SoftLayer.SoftLayerAPIError as e:
"""
# If there was an error returned from the SoftLayer API then bomb out with the
# error message.
"""
print("Unable to create the image template. faultCode=%s, faultString=%s" % (e.faultCode, e.faultString))
</code></pre>
<p>You only need to get the block devices ID (or disks), for that you can call this method:</p>
<p><a href="http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getBlockDevices" rel="nofollow">http://sldn.softlayer.com/reference/services/SoftLayer_Virtual_Guest/getBlockDevices</a></p>
<p>There is some rules for the block devices:</p>
<ol>
<li>Only block devices of type disk can be captured. </li>
<li>The block device of swap type cannot not be included in the list of block devices to capture.(this is is the disk number 1). </li>
<li>The block device which contains the OS must be included (this is the disk number 0). </li>
<li>The block devices which contain metadata cannot be included in the image.</li>
</ol>
<p>When you are ordening a new device using this image template you need to keep in mind this:</p>
<ol>
<li>If you are using the placeOrder method you need to make sure that you are adding the prices for the extra disks.</li>
<li>If you are using the createObject method, the number of disk will be taken from the image template, so it is not neccesary to specify the extra disks.</li>
</ol>
<p>And also you can use the images templates in reloads, but the reload only afects to the disk wich contains the OS. so If you have a Vitrual machine which contains 3 disks and performs a reload only the disk which contains the OS is afected even if the image template has 3 disks.</p>
<p>In case there are errors in your order due to lack of disk capacity or other issues, at provisioning time there will be errors and the VSI will not be provisioned, likely a ticket will be opened and some softlayer employee will inform you about that.</p>
<p>Regards</p>
| 0 |
2016-09-12T13:20:04Z
|
[
"python",
"api",
"softlayer"
] |
String formatting in output
| 39,445,758 |
<p>I have a python script that looks like this:</p>
<pre><code> print "Header 1"
print "\t Sub-header 1"
print "\t\t (*) Sentence 1 begins here and goes on... and ends here."
</code></pre>
<p>The sentences are being printed in a loop with the similar format, and it gives an output like this in the terminal:</p>
<pre><code>Header 1
Sub-header 1
(*) Sentence 1 begins here and goes on...
and ends here.
(*) Sentence 2 begins here and goes on ...
and ends here.
.
.
.
</code></pre>
<p>Is there any way I can make the formatting as follows? :</p>
<pre><code>Header 1
Sub-header 1
(*) Sentence 1 begins here and goes on...
and ends here.
(*) Sentence 2 begins here and goes on ...
and ends here.
.
.
.
</code></pre>
| 0 |
2016-09-12T08:00:24Z
| 39,447,706 |
<p>with the help of the <a href="https://docs.python.org/2/library/textwrap.html" rel="nofollow">textwrap</a> module, it could be done quite easily:</p>
<pre><code>import textwrap
LINE_LENGTH = 80
TAB_LENGTH = 8
def indent(text, indent="\t", level=0):
return "{}{}".format(indent * level, text)
def indent_sentence(text, indent="\t", level=0, sentence_mark=" (*) "):
indent_length = len(indent) if indent != "\t" else TAB_LENGTH
wrapped = textwrap.wrap(text,
LINE_LENGTH
- indent_length * level
- len(sentence_mark))
sentence_new_line = "\n{}{}".format(indent * level, " " * len(sentence_mark))
return "{}{}{}".format(indent * level,
sentence_mark,
sentence_new_line.join(wrapped))
print indent("Header 1")
print indent("Sub-header 1", level=1)
print indent_sentence("Sentence 1 begins here and goes on... This is a very "
"long line that we will wrap because it is nicer to not "
"have to scroll horizontally. and ends here.",
level=2)
</code></pre>
<p>It prints this in a Windows console where tab are 8 chars long:</p>
<pre><code>Header 1
Sub-header 1
(*) Sentence 1 begins here and goes on... This is a very long
line that we will wrap because it is nicer to not have to
scroll horizontally. and ends here.
</code></pre>
| 1 |
2016-09-12T09:55:16Z
|
[
"python",
"python-2.7",
"formatting",
"string-formatting"
] |
How can I make python script(X) reload dynamically changing variables in another module(Y) and then re-import updated module(Y) in same script(X)?
| 39,445,798 |
<p>I'm new to Python, I'm stuck with a code. I have tried my best to show my problem with below sample code. I'm playing with 4 files.</p>
<p>This is the runme file. That I'm running.</p>
<p>command > python runme.py</p>
<pre><code>import os
with open("schooldata.txt", "r") as filestream: #opening schooldata.txt file
for line in filestream:
currentline = line.split(",")
a = currentline[0]
b = currentline[1]
c = currentline[2]
#creating a school_info.py file with value of a,b,c that are further imported by mainfile.py
f = open('school_info.py','w')
f.write("a= \"" + currentline[1] + "\"\n")
f.write("b= \"" + currentline[2] + "\"\n")
f.write("c= \"" + currentline[3] + "\"\n")
f.close()
#importing mainfile.py and calling its functions.
from mainfile import give_to_student
give_to_student("Rickon")
from mainfile import give_to_teacher
give_to_student("Carolina")
</code></pre>
<p>Second file is schooldata.txt from where I want to read the value of a,b,c. This is our main school data file from which we take authorization data. I'm reading line by line from this file and creating a,b,c by splitting it with (,).</p>
<pre><code>12313,mshd1732,2718230efd,
fhwfw,382842324,238423049234230,
fesj32,282342rnfewk,43094309432,
fskkfns,48r209420fjwkfwk,2932042fsdfs,
38234290,fsfjskfjsdf,2942094929423,
</code></pre>
<p>Third file is school_info.py which I'm creating with this data everytime. This file is created everytime when a line is read from schooldata.txt file. So fresh file everytime with fresh and unique data of a,b,c.</p>
<pre><code>a = "asb12"
b = "121002"
c = "mya122344"
</code></pre>
<p>Now here comes the mainfile.py which is having functions like give_to_student and give_to_teacher. This file is importing data from school_info.py, so as to create authorization code using values of a,b,c. </p>
<p>and function definition of give_to_student and give_to_teacher which uses these function definitions.</p>
<pre><code>import os
import schoollib #(internal school lib)
#importing School_info.py file so as to get value of a,b,c
from school_info import *
#It creates authorisation code internally
lock = auth(a,b,c,d)
#This authorisation code is used to call internal function
def give_to_student():
lock.give(student)
def give_to_teacher():
lock.give(teacher)
</code></pre>
<p>So now let me share the exact problem that I'm facing as of now, I'm unable to get authorization code loaded for mainfile.py everytime it is imported in runme.py file. When I'm calling runme.py file it is giving same authorization code to all users every time. </p>
<p>It is not able to use authorization code that is create after reading second line of schooldata.txt</p>
<p>With mainfile.py file If I'm trying to reload module using. import importlib and then importlib.reload(mainfile.py) in runme.py. </p>
<pre><code>#Added it in runme.py file
import importlib
importlib.reload(mainfile)
</code></pre>
<p>It is still giving authorization for first line of data(schooldata.txt).</p>
<p>Similar thing I tried in mainfile.py.
I tried to import importlib and then importlib.reload(school_info).</p>
<pre><code>#added it in mainfile.py
import importlib
importlib.reload(school_info)
</code></pre>
<p>importlib.reload(school_info)
NameError: name 'school_info' is not defined</p>
<p>But it giving error, that school_info module doesn't exist.
Please throw some light on it, and how can I make it work.</p>
<p>P.S. I'm using python 3.5. Thanks</p>
| 0 |
2016-09-12T08:03:01Z
| 39,455,962 |
<p>Why don't you try to combine the school_info.py and mainfile.py.
If you can run a combined loop.</p>
<pre><code>import os
import schoollib #(internal school lib)
with open("schooldata.txt", "r") as filestream: #opening schooldata.txt file
for line in filestream:
currentline = line.split(",")
a = currentline[0]
b = currentline[1]
c = currentline[2]
#It creates authorisation code internally
lock = auth(a,b,c,d)
#This authorisation code is used to call internal function
def give_to_student():
lock.give(student)
def give_to_teacher():
lock.give(teacher)
#function calling
give_to_student("Rickon")
give_to_student("Carolina")
</code></pre>
<p>I hope this solves your purpose.</p>
| 0 |
2016-09-12T17:49:45Z
|
[
"python",
"python-3.x"
] |
Lambda function: why do I need a parameter in eventhandlers but not in Button-commands?
| 39,445,915 |
<p>In the following case of a Python lambda call, I need to set a parameter for the function to work properly:</p>
<pre><code>name = Entry(self.new_jobtile, width=30)
...
name.bind('<Return>', lambda x:self.create_tile(name.get()))
</code></pre>
<p>However, if I use a Button instead, the very same lambda call works without the "x" parameter:</p>
<pre><code>Button(self.new_jobtile, text="OK", command=lambda: self.create_tile(name.get()), width=4, height=2).pack(side=BOTTOM, pady=3, padx=5)
</code></pre>
<p>I really don't understand why?</p>
| 0 |
2016-09-12T08:11:51Z
| 39,446,219 |
<p>In Python you can create lambda function without arguments:</p>
<pre><code>bar = lambda : 4*2
bar() # 8
</code></pre>
<p>I do not know what library are you using but I think that in <code>name.bind</code> second argument should be function with one parameter (like <code>lambda x:</code> or <code>def foo(x):</code>) but in <code>Button</code> constructor argument <code>command</code> should be function with 0 parameters (like <code>lambda :</code> or <code>def foo():</code>).</p>
| 0 |
2016-09-12T08:31:17Z
|
[
"python",
"lambda"
] |
Lambda function: why do I need a parameter in eventhandlers but not in Button-commands?
| 39,445,915 |
<p>In the following case of a Python lambda call, I need to set a parameter for the function to work properly:</p>
<pre><code>name = Entry(self.new_jobtile, width=30)
...
name.bind('<Return>', lambda x:self.create_tile(name.get()))
</code></pre>
<p>However, if I use a Button instead, the very same lambda call works without the "x" parameter:</p>
<pre><code>Button(self.new_jobtile, text="OK", command=lambda: self.create_tile(name.get()), width=4, height=2).pack(side=BOTTOM, pady=3, padx=5)
</code></pre>
<p>I really don't understand why?</p>
| 0 |
2016-09-12T08:11:51Z
| 39,446,235 |
<p>I have no idea about API of that <code>Entry</code> and <code>Button</code> classes, but here is my guess. Probably <code>bind</code> method of the <code>Entry</code> requires a callback function (your lambda) to has one parameter, in other words, somewhere in the <code>bind</code> method can be a piece of code like this:</p>
<pre><code>def bind(self, an_argument, yourcallback):
yourcallback(something)
</code></pre>
<p>You just ignore this parameter, but you can figure out what that <code>bind</code> method passes to your callback:</p>
<pre><code>name.bind('<Return>', lambda x:self.create_tile(str(x) + " " + name.get()))
</code></pre>
<p>From the other side, the <code>pack</code> method does not pass a parameter. So your lambda works in that case. </p>
| 0 |
2016-09-12T08:32:51Z
|
[
"python",
"lambda"
] |
SQLite Query with Python 1
| 39,445,923 |
<p>I have generated a list and able to generate the result:</p>
<pre><code>l = [2, 3, 5, 2009 ]
cur1 = cur.execute('SELECT * from table where + or '.join(('Code = ' + str(n) for n in l)))
</code></pre>
<p>However, I want to put in another query in the same statement as follows:</p>
<pre><code>cur1 = cur.execute('SELECT * from table where '
**'Timestamp in (select max(timestamp) from table)'**
+ ' or '.join(('Code = ' + str(n) for n in l)))
</code></pre>
<p>but generated </p>
<pre><code> sqlite3.OperationalError: near "Code": syntax error.
</code></pre>
<p>Please kindly advise how I can fit Timestamp statement into the first statement in order to focus on the query result which I want. </p>
| -1 |
2016-09-12T08:12:22Z
| 39,446,238 |
<p>Your first was false and the second is of course false too.</p>
<pre><code>>>> 'SELECT * from table where + or '.join(('Code = ' + str(n) for n in l))
>>> 'Code = 2SELECT * from table where + or Code = 3SELECT * from table where + or Code = 5SELECT * from table where + or Code = 2009'
</code></pre>
<p>It's not a valid SQL statement.</p>
<p><a href="http://stackoverflow.com/questions/8159323/sqlite-select-equal-to-one-of-two-values">SQLite SELECT equal to one of two values</a></p>
<p>The right query statement should be:</p>
<pre><code>SELECT * FROM table WHERE Code in ('2', '3', '5', '2009')
</code></pre>
<p>You will get it with:</p>
<pre><code>cur.execute('SELECT * FROM table WHERE Code in ?', str(tuple(str(i) for i in l)))
</code></pre>
<p>Now you can use the same parameter for your second statement.</p>
<p><em>P/S: There is a better solution, but i don't have SQLite database to check it.</em> </p>
| 1 |
2016-09-12T08:33:01Z
|
[
"python",
"sqlite",
"python-3.x",
"sqlite3"
] |
Python3.5 erorr when import easygui
| 39,445,931 |
<p>I got below error when import easygui in Python3.5</p>
<pre><code>Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
import easygui
File "C:\Users\bhongtip\AppData\Local\Programs\Python\Python35-32\lib\site-packages\easygui-0.98.0-py3.5.egg\easygui\__init__.py", line 50, in <module>
from .boxes.choice_box import choicebox
File "C:\Users\bhongtip\AppData\Local\Programs\Python\Python35-32\lib\site-packages\easygui-0.98.0-py3.5.egg\easygui\boxes\choice_box.py", line 76
except Exception, e:
^
SyntaxError: invalid syntax
</code></pre>
| 0 |
2016-09-12T08:13:33Z
| 39,446,053 |
<p>EasyGUI 0.98 <a href="https://github.com/robertlugg/easygui/commit/b5eab34c021d1d6eb5e51b67b81da6dbee56e94a" rel="nofollow">introduced a change incompatible with Python 3</a>.</p>
<p>You'll need to either downgrade to 0.97.4 (<code>pip install -U EasyGUI==0.97.4</code>) or fix that change.</p>
<p>Fixing that line is as easy as replacing line 76:</p>
<pre><code>except Exception, e:
</code></pre>
<p>with</p>
<pre><code>except Exception as e:
</code></pre>
<p>This is tracked as <a href="https://github.com/robertlugg/easygui/issues/97" rel="nofollow">issue #97</a> by the project (with duplicates <a href="https://github.com/robertlugg/easygui/issues/101" rel="nofollow">#101</a> and <a href="https://github.com/robertlugg/easygui/issues/102" rel="nofollow">#102</a>, and pull requests <a href="https://github.com/robertlugg/easygui/pull/100" rel="nofollow">#100</a>, <a href="https://github.com/robertlugg/easygui/pull/103" rel="nofollow">#103</a>, <a href="https://github.com/robertlugg/easygui/pull/105" rel="nofollow">#105</a> and <a href="https://github.com/robertlugg/easygui/pull/107" rel="nofollow">#107</a>).</p>
| 2 |
2016-09-12T08:21:20Z
|
[
"python",
"easygui"
] |
Python Pyqt QComboBox show options
| 39,445,975 |
<p>I am trying to create a GUI with button, text box and combo box. I have problems with the combo box. I can create it but once I click on it it does not display the options. I am not getting any error which makes me hard to find the problem. This is the code so far:</p>
<pre><code>from PyQt4.QtGui import *
from PyQt4 import QtGui
import sys
class Window(QtGui.QMainWindow,QWidget):
def __init__(self):
super(Window, self).__init__()
self.setGeometry(500, 5, 1100, 1000)
self.setWindowTitle("FourC Analyser")
self.app = QtGui.QApplication([])
self.app.setStyleSheet('QMainWindow{background-color: rgb(49,79,79);border: 1px solid black;}')
extractAction = QtGui.QAction("&GET TO THE CHOPPAH!!!", self)
extractAction.setShortcut("Ctrl+Q")
extractAction.setStatusTip('Leave The App')
self.home()
def home(self):
labelCol1= 'color: rgb(255,250,205)'
textboxCol1=("QLineEdit {background-color: rgb(49,79,79); color: rgb(218,165,32);}")
#label
self.lbl_project = QtGui.QLabel('Project Name', self)
self.lbl_project.move(20, 120)
self.lbl_project.setStyleSheet(labelCol1)
#text box
self.textbox = QtGui.QLineEdit(self)
self.textbox.move(20, 150)
self.textbox.resize(280,30)
self.textbox.setStyleSheet(textboxCol1)
#Combo box
self.cb=QtGui.QComboBox(self)
self.cb = QComboBox()
self.cb.addItems(["1","2","3"])
def selectionchange(self,i):
print "Items in the list are :"
for count in range(self.cb.count()):
print self.cb.itemText(count)
print "Current index",i,"selection changed ",self.cb.currentText()
def run():
app = QtGui.QApplication(sys.argv)
GUI = Window()
GUI.show()
sys.exit(app.exec_())
run()
</code></pre>
| 0 |
2016-09-12T08:16:17Z
| 39,446,122 |
<p>You are redefining <code>self.cb</code> here:</p>
<pre><code>self.cb = QComboBox()
</code></pre>
<p>By removing this line it works for me.<br>
Both definitions work because of are your <code>import</code> statements. With <code>from PyQt4.QtGui import *</code> you import everythin within the module <code>QtGui</code> and with <code>from PyQt4 import QtGui</code> you import the module <code>QtGui</code> itself. I recommend to remove <code>from PyQt4.QtGui import *</code>.</p>
| 1 |
2016-09-12T08:25:28Z
|
[
"python",
"pyqt"
] |
Kivy--how to bind a function to a checkbox when activated
| 39,446,148 |
<p>I have a Python program in wich I use kivy's checkboxes.</p>
<p>Is there a way to let the program call a function the instant when the checkbox is disabled/enabled? please note, the active property wont work since this is only once, one would have to use a infinite while loop to check whether the user activated it wich would make everything complex.</p>
<p>so anything that can help here welcome</p>
<p>Thanks and regards</p>
<p>Cid-EL</p>
| -1 |
2016-09-12T08:26:52Z
| 39,446,291 |
<p>You could do something like this:</p>
<pre><code>from kivy.uix.checkbox import CheckBox
</code></pre>
<h1>...</h1>
<pre><code>def do_something(checkbox, value):
# Do something
checkbox = CheckBox()
checkbox.bind(active=do_something)
</code></pre>
| 1 |
2016-09-12T08:36:35Z
|
[
"python",
"checkbox",
"kivy"
] |
In NumPy, how do I set array b's data to reference the data of array a?
| 39,446,199 |
<p>Say I have ndarray a and b of compatible type and shape. I now wish for the data of b to be referring to the data of a. That is, without changing the array b object itself or creating a new one. (Imagine that b is actually an object of a class derived from ndarray and I wish to set its data reference after construction.) In the following example, how do I perform the b.set_data_reference?</p>
<pre class="lang-python prettyprint-override"><code>import numpy as np
a = np.array([1,2,3])
b = np.empty_like(a)
b.set_data_reference(a)
</code></pre>
<p>This would result in b[0] == 1, and setting operations in one array would affect the other array. E.g. if we set a[1] = 22 then we can inspect that b[1] == 22.</p>
<p>N.B.: In case I controlled the creation of array b, I am aware that I could have created it like </p>
<pre><code>b = np.array(a, copy=True)
</code></pre>
<p>This is, however, not the case.</p>
| 0 |
2016-09-12T08:30:29Z
| 39,448,774 |
<p>Every variable in python is a pointer so you can use directly <code>=</code> as follow</p>
<pre><code>import numpy as np
a = np.array([1,2,3])
b = a
</code></pre>
<p>You can check that <code>b</code> refers to <code>a</code> as follow</p>
<pre><code>assert a[1] == b[1]
a[1] = 4
assert a[1] == b[1]
</code></pre>
| 0 |
2016-09-12T10:57:21Z
|
[
"python",
"python-3.x",
"numpy"
] |
In NumPy, how do I set array b's data to reference the data of array a?
| 39,446,199 |
<p>Say I have ndarray a and b of compatible type and shape. I now wish for the data of b to be referring to the data of a. That is, without changing the array b object itself or creating a new one. (Imagine that b is actually an object of a class derived from ndarray and I wish to set its data reference after construction.) In the following example, how do I perform the b.set_data_reference?</p>
<pre class="lang-python prettyprint-override"><code>import numpy as np
a = np.array([1,2,3])
b = np.empty_like(a)
b.set_data_reference(a)
</code></pre>
<p>This would result in b[0] == 1, and setting operations in one array would affect the other array. E.g. if we set a[1] = 22 then we can inspect that b[1] == 22.</p>
<p>N.B.: In case I controlled the creation of array b, I am aware that I could have created it like </p>
<pre><code>b = np.array(a, copy=True)
</code></pre>
<p>This is, however, not the case.</p>
| 0 |
2016-09-12T08:30:29Z
| 39,457,690 |
<p>NumPy does not support this operation. If you controlled the creation of <code>b</code>, you might be able to create it in such a way that it uses <code>a</code>'s data buffer, but after <code>b</code> is created, you can't swap its buffer out for <code>a</code>'s.</p>
| 1 |
2016-09-12T19:44:29Z
|
[
"python",
"python-3.x",
"numpy"
] |
In NumPy, how do I set array b's data to reference the data of array a?
| 39,446,199 |
<p>Say I have ndarray a and b of compatible type and shape. I now wish for the data of b to be referring to the data of a. That is, without changing the array b object itself or creating a new one. (Imagine that b is actually an object of a class derived from ndarray and I wish to set its data reference after construction.) In the following example, how do I perform the b.set_data_reference?</p>
<pre class="lang-python prettyprint-override"><code>import numpy as np
a = np.array([1,2,3])
b = np.empty_like(a)
b.set_data_reference(a)
</code></pre>
<p>This would result in b[0] == 1, and setting operations in one array would affect the other array. E.g. if we set a[1] = 22 then we can inspect that b[1] == 22.</p>
<p>N.B.: In case I controlled the creation of array b, I am aware that I could have created it like </p>
<pre><code>b = np.array(a, copy=True)
</code></pre>
<p>This is, however, not the case.</p>
| 0 |
2016-09-12T08:30:29Z
| 39,458,085 |
<p>Usually when functions are not always supposed to create their own buffer they implement an interface like</p>
<pre><code>def func(a, b, c, out=None):
if out is None:
out = numpy.array(x, y)
# ...
return out
</code></pre>
<p>that way the caller can control if an existing buffer is used or not.</p>
| 0 |
2016-09-12T20:11:47Z
|
[
"python",
"python-3.x",
"numpy"
] |
Python regex with \w does not work
| 39,446,341 |
<p>I want to have a regex to find a phrase and two words preceding it if there are two words.
For example I have the string (one sentence per line):</p>
<blockquote>
<p>Chevy is my car and Rusty is my horse.
My car is very pretty my dog is red.</p>
</blockquote>
<p>If i use the regex:</p>
<pre><code>re.finditer(r'[\w+\b|^][\w+\b]my car',txt)
</code></pre>
<p>I do not get any match.</p>
<p>If I use the regex:</p>
<pre><code>re.finditer(r'[\S+\s|^][\S+\s]my car',txt)
</code></pre>
<p>I am getting:
's my car' and '. My car' (I am ignoring case and using multi-line)</p>
<p>Why is the regex with \w+\b not finding anything? It should find two words and 'my car'
How can I get two complete words before 'my car' if there are two words. If there is only one word preceding my car, I should get it. If there are no words preceding it I should get only 'my car'. In my string example I should get: 'Chevy is my car' and 'My car' (no preceding words here)</p>
| 2 |
2016-09-12T08:39:41Z
| 39,446,390 |
<p>In your <code>r'[\w+\b|^][\w+\b]my car</code> regex, <code>[\w+\b|^]</code> matches 1 symbol that is either a word char, a <code>+</code>, a backdpace, <code>|</code>, or <code>^</code> and <code>[\w+\b]</code> matches 1 symbol that is either a word char, or <code>+</code>, or a backspace.</p>
<p>The point is that inside a character class, quantifiers and a lot (<strong>but not all</strong>) special characters match literal symbols. E.g. <code>[+]</code> matches a plus symbol, <code>[|^]</code> matches either a <code>|</code> or <code>^</code>. Since you want to match a <em>sequence</em>, you need to provide a sequence of subpatterns outside of a character class.</p>
<p>It seems as if you intended to use <code>\b</code> as a word boundary, however, <code>\b</code> inside a character class matches only a backspace character.</p>
<p>To <em>find two words and 'my car'</em>, you can use, for example</p>
<pre><code>\S+\s+\S+\s+my car
</code></pre>
<p>See the <a href="https://regex101.com/r/eY4wC6/2" rel="nofollow">regex demo</a> (here, <code>\S+</code> matches one or more non-whitespace symbols, and <code>\s+</code> matches 1 or more whitespaces, and the 2 occurrences of these 2 consecutive subpatterns match these symbols as a <em>sequence</em>).</p>
<p>To make the sequences before <code>my car</code> optional, just use a <code>{0,2}</code> quantifier like this:</p>
<pre><code>(?:\S+[ \t]+){0,2}my car
</code></pre>
<p>See <a href="https://regex101.com/r/eY4wC6/3" rel="nofollow">this regex demo</a> (to be used with the <code>re.IGNORECASE</code> flag). See <a href="https://ideone.com/B930oh" rel="nofollow">Python demo</a>:</p>
<pre><code>import re
txt = 'Chevy is my car and Rusty is my horse.\nMy car is very pretty my dog is red.'
print(re.findall(r'(?:\S+[ \t]+){0,2}my car', txt, re.I))
</code></pre>
<p><strong>Details</strong>:</p>
<ul>
<li><code>(?:\S+[ \t]+){0,2}</code> - 0 to 2 sequences of 1+ non-whitespaces followed with 1+ space or tab symbols (you may also replace it with <code>[^\S\r\n]</code> to match any horizontal space or <code>\s</code> if you also plan to match linebreaks).</li>
<li><code>my car</code> - a literal text <code>my car</code>.</li>
</ul>
| 7 |
2016-09-12T08:43:01Z
|
[
"python",
"regex",
"python-3.x"
] |
Unable to import python packages in Ubuntu (ImportError : undefined symbol)
| 39,446,543 |
<p>I recently installed python on my Ubuntu 14.04. I downloaded tensorflow by <code>pip</code>.
When I tried to <code>import tensorflow</code> it said <code>ImportError:No module named tensorflow</code>.
Then I edited <code>PYTHONPATH</code> by adding <code>/usr/local/lib/python2.7/dist-packages</code>. Now when I try to import, it says </p>
<pre><code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 23, in <module>
from tensorflow.python import *
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 45, in <module>
import numpy as np
File "/usr/local/lib/python2.7/dist-packages/numpy/__init__.py", line 180, in <module>
from . import add_newdocs
File "/usr/local/lib/python2.7/dist-packages/numpy/add_newdocs.py", line 13, in <module>
from numpy.lib import add_newdoc
File "/usr/local/lib/python2.7/dist-packages/numpy/lib/__init__.py", line 8, in <module>
from .type_check import *
File "/usr/local/lib/python2.7/dist-packages/numpy/lib/type_check.py", line 11, in <module>
import numpy.core.numeric as _nx
File "/usr/local/lib/python2.7/dist-packages/numpy/core/__init__.py", line 14, in <module>
from . import multiarray
ImportError: /usr/local/lib/python2.7/dist-packages/numpy/core/multiarray.so: undefined symbol: PyUnicodeUCS4_AsUnicodeEscapeString
</code></pre>
<p>I found <a href="http://stackoverflow.com/questions/27383054/python-importerror-usr-local-lib-python2-7-lib-dynload-io-so-undefined-symb">here</a> that 2 versions of python causes the conflict, but that didn't help. Any assistance will be appreciated. Thank you </p>
| 0 |
2016-09-12T08:52:52Z
| 39,452,302 |
<p>Best way to install packages if you have more than one python installed is:</p>
<pre><code>path_to_your_python_executable -m pip install package_name
</code></pre>
<p>This way, you can make sure that you have installed package for proper python.</p>
<p>And don't forget about sudo ;)</p>
| 0 |
2016-09-12T14:07:33Z
|
[
"python",
"python-2.7",
"ubuntu",
"ubuntu-14.04",
"tensorflow"
] |
Difference between devpi and pypi server
| 39,446,579 |
<p>Had a quick question here, am used to devpi and was wondering what is the difference between devpi and pypi server ?</p>
<p>Is on better than another? Which of this one scale better?</p>
<p>Cheers</p>
| 0 |
2016-09-12T08:55:14Z
| 39,466,093 |
<p><strong>PyPI</strong> (Python Package Index)- is the official repository for third-party Python software packages. Every time you use e.g. <code>pip</code> to install a package that is not in the standard it will get downloaded from the PyPI server.</p>
<p>All of the packages that are on PyPI are publicly visible. So if you upload your own package then anybody can start using it. And obviously you need internet access in order to use it.</p>
<p><strong>devpi</strong> (not sure what the acronym stands for) - is a self hosted private Python Package server. Additionally you can use it for testing and releasing of your own packages. </p>
<p>Being self hosted it's ideal for proprietary work that maybe you wouldn't want (or can't) shear with the rest of the world.</p>
<p>So other features that devpi others:</p>
<ul>
<li>PyPI mirror - cache locally any packages that you download form PyPI. This is excellent for CI systems. Don't have to worry if a package or server goes missing. You can even still use it if you don't have internet access.</li>
<li>multiple indexes - unlike PyPI (which has only one index) in devpi you can create multiple indexes. For example a <code>main</code> index for packages that are rock solid and <code>development</code> where you can release packages that are still under development. Although you have to be careful with this because a large amount of indexes can make things hard to track. </li>
<li>The server has a simple web interface where you can you and search for packages.</li>
<li>You can integrate it with <code>pip</code> so that you can yous your local devpi server as if you were using PyPI.</li>
</ul>
<p>So answering you questions:</p>
<ul>
<li><em>Is on better than another?</em> - well these are two different tools really. No clear answer here, depends on what your needs are.</li>
<li><em>Which of this one scale better?</em> - defiantly devpi.</li>
</ul>
<p>The official web site is very useful with good examples: <a href="http://doc.devpi.net/latest/" rel="nofollow">http://doc.devpi.net/latest/</a></p>
| 0 |
2016-09-13T09:02:23Z
|
[
"python",
"pypi",
"devpi",
"python-packaging"
] |
Find an element in a list with tuple in Python
| 39,446,607 |
<p>I have a little complicated data and want to find specific element with <em>key</em> tuple. <em>target</em> tuple is a little different from <em>key</em>, because it has an <em>id</em> property. So I cannot use <strong><em>key in target</em></strong>.</p>
<p>So what's the best way to implement smart searching in this case?</p>
<pre><code>targets = [
{"id": 0, "X": (), "Y": (), "Z": () },
{"id": 1, "X": (1,), "Y": (5,), "Z": ()},
{"id": 2, "X": (1,), "Y": (5, 7), "Z": ()},
{"id": 3, "X": (2,), "Y": (5, 7), "Z": (1,)},
{"id": 4, "X": (1, 2), "Y": (5, 7), "Z": (1,)},
{"id": 5, "X": (1, 2), "Y": (5, 7), "Z": (1,3)},
]
key = {"X": (1,), "Y": (5, 7), "Z": ()}
</code></pre>
<p>I want to implement <em>find</em> method to extract expected slot like below.</p>
<pre><code>In []: find(targets, key)
Out[]: {'id': 2, 'X': (1,), 'Y': (5, 7), 'Z': ()}
</code></pre>
| -3 |
2016-09-12T08:56:45Z
| 39,446,927 |
<p>If the key-value pairs must match exactly, you can use <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects" rel="nofollow"><em>Dictionary view objects</em></a> to treat the key-value pairs as <em>sets</em>. You want to find a <a href="https://docs.python.org/2/library/stdtypes.html#set.issubset" rel="nofollow"><em>strict subset</em></a>:</p>
<pre><code>def find(targets, key):
for target in targets:
if key.items() < target.items():
return target
</code></pre>
<p>This finds the <em>first</em> match only.</p>
<p>You could turn this into a one-liner:</p>
<pre><code>next((target for target in targets if key.items() < target.items()), None)
</code></pre>
<p>If you must produce <strong>all</strong> matches, you can replace <code>return</code> with <code>yield</code> in the above method to turn it into a generator, or you could use a list comprehension:</p>
<pre><code>[target for target in targets if key.items() < target.items()]
</code></pre>
<p>The above uses Python 3 syntax. In Python 2, dictionary views are available through the special <code>.viewkeys()</code>, <code>.viewvalues()</code> and <code>.viewitems()</code> methods, so add in <code>view</code> to the method name:</p>
<pre><code>def find(targets, key):
# Python 2 version
for target in targets:
if key.viewitems() < target.viewitems():
return target
</code></pre>
<p>Demo (on Python 3):</p>
<pre><code>>>> targets = [
... {"id": 0, "X": (), "Y": (), "Z": () },
... {"id": 1, "X": (1,), "Y": (5,), "Z": ()},
... {"id": 2, "X": (1,), "Y": (5, 7), "Z": ()},
... {"id": 3, "X": (2,), "Y": (5, 7), "Z": (1,)},
... {"id": 4, "X": (1, 2), "Y": (5, 7), "Z": (1,)},
... {"id": 5, "X": (1, 2), "Y": (5, 7), "Z": (1,3)},
... ]
>>> key = {"X": (1,), "Y": (5, 7), "Z": ()}
>>> def find(targets, key):
... for target in targets:
... if key.items() < target.items():
... return target
...
>>> find(targets, key)
{'Y': (5, 7), 'X': (1,), 'Z': (), 'id': 2}
>>> next((target for target in targets if key.items() < target.items()), None)
{'Y': (5, 7), 'X': (1,), 'Z': (), 'id': 2}
>>> [target for target in targets if key.items() < target.items()]
[{'Y': (5, 7), 'X': (1,), 'Z': (), 'id': 2}]
</code></pre>
| 2 |
2016-09-12T09:14:47Z
|
[
"python",
"tuples"
] |
tkinter in tkinter makes value disappear (python 3.4.3)
| 39,446,694 |
<p>I wrote this piece of code, which is supposed to ask a user if all of his files have the same date and if yes, that he should write his date into a grid.
After entering the dates both windows should disappear and i want to keep the date.
Unfortunately I don't manage to let the first Input-Box disappear and after this whole procedure the entry date is [ ] again.</p>
<pre><code> from tkinter import *
entry_date = []
if amountfiles == 1:
def moredates():
master.destroy()
def setdate():
def entry_date():
entry_date = e1.get()
entry_date = str(entry_date)
print("Date for all files is: ",entry_date)
master.destroy()
def quit():
sys.exit()
master = Tk()
Label(master, text="Please enter date (format YYYYMMDD, i.e. 20160824): ").grid(row=0)
e1 = Entry(master)
e1.grid(row=0, column=1)
Button(master, text='Quit', command=master.destroy).grid(row=3, column=1, sticky=W, pady=4)
Button(master, text='Insert', command=entry_date).grid(row=2, column=1, sticky=W, pady=4)
mainloop( )
master = Tk()
Label(master, text="Do all files have the same date?").grid(row=0)
Button(master, text='No...', command=moredates).grid(row=2, column=0, sticky=W, pady=4)
Button(master, text='Yes!', command=setdate).grid(row=1, column=0, sticky=W, pady=4)
Button(master, text='Close & Contiune', command=master.destroy).grid(row=3, column=0, sticky=W, pady=4)
mainloop( )
</code></pre>
| -1 |
2016-09-12T09:01:51Z
| 39,447,757 |
<p>As the outer <code>master</code> variable is re-assigned in the function <code>setdate()</code>, the call <code>master.destroy()</code> will only close the new <code>master</code>, not the outer <code>master</code>. Try modifying the function <code>setdate()</code> as below:</p>
<pre><code>def setdate():
def append_date():
date = e1.get() # get the input entry date
entry_date.append(date) # save the input date
print("Date for all files is: ", date)
master.destroy()
top = Toplevel() # use Toplevel() instead of Tk()
Label(top, text="Please enter date (format YYYYMMDD, i.e. 20160824): ").grid(row=0)
e1 = Entry(top)
e1.grid(row=0, column=1)
Button(top, text='Quit', command=master.destroy).grid(row=3, column=1, sticky=W, pady=4)
Button(top, text='Insert', command=append_date).grid(row=2, column=1, sticky=W, pady=4)
master.wait_window(top) # use Tk.wait_window()
</code></pre>
| 1 |
2016-09-12T09:58:31Z
|
[
"python",
"tkinter",
"python-3.4"
] |
ImportError when importing elasticsearch.helpers in Python
| 39,446,705 |
<p>I am using a docker container with <strong>Ubuntu 16.04 Xenial</strong> with a <strong>Python 3.5.2</strong> virtual environment. Every time I am trying to initialize the server uWSGI I am getting the following Python error:</p>
<pre><code> File "/env/lib/python3.5/site-packages/elasticsearch_dsl/__init__.py", line 5, in <module>
from .search import Search
File "/env/lib/python3.5/site-packages/elasticsearch_dsl/search.py", line 3, in <module>
from elasticsearch.helpers import scan
ImportError: No module named 'elasticsearch.helpers'
</code></pre>
<p>I have been running the bash manually inside the docker container to see what is wrong with the module. By running <code>pip list</code> in the virtual environment I can tell that the packages are correctly installed:</p>
<pre><code># pip list
elasticsearch (2.1.0)
elasticsearch-dsl (0.0.8)
</code></pre>
<p>Running <strong>sys.path</strong> shows that the site packages folder was correctly added to the python path:</p>
<pre class="lang-python prettyprint-override"><code>import sys
sys.path
[
'',
'/env/lib/python35.zip',
'/env/lib/python3.5',
'/env/lib/python3.5/plat-x86_64-linux-gnu',
'/env/lib/python3.5/lib-dynload',
'/usr/lib/python3.5',
'/usr/lib/python3.5/plat-x86_64-linux-gnu',
'/env/lib/python3.5/site-packages'
]
</code></pre>
<p>There is a <strong>__init__.py</strong> file within the folder <strong>elasticsearch.helpers</strong> so that's not the problem. If I try the import from the Python console it will fail as well:</p>
<pre class="lang-python prettyprint-override"><code>from elasticsearch.helpers import scan
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'elasticsearch.helpers'
</code></pre>
<p>But now if I go to the site-packages folder <code>cd /env/lib/python3.5/site-packages</code> and run python console from here, the import will work. </p>
<p>I don't really know why this is happening any help will be appreciated.</p>
| 0 |
2016-09-12T09:02:09Z
| 39,457,911 |
<p>ouch... just a rookie mistake. One of the folders of my project was called elasticsearch and that was causing the issue.</p>
<p>Running the following command I found out that my app was simply loading the elasticsearch module from a different location. </p>
<pre class="lang-python prettyprint-override"><code>import elasticsearch
pprint.pprint(os.path.abspath(elasticsearch.__file__))
# /var/sites/my_app/elasticsearch/__init__.py
</code></pre>
| 0 |
2016-09-12T20:00:08Z
|
[
"python",
"docker",
"elasticsearch-py"
] |
print dir(XXX) gives out blank attributes
| 39,446,732 |
<p>In short, I work with an xlsx file and while checking some list with <code>print dir(alist)</code> get blank attributes.</p>
<pre><code>neglist = neglist.tolist()
</code></pre>
<p>At this point I want to check whether evth is Ok: </p>
<pre><code>def check_variab (variab):
print "The type is %s" % type(variab)
print "Its length = %i" % len(variab)
print "Its attributes are:" % dir(variab)
print 'neglist'
check_variab(neglist)
</code></pre>
<p>But what I get is:</p>
<pre><code>type: list
length: 19
attributes:
</code></pre>
<p>No attributes are printed though the type is list all right, its length and content is ok.</p>
<p>Could anyone explain why this happens?</p>
| -2 |
2016-09-12T09:03:14Z
| 39,446,808 |
<p>You forgot to use a <code>%s</code> placeholder, so <em>nothing</em> will be interpolated. Add <code>%s</code> or <code>%r</code>: </p>
<pre><code>print "Its attributes are %s:" % dir(variab)
# ^^ A placeholder for the value
</code></pre>
<p>Without that placeholder, you won't see anything, indeed:</p>
<pre><code>>>> variab = ['foo', 'bar']
>>> dir(variab)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
>>> print "Its attributes are:" % dir(variab)
Its attributes are:
>>> print "Its attributes are %s:" % dir(variab)
Its attributes are ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']:
</code></pre>
<p>You want to use <a href="https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange" rel="nofollow">standard sequence operations</a> on lists.</p>
| 0 |
2016-09-12T09:07:34Z
|
[
"python",
"list",
"xlsx"
] |
Double for loop in Python3
| 39,446,881 |
<p>There is list named L.
Which contains others list: L=[A,B,C,...N]
I want to for-loop, where B is no equal A (see #2)
Something like: for B is not A in L:</p>
<pre><code>for A in L: #1
for B in L: #2
</code></pre>
<p>How can I do that?</p>
| -1 |
2016-09-12T09:12:36Z
| 39,446,997 |
<p>Just access the rest of the list by index:</p>
<pre><code>for i in xrange(len(L)-1):
for j in xrange(i+1, len(L)):
#L[i] != L[j] always, and will check just one list against the others once
</code></pre>
| 0 |
2016-09-12T09:18:16Z
|
[
"python",
"python-3.x",
"permutation"
] |
Double for loop in Python3
| 39,446,881 |
<p>There is list named L.
Which contains others list: L=[A,B,C,...N]
I want to for-loop, where B is no equal A (see #2)
Something like: for B is not A in L:</p>
<pre><code>for A in L: #1
for B in L: #2
</code></pre>
<p>How can I do that?</p>
| -1 |
2016-09-12T09:12:36Z
| 39,461,025 |
<p>Better solution using <code>itertools</code>, either <a href="https://docs.python.org/3/library/itertools.html#itertools.permutations" rel="nofollow">with <code>permutations</code></a> or <a href="https://docs.python.org/3/library/itertools.html#itertools.combinations" rel="nofollow">with <code>combinations</code></a>:</p>
<pre><code>import itertools
# If it's okay to see L[1], L[2], and later L[2], L[1], that is, order sensitive,
# matching your original question's specification of only avoiding pairing with self:
for A, B in itertools.permutations(L, 2):
...
# If you only want to see L[x] paired with L[y] where y > x,
# equivalent to results of Daniel Sanchez's answer:
for A, B in itertools.combinations(L, 2):
...
</code></pre>
<p>Either one of these is significantly faster than using nested loops that require indexing (and bonus, requires only one level of indentation, reducing "arrow patterns" in your code).</p>
<p>If the body of the loop was <code>print(A, B, sep=',', end=' ')</code> and <code>L = [1, 2, 3]</code>, the output of the <code>permutations</code> loop would be:</p>
<pre><code>1,2 1,3 2,1 2,3 3,1 3,2
</code></pre>
<p>For <code>combinations</code>, you'd get:</p>
<pre><code>1,2 1,3 2,3
</code></pre>
<p>so choose whichever matches your desired behavior.</p>
<p>An additional benefit of using the <code>itertools</code> functions is that they'll work just fine when <code>L</code> is a non-sequence collection (e.g. a <code>set</code>), or when it's an iterator that can only be traversed once (they'll cache the values internally so they can produce them more than once). Other solutions require explicit conversion to <code>list</code>/<code>tuple</code> or the like to handle the "<code>L</code> is a one-use iterator" case.</p>
| 0 |
2016-09-13T01:37:06Z
|
[
"python",
"python-3.x",
"permutation"
] |
Double for loop in Python3
| 39,446,881 |
<p>There is list named L.
Which contains others list: L=[A,B,C,...N]
I want to for-loop, where B is no equal A (see #2)
Something like: for B is not A in L:</p>
<pre><code>for A in L: #1
for B in L: #2
</code></pre>
<p>How can I do that?</p>
| -1 |
2016-09-12T09:12:36Z
| 39,461,063 |
<p>You can use an <code>if</code> statement to filter out the cases you don't want:</p>
<pre><code>for A in L:
for B in L:
if A == B:
continue # skip
# do stuff ...
</code></pre>
| 0 |
2016-09-13T01:43:10Z
|
[
"python",
"python-3.x",
"permutation"
] |
pyqtgraph: simplest way to pause ipython script until user has placed a roi object
| 39,446,925 |
<p>I would like to implement the following sequence in a script and keep it as simple as possible (i.e., if possible avoid explicit multi-threading):</p>
<ol>
<li><p>Process some data. The result is a 2d numpy array, say <code>a</code></p></li>
<li><p>Show <code>a</code> using <code>pw = pg.show(a)</code> (after <code>import pyqtgraph as qt</code> and using pyqt5)</p></li>
<li><p>Define a circular roi, e.g. via</p></li>
</ol>
<p><code>circ = pg.CircleROI([1024,1024],300)
pw.addItem(circ)</code></p>
<ol start="4">
<li><p>The user moves the roi to the relevant place</p></li>
<li><p>Read out the roi coordinates, continue with the script (where the roi coordinates are used)</p></li>
</ol>
<p>My question is: How can I define a break in the script between 3. and 5. such that the user has time to do 4., in a way that the pyqtgraph is not blocked? Ideally, the user would confirm the correct roi position by pressing enter or clicking a button.</p>
<p>Edit: The script is executed in IPython with qt gui.</p>
<p>Edit2: Here is a full test script to be executed in IPython. What I want is that the user can move the circle before the roi is evaluated, i.e., that the print output is something different than <code>(slice(1024, 1174, None), slice(1024, 1174, None))</code></p>
<pre><code>import numpy as np
import pyqtgraph as pg
a = np.array(range(2048**2)).reshape((2048,2048))
pw = pg.show(a)
circ = pg.CircleROI([1024,1024],300)
pw.addItem(circ)
roi = np.s_[int(circ.pos().x()):int(circ.pos().x()+circ.size().x()/2),\
int(circ.pos().y()):int(circ.pos().y()+circ.size().x()/2)]
print(roi)
</code></pre>
| 0 |
2016-09-12T09:14:35Z
| 39,597,226 |
<h1>1. raw_input('') in an IPython console</h1>
<p>If the script is running in an IPython console, you could try adding a </p>
<pre><code>raw_input("Press Enter to continue...")
</code></pre>
<p>or <code>input()</code> in python3 to pause the script. The user has to go back and press enter in the ipython console but the code is simple.</p>
<pre><code>import numpy as np
import pyqtgraph as pg
a = np.array(range(2048**2)).reshape((2048,2048))
pw = pg.show(a)
circ = pg.CircleROI([1024,1024],300)
pw.addItem(circ)
raw_input("Press Enter to continue...")
roi = np.s_[int(circ.pos().x()):int(circ.pos().x()+circ.size().x()/2),\
int(circ.pos().y()):int(circ.pos().y()+circ.size().x()/2)]
print(roi)
</code></pre>
<h1>2. Monkey patching keyPressEvent</h1>
<p>Another solution could be to monkey patch the keyPressEvent in the ImageWindow.</p>
<p>Beware that this solution uses both <strong>globals</strong> and <strong>monkey patching</strong>, please make sure you know what this means.</p>
<pre><code>import numpy as np
from PyQt4 import QtCore, QtGui
import pyqtgraph as pg
a = np.array(range(2048**2)).reshape((2048,2048))
pw = pg.show(a)
circ = pg.CircleROI([1024,1024],300)
pw.addItem(circ)
def myKeyPressEvent(e):
if e.key() == QtCore.Qt.Key_Enter or e.key() == QtCore.Qt.Key_Return:
global selectionFinished
selectionFinished = True
# Monkey patch
selectionFinished = False
pw.keyPressEvent = myKeyPressEvent
while not selectionFinished:
QtGui.QApplication.processEvents()
roi = np.s_[int(circ.pos().x()):int(circ.pos().x()+circ.size().x()/2),\
int(circ.pos().y()):int(circ.pos().y()+circ.size().x()/2)]
print(roi)
</code></pre>
| 1 |
2016-09-20T14:48:06Z
|
[
"python",
"ipython",
"jupyter-notebook",
"pyqtgraph"
] |
Element wise comparison in an array of arrays in Numpy
| 39,446,944 |
<p>I have the following array of <code>shape(5,2,3)</code>, which is a collection of <code>2 * 3</code> arrays.</p>
<pre><code>a = array([[[ 0, 2, 0],
[ 3, 1, 1]],
[[ 1, 1, 0],
[ 2, 2, 1]],
[[ 0, 1, 0],
[ 3, 2, 1]],
[[-1, 2, 0],
[ 4, 1, 1]],
[[ 1, 0, 0],
[ 2, 3, 1]]])
</code></pre>
<p><strong>1)</strong> How can I check if there exists a <code>2 * 3</code> array in this array of arrays where at least one element is negative in it?</p>
<pre><code>#which is this:
[[-1, 2, 0],
[ 4, 1, 1]]
</code></pre>
<p><strong>2)</strong> After that how can I remove the above found <code>2 * 3</code> array from <code>a</code>?</p>
<p>A vectorized implementation is much appreciated but looping is fine too.</p>
| 2 |
2016-09-12T09:15:28Z
| 39,447,013 |
<p>You could do -</p>
<pre><code>a[~(a<0).any(axis=(1,2))]
</code></pre>
<p>Or the equivalent with <code>.all()</code> and thus avoid the <code>inverting</code> -</p>
<pre><code>a[(a>=0).all(axis=(1,2))]
</code></pre>
<p>Sample run -</p>
<pre><code>In [35]: a
Out[35]:
array([[[ 0, 2, 0],
[ 3, 1, 1]],
[[ 1, 1, 0],
[ 2, 2, 1]],
[[ 0, 1, 0],
[ 3, 2, 1]],
[[-1, 2, 0],
[ 4, 1, 1]],
[[ 1, 0, 0],
[ 2, 3, 1]]])
In [36]: a[~(a<0).any(axis=(1,2))]
Out[36]:
array([[[0, 2, 0],
[3, 1, 1]],
[[1, 1, 0],
[2, 2, 1]],
[[0, 1, 0],
[3, 2, 1]],
[[1, 0, 0],
[2, 3, 1]]])
</code></pre>
| 2 |
2016-09-12T09:18:51Z
|
[
"python",
"arrays",
"numpy",
"multidimensional-array",
"vectorization"
] |
Element wise comparison in an array of arrays in Numpy
| 39,446,944 |
<p>I have the following array of <code>shape(5,2,3)</code>, which is a collection of <code>2 * 3</code> arrays.</p>
<pre><code>a = array([[[ 0, 2, 0],
[ 3, 1, 1]],
[[ 1, 1, 0],
[ 2, 2, 1]],
[[ 0, 1, 0],
[ 3, 2, 1]],
[[-1, 2, 0],
[ 4, 1, 1]],
[[ 1, 0, 0],
[ 2, 3, 1]]])
</code></pre>
<p><strong>1)</strong> How can I check if there exists a <code>2 * 3</code> array in this array of arrays where at least one element is negative in it?</p>
<pre><code>#which is this:
[[-1, 2, 0],
[ 4, 1, 1]]
</code></pre>
<p><strong>2)</strong> After that how can I remove the above found <code>2 * 3</code> array from <code>a</code>?</p>
<p>A vectorized implementation is much appreciated but looping is fine too.</p>
| 2 |
2016-09-12T09:15:28Z
| 39,447,024 |
<p>Use <code>any</code>:</p>
<pre><code>In [10]: np.any(a<0,axis=-1)
Out[10]:
array([[False, False],
[False, False],
[False, False],
[ True, False],
[False, False]], dtype=bool)
</code></pre>
<p>Or more complete, if you want the corresponding index for (2,3) array:</p>
<pre><code>In [22]: np.where(np.any(a<0,axis=-1).any(axis=-1))
Out[22]: (array([3]),)
# Or as mentioned in comment you can pass a tuple to `any` np.where(np.any(a<0,axis=(1, 2)))
</code></pre>
<p>You can also get the array with a simple indexing:</p>
<pre><code>In [27]: a[np.any(a<0, axis=(1, 2))]
Out[27]:
array([[[-1, 2, 0],
[ 4, 1, 1]]])
</code></pre>
| 2 |
2016-09-12T09:19:12Z
|
[
"python",
"arrays",
"numpy",
"multidimensional-array",
"vectorization"
] |
How to extract an arbitrary line of values from a numpy matrix?
| 39,447,041 |
<p>i want to extract an interpolated straight line between two arbitrary points from a equidistant 3D matrix, such as:</p>
<pre><code>data_points_on_line=extract_line_from_3D_matrix(matrix,point1,point2,number_of_data_values_needed)
</code></pre>
<p>with the 3D matrix <code>matrix</code>, start and end point <code>point1</code>,<code>point2</code> and the resolution of returned data between <code>point1</code> and <code>point2</code> given by an integer with <code>number_of_data_values_needed</code>.</p>
<p>i know that it's pretty simple when extracting data from a 2d array with <code>scipy.ndimage</code> but does anybody know whether there's already a function in <code>scipy</code> or <code>numpy</code> which can do that in 3D?</p>
<p>many thanks in advance!</p>
| 0 |
2016-09-12T09:20:23Z
| 39,450,450 |
<p>it works for me using InterpolatingFunction, for example:</p>
<pre><code>#!/usr/bin/python
import numpy as np
from Scientific.Functions.Interpolation import InterpolatingFunction
def linear_interp_3d(point1,point2,spacing):
xi=np.linspace(point1[0],point2[0],spacing)
yi=np.linspace(point1[1],point2[1],spacing)
zi=np.linspace(point1[2],point2[2],spacing)
return xi,yi,zi
n=4
x = np.arange(0, n, 1)
y = np.arange(0, n, 1)
z = np.arange(0, n, 1)
data = np.ones(shape = (n, n, n))
for dummy in range(n):
data[dummy,:,:]=dummy**3
axes = (x,y,z)
f = InterpolatingFunction(axes, data)
point1=(0,0,0)
point2=(3,3,3)
linevals=linear_interp_3d(point1,point2,11)
line=[]
for dummy in range(len(linevals[0][:])):
line.append(f(linevals[0][dummy],linevals[1][dummy],linevals[2][dummy]))
print line
</code></pre>
| 0 |
2016-09-12T12:34:19Z
|
[
"python",
"numpy",
"scipy"
] |
How can I identify buttons, created in a loop?
| 39,447,138 |
<p>I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list of 10x10. Then I created each button using a loop just so I don't have to manually create every single button and clip them on. </p>
<pre><code>self.b=[[0 for x in range(1,12)] for y in range(1,12)] #The 2 dimensional list
for self.i in range(1,11):
for self.j in range(1,11):
self.b[self.i][self.j]=tkinter.Button(root,text = (" "),command = lambda: self.delete()) # creating the button
self.b[self.i][self.j].place(x=xp,y=yp) # placing the button
xp+=26 #because the width and height of the button is 26
yp+=26
xp=0
</code></pre>
<p>Basically I want the button to disappear upon being pressed. The problem is that I don't know how to let the program delete specifically the button that I pressed, as all the buttons are exactly the same. When creating the delete function:</p>
<pre><code>def delete(self):
self.b[???][???].destroy()
</code></pre>
<p>I don't know how to let the program know which button it was that the user presses, so it can delete that specific one.</p>
<p><strong>The question:</strong>
Is there a way to let each button have something unique that allows it to be differentiated from the other buttons? Say assign each button a specific coordinate, so when button (2,3) is pressed, the numbers 2 and 3 are passed onto the delete function, so the delete function can delete button (2,3)?</p>
| 0 |
2016-09-12T09:24:57Z
| 39,448,154 |
<p>Try modifying your code as below:</p>
<pre><code>self.b=[[0 for x in range(10)] for y in range(10)] #The 2 dimensional list
xp = yp = 0
for i in range(10):
for j in range(10):
self.b[i][j]=tkinter.Button(root,text=" ",command=lambda i=i,j=j: self.delete(i,j)) # creating the button
self.b[i][j].place(x=xp,y=yp) # placing the button
xp+=26 #because the width and height of the button is 26
yp+=26
xp=0
</code></pre>
<p>and:</p>
<pre><code>def delete(self, i, j):
self.b[i][j].destroy()
</code></pre>
| 1 |
2016-09-12T10:22:32Z
|
[
"python",
"tkinter",
"minesweeper"
] |
How can I identify buttons, created in a loop?
| 39,447,138 |
<p>I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list of 10x10. Then I created each button using a loop just so I don't have to manually create every single button and clip them on. </p>
<pre><code>self.b=[[0 for x in range(1,12)] for y in range(1,12)] #The 2 dimensional list
for self.i in range(1,11):
for self.j in range(1,11):
self.b[self.i][self.j]=tkinter.Button(root,text = (" "),command = lambda: self.delete()) # creating the button
self.b[self.i][self.j].place(x=xp,y=yp) # placing the button
xp+=26 #because the width and height of the button is 26
yp+=26
xp=0
</code></pre>
<p>Basically I want the button to disappear upon being pressed. The problem is that I don't know how to let the program delete specifically the button that I pressed, as all the buttons are exactly the same. When creating the delete function:</p>
<pre><code>def delete(self):
self.b[???][???].destroy()
</code></pre>
<p>I don't know how to let the program know which button it was that the user presses, so it can delete that specific one.</p>
<p><strong>The question:</strong>
Is there a way to let each button have something unique that allows it to be differentiated from the other buttons? Say assign each button a specific coordinate, so when button (2,3) is pressed, the numbers 2 and 3 are passed onto the delete function, so the delete function can delete button (2,3)?</p>
| 0 |
2016-09-12T09:24:57Z
| 39,448,908 |
<p>If you just want to destroy the Button widget, the simple way is to add the callback after you create the button. Eg,</p>
<pre><code>import Tkinter as tk
grid_size = 10
root = tk.Tk()
blank = " " * 3
for y in range(grid_size):
for x in range(grid_size):
b = tk.Button(root, text=blank)
b.config(command=b.destroy)
b.grid(column=x, row=y)
root.mainloop()
</code></pre>
<p>However, if you need to do extra processing in your callback, like updating your grid of buttons, it's convenient to store the Button's grid indices as an attribute of the Button object. </p>
<pre><code>from __future__ import print_function
import Tkinter as tk
class ButtonDemo(object):
def __init__(self, grid_size):
self.grid_size = grid_size
self.root = tk.Tk()
self.grid = self.button_grid()
self.root.mainloop()
def button_grid(self):
grid = []
blank = " " * 3
for y in range(self.grid_size):
row = []
for x in range(self.grid_size):
b = tk.Button(self.root, text=blank)
b.config(command=lambda widget=b: self.delete_button(widget))
b.grid(column=x, row=y)
#Store row and column indices as a Button attribute
b.position = (y, x)
row.append(b)
grid.append(row)
return grid
def delete_button(self, widget):
y, x = widget.position
print("Destroying", (y, x))
widget.destroy()
#Mark this button as invalid
self.grid[y][x] = None
ButtonDemo(grid_size=10)
</code></pre>
<p>Both of these scripts are compatible with Python 3, just change the import line to</p>
<pre><code>import tkinter as tk
</code></pre>
| 2 |
2016-09-12T11:04:45Z
|
[
"python",
"tkinter",
"minesweeper"
] |
How can I identify buttons, created in a loop?
| 39,447,138 |
<p>I am trying to program a minesweeper game on python using tkinter. I started off by creating a grid of buttons using a two dimensional list of 10x10. Then I created each button using a loop just so I don't have to manually create every single button and clip them on. </p>
<pre><code>self.b=[[0 for x in range(1,12)] for y in range(1,12)] #The 2 dimensional list
for self.i in range(1,11):
for self.j in range(1,11):
self.b[self.i][self.j]=tkinter.Button(root,text = (" "),command = lambda: self.delete()) # creating the button
self.b[self.i][self.j].place(x=xp,y=yp) # placing the button
xp+=26 #because the width and height of the button is 26
yp+=26
xp=0
</code></pre>
<p>Basically I want the button to disappear upon being pressed. The problem is that I don't know how to let the program delete specifically the button that I pressed, as all the buttons are exactly the same. When creating the delete function:</p>
<pre><code>def delete(self):
self.b[???][???].destroy()
</code></pre>
<p>I don't know how to let the program know which button it was that the user presses, so it can delete that specific one.</p>
<p><strong>The question:</strong>
Is there a way to let each button have something unique that allows it to be differentiated from the other buttons? Say assign each button a specific coordinate, so when button (2,3) is pressed, the numbers 2 and 3 are passed onto the delete function, so the delete function can delete button (2,3)?</p>
| 0 |
2016-09-12T09:24:57Z
| 39,449,125 |
<p>While creating buttons in a loop, we <em>can</em> create (actually get) the unique identity. </p>
<p>For example: if we create a button:</p>
<pre><code>button = Button(master, text="text")
</code></pre>
<p>we can identify it immediately:</p>
<pre><code>print(button)
> <tkinter.Button object .140278326922376>
</code></pre>
<p>If we store this identity into a list and asign a command to the button(s), linked to their index during creation, we can get their specific identity when pressed.</p>
<p>The only thing we have to to then is to fetch the button's identity by index, once the button is pressed.</p>
<p>To be able to set a command for the buttons <em>with the index as argument</em>, we use <code>functools</code>' <code>partial</code>.</p>
<h3>Simplified example (<code>python3</code>)</h3>
<p>In the simplified example below, we create the buttons in a loop, add their identities to the list (<code>button_identities</code>). The identity is fetched by looking it up with: <code>bname = (button_identities[n])</code>.</p>
<p>Now we have the identity, we can subsequently make the button do <em>anything</em>, including editing- or killing itself, since we have its identity.</p>
<p>In the example below, pressing the button will change its label to "clicked"</p>
<p><a href="http://i.stack.imgur.com/VJzVc.png" rel="nofollow"><img src="http://i.stack.imgur.com/VJzVc.png" alt="enter image description here"></a> </p>
<pre><code>from tkinter import *
from functools import partial
win = Tk()
button_identities = []
def change(n):
# function to get the index and the identity (bname)
print(n)
bname = (button_identities[n])
bname.configure(text = "clicked")
for i in range(5):
# creating the buttons, assigning a unique argument (i) to run the function (change)
button = Button(win, width=10, text=str(i), command=partial(change, i))
button.pack()
# add the button's identity to a list:
button_identities.append(button)
# just to show what happens:
print(button_identities)
win.mainloop()
</code></pre>
<p>Or if we make it <em>destroy</em> the buttons once clicked:</p>
<p><a href="http://i.stack.imgur.com/QvUrU.png" rel="nofollow"><img src="http://i.stack.imgur.com/QvUrU.png" alt="enter image description here"></a></p>
<pre><code>from tkinter import *
from functools import partial
win = Tk()
button_identities = []
def change(n):
# function to get the index and the identity (bname)
print(n)
bname = (button_identities[n])
bname.destroy()
for i in range(5):
# creating the buttons, assigning a unique argument (i) to run the function (change)
button = Button(win, width=10, text=str(i), command=partial(change, i))
button.place(x=0, y=i*30)
# add the button's identity to a list:
button_identities.append(button)
# just to show what happens:
print(button_identities)
win.mainloop()
</code></pre>
<h3>Simplified code for your matrix (python3):</h3>
<p>In the example below, I used <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow">itertools's product()</a> to generate the coordinates for the matrix.</p>
<p><a href="http://i.stack.imgur.com/oyfyW.png" rel="nofollow"><img src="http://i.stack.imgur.com/oyfyW.png" alt="enter image description here"></a></p>
<pre><code>#!/usr/bin/env python3
from tkinter import *
from functools import partial
from itertools import product
# produce the set of coordinates of the buttons
positions = product(range(10), range(10))
button_ids = []
def change(i):
# get the button's identity, destroy it
bname = (button_ids[i])
bname.destroy()
win = Tk()
frame = Frame(win)
frame.pack()
for i in range(10):
# shape the grid
setsize = Canvas(frame, width=30, height=0).grid(row=11, column=i)
setsize = Canvas(frame, width=0, height=30).grid(row=i, column=11)
for i, item in enumerate(positions):
button = Button(frame, command=partial(change, i))
button.grid(row=item[0], column=item[1], sticky="n,e,s,w")
button_ids.append(button)
win.minsize(width=270, height=270)
win.title("Too many squares")
win.mainloop()
</code></pre>
<h3>More options, destroying a button by coordinates</h3>
<p>Since <code>product()</code> also produces the x,y coordinates of the button(s), we can additionally store the coordinates (in <code>coords</code> in the example), and identify the button's identity by coordinates.</p>
<p>In the example below, the function <code>hide_by_coords():</code> destroys the button by coordinates, which can be useful in <code>minesweeper</code> -like game. As an example, clicking one button als destroys the one on the right:</p>
<pre><code>#!/usr/bin/env python3
from tkinter import *
from functools import partial
from itertools import product
positions = product(range(10), range(10))
button_ids = []; coords = []
def change(i):
bname = (button_ids[i])
bname.destroy()
# destroy another button by coordinates
# (next to the current one in this case)
button_nextto = coords[i]
button_nextto = (button_nextto[0] + 1, button_nextto[1])
hide_by_coords(button_nextto)
def hide_by_coords(xy):
# this function can destroy a button by coordinates
# in the matrix (topleft = (0, 0). Argument is a tuple
try:
index = coords.index(xy)
button = button_ids[index]
button.destroy()
except (IndexError, ValueError):
pass
win = Tk()
frame = Frame(win)
frame.pack()
for i in range(10):
# shape the grid
setsize = Canvas(frame, width=30, height=0).grid(row=11, column=i)
setsize = Canvas(frame, width=0, height=30).grid(row=i, column=11)
for i, item in enumerate(positions):
button = Button(frame, command=partial(change, i))
button.grid(column=item[0], row=item[1], sticky="n,e,s,w")
button_ids.append(button)
coords.append(item)
win.minsize(width=270, height=270)
win.title("Too many squares")
win.mainloop()
</code></pre>
| 1 |
2016-09-12T11:18:45Z
|
[
"python",
"tkinter",
"minesweeper"
] |
Is Numpy's argsort deterministic?
| 39,447,162 |
<p>Let's say I have a bunch of objects to sort, some of them having the same sorting criteria. Can I be certain <code>numpy.argsort()</code> will yield the same return every time ?</p>
<p>For example, If I call <code>argsort([0,0,1])</code>, will it return:</p>
<ul>
<li><p><code>[0,1,2]</code>?</p></li>
<li><p><code>[1,0,2]</code>?</p></li>
<li><p>it depends?</p></li>
</ul>
| 1 |
2016-09-12T09:26:04Z
| 39,447,202 |
<p>This is documented for the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.sort.html#numpy.sort" rel="nofollow"><code>numpy.sort()</code> function</a> (linked from the <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.argsort.html" rel="nofollow"><code>numpy.argsort()</code> page</a>).</p>
<p>Whether or not the sort is stable depends on the <em>sort algorithm</em> you picked. The default is to use <code>quicksort</code>, and quicksort is <em>not</em> a stable sort. If you <em>must</em> have a stable sort, use <code>kind='mergesort'</code> instead:</p>
<pre><code>kind speed worst case work space stable
âquicksortâ 1 O(n^2) 0 no
âmergesortâ 2 O(n*log(n)) ~n/2 yes
âheapsortâ 3 O(n*log(n)) 0 no
</code></pre>
<p>For your <em>specific</em> example, quicksort returns <code>[0, 1, 2]</code>, as does mergesort. Heapsort returns <code>[1, 0, 2]</code> instead:</p>
<pre><code>>>> from numpy import argsort
>>> argsort([0,0,1])
array([0, 1, 2])
>>> argsort([0,0,1], kind='mergesort')
array([0, 1, 2])
>>> argsort([0,0,1], kind='heapsort')
array([1, 0, 2])
</code></pre>
<p>However, given the <em>same input</em>, each sort algorithm will produce the <em>same output</em> again. You won't randomly see <code>1</code> and <code>0</code> swapped between runs with a given algorithm, even if it is an unstable. Instability doesn't imply randomness, it just means that the input order for values with the same sort key could end up being swapped. When values are swapped is entirely deterministic.</p>
<p>Also see the <a href="https://en.wikipedia.org/wiki/Sorting_algorithm#Stability" rel="nofollow"><em>stability</em> section</a> of the Wikipedia article on sorting algorithms.</p>
| 6 |
2016-09-12T09:28:22Z
|
[
"python",
"sorting",
"numpy"
] |
Get only stderr output from subprocess.check_output
| 39,447,238 |
<p>I want to run an external process in python, and process its <code>stderr</code> only.</p>
<p>I know I can use <code>subprocess.check_output</code>, but how can I redirect the stdout to <code>/dev/null</code> (or ignore it in any other way), and receive only the <code>stderr</code>?</p>
| 1 |
2016-09-12T09:30:10Z
| 39,447,963 |
<p>Unfortunately you have tagged this <a href="/questions/tagged/python-2.7" class="post-tag" title="show questions tagged 'python-2.7'" rel="tag">python-2.7</a>, as in python 3.5 and up this would be simple using <a href="https://docs.python.org/3/library/subprocess.html#subprocess.run" rel="nofollow"><code>run()</code></a>:</p>
<pre><code>import subprocess
output = subprocess.run(..., stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE).stderr
</code></pre>
<p>With <code>check_output()</code> stdout simply cannot be redirected:</p>
<pre><code>>>> subprocess.check_output(('ls', 'asdfqwer'), stdout=open(os.devnull, 'wb'), stderr=subprocess.STDOUT)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/subprocess.py", line 566, in check_output
raise ValueError('stdout argument not allowed, it will be overridden.')
ValueError: stdout argument not allowed, it will be overridden.
</code></pre>
<p>Use <a href="https://docs.python.org/2/library/subprocess.html#popen-objects" rel="nofollow"><code>Popen</code></a> objects and <a href="https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate" rel="nofollow"><code>communicate()</code></a> with python versions less than 3.5. Open <code>/dev/null</code> using <a href="https://docs.python.org/2/library/os.html#os.devnull" rel="nofollow"><code>os.devnull</code></a> in python 2.7:</p>
<pre><code>>>> import subprocess
>>> import os
>>> with open(os.devnull, 'wb') as devnull:
... proc = subprocess.Popen(('ls', 'asdfqwer'),
... stdout=devnull,
... stderr=subprocess.PIPE)
... proc.communicate()
... proc.returncode
...
(None, "ls: cannot access 'asdfqwer': No such file or directory\n")
2
</code></pre>
<p>Communicate sends input to stdin, if piped, and reads from stdout and stderr until end-of-file is reached.</p>
| 1 |
2016-09-12T10:10:46Z
|
[
"python",
"python-2.7",
"subprocess",
"stderr"
] |
Get only stderr output from subprocess.check_output
| 39,447,238 |
<p>I want to run an external process in python, and process its <code>stderr</code> only.</p>
<p>I know I can use <code>subprocess.check_output</code>, but how can I redirect the stdout to <code>/dev/null</code> (or ignore it in any other way), and receive only the <code>stderr</code>?</p>
| 1 |
2016-09-12T09:30:10Z
| 39,449,965 |
<p>I found a simple trick:</p>
<pre><code>import subprocess
stderr_str = subprocess.check_output('command 2>&1 >/dev/null')
</code></pre>
<p>This will filter out the stdout, and keeps only the stderr.</p>
| 0 |
2016-09-12T12:08:41Z
|
[
"python",
"python-2.7",
"subprocess",
"stderr"
] |
Python json schema that extracts parameters
| 39,447,263 |
<p>I need to parse requests to a single url that are coming in JSON, but in several different formats. For example, some have timestamp noted as <code>timestamp</code> attr, others as <code>unixtime</code> etc. So i want to create json schemas for all types of requests that not only validate incoming JSONs but also extract their parameters from specified places. Is there a library that can do that?</p>
<p>Example:</p>
<p>If I could define a schema that would look something like this</p>
<pre><code>schema = {
"type" : "object",
"properties" : {
"price" : {
"type" : "number",
"mapped_name": "product_price"
},
"name" : {
"type" : "string",
"mapped_name": "product_name"
},
"added_at":{
"type" : "int",
"mapped_name": "timestamp"
},
},
}
</code></pre>
<p>and then apply it to a dict </p>
<pre><code>request = {
"name" : "Eggs",
"price" : 34.99,
'added_at': 1234567
}
</code></pre>
<p>by some magical function</p>
<pre><code>params = validate_and_extract(request, schema)
</code></pre>
<p>I want <code>params</code> to have mapped values there:</p>
<pre><code>{"mapped_name": "Eggs", "product_price": 34.99, "timestamp": 1234567}
</code></pre>
<p>so this is a module I'm looking for. And it should support nested dicts in <code>request</code>, not just flat dicts.</p>
| 0 |
2016-09-12T09:31:37Z
| 39,449,386 |
<p>See <a href="http://json-schema.org" rel="nofollow">http://json-schema.org</a></p>
<p>This doesn't look like a Python question. </p>
| 0 |
2016-09-12T11:34:50Z
|
[
"python",
"json"
] |
Python json schema that extracts parameters
| 39,447,263 |
<p>I need to parse requests to a single url that are coming in JSON, but in several different formats. For example, some have timestamp noted as <code>timestamp</code> attr, others as <code>unixtime</code> etc. So i want to create json schemas for all types of requests that not only validate incoming JSONs but also extract their parameters from specified places. Is there a library that can do that?</p>
<p>Example:</p>
<p>If I could define a schema that would look something like this</p>
<pre><code>schema = {
"type" : "object",
"properties" : {
"price" : {
"type" : "number",
"mapped_name": "product_price"
},
"name" : {
"type" : "string",
"mapped_name": "product_name"
},
"added_at":{
"type" : "int",
"mapped_name": "timestamp"
},
},
}
</code></pre>
<p>and then apply it to a dict </p>
<pre><code>request = {
"name" : "Eggs",
"price" : 34.99,
'added_at': 1234567
}
</code></pre>
<p>by some magical function</p>
<pre><code>params = validate_and_extract(request, schema)
</code></pre>
<p>I want <code>params</code> to have mapped values there:</p>
<pre><code>{"mapped_name": "Eggs", "product_price": 34.99, "timestamp": 1234567}
</code></pre>
<p>so this is a module I'm looking for. And it should support nested dicts in <code>request</code>, not just flat dicts.</p>
| 0 |
2016-09-12T09:31:37Z
| 39,454,653 |
<p>The following code may help. It supports nested dict as well.</p>
<pre><code>import json
def valid_type(type_name, obj):
if type_name == "number":
return isinstance(obj, int) or isinstance(obj, float)
if type_name == "int":
return isinstance(obj, int)
if type_name == "float":
return isinstance(obj, float)
if type_name == "string":
return isinstance(obj, str)
def validate_and_extract(request, schema):
''' Validate request (dict) against the schema (dict).
Validation is limited to naming and type information.
No check is done to ensure all elements in schema
are present in the request. This could be enhanced by
specifying mandatory/optional/conditional information
within the schema and subsequently checking for that.
'''
out = {}
for k, v in request.items():
if k not in schema['properties'].keys():
print("Key '{}' not in schema ... skipping.".format(k))
continue
if schema['properties'][k]['type'] == 'object':
v = validate_and_extract(v, schema['properties'][k])
elif not valid_type(schema['properties'][k]['type'], v):
print("Wrong type for '{}' ... skipping.".format(k))
continue
out[schema['properties'][k]['mapped_name']] = v
return out
# Sample Data 1
schema1 = {
"type" : "object",
"properties" : {
"price" : {
"type" : "number",
"mapped_name": "product_price"
},
"name" : {
"type" : "string",
"mapped_name": "product_name"
},
"added_at":{
"type" : "int",
"mapped_name": "timestamp"
},
},
}
request1 = {
"name" : "Eggs",
"price" : 34.99,
'added_at': 1234567
}
# Sample Data 2: containing nested dict
schema2 = {
"type" : "object",
"properties" : {
"price" : {
"type" : "number",
"mapped_name": "product_price"
},
"name" : {
"type" : "string",
"mapped_name": "product_name"
},
"added_at":{
"type" : "int",
"mapped_name": "timestamp"
},
"discount":{
"type" : "object",
"mapped_name": "offer",
"properties" : {
"percent": {
"type" : "int",
"mapped_name": "percentage"
},
"last_date": {
"type" : "string",
"mapped_name": "end_date"
},
}
},
},
}
request2 = {
"name" : "Eggs",
"price" : 34.99,
'added_at': 1234567,
'discount' : {
'percent' : 40,
'last_date' : '2016-09-25'
}
}
params = validate_and_extract(request1, schema1)
print(params)
params = validate_and_extract(request2, schema2)
print(params)
</code></pre>
<p>Output from running this:</p>
<pre><code>{'timestamp': 1234567, 'product_name': 'Eggs', 'product_price': 34.99}
{'offer': {'percentage': 40, 'end_date': '2016-09-25'}, 'timestamp': 1234567, 'product_name': 'Eggs', 'product_price': 34.99}
</code></pre>
| 0 |
2016-09-12T16:16:37Z
|
[
"python",
"json"
] |
Equivalent ways to json.load a file in python?
| 39,447,362 |
<p>I often see this in code:</p>
<pre><code>with open(file_path) as f:
json_content = json.load(f)
</code></pre>
<p>And less often this:</p>
<pre><code>json_content = json.load(open(file_path))
</code></pre>
<p>I was wondering if the latter is an anti pattern or what the difference between the two versions is.</p>
| 2 |
2016-09-12T09:36:50Z
| 39,447,419 |
<p>When you use a context manager, it guarantees that your file will be close automatically at the end of block. The <a href="https://docs.python.org/3.5/reference/compound_stmts.html#with" rel="nofollow"><code>with</code> statement</a> does this by calling the <code>close</code> attribute of the file object, using its <code>__exit__()</code> method. </p>
<p>As said in document:</p>
<blockquote>
<p>The with statement guarantees that if the <code>__enter__()</code> method returns
without an error, then <code>__exit__()</code> will always be called.</p>
</blockquote>
<p>Read about more features <a href="https://docs.python.org/3.5/reference/compound_stmts.html#with" rel="nofollow">https://docs.python.org/3.5/reference/compound_stmts.html#with</a></p>
| 1 |
2016-09-12T09:39:57Z
|
[
"python",
"contextmanager"
] |
Equivalent ways to json.load a file in python?
| 39,447,362 |
<p>I often see this in code:</p>
<pre><code>with open(file_path) as f:
json_content = json.load(f)
</code></pre>
<p>And less often this:</p>
<pre><code>json_content = json.load(open(file_path))
</code></pre>
<p>I was wondering if the latter is an anti pattern or what the difference between the two versions is.</p>
| 2 |
2016-09-12T09:36:50Z
| 39,448,128 |
<p>In addition to other answers, a context manager is very similar to the try-finally clause.</p>
<p>This code:</p>
<pre><code>with open(file_path) as f:
json_content = json.load(f)
</code></pre>
<p>can be written as:</p>
<pre><code>f = open(file_path)
try:
json_content = json.load(f)
finally:
f.close()
</code></pre>
<p>The former is clearly preferable.</p>
| 0 |
2016-09-12T10:21:25Z
|
[
"python",
"contextmanager"
] |
Equivalent ways to json.load a file in python?
| 39,447,362 |
<p>I often see this in code:</p>
<pre><code>with open(file_path) as f:
json_content = json.load(f)
</code></pre>
<p>And less often this:</p>
<pre><code>json_content = json.load(open(file_path))
</code></pre>
<p>I was wondering if the latter is an anti pattern or what the difference between the two versions is.</p>
| 2 |
2016-09-12T09:36:50Z
| 39,449,488 |
<p><code>json.load(open(file_path))</code> relies on the GC to close the file. That's not a good idea: If someone doesn't use CPython the garbage collector might not be using refcounting (which collects unreferenced objects immediately) but e.g. collect garbage only after some time.</p>
<p>Since file handles are closed when the associated object is garbage collected or closed explicitly (<code>.close()</code> or <code>.__exit__()</code> from a context manager) the file will remain open until the GC kicks in.</p>
<p>Using <code>with</code> ensures the file is closed as soon as the block is left - even if an exception happens inside that block, so it should always be preferred for any real application.</p>
| 1 |
2016-09-12T11:40:52Z
|
[
"python",
"contextmanager"
] |
How to convert non-numeric entries to NaN in read_csv
| 39,447,559 |
<p>I am reading in a file with</p>
<pre><code>pd.read_csv("file.csv", dtype={'ID_1':float})
</code></pre>
<p>The file looks like</p>
<pre><code>ID_0, ID_1,ID_2
a,002,c
b,004,d
c, ,e
n,003,g
</code></pre>
<p>Unfortunately read_csv fails complaining it can't convert ' ' to a float.</p>
<p>What is the right way to read in a csv and convert anything that can't be converted to a float into NaN?</p>
| 2 |
2016-09-12T09:47:19Z
| 39,447,681 |
<p>This is my understanding of reading the documentation:</p>
<pre><code>def my_func(x):
try:
converted_value = float(x)
except ValueError:
converted_value = 'NaN'
return converted_value
pd.read_csv("file.csv", dtype={'ID_1':float}, converters={'ID_1':my_func})
</code></pre>
<p>As i am at work now and don't have access to <code>pandas</code> i cannot tell you if it works but it looks as it should (said every programmer ever..)</p>
<p>Also you might want to take a look at these relevant SO questions:</p>
<p><a href="http://stackoverflow.com/questions/18471859/pandas-read-csv-dtype-inference-issue">pandas read_csv dtype inference issue</a></p>
<p><a href="http://stackoverflow.com/questions/25669588/convert-percent-string-to-float-in-pandas-read-csv">Convert percent string to float in pandas read_csv</a></p>
<p>Finally, the <code>pandas.read_csv</code> documentation is <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html#pandas-read-csv" rel="nofollow">here</a></p>
| 2 |
2016-09-12T09:54:07Z
|
[
"python",
"pandas"
] |
How to convert non-numeric entries to NaN in read_csv
| 39,447,559 |
<p>I am reading in a file with</p>
<pre><code>pd.read_csv("file.csv", dtype={'ID_1':float})
</code></pre>
<p>The file looks like</p>
<pre><code>ID_0, ID_1,ID_2
a,002,c
b,004,d
c, ,e
n,003,g
</code></pre>
<p>Unfortunately read_csv fails complaining it can't convert ' ' to a float.</p>
<p>What is the right way to read in a csv and convert anything that can't be converted to a float into NaN?</p>
| 2 |
2016-09-12T09:47:19Z
| 39,447,702 |
<p>If you don't specify the <code>dtype</code> param and pass <code>skipinitialspace=True</code> then it will just work:</p>
<pre><code>In [4]:
t="""ID_0,ID_1,ID_2
a,002,c
b,004,d
c, ,e
n,003,g"""
pd.read_csv(io.StringIO(t), skipinitialspace=True)
Out[4]:
ID_0 ID_1 ID_2
0 a 2.0 c
1 b 4.0 d
2 c NaN e
3 n 3.0 g
</code></pre>
<p>So in your case:</p>
<pre><code>pd.read_csv("file.csv", skipinitialspace=True)
</code></pre>
<p>will just work</p>
<p>You can see that the <code>dtypes</code> are as expected:</p>
<pre><code>In [5]:
pd.read_csv(io.StringIO(t), skipinitialspace=True).info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
Data columns (total 3 columns):
ID_0 4 non-null object
ID_1 3 non-null float64
ID_2 4 non-null object
dtypes: float64(1), object(2)
memory usage: 176.0+ bytes
</code></pre>
| 4 |
2016-09-12T09:55:06Z
|
[
"python",
"pandas"
] |
How do I search for a saved fingerprint using sensor R305?
| 39,447,610 |
<p><strong>What am I doing?</strong>
I have GUI interface built using PyQt, which grants access to the users by validating their Fingerprint.</p>
<p>I am using Fingerprint sensor R305, for my module.</p>
<p><strong>My issue?</strong>
I have my code available on GIT, and it saves the data at a particular ID.
But it fails to search for the specified fingerprint.</p>
<p><strong>Enroll the fingerprint:</strong>
*</p>
<pre><code>ser = serial.Serial(port='COM4', baudrate=57600)
pack = [0xef01, 0xffffffff, 0x1]
def printx(l):
for i in l:
print (i)
print ('')
def readPacket():
time.sleep(1)
w = ser.inWaiting()
ret = []
if w >= 9:
s = ser.read(9) #partial read to get length
ret.extend(struct.unpack('!HIBH', s))
ln = ret[-1]
time.sleep(1)
w = ser.inWaiting()
if w >= ln:
s = ser.read(ln)
form = '!' + 'B' * (ln - 2) + 'H'
ret.extend(struct.unpack(form, s))
return ret
def writePacket(data):
pack2 = pack + [(len(data) + 2)]
a = sum(pack2[-2:] + data)
pack_str = '!HIBH' + 'B' * len(data) + 'H'
l = pack2 + data + [a]
s = struct.pack(pack_str, *l)
ser.write(s)
def verifyFinger():
data = [0x13, 0x0, 0, 0, 0]
writePacket(data)
s = readPacket()
return s[4]
def genImg():
data = [0x1]
writePacket(data)
s = readPacket()
return s[4]
def img2Tz(buf):
data = [0x2, buf]
writePacket(data)
s = readPacket()
return s[4]
def regModel():
data = [0x5]
writePacket(data)
s = readPacket()
return s[4]
def store(id):
data = [0x6, 0x1, 0x0, id]
writePacket(data)
s = readPacket()
return s[4]
if verifyFinger():
print ('Verification Error')
sys.exit(0)
print ('Put finger')
sys.stdout.flush()
time.sleep(1)
while genImg():
time.sleep(0.1)
print ('.')
sys.stdout.flush()
print ('')
sys.stdout.flush()
if img2Tz(1):
print ('Conversion Error')
sys.exit(0)
print ('Put finger again')
sys.stdout.flush()
time.sleep(1)
while genImg():
time.sleep(0.1)
print ('.')
sys.stdout.flush()
print ('')
sys.stdout.flush()
if img2Tz(2):
print ('Conversion Error')
sys.exit(0)
if regModel():
print ('Template Error')
sys.exit(0)
id = 1
if store(id):
print ('Store Error')
sys.exit(0)
print ("Enrolled successfully at id %d"%id)
*
</code></pre>
<p><strong>Searching the fingerprint:</strong>
*</p>
<pre><code>ser = serial.Serial('COM4',57600)
pack = [0xef01, 0xffffffff, 0x1]
def printx():
for i in l:
print(i)
print( '')
def readPacket():
time.sleep(1)
w = ser.inWaiting()
ret = []
if w >= 9:
s = ser.read(9) #partial read to get length
ret.extend(struct.unpack('!HIBH', s))
ln = ret[-1]
time.sleep(1)
w = ser.inWaiting()
if w >= ln:
s = ser.read(ln)
form = '!' + 'B' * (ln - 2) + 'H'
ret.extend(struct.unpack(form, s))
return ret
def writePacket(data):
pack2 = pack + [(len(data) + 2)]
a = sum(pack2[-2:] + data)
pack_str = '!HIBH' + 'B' * len(data) + 'H'
l = pack2 + data + [a]
s = struct.pack(pack_str, *l)
ser.write(s)
def verifyFinger():
data = [0x13, 0x0, 0, 0, 0]
writePacket(data)
s = readPacket()
return s[4]
def genImg():
data = [0x1]
writePacket(data)
s = readPacket()
return s[4]
def img2Tz(buf):
data = [0x2, buf]
writePacket(data)
s = readPacket()
return s[4]
def regModel():
data = [0x5]
writePacket(data)
s = readPacket()
return s[4]
def search():
data = [0x4, 0x1, 0x0, 0x0, 0x0, 0x5]
writePacket(data)
s = readPacket()
return s[4:-1]
def mainfuncn():
if verifyFinger():
print( 'Verification Error')
sys.exit(-1)
print('Put finger')
sys.stdout.flush()
time.sleep(1)
for _ in range(5):
g = genImg()
if g == 0:
break
#time.sleep(1)
print( '.')
sys.stdout.flush()
print( '')
sys.stdout.flush()
if g != 0:
sys.exit(-1)
if img2Tz(1):
print('Conversion Error')
sys.exit(-1)
r = search()
print('Search result', r)
if r[0] == 0 and r[2] in [0,1]:
print('Successful')
sys.exit(0)
else:
print('Unsuccessful')
sys.exit(1)
mainfuncn()
</code></pre>
<p>*</p>
<p><strong>THE GUI CODE:</strong>
*</p>
<pre><code>from PyQt4 import QtCore, QtGui
import serial, time, datetime, struct
import sys
import random
newarray=[]
distarray=[]
data1=""
m=""
k=0
ser = serial.Serial('COM4',57600)
pack = [0xef01, 0xffffffff, 0x1]
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("Dialog"))
Dialog.resize(400, 300)
self.verticalLayoutWidget = QtGui.QWidget(Dialog)
self.verticalLayoutWidget.setGeometry(QtCore.QRect(10, 10, 381, 281))
self.verticalLayoutWidget.setObjectName(_fromUtf8("verticalLayoutWidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.pushButton = QtGui.QPushButton(self.verticalLayoutWidget)
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.verticalLayout.addWidget(self.pushButton)
self.pushButton.clicked.connect(self.finger_call_main)
self.pushButton1 = QtGui.QPushButton(self.verticalLayoutWidget)
self.pushButton1.setObjectName(_fromUtf8("pushButton1"))
self.verticalLayout.addWidget(self.pushButton1)
self.pushButton1.clicked.connect(self.mainfuncn)
self.lineEdit = QtGui.QLineEdit(self.verticalLayoutWidget)
self.lineEdit.setText(_fromUtf8(""))
self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
self.verticalLayout.addWidget(self.lineEdit)
self.retranslateUi(Dialog)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def printx(self,l):
for i in l:
print (i)
print ('')
def readpacket(self):
time.sleep(1)
w = ser.inWaiting()
ret = []
if w >= 9:
s = ser.read(9) #partial read to get length
ret.extend(struct.unpack('!HIBH', s))
ln = ret[-1]
time.sleep(1)
w = ser.inWaiting()
if w >= ln:
s = ser.read(ln)
form = '!' + 'B' * (ln - 2) + 'H'
ret.extend(struct.unpack(form, s))
return ret
def writePacket(self,data):
pack2 = pack + [(len(data) + 2)]
a = sum(pack2[-2:] + data)
pack_str = '!HIBH' + 'B' * len(data) + 'H'
l = pack2 + data + [a]
s = struct.pack(pack_str, *l)
#print("Writepacket S value: " +s)
ser.write(s)
def verifyFinger(self):
data = [0x13, 0x0, 0, 0, 0]
self.writePacket(data)
s = self.readpacket()
return s[4]
def genImg(self):
data = [0x1]
self.writePacket(data)
s = self.readpacket()
return s[4]
def img2Tz(self,buf):
data = [0x2, buf]
self.writePacket(data)
s = self.readpacket()
return s[4]
def regModel(self):
data = [0x5]
self.writePacket(data)
s = self.readpacket()
return s[4]
def store(self,id):
data = [0x6, 0x1, 0x0, id]
self.writePacket(data)
s = self.readpacket()
return s[4]
def new(self):
m=random.randrange(1,250)
if m in distarray:
print("hii")
# newarray.append(m)
self.new()
else:
print("else")
distarray.append(m)
id1=m
print(id1)
return id1
#for x in distarray:
#print(x)
def search(self):
data = [0x4, 0x1, 0x0, 0x0, 0x0, 0x5]
self.writePacket(data)
s = self.readpacket()
return s[4:-1]
def finger_call_main(self):
if self.verifyFinger():
print ('Verification Error1')
sys.exit(0)
print ('Put finger')
sys.stdout.flush()
time.sleep(1)
while self.genImg():
time.sleep(0.1)
print ('.')
sys.stdout.flush()
print ('')
sys.stdout.flush()
if self.img2Tz(1):
print ('Conversion Error')
sys.exit(0)
print ('Put finger again')
sys.stdout.flush()
time.sleep(1)
while self.genImg():
time.sleep(0.1)
print ('.')
sys.stdout.flush()
print ('')
sys.stdout.flush()
if self.img2Tz(2):
print ('Conversion Error')
sys.exit(0)
if self.regModel():
print ('Template Error')
sys.exit(0)
id=self.new()
if self.store(id):
print ('Store Error')
sys.exit(0)
self.lineEdit.setText("Enrolled successfully at id %d"%id)
print ("Enrolled successfully at id %d"%id)
def mainfuncn(self):
if self.verifyFinger():
print( 'Verification Error')
sys.exit(-1)
print('Put finger')
sys.stdout.flush()
time.sleep(1)
for _ in range(5):
g = self.genImg()
if g == 0:
break
#time.sleep(1)
print( '.')
sys.stdout.flush()
print( '')
sys.stdout.flush()
if g != 0:
sys.exit(-1)
if self.img2Tz(1):
print('Conversion Error')
sys.exit(-1)
r = self.search()
#print('Search result', r)
if r[0] == 0:
print('Successful')
sys.exit(0)
else:
print('Unsuccessful')
sys.exit(1)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
self.pushButton.setText(_translate("Dialog", "PushButton", None))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
</code></pre>
<p>*</p>
| 1 |
2016-09-12T09:49:29Z
| 39,475,777 |
<p>After going through your code, I get that in your GUI code you are using new() to generate random id values for saving fingerprint template data. But in your search code you are checking the value of r[2] in array [0,1] which is actually your currently stored id list. This is why your search program cant find your fingerprint
To generate dynamic values of id in python you can use dynamic array or looping.
Replace this with your new() in GUI code:</p>
<pre><code> lst=[]
def new(self):
print("new")
def main1(self):
for z in range(0,256):
if z in lst:
z=z+1
self.new()
else:
lst.append(z)
a=z
z=z+1
break
return a
</code></pre>
<p>And get the value of id by calling main1():</p>
<pre><code> id=self.main1()
</code></pre>
<p>And in your search code make the following changes:</p>
<pre><code> if r[0]==0 and r[2] in lst:
</code></pre>
| 1 |
2016-09-13T17:26:17Z
|
[
"python",
"pyqt",
"fingerprint"
] |
How to delete column from .csv file without reading the whole file
| 39,447,644 |
<p>I generate very big .csv file but now it doesn't fit the RAM. So i decided to delete some inefficient columns to reduce the file size. How can I do that? </p>
<p>I tried data = <code>pd.read_csv("file.csv", index_col=0, usecols=["id", "wall"])</code> but it still doesn't fit the RAM.</p>
<p>File is about 1.5GB, RAM is 8GB. </p>
| 0 |
2016-09-12T09:51:18Z
| 39,448,247 |
<p>Instead of deleting columns, you can also read specific columns from csv file using a <code>DictReader</code> (if you're not using <code>Pandas</code> ).</p>
<pre><code>import csv
from StringIO import StringIO
columns = 'AAA,DDD,FFF,GGG'.split(',')
testdata ='''\
AAA,bbb,ccc,DDD,eee,FFF,GGG,hhh
1,2,3,4,50,3,20,4
2,1,3,5,24,2,23,5
4,1,3,6,34,1,22,5
2,1,3,5,24,2,23,5
2,1,3,5,24,2,23,5
'''
reader = csv.DictReader(StringIO(testdata))
desired_cols = (tuple(row[col] for col in columns) for row in reader)
</code></pre>
<p>Output:</p>
<pre><code>>>> list(desired_cols)
[('1', '4', '3', '20'),
('2', '5', '2', '23'),
('4', '6', '1', '22'),
('2', '5', '2', '23'),
('2', '5', '2', '23')]
</code></pre>
<p>Source: <a href="http://stackoverflow.com/a/20065131/6633975">http://stackoverflow.com/a/20065131/6633975</a></p>
<p><strong>Using Pandas:</strong></p>
<p>Here is an example illustrating the answer given by EdChum. There is a lot of additional options to load a CSV file, check the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow">API reference</a>.</p>
<pre><code>import pandas as pd
raw_data = {'first_name': ['Steve', 'Guido', 'John'],
'last_name': ['Jobs', 'Van Rossum', "von Neumann"]}
df = pd.DataFrame(raw_data)
# Saving data without header
df.to_csv(path_or_buf='test.csv', header=False)
# Telling that there is no header and loading only the first name
df = pd.read_csv(filepath_or_buffer='test.csv', header=None, usecols=[1], names=['first_name'])
df
first_name
0 Steve
1 Guido
2 John
</code></pre>
| 1 |
2016-09-12T10:27:45Z
|
[
"python",
"csv",
"pandas"
] |
How to delete column from .csv file without reading the whole file
| 39,447,644 |
<p>I generate very big .csv file but now it doesn't fit the RAM. So i decided to delete some inefficient columns to reduce the file size. How can I do that? </p>
<p>I tried data = <code>pd.read_csv("file.csv", index_col=0, usecols=["id", "wall"])</code> but it still doesn't fit the RAM.</p>
<p>File is about 1.5GB, RAM is 8GB. </p>
| 0 |
2016-09-12T09:51:18Z
| 39,448,415 |
<p>I am not sure if this is possible in pandas. You can try to do it in the Command Line. On Linux it will look like: </p>
<pre><code>cut -f1,2,5- inputfile
</code></pre>
<p>if you want to delete columns with indexes 3 and 4.</p>
| 0 |
2016-09-12T10:37:33Z
|
[
"python",
"csv",
"pandas"
] |
How to remove newline characters from csv file
| 39,447,740 |
<p>I have the below part of code that reads values from the csv file "prom output.csv" and writes them sorted in a new one "sorted output.csv".</p>
<pre><code>import collections
import csv
with open("prom output.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr)
for r in cr:
d[r[0]].append(r[1])
with open("sorted output.csv","w") as f:
cr = csv.writer(f,delimiter=",")
cr.writerow(header)
od = collections.OrderedDict(sorted(d.items()))
for k,v in od.items(): s
cr.writerow([k,",".join(v)])
</code></pre>
<p>However the output (see below) has spaces between each line and i would like to remove them. Can anybody help?</p>
<p><a href="http://i.stack.imgur.com/y6RSD.png" rel="nofollow"><img src="http://i.stack.imgur.com/y6RSD.png" alt="enter image description here"></a></p>
<p>The input file "prom output.csv" has no spaces between each line as seen below</p>
<p><a href="http://i.stack.imgur.com/SpOER.png" rel="nofollow"><img src="http://i.stack.imgur.com/SpOER.png" alt="enter image description here"></a></p>
<p>as a last midification i would like my output to look like: </p>
<p><a href="http://i.stack.imgur.com/o0igJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/o0igJ.png" alt="enter image description here"></a></p>
<p>any suggestions?</p>
| 0 |
2016-09-12T09:57:21Z
| 39,448,049 |
<p>The Python newline character is, '\n'. Therefore to remove the newline character (and hence the blank lines that are being printed) from your string, try:</p>
<pre><code>cr.writerow([k, (",".join(v)), .strip("\n")])
</code></pre>
| -1 |
2016-09-12T10:16:00Z
|
[
"python",
"excel",
"csv"
] |
How to remove newline characters from csv file
| 39,447,740 |
<p>I have the below part of code that reads values from the csv file "prom output.csv" and writes them sorted in a new one "sorted output.csv".</p>
<pre><code>import collections
import csv
with open("prom output.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr)
for r in cr:
d[r[0]].append(r[1])
with open("sorted output.csv","w") as f:
cr = csv.writer(f,delimiter=",")
cr.writerow(header)
od = collections.OrderedDict(sorted(d.items()))
for k,v in od.items(): s
cr.writerow([k,",".join(v)])
</code></pre>
<p>However the output (see below) has spaces between each line and i would like to remove them. Can anybody help?</p>
<p><a href="http://i.stack.imgur.com/y6RSD.png" rel="nofollow"><img src="http://i.stack.imgur.com/y6RSD.png" alt="enter image description here"></a></p>
<p>The input file "prom output.csv" has no spaces between each line as seen below</p>
<p><a href="http://i.stack.imgur.com/SpOER.png" rel="nofollow"><img src="http://i.stack.imgur.com/SpOER.png" alt="enter image description here"></a></p>
<p>as a last midification i would like my output to look like: </p>
<p><a href="http://i.stack.imgur.com/o0igJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/o0igJ.png" alt="enter image description here"></a></p>
<p>any suggestions?</p>
| 0 |
2016-09-12T09:57:21Z
| 39,451,664 |
<p>apparently changing the line: <code>cr = csv.writer(f,lineterminator='\n')</code>
into: <code>cr = csv.writer(f,sys.stdout, lineterminator='\n')</code> and adding <code>import sys</code> to the imports solves the problem.</p>
| 0 |
2016-09-12T13:37:26Z
|
[
"python",
"excel",
"csv"
] |
How to remove newline characters from csv file
| 39,447,740 |
<p>I have the below part of code that reads values from the csv file "prom output.csv" and writes them sorted in a new one "sorted output.csv".</p>
<pre><code>import collections
import csv
with open("prom output.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collections.defaultdict(lambda : list())
header=next(cr)
for r in cr:
d[r[0]].append(r[1])
with open("sorted output.csv","w") as f:
cr = csv.writer(f,delimiter=",")
cr.writerow(header)
od = collections.OrderedDict(sorted(d.items()))
for k,v in od.items(): s
cr.writerow([k,",".join(v)])
</code></pre>
<p>However the output (see below) has spaces between each line and i would like to remove them. Can anybody help?</p>
<p><a href="http://i.stack.imgur.com/y6RSD.png" rel="nofollow"><img src="http://i.stack.imgur.com/y6RSD.png" alt="enter image description here"></a></p>
<p>The input file "prom output.csv" has no spaces between each line as seen below</p>
<p><a href="http://i.stack.imgur.com/SpOER.png" rel="nofollow"><img src="http://i.stack.imgur.com/SpOER.png" alt="enter image description here"></a></p>
<p>as a last midification i would like my output to look like: </p>
<p><a href="http://i.stack.imgur.com/o0igJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/o0igJ.png" alt="enter image description here"></a></p>
<p>any suggestions?</p>
| 0 |
2016-09-12T09:57:21Z
| 39,488,432 |
<p>This is a simple feasible solution:</p>
<pre><code>import collections
import csv
with open('prom output.csv') as f:
header = next(csv.reader(f))
d = collections.OrderedDict()
for r in csv.reader(f):
try:
d[r[0]] += ','+r[1]
except:
d[r[0]] = ','+r[1]
with open('sorted output.csv', 'w') as f:
cw = csv.writer(f)
cw.writerow(header)
for k, v in d.items():
f.write(k+v+'\n')
</code></pre>
<p>For the input of the following CSV file (<code>prom output.csv</code>):</p>
<pre>
case,event,startTime,completeTime
101,A
101,B
101,Y
102,C
102,D
102,U
103,A
103,B
103,Y
</pre>
<p>The output was (<code>sorted output.csv</code>):</p>
<pre>
case,event,startTime,completeTime
101,A,B,Y
102,C,D,U
103,A,B,Y
</pre>
<p>Which is the output as you intended it to be.</p>
| 0 |
2016-09-14T10:42:42Z
|
[
"python",
"excel",
"csv"
] |
Pycharm expected type 'optional[bytes]' got 'str' instead
| 39,447,741 |
<p>I am using <code>rsplit</code> to split up a path name, </p>
<pre><code>rootPath = os.path.abspath(__file__)
rootPath = (rootPath.rsplit('/', 1)[0]).rsplit('/', 1)[0]
</code></pre>
<p>But <strong>Pycharm</strong> warns,</p>
<blockquote>
<p>expected type <code>optional [bytes]</code>, got <code>str</code> instead</p>
</blockquote>
<p>In <code>python doc</code>, it stated <em>using <code>sep</code> as the delimiter string</em>. </p>
<p>So how to fix this?</p>
| 2 |
2016-09-12T09:57:25Z
| 39,450,149 |
<p>I'm guessing <code>rootPath</code> is a bytes object and PyCharm is warning you that the <code>sep</code> parameter on <code>rsplit</code> has to either be <code>None</code> or <code>bytes</code>. That's specified in the beginning of the Documentation on <a href="https://docs.python.org/3/library/stdtypes.html#bytes-methods" rel="nofollow">Bytes and ByteArray Operations:</a></p>
<blockquote>
<p>The methods on bytes and bytearray objects donât accept strings as their arguments, just as the methods on strings donât accept bytes as their arguments.</p>
</blockquote>
<p>That's what <a href="https://docs.python.org/3/library/typing.html#typing.Optional" rel="nofollow"><code>Optional</code></a> means, <code>Optional[type]</code> is either <code>None</code> or <code>type</code> which in your case is <code>bytes</code>.</p>
<p>In a simple Python REPL the message is slightly different but the gist is the same:</p>
<pre><code>b'hello/world'.rsplit('/') # error bytes-like object required
</code></pre>
<p>Instead you need to supply a <code>byte</code> separator:</p>
<pre><code>b'hello/world'.rsplit(b'/')
</code></pre>
<p>or <code>None</code> in order to get it to work.</p>
| 1 |
2016-09-12T12:18:47Z
|
[
"python",
"python-3.x",
"split",
"pycharm"
] |
NameError: global name 'UserProfile' is not defined
| 39,447,797 |
<pre><code># getting error while i am running my register user code
</code></pre>
<p><a href="http://i.stack.imgur.com/QBzxZ.png" rel="nofollow">enter image description here</a></p>
<pre><code>from django.shortcuts import render
from .forms import *
from django.core.context_processors import csrf
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
import hashlib, datetime, random
from django.contrib import auth
from django.core.mail import send_mail
from django.contrib.auth import authenticate, login
# Create your views here.
def index(request):
return render(request,'app/index.html')
def register_user(request):
args = {}
args.update(csrf(request))
if request.method == 'POST':
form = RegistrationForm(request.POST)
args['form'] = form
if form.is_valid():
form.save() # save user to database if form is valid
username = form.cleaned_data['username']
email = form.cleaned_data['email']
salt = hashlib.sha1(str(random.random())).hexdigest()[:5]
activation_key = hashlib.sha1(salt+email).hexdigest()
key_expires = datetime.datetime.today() + datetime.timedelta(2)
#Get user by username
user=User.objects.get(username=username)
# Create and save user profile
new_profile = UserProfile(user=user, activation_key=activation_key,
key_expires=key_expires)
new_profile.save()
# Send email with activation key
email_subject = 'Account confirmation'
email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \
48hours http://127.0.0.1:8000/confirm/%s" % (username, activation_key)
send_mail(email_subject, email_body, 'myemail@example.com',
[email], fail_silently=False)
return render(request,'app/success',{})
else:
args['form'] = RegistrationForm()
return render_to_response('app/register.html', args, context_instance=RequestContext(request))
</code></pre>
| -3 |
2016-09-12T10:00:48Z
| 39,449,995 |
<p>You must have created class <code>UserProfile</code> in your models.py. You need to import this into your views to get the code working. </p>
| 0 |
2016-09-12T12:10:04Z
|
[
"python",
"django"
] |
Use module as class instance in Python
| 39,447,800 |
<h2>TL; DR</h2>
<p>Basically the question is about hiding from the user the fact that my modules have class implementations so that the user can use the module as if it has direct function definitions like <code>my_module.func()</code></p>
<h2>Details</h2>
<p>Suppose I have a module <code>my_module</code> and a class <code>MyThing</code> that lives in it. For example:</p>
<pre><code># my_module.py
class MyThing(object):
def say():
print("Hello!")
</code></pre>
<p>In another module, I might do something like this:</p>
<pre><code># another_module.py
from my_module import MyThing
thing = MyThing()
thing.say()
</code></pre>
<p>But suppose that I don't want to do all that. What I really want is for <code>my_module</code> to create an instance of MyThing automatically on <code>import</code> such that I can just do something like the following:</p>
<pre><code># yet_another_module.py
import my_module
my_module.say()
</code></pre>
<p>In other words, whatever method I call on the module, I want it to be forwarded directly to a default instance of the class contained in it. So, to the user of the module, it might seem that there is no class in it, just direct function definitions in the module itself (where the functions are actually methods of a class contained therein). Does that make sense? Is there a short way of doing this?</p>
<p>I know I could do the following in <code>my_module</code>:</p>
<pre><code>class MyThing(object):
def say():
print("Hello!")
default_thing = MyThing()
def say():
default_thing.say()
</code></pre>
<p>But then suppose <code>MyThing</code> has many "public" methods that I want to use, then I'd have to explicitly define a "forwarding" function for every method, which I don't want to do.</p>
<p>As an extension to my question above, is there a way to achieve what I want above, but also be able to use code like <code>from my_module import *</code> and be able to use methods of <code>MyThing</code> directly in another module, like <code>say()</code>? </p>
| 2 |
2016-09-12T10:00:55Z
| 39,447,948 |
<p>Not Sure why this wouldn't work.</p>
<pre><code>say = MyClass().say()
from my_module import *
say
>>Hello!
</code></pre>
| 0 |
2016-09-12T10:10:04Z
|
[
"python",
"class",
"module"
] |
Use module as class instance in Python
| 39,447,800 |
<h2>TL; DR</h2>
<p>Basically the question is about hiding from the user the fact that my modules have class implementations so that the user can use the module as if it has direct function definitions like <code>my_module.func()</code></p>
<h2>Details</h2>
<p>Suppose I have a module <code>my_module</code> and a class <code>MyThing</code> that lives in it. For example:</p>
<pre><code># my_module.py
class MyThing(object):
def say():
print("Hello!")
</code></pre>
<p>In another module, I might do something like this:</p>
<pre><code># another_module.py
from my_module import MyThing
thing = MyThing()
thing.say()
</code></pre>
<p>But suppose that I don't want to do all that. What I really want is for <code>my_module</code> to create an instance of MyThing automatically on <code>import</code> such that I can just do something like the following:</p>
<pre><code># yet_another_module.py
import my_module
my_module.say()
</code></pre>
<p>In other words, whatever method I call on the module, I want it to be forwarded directly to a default instance of the class contained in it. So, to the user of the module, it might seem that there is no class in it, just direct function definitions in the module itself (where the functions are actually methods of a class contained therein). Does that make sense? Is there a short way of doing this?</p>
<p>I know I could do the following in <code>my_module</code>:</p>
<pre><code>class MyThing(object):
def say():
print("Hello!")
default_thing = MyThing()
def say():
default_thing.say()
</code></pre>
<p>But then suppose <code>MyThing</code> has many "public" methods that I want to use, then I'd have to explicitly define a "forwarding" function for every method, which I don't want to do.</p>
<p>As an extension to my question above, is there a way to achieve what I want above, but also be able to use code like <code>from my_module import *</code> and be able to use methods of <code>MyThing</code> directly in another module, like <code>say()</code>? </p>
| 2 |
2016-09-12T10:00:55Z
| 39,448,048 |
<p>In module <code>my_module</code> do the following:</p>
<pre><code>class MyThing(object):
...
_inst = MyThing()
say = _inst.say
move = _inst.move
</code></pre>
<p>This is <em>exactly</em> the pattern used by the <a href="https://github.com/python/cpython/blob/master/Lib/random.py#L736" rel="nofollow"><code>random</code> module</a>.</p>
<p>Doing this automatically is somewhat contrived. First, one needs to find out <em>which</em> of the instance/class attributes are the methods to export... perhaps export only names which do not start with <code>_</code>, something like</p>
<pre><code>import inspect
for name, member in inspect.getmembers(Foo(), inspect.ismethod):
if not name.startswith('_'):
globals()[name] = member
</code></pre>
<p>However in this case I'd say that explicit is better than implicit.</p>
| 3 |
2016-09-12T10:15:59Z
|
[
"python",
"class",
"module"
] |
Use module as class instance in Python
| 39,447,800 |
<h2>TL; DR</h2>
<p>Basically the question is about hiding from the user the fact that my modules have class implementations so that the user can use the module as if it has direct function definitions like <code>my_module.func()</code></p>
<h2>Details</h2>
<p>Suppose I have a module <code>my_module</code> and a class <code>MyThing</code> that lives in it. For example:</p>
<pre><code># my_module.py
class MyThing(object):
def say():
print("Hello!")
</code></pre>
<p>In another module, I might do something like this:</p>
<pre><code># another_module.py
from my_module import MyThing
thing = MyThing()
thing.say()
</code></pre>
<p>But suppose that I don't want to do all that. What I really want is for <code>my_module</code> to create an instance of MyThing automatically on <code>import</code> such that I can just do something like the following:</p>
<pre><code># yet_another_module.py
import my_module
my_module.say()
</code></pre>
<p>In other words, whatever method I call on the module, I want it to be forwarded directly to a default instance of the class contained in it. So, to the user of the module, it might seem that there is no class in it, just direct function definitions in the module itself (where the functions are actually methods of a class contained therein). Does that make sense? Is there a short way of doing this?</p>
<p>I know I could do the following in <code>my_module</code>:</p>
<pre><code>class MyThing(object):
def say():
print("Hello!")
default_thing = MyThing()
def say():
default_thing.say()
</code></pre>
<p>But then suppose <code>MyThing</code> has many "public" methods that I want to use, then I'd have to explicitly define a "forwarding" function for every method, which I don't want to do.</p>
<p>As an extension to my question above, is there a way to achieve what I want above, but also be able to use code like <code>from my_module import *</code> and be able to use methods of <code>MyThing</code> directly in another module, like <code>say()</code>? </p>
| 2 |
2016-09-12T10:00:55Z
| 39,448,114 |
<p>You could just replace:</p>
<pre><code>def say():
return default_thing.say()
</code></pre>
<p>with:</p>
<pre><code>say = default_thing.say
</code></pre>
<p>You still have to list everything that's forwarded, but the boilerplate is fairly concise.</p>
<p>If you want to replace that boilerplate with something more automatic, note that (details depending on Python version), <code>MyThing.__dict__.keys()</code> is something along the lines of <code>['__dict__', '__weakref__', '__module__', 'say', '__doc__']</code>. So in principle you could iterate over that, skip the <code>__</code> Python internals, and call <code>setattr</code> on the current module (which is available as <code>sys.modules[__name__]</code>). You might later regret not listing this stuff explicitly in the code, but you could certainly do it.</p>
<p>Alternatively you <em>could</em> get rid of the class entirely as use the module as the unit of encapsulation. Wherever there is data on the object, replace it with global variables. "But", you might say, "I've been warned against using global variables because supposedly they cause problems". The bad news is that you've already created a global variable, <code>default_thing</code>, so the ship has sailed on that one. The even worse news is that if there is any data on the object, then the whole concept of what you want to do: module-level functions that mutate a shared global state, carries with it most of the problems of globals.</p>
| 2 |
2016-09-12T10:20:27Z
|
[
"python",
"class",
"module"
] |
How to write output file in CSV format in python?
| 39,447,817 |
<p>I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.</p>
<p>Getting error in Python 3.5:</p>
<pre><code>wr.writerow(var)
TypeError: a bytes-like object is required, not 'str'
</code></pre>
<p>and </p>
<p>In Python 2.7, I am getting all column result in one column. </p>
<p>Expected Result:<br>
An output file same format as the input file.</p>
<p>Code:</p>
<pre><code>import csv
f1 = open("input_1.csv", "r")
resultFile = open("out.csv", "wb")
wr = csv.writer(resultFile, quotechar=',')
def sort_duplicates(f1):
for i in range(0, len(f1)):
f1.insert(f1.index(f1[i])+1, f1[i])
f1.pop(i+1)
for var in f1:
#print (var)
wr.writerow([var])
</code></pre>
<p>If I am using <code>resultFile = open("out.csv", "w")</code>, I get one row extra in the output file. </p>
<p>If I am using above code, getting one row and column extra.</p>
| 1 |
2016-09-12T10:01:57Z
| 39,447,867 |
<p>On Python 3, <code>csv</code> <em>requires</em> that you open the file in text mode, not binary mode. Drop the <code>b</code> from your file mode. You should really use <code>newline=''</code> too:</p>
<pre><code>resultFile = open("out.csv", "w", newline='')
</code></pre>
<p>Better still, use the file object as a context manager to ensure it is closed automatically:</p>
<pre><code>with open("input_1.csv", "r") as f1, \
open("out.csv", "w", newline='') as resultFile:
wr = csv.writer(resultFile, dialect='excel')
for var in f1:
wr.writerow([var.rstrip('\n')])
</code></pre>
<p>I've also <em>stripped</em> the lines from <code>f1</code> (just to remove the newline) and put the line in a list; <code>csv.writer.writerow</code> wants a sequence with columns, not a single string.</p>
<p>Quoting the <a href="https://docs.python.org/3/library/csv.html#csv.writer" rel="nofollow"><code>csv.writer()</code> documentation</a>:</p>
<blockquote>
<p>If <em>csvfile</em> is a file object, it should be opened with <code>newline=''</code> [1]. <em>[...]</em> All other non-string data are stringified with <code>str()</code> before being written.</p>
<p>[1] If <code>newline=''</code> is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use <code>\r\n</code> linendings on write an extra <code>\r</code> will be added. It should always be safe to specify <code>newline=''</code>, since the csv module does its own (<a href="https://docs.python.org/3/glossary.html#term-universal-newlines" rel="nofollow">universal</a>) newline handling.</p>
</blockquote>
| 3 |
2016-09-12T10:04:56Z
|
[
"python",
"csv"
] |
How to write output file in CSV format in python?
| 39,447,817 |
<p>I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.</p>
<p>Getting error in Python 3.5:</p>
<pre><code>wr.writerow(var)
TypeError: a bytes-like object is required, not 'str'
</code></pre>
<p>and </p>
<p>In Python 2.7, I am getting all column result in one column. </p>
<p>Expected Result:<br>
An output file same format as the input file.</p>
<p>Code:</p>
<pre><code>import csv
f1 = open("input_1.csv", "r")
resultFile = open("out.csv", "wb")
wr = csv.writer(resultFile, quotechar=',')
def sort_duplicates(f1):
for i in range(0, len(f1)):
f1.insert(f1.index(f1[i])+1, f1[i])
f1.pop(i+1)
for var in f1:
#print (var)
wr.writerow([var])
</code></pre>
<p>If I am using <code>resultFile = open("out.csv", "w")</code>, I get one row extra in the output file. </p>
<p>If I am using above code, getting one row and column extra.</p>
| 1 |
2016-09-12T10:01:57Z
| 39,447,892 |
<p>open file without b mode</p>
<p>b mode open your file as binary</p>
<p>you can open file as w</p>
<pre><code>open_file = open("filename.csv", "w")
</code></pre>
| 1 |
2016-09-12T10:06:41Z
|
[
"python",
"csv"
] |
How to write output file in CSV format in python?
| 39,447,817 |
<p>I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.</p>
<p>Getting error in Python 3.5:</p>
<pre><code>wr.writerow(var)
TypeError: a bytes-like object is required, not 'str'
</code></pre>
<p>and </p>
<p>In Python 2.7, I am getting all column result in one column. </p>
<p>Expected Result:<br>
An output file same format as the input file.</p>
<p>Code:</p>
<pre><code>import csv
f1 = open("input_1.csv", "r")
resultFile = open("out.csv", "wb")
wr = csv.writer(resultFile, quotechar=',')
def sort_duplicates(f1):
for i in range(0, len(f1)):
f1.insert(f1.index(f1[i])+1, f1[i])
f1.pop(i+1)
for var in f1:
#print (var)
wr.writerow([var])
</code></pre>
<p>If I am using <code>resultFile = open("out.csv", "w")</code>, I get one row extra in the output file. </p>
<p>If I am using above code, getting one row and column extra.</p>
| 1 |
2016-09-12T10:01:57Z
| 39,448,055 |
<p>You are opening the input file in normal read mode but the output file is opened in binary mode, correct way</p>
<pre><code>resultFile = open("out.csv", "w")
</code></pre>
<p>As shown above if you replace "wb" with "w" it will work.</p>
| 1 |
2016-09-12T10:16:25Z
|
[
"python",
"csv"
] |
How to write output file in CSV format in python?
| 39,447,817 |
<p>I tried to write output file as a CSV file but getting either an error or not the expected result. I am using Python 3.5.2 and 2.7 also.</p>
<p>Getting error in Python 3.5:</p>
<pre><code>wr.writerow(var)
TypeError: a bytes-like object is required, not 'str'
</code></pre>
<p>and </p>
<p>In Python 2.7, I am getting all column result in one column. </p>
<p>Expected Result:<br>
An output file same format as the input file.</p>
<p>Code:</p>
<pre><code>import csv
f1 = open("input_1.csv", "r")
resultFile = open("out.csv", "wb")
wr = csv.writer(resultFile, quotechar=',')
def sort_duplicates(f1):
for i in range(0, len(f1)):
f1.insert(f1.index(f1[i])+1, f1[i])
f1.pop(i+1)
for var in f1:
#print (var)
wr.writerow([var])
</code></pre>
<p>If I am using <code>resultFile = open("out.csv", "w")</code>, I get one row extra in the output file. </p>
<p>If I am using above code, getting one row and column extra.</p>
| 1 |
2016-09-12T10:01:57Z
| 39,448,412 |
<p>Others have answered that you should open the output file in text mode when using Python 3, i.e.</p>
<pre><code>with open('out.csv', 'w', newline='') as resultFile:
...
</code></pre>
<p>But you also need to parse the incoming CSV data. As it is your code reads each line of the input CSV file as a single string. Then, without splitting that line into its constituent fields, it passes the string to the CSV writer. As a result, the <code>csv.writer</code> will treat the string as a sequence and output each <em>character</em> , including any terminating new line character, as a separate field. For example, if your input CSV file contains:</p>
<pre>
1,2,3,4
</pre>
<p>Your output file would be written like this:</p>
<pre>
1,",",2,",",3,",",4,"
"
</pre>
<p>You should change the <code>for</code> loop to this:</p>
<pre><code>for row in csv.reader(f1):
# process the row
wr.writerow(row)
</code></pre>
<p>Now the input CSV file will be parsed into fields and <code>row</code> will contain a list of strings - one for each field. For the previous example, <code>row</code> would be:</p>
<pre><code>for row in csv.reader(f1):
print(row)
</code></pre>
<pre>
['1', '2', '3', '4']
</pre>
<p>And when that list is passed to the <code>csv.writer</code> the output to the file will be:</p>
<pre>
1,2,3,4
</pre>
<hr>
<p>Putting all of that together you get this code:</p>
<pre><code>import csv
with open('input_1.csv') as f1, open('out.csv', 'w', newline='') as resultFile:
wr = csv.writer(resultFile, dialect='excel')
for row in csv.reader(f1):
wr.writerow(row)
</code></pre>
| 0 |
2016-09-12T10:37:18Z
|
[
"python",
"csv"
] |
Django: AJAX and path params
| 39,448,032 |
<p>I am trying to figure out how to communicate variables a particular js file that makes an AJAX request in Django.</p>
<p>Say we have an url with a path param that maps to a particular view:</p>
<pre><code>url(r'^post/(?P<post_id>\d+)/$', TemplateView.as_view('post.html'))
</code></pre>
<p>And then the <code>post.html</code> includes a script that performs an AJAX request to fetch the post as JSON:</p>
<pre><code>post.html
<script src="{{ STATIC_URL }}/js/post.js"></script>
<div id="post-container"></div>
</code></pre>
<p>This could be the js file. Let's say we do it this way because the post (as JSON) needs to be used in a js plugin to display it in a particular fancy manner.</p>
<pre><code>post.js
$.ajax({
url: '/post/??post_id??',
contentType: 'application/json'
})
.done(function(post_data) {
togglePlugin(post_data);
});
</code></pre>
<p>My main concern is how to figure out what <code>post_id</code> is from the js file in order to make the appropriate call.</p>
<p>How are these parts usually connected in Django? The parts I am talking about are urls, path params, views and ajax.</p>
| 0 |
2016-09-12T10:15:06Z
| 39,448,183 |
<p>You can pass a post_id variable to django template.
However if you don't want it to "hurt", put your .js code (script) in you html file, rendered by django. So you can use django template tags.</p>
<p>For example:</p>
<pre><code> var url = "/post/{{post_id}}";
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: {
some_field: field_data,
some_other_field: field_data
},
success: function(data) {
do_something();
},
error: function(data) {
do_somethin();
}
});
</code></pre>
| 0 |
2016-09-12T10:23:59Z
|
[
"python",
"json",
"ajax",
"django"
] |
Django: AJAX and path params
| 39,448,032 |
<p>I am trying to figure out how to communicate variables a particular js file that makes an AJAX request in Django.</p>
<p>Say we have an url with a path param that maps to a particular view:</p>
<pre><code>url(r'^post/(?P<post_id>\d+)/$', TemplateView.as_view('post.html'))
</code></pre>
<p>And then the <code>post.html</code> includes a script that performs an AJAX request to fetch the post as JSON:</p>
<pre><code>post.html
<script src="{{ STATIC_URL }}/js/post.js"></script>
<div id="post-container"></div>
</code></pre>
<p>This could be the js file. Let's say we do it this way because the post (as JSON) needs to be used in a js plugin to display it in a particular fancy manner.</p>
<pre><code>post.js
$.ajax({
url: '/post/??post_id??',
contentType: 'application/json'
})
.done(function(post_data) {
togglePlugin(post_data);
});
</code></pre>
<p>My main concern is how to figure out what <code>post_id</code> is from the js file in order to make the appropriate call.</p>
<p>How are these parts usually connected in Django? The parts I am talking about are urls, path params, views and ajax.</p>
| 0 |
2016-09-12T10:15:06Z
| 39,448,346 |
<p>To get urls from your template you should use <code>{% url %}</code> template tag, for that you should add a name to your url: </p>
<p><code>url(r'^post/(?P<post_id>\d+)/$', TemplateView.as_view('post.html'), name='my_name)</code></p>
<p>then in your can template call that url in this way <code>{% url 'my_name' object.pk %}</code> see <a href="https://docs.djangoproject.com/es/1.10/ref/templates/builtins/#url" rel="nofollow">this</a> for more.</p>
<p>when you work with different file for your js, and you want to pass django variables, you should declare a <code><script></code> before import the js file, and there declare your variable:</p>
<pre><code><srcipt>var foo={{django_var}}</script>
<script src="{{ STATIC_URL }}/js/post.js"></script>
</code></pre>
<p>and then use the variable <code>foo</code> in the js.</p>
| 0 |
2016-09-12T10:33:14Z
|
[
"python",
"json",
"ajax",
"django"
] |
several forms on the same page with django
| 39,448,079 |
<p>i have a very simple model... something like this:</p>
<pre><code>class MachineTransTable(models.Model):
...
file = models.ForeignKey('File', related_name='the_file')
source = models.TextField()
target = models.TextField()
...
</code></pre>
<p>What I'd like to do is to have a page where the user has the source on the left (disable), the target on the right (editable) and a submit button to post the edited target text for EACH selected object in the MachineTransTable table. Here are some more information to better understand my request:</p>
<ul>
<li>A page refers to a single file and there are several (sometimes hundreds) of objects in the MachineTransTable table belonging to the same file</li>
<li>Each time the user edit a single target and hit the submit button for that object, the object is saved/updated (depending on the initial value of the object) in the DB and the the user can continue to edit all the other objects...</li>
<li>At the end of the page there is another submit button which is used to exit from the page at the end of the work (all the objects have been edited/updated). If an object has not been edited/updated, it keeps its original value.</li>
</ul>
<p>I tried to use a formset but I guess it's not the right choice... This is the file forms.py</p>
<pre><code>class SegmentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SegmentForm, self).__init__(*args, **kwargs)
if self.instance.id:
self.fields['source'].widget.attrs['readonly'] = True
class Meta:
model = MachineTransTable
fields = ['source','target',]
SegmentFormSet = inlineformset_factory(File, MachineTransTable, form=SegmentForm, fields=('source','target'), extra=0)
</code></pre>
<p>and the view.py file is:</p>
<pre><code>class CatUpdateView(LoginRequiredMixin,UpdateView):
Model = MachineTransTable
context_object_name = 'file'
template_name = 'app_cat/cat.html'
form_class = SegmentForm
...
def get_context_data(self, **kwargs):
context = super(CatUpdateView, self).get_context_data(**kwargs)
formset = SegmentFormSet(instance=self.get_object())
context['formset_Segment'] = formset
return context
</code></pre>
<p>Using this approach, I have a single form and all the related objects are saved/updated at once when the submit button is hit... </p>
<p>What can I do to achieve what I described above? Thanks</p>
| 0 |
2016-09-12T10:17:59Z
| 39,451,224 |
<p>I think your choice is correct, you should not use <strong>several (hundreds eventually) forms</strong> here if the field in the same model. For two reasons:</p>
<ul>
<li><p>You have to do a lot of repeat job to write so many forms and that is easy to make mistake and hard to maintain.</p></li>
<li><p>You still have to connect the database and update the record no matter how many field had been edit, and they almost efficiency.</p></li>
</ul>
<p>But if you really want to do this,you can just use Ajax to post the current parameters name to the api, then update it, For instance, you have a button for target field:</p>
<pre><code><a href="api/table_id" class="button target">value_in_the_html</a>
</code></pre>
<p>Use Ajax to post the field name and value:</p>
<pre><code>$ajax({
url: "api/table_id",
type: "POST",
datatype: "json",
data: {"field": "target", "value": "value_in_the_html"}
});
</code></pre>
<p>In view.py:</p>
<pre><code>def UpdateTable(request, id):
field = request.POST.get("field", None)
value = request.POST.get("value", None)
machine = MachineTransTable.objects.filter(id=id).first()
machine.getattr(machine,field) = value
machine.save()
return HttpResponse("Saved!")
</code></pre>
| 0 |
2016-09-12T13:14:54Z
|
[
"python",
"django",
"django-forms",
"formset"
] |
Python FTP filename invalid error
| 39,448,121 |
<p>I'm trying to upload a file using ftp in python, but I get an error saying:</p>
<pre><code>ftplib.error_perm: 550 Filename invalid
</code></pre>
<p>when I run the following code:</p>
<pre><code>ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '')
ftp.cwd("/incoming")
file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb')
ftp.storbinary('STOR c:\Automation\FTP_Files\MaxErrors1.json', file)
ftp.close()
</code></pre>
<p>I've checked that the file exists in the location I specified, does anyone know what might be causing the issue?</p>
| 0 |
2016-09-12T10:21:03Z
| 39,448,185 |
<p>The argument to STOR needs to be the destination file name, not the source path. You should just do <code>ftp.storbinary('STOR MaxErrors1.json', file)</code>.</p>
| 0 |
2016-09-12T10:24:01Z
|
[
"python",
"ftp"
] |
Python FTP filename invalid error
| 39,448,121 |
<p>I'm trying to upload a file using ftp in python, but I get an error saying:</p>
<pre><code>ftplib.error_perm: 550 Filename invalid
</code></pre>
<p>when I run the following code:</p>
<pre><code>ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '')
ftp.cwd("/incoming")
file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb')
ftp.storbinary('STOR c:\Automation\FTP_Files\MaxErrors1.json', file)
ftp.close()
</code></pre>
<p>I've checked that the file exists in the location I specified, does anyone know what might be causing the issue?</p>
| 0 |
2016-09-12T10:21:03Z
| 39,448,193 |
<p>The problem is that on the server, the path <code>c:\Automation\FTP_Files\MaxErrors1.json</code> is not valid. Instead try just doing: </p>
<pre><code>ftp.storbinary('STOR MaxErrors1.json', file)
</code></pre>
| 1 |
2016-09-12T10:24:26Z
|
[
"python",
"ftp"
] |
Python FTP filename invalid error
| 39,448,121 |
<p>I'm trying to upload a file using ftp in python, but I get an error saying:</p>
<pre><code>ftplib.error_perm: 550 Filename invalid
</code></pre>
<p>when I run the following code:</p>
<pre><code>ftp = FTP('xxx.xxx.x.xxx', 'MY_FTP', '')
ftp.cwd("/incoming")
file = open('c:\Automation\FTP_Files\MaxErrors1.json', 'rb')
ftp.storbinary('STOR c:\Automation\FTP_Files\MaxErrors1.json', file)
ftp.close()
</code></pre>
<p>I've checked that the file exists in the location I specified, does anyone know what might be causing the issue?</p>
| 0 |
2016-09-12T10:21:03Z
| 39,448,509 |
<p>you should upload file without absolute path in ftp server
for example :</p>
<pre><code>import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('kitten.jpg','rb') # file to send
session.storbinary('STOR kitten.jpg', file) # send the file
file.close() # close file and FTP
session.quit()
</code></pre>
| 1 |
2016-09-12T10:42:45Z
|
[
"python",
"ftp"
] |
Python parsing an ugly configuration file
| 39,448,135 |
<p>I have an application generating a weird config file</p>
<pre><code>app_id1 {
key1 = val
key2 = val
...
}
app_id2 {
key1 = val
key2 = val
...
}
...
</code></pre>
<p>And I am struggling on how to parse this in python. The keys of each app may vary too.
I can't change the application to generate the configuration file in some easily parsable format :)</p>
<p>Any suggestions on how to do this pythonically ?
I am thinking along the lines of dict of dict</p>
<pre><code>conf = {'app_id1': {'key1' : 'val', 'key2' : 'val'},
'app_id2' : {'key1' : 'val', 'key2' : 'val'}
}
</code></pre>
| -1 |
2016-09-12T10:21:39Z
| 39,448,288 |
<p>Try something like this:</p>
<p>I assumed you read the content of the file to a string</p>
<pre><code>config_file_string = '''app_id1 {
key1 = val
key2 = val
key3 = val
}
app_id2 {
key1 = val
key2 = val
}'''
config = {}
appid = ''
for line in config_file_string.splitlines():
print(line)
if line.endswith('{'):
appid = line.split()[0].strip()
placeholder_dict = {}
elif line.startswith('}'):
config[appid] = placeholder_dict
else:
placeholder_dict[line.split('=')[0].strip()] = line.split('=')[1].strip()
print(config)
</code></pre>
<p>This returns:</p>
<pre><code>{'app_id2': {'key2 ': ' val', 'key1 ': ' val'}, 'app_id1': {'key3 ': ' val', 'key2 ': ' val', 'key1 ': ' val'}}
</code></pre>
| 2 |
2016-09-12T10:29:38Z
|
[
"python",
"parsing"
] |
Python parsing an ugly configuration file
| 39,448,135 |
<p>I have an application generating a weird config file</p>
<pre><code>app_id1 {
key1 = val
key2 = val
...
}
app_id2 {
key1 = val
key2 = val
...
}
...
</code></pre>
<p>And I am struggling on how to parse this in python. The keys of each app may vary too.
I can't change the application to generate the configuration file in some easily parsable format :)</p>
<p>Any suggestions on how to do this pythonically ?
I am thinking along the lines of dict of dict</p>
<pre><code>conf = {'app_id1': {'key1' : 'val', 'key2' : 'val'},
'app_id2' : {'key1' : 'val', 'key2' : 'val'}
}
</code></pre>
| -1 |
2016-09-12T10:21:39Z
| 39,448,322 |
<p>You could use regex: <code>(\w+)\s*\{([^}]*)</code> will find a <code>name { values }</code> construct, and <code>([^\s=]+)\s*=\s*([^\n]*)</code> will find <code>key = value</code> pairs.</p>
<p>As a one-liner, assuming the contents of the file are in the variable <code>s</code>:</p>
<pre><code>config= {key:dict(re.findall(r'([^\s=]+)\s*=\s*([^\n]*)', values)) for key,values in re.findall(r'(\w+)\s*\{([^}]*)', s)}
</code></pre>
| 2 |
2016-09-12T10:31:29Z
|
[
"python",
"parsing"
] |
Python parsing an ugly configuration file
| 39,448,135 |
<p>I have an application generating a weird config file</p>
<pre><code>app_id1 {
key1 = val
key2 = val
...
}
app_id2 {
key1 = val
key2 = val
...
}
...
</code></pre>
<p>And I am struggling on how to parse this in python. The keys of each app may vary too.
I can't change the application to generate the configuration file in some easily parsable format :)</p>
<p>Any suggestions on how to do this pythonically ?
I am thinking along the lines of dict of dict</p>
<pre><code>conf = {'app_id1': {'key1' : 'val', 'key2' : 'val'},
'app_id2' : {'key1' : 'val', 'key2' : 'val'}
}
</code></pre>
| -1 |
2016-09-12T10:21:39Z
| 39,451,752 |
<p>You can use <a href="http://pyparsing.wikispaces.com/" rel="nofollow">pyparsing</a> for less strict grammar:</p>
<pre><code>from pyparsing import alphanums, restOfLine, OneOrMore, Word, Suppress
from copy import copy
lbrace,rbrace,eq = map(Suppress,"{}=")
configitem = {}
configall = {}
wd = Word(alphanums+'_')
kw = wd + eq + restOfLine
kw.setParseAction(lambda x: configitem.__setitem__(x[0],x[1].strip()))
group = wd + lbrace + OneOrMore(kw) + rbrace
group.addParseAction(lambda x: configall.__setitem__(x[0],copy(configitem)))
group.addParseAction(lambda x: configitem.clear())
config = OneOrMore(group)
config_file_string = '''app_id1
{
key1 = val
key2 = val
key3 = val
}
app_id2 {
key1 = val
key2 = val
}'''
config.parseString(config_file_string)
print(configall)
</code></pre>
| 1 |
2016-09-12T13:41:42Z
|
[
"python",
"parsing"
] |
Simple sijax exapmle dont work
| 39,448,147 |
<p>I'm learning Python and Flask, I have very little experience, but something that is impossible.
With the usual AJAX does not have any problems, but I decided to try sijax, and even a simple example does not work. I'm sure this is due to incorrect connection and initialization, because I did git clone from the official repository git hub, and everything worked.</p>
<p>In the three examples, sijax working and initialized in one-file application, I want to use in the blueprint</p>
<p>If i click on the <code><a href="javascript://"onclick="Sijax.request('say_hi');">Say Hi!</a></code>
Traceback return : 127.0.0.1 - - [12/Sep/2016 14:19:56] "POST / HTTP/1.1" 400 -</p>
<p>app <strong>init</strong>.py</p>
<pre><code>import os
from flask import (Flask,
redirect,
url_for,
session)
# from flask_login import LoginManager
from flask_wtf.csrf import CsrfProtect
from os import path
from .database import db
from werkzeug.contrib.fixers import ProxyFix
import flask_sijax
import hmac
from hashlib import sha1
def create_app(config=None):
app = Flask(__name__)
app.config.from_object(os.environ['APP_SETTINGS'])
app.wsgi_app = ProxyFix(app.wsgi_app)
db.init_app(app)
app.config["SIJAX_STATIC_PATH"] = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')
app.config["SIJAX_JSON_URI"] = '/static/js/sijax/json2.js'
'''
if app.debug == True:
try:
from flask_debugtoolbar import DebugToolbarExtension
toolbar = DebugToolbarExtension(app)
except:
pass
'''
with app.test_request_context():
db.create_all()
from .general import controllers as general
from .shop import controllers as shop
from .test import controllers as test
app.register_blueprint(shop.module)
app.register_blueprint(general.module)
app.register_blueprint(test.module)
flask_sijax.Sijax(app)
CsrfProtect(app)
@app.template_global('csrf_token')
def csrf_token():
"""
Generate a token string from bytes arrays. The token in the session is user
specific.
"""
if "_csrf_token" not in session:
session["_csrf_token"] = os.urandom(128)
return hmac.new(app.secret_key, session["_csrf_token"],
digestmod=sha1).hexdigest()
@app.route('/')
def index():
return redirect(url_for('test.index'))
return app
</code></pre>
<p>test blueprint controllers.py</p>
<pre><code>from flask import (render_template,
Blueprint,
g)
import flask_sijax
module = Blueprint('test',
__name__)
@flask_sijax.route(module, '/')
def index():
def say_hi(obj_response):
obj_response.alert('Hi there!')
if g.sijax.is_sijax_request:
g.sijax.register_callback('say_hi', say_hi)
return g.sijax.process_request()
return render_template('test/hello.html')
</code></pre>
<p>template hello.html</p>
<pre><code><!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="{{ url_for('static', filename='js/sijax/sijax.js') }}"></script>
<script src="{{ url_for('static', filename='js/sijax/json2.js') }}"></script>
<script>{{ g.sijax.get_js()|safe }}</script>
</head>
<body>
<a href="javascript://" onclick="Sijax.request('say_hi');">Say Hi!</a>
</body>
</html>
</code></pre>
| 0 |
2016-09-12T10:22:09Z
| 39,539,456 |
<p>The reason was not working sijax, it was the fact that the {{csrf_token ()}} was not active</p>
<p>It is necessary to do so either: <code><a href="javascript://" onclick="Sijax.request('say_hi', { data: { csrf_token: '{{ csrf_token() }}' } });">Say Hi!</a></code></p>
<p>Either connect to the html file:</p>
<pre><code><script type="text/javascript">
var csrfToken = "{{ csrf_token() }}"
</script>
</code></pre>
| 0 |
2016-09-16T20:15:10Z
|
[
"python",
"flask",
"sijax"
] |
How to install all APT dependencies needed in python project?
| 39,448,253 |
<p>I am new to python. And just got a question,
I know pip can manage the python package needed in a project, but what about the APT needed in the project?</p>
| -2 |
2016-09-12T10:28:01Z
| 39,448,605 |
<p>Off course some python packages require libs or development sources (like MySQLdb). You will not be able to install them without dev libraries (source code) or binary libs and you will be notified about that during pip install. You can easily google error string and check what dependency you miss and install it.
For handling system packages during deployment you can use any automation tool or configuration management system like ansible.</p>
| 0 |
2016-09-12T10:47:58Z
|
[
"python"
] |
assertRaises in unittest not catching Exception properly
| 39,448,269 |
<p>I have a file testtest.py that i contains the code</p>
<pre><code>import unittest
def add(self, a, b):
return a + b
class Test(unittest.TestCase):
def test_additon(self):
self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed")
#self.assertRaises(TypeError, lambda: add(1 + '1'), msg="Addition failed")
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>The problem is that <code>assertRaises</code> doesn't catch the exception properly and all my tests keep failing as errors not based on the condition, this is the output that I'm getting:</p>
<pre><code>E
======================================================================
ERROR: test_additon (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "testtest.py", line 9, in test_additon
self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
</code></pre>
<p>I know i can get around it by using lambda (i commented it out in the code) to make my tests properly catch the exceptions, but according to the docs, passing a callable and the arguments to <code>assertRaises</code> should work, as it will call the function internally by itself and be able to trap any exception that was raised.</p>
<pre><code>assertRaises(*callable*, *args*, *kwargs*)
</code></pre>
<p>but it doesn't</p>
<p>if i run it with lambda which is a callable that would be evaluated later by <code>assertRaises</code>, it works as expected and i get this</p>
<pre><code>----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
</code></pre>
<p><code>I'm running python 3.5</code></p>
<pre><code>Python 3.5.2 (default, Jun 28 2016, 08:46:01)
[GCC 6.1.1 20160602] on linux
</code></pre>
<p>but i also get the same behaviour with <code>python2.7</code></p>
| 0 |
2016-09-12T10:28:42Z
| 39,448,348 |
<p>You should be passing arguments to the callable <em>separately</em>, as separate arguments:</p>
<pre><code>self.assertRaises(TypeError, add, 1, '1', msg="Additon failed")
</code></pre>
| 2 |
2016-09-12T10:33:16Z
|
[
"python",
"unit-testing",
"lambda",
"python-3.5",
"python-unittest"
] |
assertRaises in unittest not catching Exception properly
| 39,448,269 |
<p>I have a file testtest.py that i contains the code</p>
<pre><code>import unittest
def add(self, a, b):
return a + b
class Test(unittest.TestCase):
def test_additon(self):
self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed")
#self.assertRaises(TypeError, lambda: add(1 + '1'), msg="Addition failed")
if __name__ == '__main__':
unittest.main()
</code></pre>
<p>The problem is that <code>assertRaises</code> doesn't catch the exception properly and all my tests keep failing as errors not based on the condition, this is the output that I'm getting:</p>
<pre><code>E
======================================================================
ERROR: test_additon (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
File "testtest.py", line 9, in test_additon
self.assertRaises(TypeError, add, 1 + '1', msg="Additon failed")
TypeError: unsupported operand type(s) for +: 'int' and 'str'
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
</code></pre>
<p>I know i can get around it by using lambda (i commented it out in the code) to make my tests properly catch the exceptions, but according to the docs, passing a callable and the arguments to <code>assertRaises</code> should work, as it will call the function internally by itself and be able to trap any exception that was raised.</p>
<pre><code>assertRaises(*callable*, *args*, *kwargs*)
</code></pre>
<p>but it doesn't</p>
<p>if i run it with lambda which is a callable that would be evaluated later by <code>assertRaises</code>, it works as expected and i get this</p>
<pre><code>----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
</code></pre>
<p><code>I'm running python 3.5</code></p>
<pre><code>Python 3.5.2 (default, Jun 28 2016, 08:46:01)
[GCC 6.1.1 20160602] on linux
</code></pre>
<p>but i also get the same behaviour with <code>python2.7</code></p>
| 0 |
2016-09-12T10:28:42Z
| 39,448,370 |
<p>Try</p>
<pre><code>def test_additon(self):
with self.assertRaises(TypeError):
add(1 + '1')
</code></pre>
<p>The problem is that the exception is raised during argument evaluation before self.assertRaises can kick in.</p>
| 1 |
2016-09-12T10:34:33Z
|
[
"python",
"unit-testing",
"lambda",
"python-3.5",
"python-unittest"
] |
Sort by (unstructured) dates in Pandas DataFrame
| 39,448,442 |
<p>I have an Excel table with the following data</p>
<p>Please note that I have a single column where the date, month, and time are given in the following format.</p>
<p>I wish to sort out the rows with respect to the date and time (i.e Jan-1-1.0, Jan-2-2.0, Jan-1-3.0) and looking for ways to do in Python Pandas DataFrame. (dates are in French)</p>
<p>Kindly provide your suggestions.</p>
<pre><code>Date-heure
Vendredi 03 novembre 10.0
Vendredi 03 novembre 5.0
Vendredi 03 novembre 18.0
Vendredi 03 novembre 24.0
Samedi 04 novembre 1.0
Samedi 04 novembre 2.0
Samedi 04 novembre 4.0
Samedi 04 novembre 5.0
Samedi 04 novembre 7.0
Samedi 04 novembre 13.0
Samedi 04 novembre 21.0
Vendredi 20 avril 1.0
Dimanche 05 novembre 2.0
Dimanche 05 novembre 8.0
</code></pre>
<p>Thank you for your prompt response. In my excel the cell is of Date. And when I loaded as a DataFrame, it shows me a datatype as</p>
<pre><code>pandas.core.series.Series
</code></pre>
<p>And I just could not sort it out. Also please note I have a time as well in the same cell. </p>
<p>Presenting you all the dtypes here as below;</p>
<pre><code>Date_heure object
Heure int64
Industrie (MW) int64
Tertiaire Chauffage (MW) int64
Tertiaire Climatisation (MW) int64
Tertiaire Autres usages (MW) int64
Résidentiel Chauffage (MW) int64
Résidentiel Eau chaude (MW) int64
dtype: object
</code></pre>
<p>Thank you.</p>
| 1 |
2016-09-12T10:39:11Z
| 39,449,015 |
<p>OK you can use <a href="https://pypi.python.org/pypi/dateparser" rel="nofollow"><code>dateparser</code></a> to parse your strings and then construct a TimedeltaIndex to add the hour component:</p>
<pre><code>In [36]:
import dateparser
t="""Date-heure
Vendredi 03 novembre 10.0
Vendredi 03 novembre 5.0
Vendredi 03 novembre 18.0
Vendredi 03 novembre 24.0
Samedi 04 novembre 1.0
Samedi 04 novembre 2.0
Samedi 04 novembre 4.0
Samedi 04 novembre 5.0
Samedi 04 novembre 7.0
Samedi 04 novembre 13.0
Samedi 04 novembre 21.0
Vendredi 20 avril 1.0
Dimanche 05 novembre 2.0
Dimanche 05 novembre 8.0"""
df = pd.read_csv(io.StringIO(t))
df['date-time'] = df['Date-heure'].str.split().str[:-1].str.join(' ').apply(dateparser.parse) + pd.TimedeltaIndex((df['Date-heure'].str.rsplit().str[-1]).astype(float), unit='H')
df
Out[36]:
Date-heure date-time
0 Vendredi 03 novembre 10.0 2016-11-03 10:00:00
1 Vendredi 03 novembre 5.0 2016-11-03 05:00:00
2 Vendredi 03 novembre 18.0 2016-11-03 18:00:00
3 Vendredi 03 novembre 24.0 2016-11-04 00:00:00
4 Samedi 04 novembre 1.0 2016-11-04 01:00:00
5 Samedi 04 novembre 2.0 2016-11-04 02:00:00
6 Samedi 04 novembre 4.0 2016-11-04 04:00:00
7 Samedi 04 novembre 5.0 2016-11-04 05:00:00
8 Samedi 04 novembre 7.0 2016-11-04 07:00:00
9 Samedi 04 novembre 13.0 2016-11-04 13:00:00
10 Samedi 04 novembre 21.0 2016-11-04 21:00:00
11 Vendredi 20 avril 1.0 2016-04-20 01:00:00
12 Dimanche 05 novembre 2.0 2016-11-05 02:00:00
13 Dimanche 05 novembre 8.0 2016-11-05 08:00:00
</code></pre>
<p>So this:</p>
<pre><code>df['Date-heure'].str.split().str[:-1].str.join(' ').apply(dateparser.parse) + pd.TimedeltaIndex((df['Date-heure'].str.rsplit().str[-1]).astype(float), unit='H')
</code></pre>
<p>is the line that should interest you, here I call <code>apply</code> on your strings to <code>apply</code> <code>dateparser.parse</code> but this will only give you the date as it doesn't understand the float value, so I then <code>rsplit</code> the string to get the hour and cast to float and then construct a timedeltaindex.</p>
<p>After which I can use <code>sort_values</code> to sort the df:</p>
<pre><code>In [37]:
df.sort_values('date-time')
Out[37]:
Date-heure date-time
11 Vendredi 20 avril 1.0 2016-04-20 01:00:00
1 Vendredi 03 novembre 5.0 2016-11-03 05:00:00
0 Vendredi 03 novembre 10.0 2016-11-03 10:00:00
2 Vendredi 03 novembre 18.0 2016-11-03 18:00:00
3 Vendredi 03 novembre 24.0 2016-11-04 00:00:00
4 Samedi 04 novembre 1.0 2016-11-04 01:00:00
5 Samedi 04 novembre 2.0 2016-11-04 02:00:00
6 Samedi 04 novembre 4.0 2016-11-04 04:00:00
7 Samedi 04 novembre 5.0 2016-11-04 05:00:00
8 Samedi 04 novembre 7.0 2016-11-04 07:00:00
9 Samedi 04 novembre 13.0 2016-11-04 13:00:00
10 Samedi 04 novembre 21.0 2016-11-04 21:00:00
12 Dimanche 05 novembre 2.0 2016-11-05 02:00:00
13 Dimanche 05 novembre 8.0 2016-11-05 08:00:00
</code></pre>
| 0 |
2016-09-12T11:11:20Z
|
[
"python",
"python-2.7",
"sorting",
"pandas",
"dataframe"
] |
Embed Plotly HTML in PyCharm IDE
| 39,448,549 |
<p>I would like to see Plotly's HTML output in the PyCharm IDE. It currently says:
</p>
<p>Process finished with exit code 0</p>
<p>for the output. However, I receive a graphical result in Jupyter</p>
| 0 |
2016-09-12T10:44:48Z
| 39,581,736 |
<p>To see the Plotly html output use the offline feature. For example, like this:</p>
<pre><code>plotly.offline.plot(*yourplotname*, filename='file.html')
</code></pre>
<p>Run the code in pycharm and it will save the .html file locally in your work folder and open the .html in your browser to view.</p>
| 1 |
2016-09-19T20:40:32Z
|
[
"python",
"html",
"pycharm",
"jupyter",
"plotly"
] |
Can you dynamically add class variables to subclass python?
| 39,448,551 |
<p>I have a large amount of auto-generated classes in python that essentially represent enums for part of a communication protocol, they look like so</p>
<pre><code># definitions.py
class StatusCodes(ParamEnum):
Success = 1
Error = 2
UnexpectedAlpaca = 3
class AlpacaType(ParamEnum):
Fuzzy = 0
ReallyMean = 1
# etc etc etc
</code></pre>
<p>Defining things this way makes it easy for the auto-generator and also for humans to modify. The ParamEnum class provides all the functionality, get/setting, comparison, conversion and creation from the incoming network data and etc.</p>
<p>However, these classes require some extra meta-data. I do <em>not</em> want to add this into the source definition of each class though, as it makes it less readable and will break the autogenerator</p>
<p>At the moment I am doing it like this</p>
<pre><code># param_enum.py
class ParamEnum(object):
def __init__(self):
self.__class__._metadata = get_class_metadata(self.__class__)
</code></pre>
<p>however that strikes me as somewhat inefficient, since this will happen every time we instantiate one of these Enums (which happens often), not just on definition (the metadata does not change, so it only needs to be set once)</p>
<p>I tried added this to the bottom of the definition file, but ran into problems there too.</p>
<pre><code>class StatusCodes(ParamEnum):
Success = 1
Error = 2
UnexpectedAlpaca = 3
for var in locals(): # or globals?
add_metadata(var)
#doesn't work because it is in the same file, modifying dict while iteratng
</code></pre>
<p>Is there a way in python of overriding/adding functionality to when the class is defined, that can be inherited to subclasses? Ideally I'd like something like</p>
<pre><code>class ParamEnum(object):
def __when_class_defined__(cls):
add_metadata(cls)
</code></pre>
| 6 |
2016-09-12T10:44:51Z
| 39,448,643 |
<p>Use a class decorator</p>
<pre><code>def add_metadata(cls):
cls._metadata = get_class_metadata(cls)
return cls
@add_metadata
class StatusCodes(ParamEnum):
Success = 1
Error = 2
UnexpectedAlpaca = 3
</code></pre>
<p>What you want to do is in fact the very motivation to have decorators: The modification of a class or function after it has been created.</p>
<p>If you are unfamiliar with decorators, please read <a href="http://stackoverflow.com/a/1594484/4806820">this</a> (although it's a bit lengthy).</p>
<p>You could also use metaclasses, but they introduce more complexity than a decorator. If you want to avoid the additional decoration line <code>@add_metadata</code> and you think it is redundant with respect to the specified subclass <code>ParamEnum</code>, you could also make <code>_metadata</code> <a href="https://docs.python.org/3/howto/descriptor.html#descriptor-protocol" rel="nofollow">a descriptor</a> with lazy evaluation within the base class <code>ParamEnum</code>.</p>
<pre><code>class MetadataDescriptor(object):
def __get__(self, obj, cls):
if cls._metadata_value is None:
cls._metadata_value = get_class_metadata(cls)
return cls._metadata_value
class ParamEnum(object):
_metadata_value = None
_metadata = MetadataDescriptor()
</code></pre>
| 5 |
2016-09-12T10:49:48Z
|
[
"python",
"inheritance"
] |
Python Selenium click function does not perform any action, test is not failing
| 39,448,587 |
<p>I write automated test in Python using Selenium webdriver and for one element the function click() does not perform any action. But the test does not even fail (e.g. for no such element or not clickable,..)</p>
<p>My code:</p>
<pre><code>def fill_applications_tab(self):
wait = WebDriverWait(self.driver, 20)
wait.until(EC.element_to_be_clickable((By.XPATH,"//span[@name='application' and text()[contains(.,'JBoss')]]/parent::*/parent::tr/td[1]/input[@type='checkbox' and @name='man']")))
self.driver.find_element_by_xpath("//span[@name='application' and text()[contains(.,'JBoss')]]/parent::*/parent::tr/td[1]/input[@type='checkbox' and @name='man']").click()
</code></pre>
<p>HTML</p>
<pre><code><div class="col-sm-12" id="appl_applications_mw_error_div">
<table class="table white table-condensed table-bordered tight-col">
<thead>
<tr class="app-table-descr">
<td colspan="7">Middleware</td>
</tr>
<tr>
<th class="t-center">Install</th>
<th>Application name</th>
</tr>
</thead>
<tbody class="sort">
<tr class="show-info" name="appl_applications_mw" data-type="array" data-tab-id="#tab-app" data-upform-error="#appl_applications_mw_error_div" data-show-info-field="man">
<td class="form-group-sm">
<span name="version" data-type="arrayitem" disabled="disabled">2.0.x (HP)</span>
</td>
</tr><tr class="show-info" name="appl_applications_mw" data-type="array" data-tab-id="#tab-app" data-upform-error="#appl_applications_mw_error_div" data-show-info-field="man">
<td class="t-center">
<input name="type" type="hidden" data-type="arrayitem" value="mw">
<input class="show-info-field" name="man" type="checkbox" data-type="arrayitem">
<input class="app-man-default hidden" name="man_default" type="checkbox" data-type="arrayitem">
</td>
<td>
<span name="application" data-type="arrayitem">JBoss</span>
</td>
</code></pre>
<p>Any idea how to fix it?
I already tried to add the click() action twice in the code (found somewhere as a solution for someone), but it didn't help..
Thank you! </p>
| 0 |
2016-09-12T10:46:41Z
| 39,489,846 |
<p>So it started to work when I add another different action after save_button.click()
So the code is like:</p>
<pre><code>element_xpath.click()
save_button.click()
navigate_to_another_tab.click()
</code></pre>
<p>After that the checkbox is chosen and the True is saved</p>
| 0 |
2016-09-14T11:55:42Z
|
[
"python",
"selenium",
"xpath",
"automation",
"webdriver"
] |
Only passing the first letter into the dictionary. (python 3.x)
| 39,448,604 |
<pre><code> print(single_website)
print(status_str)
print(contact_link)
for link, status_code, contact_info in zip(single_website, status_str, contact_link):
data = {
"Link": link,
"Status": status_code,
"Contact": contact_info
}
</code></pre>
<p>this is how my code looks like. It is weird that the expected value should be {link: <a href="http://wizters.com" rel="nofollow">http://wizters.com</a>,
status: 200,
contact: Contact Info Not Available"}</p>
<p>However, the result is :</p>
<pre><code>http://wizters.com
200
Contact Info Not Available
{'Status': '2', 'Link': 'h', 'Contact': 'C'}
</code></pre>
<p>Only the first letter or number is passed into the value. Btw, I used str() to make status "200" to a string. </p>
| -3 |
2016-09-12T10:47:56Z
| 39,448,645 |
<p>because strings are iterable, that is why it takes 1st later in your zip, you should wrap it into tuple or list</p>
| 0 |
2016-09-12T10:49:53Z
|
[
"python",
"dictionary"
] |
Only passing the first letter into the dictionary. (python 3.x)
| 39,448,604 |
<pre><code> print(single_website)
print(status_str)
print(contact_link)
for link, status_code, contact_info in zip(single_website, status_str, contact_link):
data = {
"Link": link,
"Status": status_code,
"Contact": contact_info
}
</code></pre>
<p>this is how my code looks like. It is weird that the expected value should be {link: <a href="http://wizters.com" rel="nofollow">http://wizters.com</a>,
status: 200,
contact: Contact Info Not Available"}</p>
<p>However, the result is :</p>
<pre><code>http://wizters.com
200
Contact Info Not Available
{'Status': '2', 'Link': 'h', 'Contact': 'C'}
</code></pre>
<p>Only the first letter or number is passed into the value. Btw, I used str() to make status "200" to a string. </p>
| -3 |
2016-09-12T10:47:56Z
| 39,449,010 |
<pre><code>>>> single_website = 'http://wizters.com'
>>> status_str = '200'
>>> contact_link = 'Contact Info Not Available'
>>> list(zip(single_website, status_str, contact_link))
[('h', '2', 'C'), ('t', '0', 'o'), ('t', '0', 'n')]
>>> list(zip((single_website, ), (status_str, ), (contact_link, )))
[('http://wizters.com', '200', 'Contact Info Not Available')]
</code></pre>
| 0 |
2016-09-12T11:10:57Z
|
[
"python",
"dictionary"
] |
Only passing the first letter into the dictionary. (python 3.x)
| 39,448,604 |
<pre><code> print(single_website)
print(status_str)
print(contact_link)
for link, status_code, contact_info in zip(single_website, status_str, contact_link):
data = {
"Link": link,
"Status": status_code,
"Contact": contact_info
}
</code></pre>
<p>this is how my code looks like. It is weird that the expected value should be {link: <a href="http://wizters.com" rel="nofollow">http://wizters.com</a>,
status: 200,
contact: Contact Info Not Available"}</p>
<p>However, the result is :</p>
<pre><code>http://wizters.com
200
Contact Info Not Available
{'Status': '2', 'Link': 'h', 'Contact': 'C'}
</code></pre>
<p>Only the first letter or number is passed into the value. Btw, I used str() to make status "200" to a string. </p>
| -3 |
2016-09-12T10:47:56Z
| 39,449,169 |
<pre><code> management_links = [get_management_link(source, soup, single_website)]
contact_link = [get_contact_link(source, soup, single_website)]
status_str = [str(status)]
single_link = [single_website]
for link, status_code, management_info, contact_info in zip(single_link, status_str, management_links, contact_link):
data = {
"Link": link,
"Status": status_code,
"Management": management_info,
"Contact": contact_info
}
</code></pre>
<p>after putting these values into lists, it works now. thank you guys!</p>
| 0 |
2016-09-12T11:20:35Z
|
[
"python",
"dictionary"
] |
while loop in Python3
| 39,448,622 |
<p>This is what I have to do:</p>
<blockquote>
<p>Create a while-loop that adds 6 to the number 27, 73 times. Answer
with the result. </p>
<p>Write your code below and put the answer into the variable ANSWER.</p>
</blockquote>
<p>And this is what I have done, </p>
<pre><code>n = 6
while n < 73:
27 + n
n + = 1
ANSWER = n
</code></pre>
| -7 |
2016-09-12T10:48:53Z
| 39,448,698 |
<p>While you literally nearly do what was requested (adding 6 to the 27 a number of times), this is not what was wanted.</p>
<p>What they want you to do is</p>
<blockquote>
<p>Initialize a variable with 27 and add 6 to it, 73 times.</p>
</blockquote>
<p>So just do</p>
<pre><code>value = 27
i = 0
while i < 73:
value += 6
i += 1
ANSWER = value
</code></pre>
| 3 |
2016-09-12T10:52:49Z
|
[
"python",
"loops",
"while-loop"
] |
Django: accessing variable value from TemplateView
| 39,448,640 |
<p>Say I have the following url that maps to a <code>TemplateView</code>:</p>
<pre><code>url(r'^path/(?P<var1>\d+)/(?P<var2>\d+)/$', TemplateView.as_view('a_view.html'))
</code></pre>
<p>I thought in the template view <code>a_view.html</code> I could access the values of <code>var1</code> and <code>var2</code> as they're being captured and extracted into named parameters:</p>
<pre><code><!-- a_view.html -->
<p>var1 value = {{ var1 }}</p>
<p>var2 value = {{ var2 }}</p>
</code></pre>
<p>However, these values are blank when visiting <code>/path/10/89</code>. Why? How can I access them then? Would I need an explicit view?</p>
| 0 |
2016-09-12T10:49:40Z
| 39,448,788 |
<p>From template you can access the instance of <a href="https://docs.djangoproject.com/en/1.10/ref/urlresolvers/#django.urls.ResolverMatch" rel="nofollow">ResolverMatch</a> representing the resolved URL</p>
<pre><code><p>var1 value = {{ request.resolver_match.kwargs.var1 }}</p>
<p>var2 value = {{ request.resolver_match.kwargs.var2 }}</p>
</code></pre>
| 0 |
2016-09-12T10:58:19Z
|
[
"python",
"django"
] |
Django: accessing variable value from TemplateView
| 39,448,640 |
<p>Say I have the following url that maps to a <code>TemplateView</code>:</p>
<pre><code>url(r'^path/(?P<var1>\d+)/(?P<var2>\d+)/$', TemplateView.as_view('a_view.html'))
</code></pre>
<p>I thought in the template view <code>a_view.html</code> I could access the values of <code>var1</code> and <code>var2</code> as they're being captured and extracted into named parameters:</p>
<pre><code><!-- a_view.html -->
<p>var1 value = {{ var1 }}</p>
<p>var2 value = {{ var2 }}</p>
</code></pre>
<p>However, these values are blank when visiting <code>/path/10/89</code>. Why? How can I access them then? Would I need an explicit view?</p>
| 0 |
2016-09-12T10:49:40Z
| 39,448,821 |
<p>I think something like this should work.</p>
<p>Change you urls.py to use a named view:</p>
<pre><code>url(r'^path/(?P<var1>\d+)/(?P<var2>\d+)/$', YourNamedView.as_view('a_view.html'))
</code></pre>
<p>Create a TemplateView and let it grab your vars and add it to the context:</p>
<pre><code>class YourNamedView(TemplateView):
template_name = 'a_view.html'
def get_context_data(self, **kwargs):
context = super(YourNamedView, self).get_context_data(**kwargs)
context.update({
'var1': self.kwargs.get('var1', None),
'var2': self.kwargs.get('var2', None),
})
return context
</code></pre>
<p>and in the template:</p>
<pre><code><h1>{{ var1 }} {{ var2 }}</h1>
</code></pre>
| 0 |
2016-09-12T11:00:00Z
|
[
"python",
"django"
] |
Parsing date in JSON format using Python
| 39,448,713 |
<p>I have a set of news articles in JSON format and I am having problems parsing the date of the data. The problem is that once the articles were converted in JSON format, the date successfully got converted but also did the edition. Here is an illustration:</p>
<pre><code>{"date": "December 31, 1995, Sunday, Late Edition - Final", "body": "AFTER a year of dizzying new heights for the market, investors may despair of finding any good stocks left. Navistar plans to slash costs by $112 million in 1996. Advanced Micro Devices has made a key acquisition. For the bottom-fishing investor, therefore, the big nail-biter is: Will the changes be enough to turn a company around? ", "title": "INVESTING IT;"}
{"date": "December 31, 1995, Sunday, Late Edition - Final", "body": "Few issues stir as much passion in so many communities as the simple act of moving from place to place: from home to work to the mall and home again. It was an extremely busy and productive year for us, said Frank J. Wilson, the State Commissioner of Transportation. There's a sense of urgency to get things done. ", "title": "ROAD AND RAIL;"}
{"date": "December 31, 1996, Sunday, Late Edition - Final", "body": "Widespread confidence in the state's economy prevailed last January as many businesses celebrated their most robust gains since the recession. And Steven Wynn, the chairman of Mirage Resorts, who left Atlantic City eight years ago because of local and state regulations, is returning to build a $1 billion two-casino complex. ", "title": "NEW JERSEY & CO.;"}
</code></pre>
<p>Since I am aiming at counting the number of articles that contain certain words I loop the articles in the following way:</p>
<pre><code>import json
import re
import pandas
for i in range(1995,2017):
df = pandas.DataFrame([json.loads(l) for l in open('USAT_%d.json' % i)])
# Parse dates and set index
df.date = pandas.to_datetime(df.date) # is giving me a problem
df.set_index('date', inplace=True)
</code></pre>
<p>I am looking after orientation on how to tackle the problem in the most efficient way. I was thinking of something such "ignore anything that goes after the date of the week" when parsing the date. Is there such thing?</p>
<p>Thanks in advance </p>
| 2 |
2016-09-12T10:53:48Z
| 39,448,874 |
<p>You can split column <code>date</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>str.split</code></a>, concanecate first and second column - <code>month</code>, <code>day</code> and <code>year</code> together (<code>December 31</code> and <code>1995</code>)and last call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a>:</p>
<pre><code>for i in range(1995,2017):
df = pandas.DataFrame([json.loads(l) for l in open('USAT_%d.json' % i)])
# Parse dates and set index
#print (df)
a = df.date.str.split(', ', expand=True)
df.date = a.iloc[:,0] + ' ' + a.iloc[:,1]
df.date = pandas.to_datetime(df.date)
df.set_index('date', inplace=True)
print (df)
body \
date
1995-12-31 AFTER a year of dizzying new heights for the m...
1995-12-31 Few issues stir as much passion in so many com...
1996-12-31 Widespread confidence in the state's economy p...
title
date
1995-12-31 INVESTING IT;
1995-12-31 ROAD AND RAIL;
1996-12-31 NEW JERSEY & CO.;
</code></pre>
| 2 |
2016-09-12T11:02:47Z
|
[
"python",
"json",
"parsing",
"datetime",
"pandas"
] |
Only one usage of each socket address is normally permitted Python
| 39,448,720 |
<p>I wrote a basic program in to create a socket with a server and a client. But the problem is that when I run the code, it gives me an error saying that only one usage of each socket address is normally permitted. So I think the problem is due to the port, I changed the port and it still don't work. How do I get this to work?</p>
<p>This is my code :</p>
<p>Server</p>
<pre><code>import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind(('localhost',3200))
sock.listen(1)
print "Server is ready to receive data..."
client, address = sock.accept()
msg = client.recv(1024)
print msg
</code></pre>
<p>Client</p>
<pre><code>import socket
connection_to_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connection_to_server.bind(('localhost',3200))
msg = raw_input("Please enter a content :")
connection_to_server.send(msg)
</code></pre>
<p>Thanks for your help !</p>
| 0 |
2016-09-12T10:54:13Z
| 39,448,814 |
<p>I think there's a fundamental misunderstanding of how sockets work here.</p>
<p>The <a href="https://docs.python.org/2/library/socket.html#socket.socket.bind" rel="nofollow"><code>socket.bind()</code></a> call is used to bind to a particular port on a particular interface, the pair specified using a network address (bind to port <code>8080</code> on <code>127.0.0.1)</code>. You need to do this on the server side before you can start reading incoming data i.e "listening" on a particular socket. Only the server needs to do this. The client will then use <a href="https://docs.python.org/2/library/socket.html#socket.socket.connect" rel="nofollow"><code>socket.connect</code></a> to connect to this socket.</p>
<p>As spectras pointed out in the comments, a bind is necessary when you need to communicate through a particular interface/port combination, which is almost always necessary for the server, but not always for the client. The client and server can't <em>both</em> have access/bind to the same port on the same interface, it makes little sense to do so.</p>
<p>Your client and server both try to start listening on the same socket, which is as the error message suggests, not allowed.</p>
<p>You should go through the <a href="https://docs.python.org/2/howto/sockets.html" rel="nofollow">Socket Programming HOWTO</a> before proceeding further.</p>
| 1 |
2016-09-12T10:59:36Z
|
[
"python",
"sockets"
] |
Only one usage of each socket address is normally permitted Python
| 39,448,720 |
<p>I wrote a basic program in to create a socket with a server and a client. But the problem is that when I run the code, it gives me an error saying that only one usage of each socket address is normally permitted. So I think the problem is due to the port, I changed the port and it still don't work. How do I get this to work?</p>
<p>This is my code :</p>
<p>Server</p>
<pre><code>import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind(('localhost',3200))
sock.listen(1)
print "Server is ready to receive data..."
client, address = sock.accept()
msg = client.recv(1024)
print msg
</code></pre>
<p>Client</p>
<pre><code>import socket
connection_to_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connection_to_server.bind(('localhost',3200))
msg = raw_input("Please enter a content :")
connection_to_server.send(msg)
</code></pre>
<p>Thanks for your help !</p>
| 0 |
2016-09-12T10:54:13Z
| 39,448,823 |
<p>Rather than </p>
<pre><code>> connection_to_server.bind(('localhost',3200))
</code></pre>
<p>you should have </p>
<pre><code>connection_to_server.connect(('localhost',3200))
</code></pre>
| 0 |
2016-09-12T11:00:10Z
|
[
"python",
"sockets"
] |
Only one usage of each socket address is normally permitted Python
| 39,448,720 |
<p>I wrote a basic program in to create a socket with a server and a client. But the problem is that when I run the code, it gives me an error saying that only one usage of each socket address is normally permitted. So I think the problem is due to the port, I changed the port and it still don't work. How do I get this to work?</p>
<p>This is my code :</p>
<p>Server</p>
<pre><code>import socket
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.bind(('localhost',3200))
sock.listen(1)
print "Server is ready to receive data..."
client, address = sock.accept()
msg = client.recv(1024)
print msg
</code></pre>
<p>Client</p>
<pre><code>import socket
connection_to_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connection_to_server.bind(('localhost',3200))
msg = raw_input("Please enter a content :")
connection_to_server.send(msg)
</code></pre>
<p>Thanks for your help !</p>
| 0 |
2016-09-12T10:54:13Z
| 39,448,830 |
<p>For SOCK_STREAM sockets, your client should connect, not bind. From the <a href="https://docs.python.org/2/howto/sockets.html" rel="nofollow">Sockets HOWTO</a>:</p>
<pre><code>import socket
connection_to_server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
connection_to_server.connect(('localhost',3200))
msg = raw_input("Please enter a content :")
connection_to_server.send(msg)
</code></pre>
| 0 |
2016-09-12T11:00:24Z
|
[
"python",
"sockets"
] |
Python - File to Dictionary with specific substrings for key value pairs
| 39,448,760 |
<p>I have a text file that looks like :</p>
<pre><code>AAAAA123123423452452BBBASDASAS323423423432
BBBBB453453453466123AAAAADDFFG6565656565665
</code></pre>
<p>...</p>
<p>I want to create a dictionary out of this, with keys the slices of each line like this :</p>
<p>file.txt :</p>
<pre><code>hash[123123] = "BBBASD"
hash[453453] = "AAAAAD"
</code></pre>
<p>I ve written the following try, but it doesnt work so far. Prints nothing :</p>
<pre><code>myhash{}
with open('file.txt') as fi:
for life in fi:
key = [line:6:13]
value = [line:21:27]
myhash[key] = value
print(myhash)
</code></pre>
<p>Can someone help? Thanks in advance!</p>
| 0 |
2016-09-12T10:56:27Z
| 39,448,861 |
<p>You should use:</p>
<pre><code>myhash = {}
with open('file.txt') as fi:
for line in fi.readlines():
key = line[5:11]
value = line[20:26]
myhash[key] = value
print(myhash)
</code></pre>
<p>You can get <a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation">more info here</a> about string slicing in Python.</p>
| 2 |
2016-09-12T11:02:10Z
|
[
"python",
"compare",
"comparison",
"substring"
] |
When we submit a form, what happened?
| 39,448,872 |
<p>Actually, I just want to get a very simple web application:</p>
<ol>
<li>a form in a webpage that I can upload a file within some parameters;</li>
<li>submit the form when I choose a proper file;</li>
<li>do some calculation using these parameters in uploaded file;</li>
<li>redirect to a new webpage with the calculation result;</li>
<li>display the result in this new webpage.</li>
</ol>
<p>I use Django 1.10. </p>
<p><strong>index.html</strong> with <code><form></code> like this:</p>
<pre><code><form action="/index/result/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type=">
<div class="field">
<label for="id_file">Input File:</label>
{{ form.file }} <!--from django model-->
</div>
<p><input type="submit" value="Submit"/></p>
</form>
</code></pre>
<p><strong>result.html</strong> for display result like this:</p>
<pre><code><div id="out">
<table id="result_display" border="1px" hidden>
<thead>
<tr>
<th>No.</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<!--here will display the value comes from result-->
<th id="r_name"> {{ result }} </th>
</tr>
</tbody>
</table>
</div>
</code></pre>
<p>my <strong>views.py</strong> like this:</p>
<pre><code>from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from forms import UploadFileForm
# Create your views here.
@csrf_exempt
def index_view(request):
para = ''
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
cd = form.cleaned_data
if cd['file']:
para = cd.get('file').read().split('\r\n')
else:
return HttpResponse('Please Input a File!')
else:
return HttpResponse('Form is invalid!')
if para:
# do some calculation with para
result = {"name": "NAD"}
return redirect('result_view', result=result) # to another view 'result_view'
else:
form = UploadFileForm()
return render(request, 'index.html', {'form': form})
def result_view(request, result=''):
if result:
return render(request, 'result.html', {'result': result})
else:
return HttpResponse('no result!')
</code></pre>
<p>my <strong>urls.py</strong> like this:</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^index/$', index_view),
url(r'^index/result/?(?P<result>.*)/$', result_view, name='result_view'),
]
</code></pre>
<p>Here are what really confuse me a lot:</p>
<p><strong>Q1</strong>: There are two places give result url address <code><form action="/index/result/" method="post" enctype="multipart/form-data"></code> in index.html and <code>url(r'^index/result/?(?P<result>.*)/$', result, name='result'),</code> in urls.py, which one is dominated?</p>
<p><strong>Q2</strong>: How to pass data (i.e. calculation result) from <code>index_view</code> to <code>result_view</code>?
I didn't get <code>result</code> in <code>result_view</code> function using current method.</p>
| 0 |
2016-09-12T11:02:43Z
| 39,448,957 |
<p>The problem is that your form is posting directly to the result view. This means that the calculations that happen on POST in your index view are never called, and the result value is always empty.</p>
<p>Your form should post to just <code>/index/</code>, or even better to <code>{% url "index_view" %}</code>; and your result view should not make the result value optional.</p>
| 1 |
2016-09-12T11:07:50Z
|
[
"python",
"django"
] |
When we submit a form, what happened?
| 39,448,872 |
<p>Actually, I just want to get a very simple web application:</p>
<ol>
<li>a form in a webpage that I can upload a file within some parameters;</li>
<li>submit the form when I choose a proper file;</li>
<li>do some calculation using these parameters in uploaded file;</li>
<li>redirect to a new webpage with the calculation result;</li>
<li>display the result in this new webpage.</li>
</ol>
<p>I use Django 1.10. </p>
<p><strong>index.html</strong> with <code><form></code> like this:</p>
<pre><code><form action="/index/result/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type=">
<div class="field">
<label for="id_file">Input File:</label>
{{ form.file }} <!--from django model-->
</div>
<p><input type="submit" value="Submit"/></p>
</form>
</code></pre>
<p><strong>result.html</strong> for display result like this:</p>
<pre><code><div id="out">
<table id="result_display" border="1px" hidden>
<thead>
<tr>
<th>No.</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<!--here will display the value comes from result-->
<th id="r_name"> {{ result }} </th>
</tr>
</tbody>
</table>
</div>
</code></pre>
<p>my <strong>views.py</strong> like this:</p>
<pre><code>from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.views.decorators.csrf import csrf_exempt
from forms import UploadFileForm
# Create your views here.
@csrf_exempt
def index_view(request):
para = ''
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
cd = form.cleaned_data
if cd['file']:
para = cd.get('file').read().split('\r\n')
else:
return HttpResponse('Please Input a File!')
else:
return HttpResponse('Form is invalid!')
if para:
# do some calculation with para
result = {"name": "NAD"}
return redirect('result_view', result=result) # to another view 'result_view'
else:
form = UploadFileForm()
return render(request, 'index.html', {'form': form})
def result_view(request, result=''):
if result:
return render(request, 'result.html', {'result': result})
else:
return HttpResponse('no result!')
</code></pre>
<p>my <strong>urls.py</strong> like this:</p>
<pre><code>from django.conf.urls import url, include
from django.contrib import admin
admin.autodiscover()
urlpatterns = [
url(r'^index/$', index_view),
url(r'^index/result/?(?P<result>.*)/$', result_view, name='result_view'),
]
</code></pre>
<p>Here are what really confuse me a lot:</p>
<p><strong>Q1</strong>: There are two places give result url address <code><form action="/index/result/" method="post" enctype="multipart/form-data"></code> in index.html and <code>url(r'^index/result/?(?P<result>.*)/$', result, name='result'),</code> in urls.py, which one is dominated?</p>
<p><strong>Q2</strong>: How to pass data (i.e. calculation result) from <code>index_view</code> to <code>result_view</code>?
I didn't get <code>result</code> in <code>result_view</code> function using current method.</p>
| 0 |
2016-09-12T11:02:43Z
| 39,449,958 |
<p>Q1: urls.py only maps the urls to the views used to render them. When you submit a form to <code>/index/result/</code>, Django will try to find a view, that matches the url, in this case <code>results_view</code>.</p>
<p>Q2: Instead of passing the result from <code>index_view</code> to <code>result_view</code>, you should move the whole logic of calculating the result to the <code>result_view</code>.</p>
| 1 |
2016-09-12T12:07:49Z
|
[
"python",
"django"
] |
Is it possible to catch data streams other than stdin, stdout and stderr in a Popen call?
| 39,448,884 |
<p>I am working on incorporating a program (samtools) into a pipeline. FYI samtools is a program used to manipulate DNA sequence alignments that are in a SAM format. It takes input and generates an output file via stdin and stdout, so it is quite easily controlled via pythons subprocess.Popen().</p>
<p>When it runs, it also outputs short messages to the console - not using stdout, obviously - and I wonder if it would be possible to catch these as well - potentially by getting a os generated handler list? </p>
<p>I guess my question in general is if it is possible to catch a programs console output if it is not coming from stdout? Thank you.</p>
| 0 |
2016-09-12T11:03:37Z
| 39,449,018 |
<p>There is no other console output than stdout and stderr (assuming that samtools does not write to the terminal directly via a tty device). So, if the output is not captured with the subprocesses stdout, it must have been written to stderr, which can be captured as well using <code>Popen()</code> with <code>stderr=subprocess.PIPE</code> and inspecting the <code>stderr</code> attribute of the resulting process object.</p>
| 2 |
2016-09-12T11:11:38Z
|
[
"python",
"stream",
"subprocess",
"stdout",
"stderr"
] |
(Python) Generating Numbers then Printing them on One Line
| 39,449,026 |
<p>I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.</p>
<p>This is my code below:</p>
<pre><code>for i in range(10):
number1 = (random.randint(0,20))
number2 = (random.randint(0,20))
print (number1 + number2)
answer = input("Enter your answer: ")
</code></pre>
<p>If someone could help me out I would appreciate it, I believe the line</p>
<pre><code> print (number1 + number2)
</code></pre>
<p>is the problem, as it is adding them when I just want the random numbers printed in the sum.</p>
<p>Thanks in advance,</p>
<p>Flynn.</p>
| -1 |
2016-09-12T11:12:07Z
| 39,449,063 |
<p>To convert numbers to a string for concatenation use <code>str()</code>.</p>
<pre><code>print str(number1) + ", " + str(number2)
</code></pre>
<p>or using natural delimiter</p>
<pre><code>print number1, number2
</code></pre>
<p><em>(The <code>,</code> tells python to output them one after the other with space. <code>str()</code> isn't really necessary in that case.)</em></p>
| 1 |
2016-09-12T11:14:25Z
|
[
"python",
"random",
"numbers",
"sum"
] |
(Python) Generating Numbers then Printing them on One Line
| 39,449,026 |
<p>I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.</p>
<p>This is my code below:</p>
<pre><code>for i in range(10):
number1 = (random.randint(0,20))
number2 = (random.randint(0,20))
print (number1 + number2)
answer = input("Enter your answer: ")
</code></pre>
<p>If someone could help me out I would appreciate it, I believe the line</p>
<pre><code> print (number1 + number2)
</code></pre>
<p>is the problem, as it is adding them when I just want the random numbers printed in the sum.</p>
<p>Thanks in advance,</p>
<p>Flynn.</p>
| -1 |
2016-09-12T11:12:07Z
| 39,449,073 |
<p>Try this, </p>
<pre><code>print number1, '+', number2
</code></pre>
| 1 |
2016-09-12T11:15:09Z
|
[
"python",
"random",
"numbers",
"sum"
] |
(Python) Generating Numbers then Printing them on One Line
| 39,449,026 |
<p>I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.</p>
<p>This is my code below:</p>
<pre><code>for i in range(10):
number1 = (random.randint(0,20))
number2 = (random.randint(0,20))
print (number1 + number2)
answer = input("Enter your answer: ")
</code></pre>
<p>If someone could help me out I would appreciate it, I believe the line</p>
<pre><code> print (number1 + number2)
</code></pre>
<p>is the problem, as it is adding them when I just want the random numbers printed in the sum.</p>
<p>Thanks in advance,</p>
<p>Flynn.</p>
| -1 |
2016-09-12T11:12:07Z
| 39,449,150 |
<p>Your following line first computes the sum of the two numbers, then prints it</p>
<pre><code>print (number1 + number2)
</code></pre>
<p>you have to print a string:</p>
<pre><code>print(str(number1) + " + " + str(number2))
</code></pre>
<hr>
<p>or prefer formating features instead of concatenation:</p>
<pre><code>print("{} + {}".format(number1, number2))
</code></pre>
<p>or:</p>
<pre><code>print("%s + %s" % (number1, number2))
</code></pre>
<hr>
<p>Finally, you may want to read some doc:</p>
<ul>
<li><a href="https://docs.python.org/2.7/library/stdtypes.html?highlight=str.format#str.format" rel="nofollow">str.format</a></li>
<li><a href="https://docs.python.org/2.7/library/stdtypes.html?highlight=str.format#string-formatting" rel="nofollow">string formatting with the <code>%</code> operator</a></li>
<li><a href="https://docs.python.org/2.7/tutorial/index.html" rel="nofollow">Python tutorial</a></li>
</ul>
| 1 |
2016-09-12T11:19:55Z
|
[
"python",
"random",
"numbers",
"sum"
] |
(Python) Generating Numbers then Printing them on One Line
| 39,449,026 |
<p>I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.</p>
<p>This is my code below:</p>
<pre><code>for i in range(10):
number1 = (random.randint(0,20))
number2 = (random.randint(0,20))
print (number1 + number2)
answer = input("Enter your answer: ")
</code></pre>
<p>If someone could help me out I would appreciate it, I believe the line</p>
<pre><code> print (number1 + number2)
</code></pre>
<p>is the problem, as it is adding them when I just want the random numbers printed in the sum.</p>
<p>Thanks in advance,</p>
<p>Flynn.</p>
| -1 |
2016-09-12T11:12:07Z
| 39,449,159 |
<p>This should do the job:</p>
<pre><code>from random import randint
for i in range(10):
num1 = randint(0,20)
num2 = randint(0,20)
answer = input('Sum of %i + %i?: ' % (num1,num2)
</code></pre>
<p>Perhaps you know what to do with the rest? (e.g. handling the answer section)</p>
| 0 |
2016-09-12T11:20:13Z
|
[
"python",
"random",
"numbers",
"sum"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.