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
Matplotlib contour map colorbar
39,144,381
<p>I am plotting my data into a contour map. The computations work on the translated values, so I need to put it back to its original value. On the fourth line of the code, is the re-translation process. However, when I plotted it the colorbar shows the relative values, and just a note of the shift value at the top of the color bar. It is just weird that I checked the matrix values, and it contains the original values.</p> <p><a href="http://i.stack.imgur.com/sqMRe.png" rel="nofollow"><img src="http://i.stack.imgur.com/sqMRe.png" alt="enter image description here"></a></p> <p>How can I show the colorbar, with the original values displayed? </p> <pre><code>fig=plt.figure() v=np.linspace(-180,180,25) x,y = np.meshgrid(v,v) z = np.add(z,-shift) z = z.reshape(25,25).T plt.contourf(x,y,z,25) fig.suptitle(AA(prefix)+' Input Data Contour Map') plt.xlabel('$\phi$ (deg)') plt.ylabel('$\psi$ (deg)') plt.xticks(np.arange(-180, 181, 30)) plt.yticks(np.arange(-180, 181, 30)) plt.colorbar() </code></pre> <p>UPDATE: I used set_ticklabels() for a temporary fix, where <code>labels</code> is a list of custom labels. </p> <p>But I am still looking for a better way to solve this problem.</p> <pre><code>plt.colorbar().set_ticklabels(labels) </code></pre> <p><a href="http://i.stack.imgur.com/IsZZ3.png" rel="nofollow">updated contour map</a></p>
0
2016-08-25T11:44:08Z
39,144,965
<p>Matplotlib doesn't know about your <code>shift</code> variable. It is choosing to plot it that way because the changes you are trying to visualize are 10^(-6) of the background value. </p> <p>You can force the colorbar to have tick marks at specific locations as they do in <a href="http://matplotlib.org/examples/pylab_examples/colorbar_tick_labelling_demo.html" rel="nofollow">this pylab example</a> using:</p> <pre><code>cbar = fig.colorbar(cax, ticks=[-1, 0, 1]) cbar.ax.set_yticklabels(['&lt; -1', '0', '&gt; 1']) # vertically oriented colorbar </code></pre> <p>However, doing so will make the scale very difficult to read.</p>
1
2016-08-25T12:10:44Z
[ "python", "matplotlib", "colorbar" ]
Matplotlib plot_surface transparency artefact
39,144,482
<p>I'm trying to plot a surface in 3D from a set of data which specifies the z-values. I get some weird transparency artefact though, where I can see through the surface, even though I set alpha=1.0.</p> <p>The artefact is present both when plotting and when saved to file (both as png and pdf): <a href="http://i.stack.imgur.com/2bXbI.png" rel="nofollow"><img src="http://i.stack.imgur.com/2bXbI.png" alt="enter image description here"></a></p> <p>I have tried changing the line width, and changing the number of strides from 1 to 10 (in the latter case, the surface is not visible though due to too rough resolution).</p> <p><strong>Q: How can I get rid of this transparency?</strong></p> <p>Here is my code:</p> <pre><code>import sys import numpy as np import numpy.ma as ma import matplotlib as mpl import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D y_label = r'x' x_label = r'y' z_label = r'z' x_scale = 2.0*np.pi y_scale = 2.0*np.pi y_numPoints = 250 x_numPoints = 250 def quasiCrystal(x, y): z = 0 for i in range(0,5): z += np.sin(x * np.cos(float(i)*np.pi/5.0) + y * np.sin(float(i)*np.pi/5.0)) return z x = np.linspace(-x_scale, x_scale, x_numPoints) y = np.linspace(-y_scale, y_scale, y_numPoints) X,Y = np.meshgrid(x,y) Z = quasiCrystal(X, Y) f = plt.figure() ax = f.gca(projection='3d') surf = ax.plot_surface( X, Y, Z, rstride=5, cstride=5, cmap='seismic', alpha=1, linewidth=0, antialiased=True, vmin=np.min(Z), vmax=np.max(Z) ) ax.set_zlim3d(np.min(Z), np.max(Z)) f.colorbar(surf, label=z_label) ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.set_zlabel(z_label) plt.show() </code></pre> <p>Here is another picture of my actual data where it is easier to see the artefact: <a href="http://i.stack.imgur.com/nXivZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/nXivZ.png" alt="enter image description here"></a></p>
1
2016-08-25T11:49:04Z
39,145,791
<p>Matplotlib is not a "real" 3D engine. This is a very well known problem and once in a while a similar question to yours appears appears (see <a href="http://stackoverflow.com/questions/37488379/matplotlib-3dplot-extra-lines-when-dimensions-not-equal/37489040#37489040">this</a> and <a href="http://stackoverflow.com/questions/37380912/matplotlib-3d-plot-plot-surface-black/37501084#37501084">this</a>). The problem is that the same artefact can originate problems that seem to be different. I believe such is the case for you.</p> <p>Before going on with my recommendations let me just <a href="http://matplotlib.org/mpl_toolkits/mplot3d/faq.html" rel="nofollow">quote this information from the maplotlib website</a>:</p> <blockquote> <p><strong>My 3D plot doesn’t look right at certain viewing angles</strong> </p> <p>This is probably the most commonly reported issue with mplot3d. The problem is that – from some viewing angles – a 3D object would appear in front of another object, even though it is physically behind it. This can result in plots that do not look “physically correct.”</p> <p>Unfortunately, while some work is being done to reduce the occurance of this artifact, it is currently an intractable problem, and <strong>can not</strong> <strong>be fully solved until matplotlib supports 3D graphics rendering at its</strong> <strong>core</strong>.</p> <p>The problem occurs due to the reduction of 3D data down to 2D + z-order scalar. A single value represents the 3rd dimension for all parts of 3D objects in a collection. Therefore, when the bounding boxes of two collections intersect, it becomes possible for this artifact to occur. Furthermore, the intersection of two 3D objects (such as polygons or patches) can not be rendered properly in matplotlib’s 2D rendering engine.</p> <p><strong>This problem will likely not be solved until OpenGL support is added</strong> to all of the backends (patches are greatly welcomed). Until then, if you need complex 3D scenes, we recommend using <a href="http://docs.enthought.com/mayavi/mayavi/" rel="nofollow">MayaVi</a>.</p> </blockquote> <p><a href="http://docs.enthought.com/mayavi/mayavi/auto/changes.html?highlight=python3" rel="nofollow">It seems that Mayavi has finally moved on to Python 3</a>, so its certainly a possibility. If you want to stick with matplotlib for this kind of plot my advice is that you work with rstride and cstride values to see which ones produce a plot satisfactory to you.</p> <pre><code>surf = ax.plot_surface( X, Y, Z, rstride=5, cstride=5, cmap='jet', alpha=1, linewidth=0, antialiased=True, vmin=0, rstride=10, cstride=10, vmax=z_scale ) </code></pre> <p>Other possibility is to try to see if other kinds of 3D plots do better. Check <a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#tri-surface-plots" rel="nofollow">plot_trisurf</a>, <a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#contour-plots" rel="nofollow">contour</a> or <a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html#filled-contour-plots" rel="nofollow">contourf</a>. I know its not ideal but in the past I also managed to <a href="http://stackoverflow.com/questions/36737053/mplot3d-fill-between-extends-over-axis-limits/36738573#36738573">circumvent other type of artefacts using 3D polygons</a>.</p> <p>Sorry for not having a more satisfactory answer. Perhaps other SO users have better solutions for this. Best of luck.</p>
2
2016-08-25T12:49:17Z
[ "python", "numpy", "matplotlib" ]
Imported a Python module; why does a reassigning a member in it also affect an import elsewhere?
39,144,498
<p>I am seeing Python behavior that I don't understand. Consider this layout:</p> <pre><code>project | main.py | test1.py | test2.py | config.py </code></pre> <p>main.py:</p> <pre><code>import config as conf import test1 import test2 print(conf.test_var) test1.test1() print(conf.test_var) test2.test2() </code></pre> <p>test1.py:</p> <pre><code>import config as conf def test1(): conf.test_var = 'test1' </code></pre> <p>test2.py:</p> <pre><code>import config as conf def test2(): print(conf.test_var) </code></pre> <p>config.py:</p> <pre><code>test_var = 'initial_value' </code></pre> <p>so, <code>python main.py</code> produce:</p> <pre><code>initial_value test1 test1 </code></pre> <p>I am confused by the last line. I thought that it would print <code>initial_value</code> again because I'm importing <code>config.py</code> in <code>test2.py</code> again, and I thought that changes that I've made in the previous step would be overwritten. Am I misunderstanding something?</p>
18
2016-08-25T11:49:35Z
39,144,632
<p>You edited the <code>test_var</code> in <code>test1.py</code> and then just printed it again using <code>test2.py</code>. Importing again does not change the fact than you assigned new value to the variable - it does not "reset" the value to the first one.</p>
3
2016-08-25T11:55:14Z
[ "python", "import" ]
Imported a Python module; why does a reassigning a member in it also affect an import elsewhere?
39,144,498
<p>I am seeing Python behavior that I don't understand. Consider this layout:</p> <pre><code>project | main.py | test1.py | test2.py | config.py </code></pre> <p>main.py:</p> <pre><code>import config as conf import test1 import test2 print(conf.test_var) test1.test1() print(conf.test_var) test2.test2() </code></pre> <p>test1.py:</p> <pre><code>import config as conf def test1(): conf.test_var = 'test1' </code></pre> <p>test2.py:</p> <pre><code>import config as conf def test2(): print(conf.test_var) </code></pre> <p>config.py:</p> <pre><code>test_var = 'initial_value' </code></pre> <p>so, <code>python main.py</code> produce:</p> <pre><code>initial_value test1 test1 </code></pre> <p>I am confused by the last line. I thought that it would print <code>initial_value</code> again because I'm importing <code>config.py</code> in <code>test2.py</code> again, and I thought that changes that I've made in the previous step would be overwritten. Am I misunderstanding something?</p>
18
2016-08-25T11:49:35Z
39,144,647
<p>no, you're changing with <code>test1()</code> in the config.py a constant value. This won't be resetted. Since you print it in <code>test2()</code>, the modified value gets printed again.</p>
1
2016-08-25T11:55:53Z
[ "python", "import" ]
Imported a Python module; why does a reassigning a member in it also affect an import elsewhere?
39,144,498
<p>I am seeing Python behavior that I don't understand. Consider this layout:</p> <pre><code>project | main.py | test1.py | test2.py | config.py </code></pre> <p>main.py:</p> <pre><code>import config as conf import test1 import test2 print(conf.test_var) test1.test1() print(conf.test_var) test2.test2() </code></pre> <p>test1.py:</p> <pre><code>import config as conf def test1(): conf.test_var = 'test1' </code></pre> <p>test2.py:</p> <pre><code>import config as conf def test2(): print(conf.test_var) </code></pre> <p>config.py:</p> <pre><code>test_var = 'initial_value' </code></pre> <p>so, <code>python main.py</code> produce:</p> <pre><code>initial_value test1 test1 </code></pre> <p>I am confused by the last line. I thought that it would print <code>initial_value</code> again because I'm importing <code>config.py</code> in <code>test2.py</code> again, and I thought that changes that I've made in the previous step would be overwritten. Am I misunderstanding something?</p>
18
2016-08-25T11:49:35Z
39,144,651
<p>You changed the value of <code>test_var</code> when you ran <code>test1</code>, and so it was already changed when you ran <code>test2</code>.</p> <p>That variable will not reset for every file in which you import it. It will be one value for everything.</p>
3
2016-08-25T11:56:04Z
[ "python", "import" ]
Imported a Python module; why does a reassigning a member in it also affect an import elsewhere?
39,144,498
<p>I am seeing Python behavior that I don't understand. Consider this layout:</p> <pre><code>project | main.py | test1.py | test2.py | config.py </code></pre> <p>main.py:</p> <pre><code>import config as conf import test1 import test2 print(conf.test_var) test1.test1() print(conf.test_var) test2.test2() </code></pre> <p>test1.py:</p> <pre><code>import config as conf def test1(): conf.test_var = 'test1' </code></pre> <p>test2.py:</p> <pre><code>import config as conf def test2(): print(conf.test_var) </code></pre> <p>config.py:</p> <pre><code>test_var = 'initial_value' </code></pre> <p>so, <code>python main.py</code> produce:</p> <pre><code>initial_value test1 test1 </code></pre> <p>I am confused by the last line. I thought that it would print <code>initial_value</code> again because I'm importing <code>config.py</code> in <code>test2.py</code> again, and I thought that changes that I've made in the previous step would be overwritten. Am I misunderstanding something?</p>
18
2016-08-25T11:49:35Z
39,144,686
<p>Python caches imported modules. The second <code>import</code> call doesn't reload the file.</p>
26
2016-08-25T11:57:29Z
[ "python", "import" ]
Imported a Python module; why does a reassigning a member in it also affect an import elsewhere?
39,144,498
<p>I am seeing Python behavior that I don't understand. Consider this layout:</p> <pre><code>project | main.py | test1.py | test2.py | config.py </code></pre> <p>main.py:</p> <pre><code>import config as conf import test1 import test2 print(conf.test_var) test1.test1() print(conf.test_var) test2.test2() </code></pre> <p>test1.py:</p> <pre><code>import config as conf def test1(): conf.test_var = 'test1' </code></pre> <p>test2.py:</p> <pre><code>import config as conf def test2(): print(conf.test_var) </code></pre> <p>config.py:</p> <pre><code>test_var = 'initial_value' </code></pre> <p>so, <code>python main.py</code> produce:</p> <pre><code>initial_value test1 test1 </code></pre> <p>I am confused by the last line. I thought that it would print <code>initial_value</code> again because I'm importing <code>config.py</code> in <code>test2.py</code> again, and I thought that changes that I've made in the previous step would be overwritten. Am I misunderstanding something?</p>
18
2016-08-25T11:49:35Z
39,144,726
<p>test2.py</p> <pre><code>import config as conf def test2(): print(id(conf.test_var)) print(conf.test_var) </code></pre> <p>test1.py</p> <pre><code>import config as conf def test1(): conf.test_var = 'test1' print(id(conf.test_var)) </code></pre> <p>Change code like this. </p> <p>And run <code>main.py</code></p> <pre><code>initial_value 140007892404912 test1 140007892404912 test1 </code></pre> <p>So, you can see that in both cases you are changing value of the same variable. See these <code>id</code>'s are same. </p>
7
2016-08-25T11:59:31Z
[ "python", "import" ]
Run a script in Python several times and save the output
39,144,597
<p>I have a script called <code>script.py</code> in python which chooses some random values from some distributions with given mean and standard deviation and then do some calculations with these values. I'm doing this for seven different distributions in a loop of 2000 time steps. After some extra calculations, <code>script.py</code> returns a vector as a final output. What I want to do is run this script 100 times simultaneously (I don't want the results of one run affect the results of others) and I want to know this output vector for each of the 100 runs in order to find an average at the end. A good way would be to save each vector as a column in a matrix with 100 columns.</p> <p>I have tried subproccess but I'm having trouble finding a way to save the output of each run. Any help would be much appreciated.</p> <p>A part of my code includes the following: </p> <pre><code>for k in range(N2): for i in range(7): sample2 = np.random.normal(prior[i,0],prior[i,1],1) y[i] = sample2[0] index, value = max(enumerate(y), key=operator.itemgetter(1)) indices[k] = index #trials[k,index] = trials[k-1,index]+1 realdata = np.random.normal(parameters[index,0],parameters[index,1],1) ytrue[k] = realdata[0] prior[index,0] = (prior[index,0]/prior[index,1]**2+ytrue[k]/variance)/(1./prior[index,1]**2+1./variance) prior[index,1] = math.sqrt(1./(1./prior[index,1]**2+1./variance)) meanforoptions[k,:] = prior[:,0] regret = parameters[1,0]-ytrue[k] cumulativeregret[k] = cumulativeregret[k-1]+regret </code></pre> <p>Basically I want to calculate cumulativeregret 100 times and then calculate the average. Running the script only one time doesn't give me sufficient results because there is a lot of randomness in the proccess. Hope this helps.</p>
0
2016-08-25T11:53:36Z
39,145,019
<p>You could run it 100 time using <strong>parallel</strong> - if you have a multi core server with multi CPU's it will genuinely run them all in parallel. </p> <p>Off the top of my head something like this should work.</p> <pre><code> parallel -j 100 python script.py &gt; script.out </code></pre>
0
2016-08-25T12:13:40Z
[ "python" ]
Having a wrong Output in topic modelling
39,144,787
<p>I have tried topic modelling in python . But its displaying wrong output. I have provided sample example and codes below.</p> <pre><code>## Documents doc1 = "Sugar is bad to consume. My sister likes to have sugar, but not my father." doc2 = "My father spends a lot of time driving my sister around to dance practice." doc3 = "Doctors suggest that driving may cause increased stress and blood pressure." doc4 = "Sometimes I feel pressure to perform well at school, but my father never seems to drive my sister to do better." doc5 = "Health experts say that Sugar is not good for your lifestyle." # compile documents doc_complete = [doc1, doc2, doc3, doc4, doc5] from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer import string stop = set(stopwords.words('english')) exclude = set(string.punctuation) lemma = WordNetLemmatizer() def clean(doc): stop_free = "".join([i for i in doc.lower() if i not in stop]) punc_free = ''.join(ch for ch in stop_free if ch not in exclude) normalized = " ".join(lemma.lemmatize(word) for word in punc_free.split()) return normalized doc_clean = [clean(doc) for doc in doc_complete] #Preparing Document Term Matrix import gensim dictionary = corpora.Dictionary([doc_clean]) corpus = [dictionary.doc2bow(doc) for doc in [doc_clean]] #Running LDA Model Lda = gensim.models.ldamodel.LdaModel ldamodel = Lda(corpus, num_topics=3, id2word = dictionary, passes=50) print(ldamodel.print_topics(num_topics=3, num_words=3)) </code></pre> <p>I am getting an output like following :</p> <pre><code>[(0, u'0.200*cr ugge h rvng cue ncree re n bl preure + 0.200*fher pen l f e rvng er run nce prcce + 0.200*ee feel preure perfr well chl bu fher never ee rve er beer'), (1, u'0.200*helh exper h ugr n g fr ur lfele + 0.200*cr ugge h rvng cue ncree re n bl preure + 0.200*ee feel preure perfr well chl bu fher never ee rve er beer'), (2, u'0.200*fher pen l f e rvng er run nce prcce + 0.200*ugr b cnue er lke hve ugr bu n fher + 0.200*ee feel preure perfr well chl bu fher never ee rve er beer')] </code></pre> <p>I am wondering , what I have missed. Thanks</p>
0
2016-08-25T12:02:18Z
39,146,033
<p>The problem happens because of you didn't tokenize your documents before removing the stop words. Instead you iterate through each character and remove the characters that are stopwords, e.g. "a", "i":</p> <pre><code>&gt;&gt;&gt; from nltk.corpus import stopwords &gt;&gt;&gt; stop = stopwords.words('english') &gt;&gt;&gt; stop [u'i', u'me', u'my', u'myself', u'we', u'our', u'ours', u'ourselves', u'you', u'your', u'yours', u'yourself', u'yourselves', u'he', u'him', u'his', u'himself', u'she', u'her', u'hers', u'herself', u'it', u'its', u'itself', u'they', u'them', u'their', u'theirs', u'themselves', u'what', u'which', u'who', u'whom', u'this', u'that', u'these', u'those', u'am', u'is', u'are', u'was', u'were', u'be', u'been', u'being', u'have', u'has', u'had', u'having', u'do', u'does', u'did', u'doing', u'a', u'an', u'the', u'and', u'but', u'if', u'or', u'because', u'as', u'until', u'while', u'of', u'at', u'by', u'for', u'with', u'about', u'against', u'between', u'into', u'through', u'during', u'before', u'after', u'above', u'below', u'to', u'from', u'up', u'down', u'in', u'out', u'on', u'off', u'over', u'under', u'again', u'further', u'then', u'once', u'here', u'there', u'when', u'where', u'why', u'how', u'all', u'any', u'both', u'each', u'few', u'more', u'most', u'other', u'some', u'such', u'no', u'nor', u'not', u'only', u'own', u'same', u'so', u'than', u'too', u'very', u's', u't', u'can', u'will', u'just', u'don', u'should', u'now', u'd', u'll', u'm', u'o', u're', u've', u'y', u'ain', u'aren', u'couldn', u'didn', u'doesn', u'hadn', u'hasn', u'haven', u'isn', u'ma', u'mightn', u'mustn', u'needn', u'shan', u'shouldn', u'wasn', u'weren', u'won', u'wouldn'] &gt;&gt;&gt; doc = "Sugar is bad to consume. My sister likes to have sugar, but not my father." &gt;&gt;&gt; "".join([i for i in doc.lower() if i not in stop]) 'ugr b cnue. er lke hve ugr, bu n fher.' </code></pre> <p>You should have processed the stopword removals like this:</p> <pre><code>&gt;&gt;&gt; from nltk import word_tokenize &gt;&gt;&gt; doc = "Sugar is bad to consume. My sister likes to have sugar, but not my father." &gt;&gt;&gt; " ".join([i for i in word_tokenize(doc.lower()) if i not in stop]) 'sugar bad consume . sister likes sugar , father .' </code></pre> <p>See <a href="http://stackoverflow.com/questions/19130512/stopword-removal-with-nltk">Stopword removal with NLTK</a></p> <hr> <p>Actually, you pre-processsing pipeline can be simplified.</p> <pre><code>&gt;&gt;&gt; import gensim &gt;&gt;&gt; doc1 = "Sugar is bad to consume. My sister likes to have sugar, but not my father." &gt;&gt;&gt; doc2 = "My father spends a lot of time driving my sister around to dance practice." &gt;&gt;&gt; doc3 = "Doctors suggest that driving may cause increased stress and blood pressure." &gt;&gt;&gt; doc4 = "Sometimes I feel pressure to perform well at school, but my father never seems to drive my sister to do better." &gt;&gt;&gt; doc5 = "Health experts say that Sugar is not good for your lifestyle." &gt;&gt;&gt; documents = [doc1, doc2, doc3, doc4, doc5] &gt;&gt;&gt; texts = map(gensim.utils.lemmatize,documents) &gt;&gt;&gt; texts [['sugar/NN', 'be/VB', 'bad/JJ', 'consume/VB', 'sister/NN', 'like/VB', 'have/VB', 'sugar/NN', 'not/RB', 'father/NN'], ['father/NN', 'spend/VB', 'lot/NN', 'time/NN', 'drive/VB', 'sister/NN', 'dance/VB', 'practice/NN'], ['doctor/NN', 'suggest/VB', 'drive/VB', 'cause/VB', 'increased/JJ', 'stress/NN', 'blood/NN', 'pressure/NN'], ['sometimes/RB', 'feel/JJ', 'pressure/NN', 'perform/VB', 'well/RB', 'school/NN', 'father/NN', 'never/RB', 'seem/VB', 'drive/VB', 'sister/NN', 'do/VB', 'better/JJ'], ['health/NN', 'expert/NN', 'say/VB', 'sugar/NN', 'be/VB', 'not/RB', 'good/JJ', 'lifestyle/NN']] </code></pre> <p>Then to train the topic model:</p> <pre><code>&gt;&gt;&gt; dictionary = gensim.corpora.Dictionary(texts) &gt;&gt;&gt; corpus = [dictionary.doc2bow(doc) for doc in texts] &gt;&gt;&gt; Lda = gensim.models.ldamodel.LdaModel &gt;&gt;&gt; ldamodel = Lda(corpus, num_topics=3, id2word = dictionary, passes=50) &gt;&gt;&gt; ldamodel.print_topics() [(0, u'0.067*drive/VB + 0.067*pressure/NN + 0.067*stress/NN + 0.067*blood/NN + 0.067*doctor/NN + 0.067*increased/JJ + 0.067*cause/VB + 0.067*suggest/VB + 0.017*sister/NN + 0.017*father/NN'), (1, u'0.078*sugar/NN + 0.054*not/RB + 0.054*be/VB + 0.054*father/NN + 0.054*sister/NN + 0.031*do/VB + 0.031*seem/VB + 0.031*school/NN + 0.031*well/RB + 0.031*better/JJ'), (2, u'0.067*drive/VB + 0.067*sister/NN + 0.067*father/NN + 0.067*lot/NN + 0.067*practice/NN + 0.067*dance/VB + 0.067*spend/VB + 0.067*time/NN + 0.017*pressure/NN + 0.017*expert/NN')] </code></pre>
2
2016-08-25T12:58:52Z
[ "python", "nltk", "topic-modeling" ]
Add a ScrollView to kivy Popup
39,144,853
<p>I am trying to add a ScrollView to a Popup which opens when button is clicked on the main interface. But the scrollview is not displaying the content properly. How can I fix this?</p> <pre><code>from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.popup import Popup from kivy.uix.scrollview import ScrollView from kivy.app import App from kivy.core.window import Window def btn_clicked(instance): layout_popup = GridLayout(cols=1, spacing=10, size_hint_y=None) layout_popup.bind(minimum_height=layout_popup.setter('height')) for i in range(0, 15): btn1 = Button(text=str(i), id=str(i)) layout_popup.add_widget(btn1) root = ScrollView(size_hint=(1, None), size=(Window.width, Window.height)) root.add_widget(layout_popup) popup = Popup(title='Numbers', content=root, size_hint=(1, 1)) popup.open() class TutorialApp(App): def build(self): g = GridLayout(cols=1) btn = Button(text='Click') btn.bind(on_press=btn_clicked) g.add_widget(btn) return g TutorialApp().run() </code></pre>
0
2016-08-25T12:05:45Z
39,147,431
<p>Pass <code>size_hint_y=None</code> to the button constructor and it should work.</p>
1
2016-08-25T14:02:17Z
[ "python", "popup", "scrollview", "kivy" ]
NLTK - nltk.tokenize.RegexpTokenizer - regex not working as expected
39,144,991
<p>I am trying to Tokenize text using RegexpTokenizer.</p> <p><strong>Code:</strong></p> <pre><code>from nltk.tokenize import RegexpTokenizer #from nltk.tokenize import word_tokenize line = "U.S.A Count U.S.A. Sec.of U.S. Name:Dr.John Doe J.Doe 1.11 1,000 10--20 10-20" pattern = '[\d|\.|\,]+|[A-Z][\.|A-Z]+\b[\.]*|[\w]+|\S' tokenizer = RegexpTokenizer(pattern) print tokenizer.tokenize(line) #print word_tokenize(line) </code></pre> <p><strong>Output:</strong></p> <blockquote> <p>['U', '.', 'S', '.', 'A', 'Count', 'U', '.', 'S', '.', 'A', '.', 'Sec', '.', 'of', 'U', '.', 'S', '.', 'Name', ':', 'Dr', '.', 'John', 'Doe', 'J', '.', 'Doe', '1.11', '1,000', '10', '-', '-', '20', '10', '-', '20']</p> </blockquote> <p><strong>Expected Output:</strong></p> <blockquote> <p>['U.S.A', 'Count', 'U.S.A.', 'Sec', '.', 'of', 'U.S.', 'Name', ':', 'Dr', '.', 'John', 'Doe', 'J.', 'Doe', '1.11', '1,000', '10', '-', '-', '20', '10', '-', '20']</p> </blockquote> <p>Why tokenizer is also spiltting my expected tokens "U.S.A" , "U.S."? How can I resolve this issue?</p> <p>My regex : <a href="https://regex101.com/r/dS1jW9/1" rel="nofollow">https://regex101.com/r/dS1jW9/1</a></p>
3
2016-08-25T12:12:05Z
39,145,213
<p>If you mod your regex</p> <pre><code>pattern = '[USA\.]{4,}|[\w]+|[\S]' </code></pre> <p>Then </p> <pre><code>pattern = '[USA\.]{4,}|[\w]+' tokenizer = RegexpTokenizer(pattern) print (''+str(tokenizer.tokenize(line))) </code></pre> <p>You get the output that you wanted</p> <pre><code>['U.S.A', 'Count', 'U.S.A.', 'Sec', '.', 'of', 'U.S.', 'Name', ':', 'Dr', '.', 'John', 'Doe', 'J', '.', 'Doe', '1', '.', '11', '1', ',', '000', '10', '-', '-', '20', '10', '-', '20'] </code></pre>
0
2016-08-25T12:22:20Z
[ "python", "regex", "nlp", "nltk", "tokenize" ]
NLTK - nltk.tokenize.RegexpTokenizer - regex not working as expected
39,144,991
<p>I am trying to Tokenize text using RegexpTokenizer.</p> <p><strong>Code:</strong></p> <pre><code>from nltk.tokenize import RegexpTokenizer #from nltk.tokenize import word_tokenize line = "U.S.A Count U.S.A. Sec.of U.S. Name:Dr.John Doe J.Doe 1.11 1,000 10--20 10-20" pattern = '[\d|\.|\,]+|[A-Z][\.|A-Z]+\b[\.]*|[\w]+|\S' tokenizer = RegexpTokenizer(pattern) print tokenizer.tokenize(line) #print word_tokenize(line) </code></pre> <p><strong>Output:</strong></p> <blockquote> <p>['U', '.', 'S', '.', 'A', 'Count', 'U', '.', 'S', '.', 'A', '.', 'Sec', '.', 'of', 'U', '.', 'S', '.', 'Name', ':', 'Dr', '.', 'John', 'Doe', 'J', '.', 'Doe', '1.11', '1,000', '10', '-', '-', '20', '10', '-', '20']</p> </blockquote> <p><strong>Expected Output:</strong></p> <blockquote> <p>['U.S.A', 'Count', 'U.S.A.', 'Sec', '.', 'of', 'U.S.', 'Name', ':', 'Dr', '.', 'John', 'Doe', 'J.', 'Doe', '1.11', '1,000', '10', '-', '-', '20', '10', '-', '20']</p> </blockquote> <p>Why tokenizer is also spiltting my expected tokens "U.S.A" , "U.S."? How can I resolve this issue?</p> <p>My regex : <a href="https://regex101.com/r/dS1jW9/1" rel="nofollow">https://regex101.com/r/dS1jW9/1</a></p>
3
2016-08-25T12:12:05Z
39,145,251
<p>The point is that your <code>\b</code> was a backspace character, you need to use a raw string literal. Also, you have literal pipes in the character classes that would also mess your output.</p> <p>This works as expected:</p> <pre><code>&gt;&gt;&gt; pattern = r'[\d.,]+|[A-Z][.A-Z]+\b\.*|\w+|\S' &gt;&gt;&gt; tokenizer = RegexpTokenizer(pattern) &gt;&gt;&gt; print(tokenizer.tokenize(line)) ['U.S.A', 'Count', 'U.S.A.', 'Sec', '.', 'of', 'U.S.', 'Name', ':', 'Dr', '.', 'John', 'Doe', 'J.', 'Doe', '1.11', '1,000', '10', '-', '-', '20', '10', '-', '20'] </code></pre> <p>Note that putting a single <code>\w</code> into a character class is pointless. Also, you do not need to escape every non-word char (like a dot) in the character class as they are mostly treated as literal chars there (only <code>^</code>, <code>]</code>, <code>-</code> and <code>\</code> require special attention).</p>
4
2016-08-25T12:23:56Z
[ "python", "regex", "nlp", "nltk", "tokenize" ]
Checking Valid Country Names Python Pandas
39,145,153
<p>I got a column that contains countries. I was wondering, is there a way to check if the column contains any invalid country names and print them out?</p> <pre><code> Column1 Hong Kong United States of America Malaysia Thailand Canada Indi Koreai Japan Australia </code></pre> <p>My desire result will be</p> <pre><code> Column1 Indi Koreai </code></pre>
-1
2016-08-25T12:19:27Z
39,145,394
<p>You can start with pycountry is it a module - however it is inaccurate !! it contains 249 countries - where as the UN currently lists 241.</p> <p>This is what I currently use</p> <pre><code>class nation(object): def __init__(self, un_code, un_name, un_3_str): self._code = int(un_code) self._name = un_name self._code3 = un_3_str @property def numeric(self): return self._code @property def name(self): return self._name @property def code(self): return self._code3 class UN_db(object): def __init__(self): self.UN = [("4", "Afghanistan", "AFG"), ("248", "Aland Islands", "ALA"), ("8", "Albania", "ALB"), ("12", "Algeria", "DZA"), ("16", "American Samoa", "ASM"), ("20", "Andorra", "AND"), ("24", "Angola", "AGO"), ("660", "Anguilla", "AIA"), ("28", "Antigua and Barbuda", "ATG"), ("32", "Argentina", "ARG"), ("51", "Armenia", "ARM"), ("533", "Aruba", "ABW"), ("36", "Australia", "AUS"), ("40", "Austria", "AUT"), ("31", "Azerbaijan", "AZE"), ("44", "Bahamas", "BHS"), ("48", "Bahrain", "BHR"), ("50", "Bangladesh", "BGD"), ("52", "Barbados", "BRB"), ("112", "Belarus", "BLR"), ("56", "Belgium", "BEL"), ("84", "Belize", "BLZ"), ("204", "Benin", "BEN"), ("60", "Bermuda", "BMU"), ("64", "Bhutan", "BTN"), ("68", "Bolivia (Plurinational State of)", "BOL"), ("535", "Bonaire, Sint Eustatius and Saba", "BES"), ("70", "Bosnia and Herzegovina", "BIH"), ("72", "Botswana", "BWA"), ("76", "Brazil", "BRA"), ("92", "British Virgin Islands", "VGB"), ("96", "Brunei Darussalam", "BRN"), ("100", "Bulgaria", "BGR"), ("854", "Burkina Faso", "BFA"), ("108", "Burundi", "BDI"), ("132", "Cabo Verde", "CPV"), ("116", "Cambodia", "KHM"), ("120", "Cameroon", "CMR"), ("124", "Canada", "CAN"), ("136", "Cayman Islands", "CYM"), ("140", "Central African Republic", "CAF"), ("148", "Chad", "TCD"), ("830", "Channel Islands", ""), ("152", "Chile", "CHL"), ("156", "China", "CHN"), ("344", "China, Hong Kong Special Administrative Region", "HKG"), ("446", "China, Macao Special Administrative Region", "MAC"), ("170", "Colombia", "COL"), ("174", "Comoros", "COM"), ("178", "Congo", "COG"), ("184", "Cook Islands", "COK"), ("188", "Costa Rica", "CRI"), ("384", "Cote d'Ivoire", "CIV"), ("191", "Croatia", "HRV"), ("192", "Cuba", "CUB"), ("531", "Curacao", "CUW"), ("196", "Cyprus", "CYP"), ("203", "Czech Republic", "CZE"), ("408", "Democratic People's Republic of Korea", "PRK"), ("180", "Democratic Republic of the Congo", "COD"), ("208", "Denmark", "DNK"), ("262", "Djibouti", "DJI"), ("212", "Dominica", "DMA"), ("214", "Dominican Republic", "DOM"), ("218", "Ecuador", "ECU"), ("818", "Egypt", "EGY"), ("222", "El Salvador", "SLV"), ("226", "Equatorial Guinea", "GNQ"), ("232", "Eritrea", "ERI"), ("233", "Estonia", "EST"), ("231", "Ethiopia", "ETH"), ("234", "Faeroe Islands", "FRO"), ("238", "Falkland Islands (Malvinas)", "FLK"), ("242", "Fiji", "FJI"), ("246", "Finland", "FIN"), ("250", "France", "FRA"), ("254", "French Guiana", "GUF"), ("258", "French Polynesia", "PYF"), ("266", "Gabon", "GAB"), ("270", "Gambia", "GMB"), ("268", "Georgia", "GEO"), ("276", "Germany", "DEU"), ("288", "Ghana", "GHA"), ("292", "Gibraltar", "GIB"), ("300", "Greece", "GRC"), ("304", "Greenland", "GRL"), ("308", "Grenada", "GRD"), ("312", "Guadeloupe", "GLP"), ("316", "Guam", "GUM"), ("320", "Guatemala", "GTM"), ("831", "Guernsey", "GGY"), ("324", "Guinea", "GIN"), ("624", "Guinea-Bissau", "GNB"), ("328", "Guyana", "GUY"), ("332", "Haiti", "HTI"), ("336", "Holy See", "VAT"), ("340", "Honduras", "HND"), ("348", "Hungary", "HUN"), ("352", "Iceland", "ISL"), ("356", "India", "IND"), ("360", "Indonesia", "IDN"), ("364", "Iran (Islamic Republic of)", "IRN"), ("368", "Iraq", "IRQ"), ("372", "Ireland", "IRL"), ("833", "Isle of Man", "IMN"), ("376", "Israel", "ISR"), ("380", "Italy", "ITA"), ("388", "Jamaica", "JAM"), ("392", "Japan", "JPN"), ("832", "Jersey", "JEY"), ("400", "Jordan", "JOR"), ("398", "Kazakhstan", "KAZ"), ("404", "Kenya", "KEN"), ("296", "Kiribati", "KIR"), ("414", "Kuwait", "KWT"), ("417", "Kyrgyzstan", "KGZ"), ("418", "Lao People's Democratic Republic", "LAO"), ("428", "Latvia", "LVA"), ("422", "Lebanon", "LBN"), ("426", "Lesotho", "LSO"), ("430", "Liberia", "LBR"), ("434", "Libya", "LBY"), ("438", "Liechtenstein", "LIE"), ("440", "Lithuania", "LTU"), ("442", "Luxembourg", "LUX"), ("450", "Madagascar", "MDG"), ("454", "Malawi", "MWI"), ("458", "Malaysia", "MYS"), ("462", "Maldives", "MDV"), ("466", "Mali", "MLI"), ("470", "Malta", "MLT"), ("584", "Marshall Islands", "MHL"), ("474", "Martinique", "MTQ"), ("478", "Mauritania", "MRT"), ("480", "Mauritius", "MUS"), ("175", "Mayotte", "MYT"), ("484", "Mexico", "MEX"), ("583", "Micronesia (Federated States of)", "FSM"), ("492", "Monaco", "MCO"), ("496", "Mongolia", "MNG"), ("499", "Montenegro", "MNE"), ("500", "Montserrat", "MSR"), ("504", "Morocco", "MAR"), ("508", "Mozambique", "MOZ"), ("104", "Myanmar", "MMR"), ("516", "Namibia", "NAM"), ("520", "Nauru", "NRU"), ("524", "Nepal", "NPL"), ("528", "Netherlands", "NLD"), ("540", "New Caledonia", "NCL"), ("554", "New Zealand", "NZL"), ("558", "Nicaragua", "NIC"), ("562", "Niger", "NER"), ("566", "Nigeria", "NGA"), ("570", "Niue", "NIU"), ("574", "Norfolk Island", "NFK"), ("580", "Northern Mariana Islands", "MNP"), ("578", "Norway", "NOR"), ("512", "Oman", "OMN"), ("586", "Pakistan", "PAK"), ("585", "Palau", "PLW"), ("591", "Panama", "PAN"), ("598", "Papua New Guinea", "PNG"), ("600", "Paraguay", "PRY"), ("604", "Peru", "PER"), ("608", "Philippines", "PHL"), ("612", "Pitcairn", "PCN"), ("616", "Poland", "POL"), ("620", "Portugal", "PRT"), ("630", "Puerto Rico", "PRI"), ("634", "Qatar", "QAT"), ("410", "Republic of Korea", "KOR"), ("498", "Republic of Moldova", "MDA"), ("638", "Réunion", "REU"), ("642", "Romania", "ROU"), ("643", "Russian Federation", "RUS"), ("646", "Rwanda", "RWA"), ("652", "Saint Barthélemy", "BLM"), ("654", "Saint Helena", "SHN"), ("659", "Saint Kitts and Nevis", "KNA"), ("662", "Saint Lucia", "LCA"), ("663", "Saint Martin (French part)", "MAF"), ("666", "Saint Pierre and Miquelon", "SPM"), ("670", "Saint Vincent and the Grenadines", "VCT"), ("882", "Samoa", "WSM"), ("674", "San Marino", "SMR"), ("678", "Sao Tome and Principe", "STP"), ("680", "Sark", " "), ("682", "Saudi Arabia", "SAU"), ("686", "Senegal", "SEN"), ("688", "Serbia", "SRB"), ("690", "Seychelles", "SYC"), ("694", "Sierra Leone", "SLE"), ("702", "Singapore", "SGP"), ("534", "Sint Maarten (Dutch part)", "SXM"), ("703", "Slovakia", "SVK"), ("705", "Slovenia", "SVN"), ("90", "Solomon Islands", "SLB"), ("706", "Somalia", "SOM"), ("710", "South Africa", "ZAF"), ("728", "South Sudan", "SSD"), ("724", "Spain", "ESP"), ("144", "Sri Lanka", "LKA"), ("275", "State of Palestine", "PSE"), ("729", "Sudan", "SDN"), ("740", "Suriname", "SUR"), ("744", "Svalbard and Jan Mayen Islands", "SJM"), ("748", "Swaziland", "SWZ"), ("752", "Sweden", "SWE"), ("756", "Switzerland", "CHE"), ("760", "Syrian Arab Republic", "SYR"), ("762", "Tajikistan", "TJK"), ("764", "Thailand", "THA"), ("807", "The former Yugoslav Republic of Macedonia", "MKD"), ("626", "Timor-Leste", "TLS"), ("768", "Togo", "TGO"), ("772", "Tokelau", "TKL"), ("776", "Tonga", "TON"), ("780", "Trinidad and Tobago", "TTO"), ("788", "Tunisia", "TUN"), ("792", "Turkey", "TUR"), ("795", "Turkmenistan", "TKM"), ("796", "Turks and Caicos Islands", "TCA"), ("798", "Tuvalu", "TUV"), ("800", "Uganda", "UGA"), ("804", "Ukraine", "UKR"), ("784", "United Arab Emirates", "ARE"), ("826", "United Kingdom of Great Britain and Northern Ireland", "GBR"), ("834", "United Republic of Tanzania", "TZA"), ("840", "United States of America", "USA"), ("850", "United States Virgin Islands", "VIR"), ("858", "Uruguay", "URY"), ("860", "Uzbekistan", "UZB"), ("548", "Vanuatu", "VUT"), ("862", "Venezuela (Bolivarian Republic of)", "VEN"), ("704", "Viet Nam", "VNM"), ("876", "Wallis and Futuna Islands", "WLF"), ("732", "Western Sahara", "ESH"), ("887", "Yemen", "YEM"), ("894", "Zambia", "ZMB"), ("716", "Zimbabwe", "ZWE"), ("000", "000", "UNK")] @property def count(self): return len(self.UN) @property def UN_Codes(self): codes = [int(a[0]) for a in self.UN] return codes @property def Str_Codes(self): return [a[2] for a in self.UN] def getby_int(self, un_code_as_int): ''' Look up UN code using integer i.e. Oman is 512 :param un_code_as_int: :return: ''' for ctry in self.UN: if int(ctry[0]) == un_code_as_int: return nation(ctry[0], ctry[1], ctry[2]) return self.UN[:-1] def getby_code(self, un_code_as_code): ''' Look up UN code using integer i.e. Oman is OMN :param un_code_as_code: :return: Tuple containing (Integer Code, String Code, Country Name) All return items are strings ''' un_code_as_code = un_code_as_code.upper().lstrip().rstrip() for ctry in self.UN: if ctry[0] == un_code_as_code: return nation(ctry[0], ctry[1], ctry[2]) return self.UN[:-1] </code></pre>
1
2016-08-25T12:31:10Z
[ "python", "pandas" ]
Puppet Dependency file failing in local Vagrant Environmnet
39,145,182
<p>Below is my Puppet code for a Python Django App.</p> <pre><code>class ltp ($project_dir = '/vagrant') { exec { "install_project_dependencies": cwd =&gt; $project_dir, command =&gt; "/usr/bin/python setup.py install &gt; /tmp/setuplog 2&gt;&amp;1", timeout =&gt; 0, } exec { "install_nltk_data": cwd =&gt; $project_dir, command =&gt; "su - vagrant -c \"cd /opt/vagrant; /usr/bin/python -m nltk.downloader stopwords &gt; /tmp/nltklog 2&gt;&amp;1\"", require =&gt; Exec['install_project_dependencies'] } exec { "install_django_db": cwd =&gt; $project_dir, user =&gt; 'vagrant', environment =&gt; ["ENV=DEV"], command =&gt; "/usr/bin/python manage.py syncdb --noinput &gt; /tmp/syncdblog 2&gt;&amp;1", require =&gt; Exec['create_ba_database'] } exec { "create_ba_database": cwd =&gt; $project_dir, command =&gt; "echo \"psql -c 'create database burson_clips;'\" | sudo su postgres", require =&gt; Exec['change_pg_password'] } exec { "change_pg_password": cwd =&gt; $project_dir, command =&gt; "sudo -u postgres psql -c \"alter user postgres with password 'postgres';\"" } } </code></pre> <p>Below is the error Vagrant gives when I run <code>vagrant provision</code></p> <pre><code>clips: Error: /usr/bin/python setup.py install &gt; /tmp/setuplog 2&gt;&amp;1 returned 1 instead of one of [0] ==&gt; clips: Error: /Stage[main]/Ltp/Exec[install_project_dependencies]/returns: change from notrun to 0 failed: /usr/bin/python setup.py install &gt; /tmp/setuplog 2&gt;&amp;1 returned 1 instead of one of [0] ==&gt; clips: Warning: /Stage[main]/Ltp/Exec[install_nltk_data]: Skipping because of failed dependencies ==&gt; clips: Notice: /Stage[main]/Ltp/Exec[change_pg_password]/returns: executed successfully ==&gt; clips: Notice: /Stage[main]/Ltp/Exec[create_ba_database]/returns: ERROR: database "burson_clips" already exists ==&gt; clips: Notice: /Stage[main]/Ltp/Exec[install_django_db]: Dependency Exec[create_ba_database] has failures: true ==&gt; clips: Error: echo "psql -c 'create database burson_clips;'" | sudo su postgres returned 1 instead of one of [0] ==&gt; clips: Error: /Stage[main]/Ltp/Exec[create_ba_database]/returns: change from notrun to 0 failed: echo "psql -c 'create database burson_clips;'" | sudo su postgres returned 1 instead of one of [0] ==&gt; clips: Warning: /Stage[main]/Ltp/Exec[install_django_db]: Skipping because of failed dependencies </code></pre> <p>Did any body received this error previously? Can any body let me know if any area of code I should look into. This happens on my local vagrant setup.</p> <p><strong>Update</strong></p> <p>So I tried Vagrant destroy and recreate the dependency now I am getting error.</p> <pre><code>==&gt; clips: Error: /usr/bin/python setup.py install &gt; /tmp/setuplog 2&gt;&amp;1 returned 1 instead of one of [0] ==&gt; clips: Error: /Stage[main]/Ltp/Exec[install_project_dependencies]/returns: change from notrun to 0 failed: /usr/bin/python setup.py install &gt; /tmp/setuplog 2&gt;&amp;1 returned 1 instead of one of [0] ==&gt; clips: Warning: /Stage[main]/Ltp/Exec[install_nltk_data]: Skipping because of failed dependencies ==&gt; clips: Notice: /Stage[main]/Ltp/Exec[change_pg_password]/returns: executed successfully ==&gt; clips: Notice: /Stage[main]/Ltp/Exec[create_ba_database]/returns: executed successfully ==&gt; clips: Error: /usr/bin/python manage.py syncdb --noinput &gt; /tmp/syncdblog 2&gt;&amp;1 returned 1 instead of one of [0] ==&gt; clips: Error: /Stage[main]/Ltp/Exec[install_django_db]/returns: change from notrun to 0 failed: /usr/bin/python manage.py syncdb --noinput &gt; /tmp/syncdblog 2&gt;&amp;1 returned 1 instead of one of [0] </code></pre> <p>Adding setup.py</p> <pre><code>#!/usr/bin/env python from setuptools import setup # fix setuptools: # wget http://bootstrap.pypa.io/ez_setup.py -O - | sudo python install_requires = [ 'Django==1.8', 'django-celery', 'celery==3.1.23', 'ipdb', # 'ipython', 'django-kombu', 'kombu', 'billiard', 'eventlet', # 'uwsgi', 'xlutils', 'pip-tools', 'djangorestframework', 'markdown', 'django-filter', 'django-cors-headers', 'pyyaml', 'sh', 'pika==0.9.12', 'pyparsing', 'pyrabbit', 'lxml==3.3.5', 'xlrd', 'raven', 'six', 'requests', 'uritemplate', 'twitter-text-python', # for the ttp 'python-dateutil==2.4.0', 'redis', 'python-docx', ##for opening word documents 'sqlparse', 'httplib2', 'simplejson', 'requests==2.5.1', 'six&gt;=1.7.3', 'django-organizations', 'django_extensions', 'feedparser==5.1.3', # The entry for this on pypi is f'd up. # pip install https://github.com/timothycrosley/RedisStore/blob/master/dist/RedisStore-0.1.tar.gz?raw=true # 'RedisStore', 'xlsxwriter', 'django-grappelli', # MDM: setuptools/pip can't install these # 'gensim', # 'numpy', # 'scikit-learn', # 'matplotlib', # MDM: only pip can install this one! # 'CairoSVG', 'xmltodict', 'twitter', 'pygal', 'tinycss', 'cssselect', 'dashboard_common==1.3.3', 'pytz', 'greenlet', 'xlsxwriter', 'pattern', 'oauth2', 'wordcloud', # MDM this is a dep-lib cluser-f # pip install it last so it can f up dependencies how ever it likes # 'python-social-auth', # 'newspaper', ##for article extraction 'python-saml', 'python-openid', 'xmlsec', 'paramiko', # has apt-get/brew deps 'psycopg2' ] # sudo -H pip install CairoSVG dependency_links = [ # fails unless vagrant box has a .ssh identity w/ git hub &amp; trust github 'workinggithublink', ] </code></pre>
0
2016-08-25T12:20:43Z
39,145,306
<p>The error is this </p> <pre><code>==&gt; clips: Notice: /Stage[main]/Ltp/Exec[create_ba_database]/returns: ERROR: database "burson_clips" already exists ==&gt; clips: Error: echo "psql -c 'create database burson_clips;'" | sudo su postgres returned 1 instead of one of [0] </code></pre> <p>your db already exists as <code>burson_clips</code> so the command fails and the rest of the provisioning fails.</p> <p>You should be able to leverage some answers from <a href="http://stackoverflow.com/questions/14549270/check-if-database-exists-in-postgresql-using-shell">Check if database exists in postgreSQL using shell</a> to check if the db exists first and then create only if needed; something like</p> <pre><code>exec { "create_ba_database": cwd =&gt; $project_dir, command =&gt; "echo \"psql -c 'create database burson_clips;'\" | sudo su postgres", require =&gt; Exec['change_pg_password'], unless =&gt; "psql -lqt | cut -d \| -f 1 | grep -qw 'burson_clips'" } </code></pre>
1
2016-08-25T12:26:59Z
[ "python", "django", "vagrant", "puppet", "vagrant-provision" ]
"""TypeError: only length-1 arrays can be converted to Python scalars""" when trying to make run a counter on Pi3 with 7segment display
39,145,284
<p>I'm currrently working on a simple count program for RPi-3 with a seven-segment-Display. I have two ways of counting from one to ten, one manually, always lighting up the single segments I need, and another way, which is based on a numpy matrix. </p> <p>The manual way works fine but I have Problems with the matrix way of doing it. Here is the code with some explications for understanding:</p> <pre><code>import RPi.GPIO as GPIO import time import numpy GPIO.setmode(GPIO.BOARD) GPIO.setup(31, GPIO.OUT) #up right GPIO.setup(32, GPIO.OUT) #up GPIO.setup(33, GPIO.OUT) #up left GPIO.setup(35, GPIO.OUT) #middle GPIO.setup(36, GPIO.OUT) #down right GPIO.setup(37, GPIO.OUT) #down left GPIO.setup(38, GPIO.OUT) #decimal point(in the bottom right corner) GPIO.setup(40, GPIO.OUT) #down def all_off(): #turns all segments off, works as well! GPIO.output(31, False) GPIO.output(32, False) GPIO.output(33, False) GPIO.output(35, False) GPIO.output(36, False) GPIO.output(37, False) GPIO.output(38, False) GPIO.output(40, False) matrix = numpy.matrix([[1,0,0,0,1,0,0,0], #those are the combinations [1,1,0,1,0,1,0,1], #from one to nine and finishing [1,1,0,1,1,0,0,1], #with zero [1,0,1,1,1,0,0,0], #first number of a line is value for Pin31 then 32, [0,1,1,1,1,0,0,1], #33, 35, 36, 37, 38, 40 [0,1,1,1,1,1,0,1], [1,1,0,0,1,0,0,0], #combinations are correct, btw! [1,1,1,1,1,1,0,1], [1,1,1,1,1,0,0,1]]) def set_to(byte): all_off() GPIO.output(31, int(byte[0])) #&lt;-- this is the line where the error GPIO.output(32, int(byte[1])) #occurs GPIO.output(33, int(byte[2])) GPIO.output(35, int(byte[3])) GPIO.output(36, int(byte[4])) GPIO.output(37, int(byte[5])) GPIO.output(38, int(byte[6])) GPIO.output(40, int(byte[7])) for line in matrix: #the actual counting program set_to(matrix[line]) time.sleep(1) GPIO.cleanup() </code></pre> <p>The problem is apparently, that the array can't be read? I don't get what the problem is or what to do to fix this issue. It seems to have something to do with the 'line' of the matrix is just anouther matrix(with just one line). </p> <p>I really don't know what to do, please help!!</p>
1
2016-08-25T12:25:25Z
39,147,279
<p>I have changed my strategy and now use an numpy array. Now I have a working code:</p> <pre><code>import RPi.GPIO as GPIO import time import numpy GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(31, GPIO.OUT) GPIO.setup(32, GPIO.OUT) GPIO.setup(33, GPIO.OUT) GPIO.setup(35, GPIO.OUT) GPIO.setup(36, GPIO.OUT) GPIO.setup(37, GPIO.OUT) GPIO.setup(38, GPIO.OUT) GPIO.setup(40, GPIO.OUT) pinlist = [(31, 0), (32, 1) ,(33, 2) ,(35, 3) ,(36, 4) ,(37, 5) ,(38, 6), (40, 7)] def all_off(): GPIO.output(31, False) GPIO.output(32, False) GPIO.output(33, False) GPIO.output(35, False) GPIO.output(36, False) GPIO.output(37, False) GPIO.output(38, False) GPIO.output(40, False) matrix = numpy.array([[1,0,0,0,1,0,0,0], [1,1,0,1,0,1,0,1], [1,1,0,1,1,0,0,1], [1,0,1,1,1,0,0,0], [0,1,1,1,1,0,0,1], [0,1,1,1,1,1,0,1], [1,1,0,0,1,0,0,0], [1,1,1,1,1,1,0,1], [1,1,1,1,1,0,0,1]]) for i in range(0, 9): all_off() for (pin, j) in pinlist: GPIO.output(pin, int(matrix[i][j])) time.sleep(0.25) GPIO.cleanup() </code></pre> <p>This works as following:</p> <p>I created a list of all Pin's with their number(packed in a tuple). Those Tuple's are read by the for-loop inside of the big for-loop. Now I take reference to the "coordinates" of a single Point inside of my array. This means, that it's a bit slow(you can see the single segment's pop up), but I luckily don't have to care!</p> <p>Nevertheless a big thank you for your support!</p>
1
2016-08-25T13:55:15Z
[ "python", "arrays", "numpy", "matrix", "gpio" ]
How to change the background color of RawTurtle
39,145,285
<p>I wrote a python script, which should open a Tkinter window with a canvas and let turtle draw in this canvas. Now I want to change the background color of the canvas, but it stays always white (default settings of <code>RawTurtle</code>?). Is there any possibility to draw on a background with another color?</p> <pre><code>from Tkinter import * import turtle root = Tk() root.overrideredirect(1) ccanvas = Canvas(root, width = 800, height = 480) ccanvas.pack() turtle = turtle.RawTurtle(ccanvas) turtle = turtle.bgcolor("black") mainloop() </code></pre> <p>If I try <code>turtle = turtle.bgcolor("black")</code> the error looks like this: <code>'RawTurtle' object has no attribute 'bgcolor'</code>.</p>
0
2016-08-25T12:25:42Z
39,146,635
<p>You can supply a <code>turtle.TurtleScreen</code> (provides a <code>bgcolor</code> method) to <code>turtle.RawTurtle</code> instead of directly using <code>Canvas</code> :</p> <pre><code>ccanvas = Canvas(root, width = 800, height = 480) turtle_screen = turtle.TurtleScreen(ccanvas) turtle_screen.bgcolor("black") ccanvas.pack() turtle = turtle.RawTurtle(turtle_screen) </code></pre>
0
2016-08-25T13:26:24Z
[ "python", "canvas", "tkinter", "background-color", "turtle-graphics" ]
Python error: "socket.error: [Errno 11] Resource temporarily unavailable" when sending image
39,145,357
<p>I want to make a program that accesses images from files, encodes them, and sends them to an server. Than the server is supposed to decode the image, and save it to file. I tested the image encoding itself, and it worked, so the problem lies in the server and client connection.</p> <p>Here is the server:</p> <pre><code>import socket import errno import base64 from PIL import Image import StringIO def connect(c): try: image = c.recv(8192) return image except IOError as e: if e.errno == errno.EWOULDBLOCK: connect(c) def Main(): host = '138.106.180.21' port = 12345 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((host, port)) s.listen(1) while True: c, addr = s.accept() c.setblocking(0) print "Connection from: " + str(addr) image = c.recv(8192)#connect(c) imgname = 'test.png' fh = open(imgname, "wb") if image == 'cusdom_image': with open('images.png', "rb") as imageFile: image = '' image = base64.b64encode(imageFile.read()) print image fh.write(image.decode('base64')) fh.close() if __name__ == '__main__': Main() </code></pre> <p>And here is the client:</p> <pre><code>import socket import base64 from PIL import Image import StringIO import os, sys ip = '138.106.180.21' port = 12345 print 'Add event executed' s = socket.socket() s.connect((ip, port)) image_path = '/home/gilgamesch/Bilder/Bildschirmfoto.png' print os.getcwd() olddir = os.getcwd() os.chdir('/') print os.getcwd() if image_path != '': with open(image_path, "rb") as imageFile: image_data = base64.b64encode(imageFile.read()) print 'open worked' else: image_data = 'cusdom_image' os.chdir(olddir) s.send(image_data) s.close() </code></pre> <p>And the error message is:</p> <pre><code>Traceback (most recent call last): File "imgserv.py", line 49, in &lt;module&gt; Main() File "imgserv.py", line 34, in Main image = c.recv(8192)#connect(c) socket.error: [Errno 11] Resource temporarily unavailable </code></pre>
1
2016-08-25T12:29:37Z
39,145,994
<p>In the server you are setting the remote socket (that returned by <code>accept()</code>) to non-blocking mode, which means that I/O on that socket will terminate immediately by an exception if there is no data to read.</p> <p>There will usually be a period of time between establishing the connection with the server and the image data being sent by the client. The server attempts to immediately read data from the client once the connection is accepted, however, there might not be any data to read yet, so <code>c.recv()</code> raises a <code>socket.error: [Errno 11] Resource temporarily unavailable</code> exception. Errno 11 corresponds to <code>EWOULDBLOCK</code>, so <code>recv()</code> aborted because there was no data ready to read.</p> <p>Your code does not seem to require non-blocking sockets because there is an <code>accept()</code> at the top of the while loop, and so only one connection can be handled at a time. You can just remove the call to <code>c.setblocking(0)</code> and this problem should go away.</p>
1
2016-08-25T12:56:49Z
[ "python", "image", "sockets" ]
Row operations within a group of a pandas dataframe
39,145,468
<p>I have a pandas dataframe and I need to perform various operations between rows that belong to the same group, e.g. find the difference between them. For example, I have the following:</p> <pre><code> var1 var2 1 7 1 10 1 15 2 3 2 9 2 5 </code></pre> <p>and I want to get the following:</p> <pre><code> var1 var2 var3 1 7 NaN 1 10 3 1 15 5 2 3 NaN 2 9 6 2 5 -4 </code></pre> <p>I understand I can loop over the different groups of var1, get the difference using the shift operator, and then append the results. I wonder if there is a better way to do it. Thanks for the help.</p>
1
2016-08-25T12:34:23Z
39,145,559
<p>You want to use <code>transform</code> on the <code>groupby</code> object to add a new column back to the original df:</p> <pre><code>In [58]: df['var3'] = df.groupby('var1')['var2'].transform(lambda x: x.diff()) df Out[58]: var1 var2 var3 0 1 7 NaN 1 1 10 3.0 2 1 15 5.0 3 2 3 NaN 4 2 9 6.0 5 2 5 -4.0 </code></pre> <p>So this groups on 'var1' and then calls a lambda on each group to calculate the difference and using <code>transform</code> will return a series with it's index aligned to the original df so you can add it back as a new column</p>
1
2016-08-25T12:38:36Z
[ "python", "pandas" ]
Handle json-string with array properly
39,145,636
<p>I would like to find a way to handle json - input that contains arrays in Python. What I have is the following:</p> <pre><code>import json def main(): jsonString = '{"matrix":[["1","2"],["3","4"]]}' jsonMatrix = json.loads(jsonString) Matrix = jsonMatrix["matrix"] term1 = Matrix[0][0] # yields: '1' expected: 1 term2 = Matrix[0][1] # yields: '2' expected: 2 result = term1 + term2 # yields: '12' expected: 3 return if __name__ == "__main__": main() </code></pre> <p>By now I have achieved to find "json.loads" to convert the json into a python object. However, the numbers are still represented as strings. Of course I could do one of the following conversions:</p> <pre><code>Matrix = map(int, Matrix[0]) term1 = Matrix[0] term2 = Matrix[1] </code></pre> <p>or</p> <pre><code>term1 = map(int, Matrix[0][0]) term2 = map(int, Matrix[0][1]) </code></pre> <p>However, I am looking for an easy way to convert the <strong>entire</strong> "Matrix"-object to int rather than just Matrix[0] or Matrix[0][0] for example. So I am looking for a correct version of the following:</p> <pre><code>Matrix = map(int, Matrix) term1 = Matrix[0][0] term2 = Matrix[0][1] result = term1 + term2 </code></pre> <p>I am aware that I could do this conversion using for loops, but I guess there is a better way with more efficient code?</p> <p>Thanks for your help!</p>
0
2016-08-25T12:41:51Z
39,145,706
<pre><code>import json def main(): jsonString = '{"matrix":[["1","2"],["3","4"]]}' jsonMatrix = json.loads(jsonString) # convert entire matrix to integers Matrix = [[int(v) for v in row] for row in jsonMatrix["matrix"]] term1 = Matrix[0][0] # yields: 1 term2 = Matrix[0][1] # yields: 2 result = term1 + term2 print('result: {}'.format(result)) # -&gt; result: 3 return if __name__ == "__main__": main() </code></pre>
0
2016-08-25T12:45:02Z
[ "python", "json" ]
Handle json-string with array properly
39,145,636
<p>I would like to find a way to handle json - input that contains arrays in Python. What I have is the following:</p> <pre><code>import json def main(): jsonString = '{"matrix":[["1","2"],["3","4"]]}' jsonMatrix = json.loads(jsonString) Matrix = jsonMatrix["matrix"] term1 = Matrix[0][0] # yields: '1' expected: 1 term2 = Matrix[0][1] # yields: '2' expected: 2 result = term1 + term2 # yields: '12' expected: 3 return if __name__ == "__main__": main() </code></pre> <p>By now I have achieved to find "json.loads" to convert the json into a python object. However, the numbers are still represented as strings. Of course I could do one of the following conversions:</p> <pre><code>Matrix = map(int, Matrix[0]) term1 = Matrix[0] term2 = Matrix[1] </code></pre> <p>or</p> <pre><code>term1 = map(int, Matrix[0][0]) term2 = map(int, Matrix[0][1]) </code></pre> <p>However, I am looking for an easy way to convert the <strong>entire</strong> "Matrix"-object to int rather than just Matrix[0] or Matrix[0][0] for example. So I am looking for a correct version of the following:</p> <pre><code>Matrix = map(int, Matrix) term1 = Matrix[0][0] term2 = Matrix[0][1] result = term1 + term2 </code></pre> <p>I am aware that I could do this conversion using for loops, but I guess there is a better way with more efficient code?</p> <p>Thanks for your help!</p>
0
2016-08-25T12:41:51Z
39,145,793
<p>This is pretty basic, sorry but you can convert the string into integers by any one of the following methods.</p> <pre><code>new=map(int,Matrix[0]) term1=new[0] term2=new[1] </code></pre> <p>Convert the strings into numbers and then use them</p> <pre><code>term1=int(Matrix[0][0]) term2=int(Matrix[0][1]) </code></pre> <p>You can also do the following:</p> <pre><code>j=[map(int, y) for y in Matrix] term1=j[0][0] term2=j[0][1] </code></pre> <p>I hope this helps.</p>
0
2016-08-25T12:49:22Z
[ "python", "json" ]
set time limitations for timer
39,145,662
<p>Is there are nicer way to write the code like this?</p> <pre><code># ugly piece of code seconds = 0 if seconds &lt; 0 else seconds seconds = 86399 if seconds &gt;= 86400 else seconds </code></pre> <p>I mean - I need to setup the strict possible range of seconds</p>
0
2016-08-25T12:42:48Z
39,145,711
<pre><code>seconds = max(0, min(86399, seconds)) </code></pre>
4
2016-08-25T12:45:44Z
[ "python", "time" ]
set time limitations for timer
39,145,662
<p>Is there are nicer way to write the code like this?</p> <pre><code># ugly piece of code seconds = 0 if seconds &lt; 0 else seconds seconds = 86399 if seconds &gt;= 86400 else seconds </code></pre> <p>I mean - I need to setup the strict possible range of seconds</p>
0
2016-08-25T12:42:48Z
39,145,873
<p>Maybe something like this:</p> <pre><code>def check(start, end, sec): return end if sec &gt; end else start if sec &lt; start else sec </code></pre>
0
2016-08-25T12:52:35Z
[ "python", "time" ]
Finding Missing Elements among a range of number lines
39,145,665
<p>Let's say I have a list of ranges (ie. <code>[[1,100][102, 200], etc]]</code>. I want to find the number of missing elements in the total range. I have a working algorithm below:</p> <pre><code>def missing(numranges): (minimum, maximum) = (min(map(lambda x: x[0], numranges)), max(map(lambda x: x[1], numranges))) (count, i) = (0, minimum) while i &lt; maximum: if any(j &lt;= i &lt;= k for j, k in numranges): count += 1 i += 1 return maximum - minimum - count </code></pre> <p>The problem is if you have say a number line that say is like <code>[[1, 10000], [10002, 20000]]</code>, then i goes over all 20,000 elements and it seems to me that this is very inefficient. I'm trying to find a way to make the algorithm better but I'm a bit stumped. </p> <p>Edit: Sorry, should have mentioned that the number ranges could overlap (ie. <code>[1, 10000], [1, 100001], [100003, 100005], etc]]</code></p>
-2
2016-08-25T12:43:01Z
39,145,818
<p>Here I am assuming based on your example that your list is in increasing order and your ranges will not overlap</p> <pre><code>&gt;&gt;&gt; l = [[1, 50] ,[55, 90], [95, 100]] &gt;&gt;&gt; sum([l[i+1][0]-m[1]-1 for i, m in enumerate(l[:-1])]) 8 </code></pre> <p><strong>Logic</strong>: I am subtracting index 0 of the sublist with index 1 of the previous sublist. It is most optimised way to achieve what you want.</p>
0
2016-08-25T12:50:21Z
[ "python", "python-2.7" ]
Finding Missing Elements among a range of number lines
39,145,665
<p>Let's say I have a list of ranges (ie. <code>[[1,100][102, 200], etc]]</code>. I want to find the number of missing elements in the total range. I have a working algorithm below:</p> <pre><code>def missing(numranges): (minimum, maximum) = (min(map(lambda x: x[0], numranges)), max(map(lambda x: x[1], numranges))) (count, i) = (0, minimum) while i &lt; maximum: if any(j &lt;= i &lt;= k for j, k in numranges): count += 1 i += 1 return maximum - minimum - count </code></pre> <p>The problem is if you have say a number line that say is like <code>[[1, 10000], [10002, 20000]]</code>, then i goes over all 20,000 elements and it seems to me that this is very inefficient. I'm trying to find a way to make the algorithm better but I'm a bit stumped. </p> <p>Edit: Sorry, should have mentioned that the number ranges could overlap (ie. <code>[1, 10000], [1, 100001], [100003, 100005], etc]]</code></p>
-2
2016-08-25T12:43:01Z
39,145,883
<p>You can do something like this,</p> <pre><code>In [22]: input_list = [range(1,100),range(102, 200)] In [23]: total_list = sum(input_list,[]) In [24]: master_total_list = range(min(total_list),max(total_list)+1) In [25]: [i for i in master_total_list if i not in total_list] Out[25]: [100, 101] </code></pre>
0
2016-08-25T12:52:51Z
[ "python", "python-2.7" ]
Finding Missing Elements among a range of number lines
39,145,665
<p>Let's say I have a list of ranges (ie. <code>[[1,100][102, 200], etc]]</code>. I want to find the number of missing elements in the total range. I have a working algorithm below:</p> <pre><code>def missing(numranges): (minimum, maximum) = (min(map(lambda x: x[0], numranges)), max(map(lambda x: x[1], numranges))) (count, i) = (0, minimum) while i &lt; maximum: if any(j &lt;= i &lt;= k for j, k in numranges): count += 1 i += 1 return maximum - minimum - count </code></pre> <p>The problem is if you have say a number line that say is like <code>[[1, 10000], [10002, 20000]]</code>, then i goes over all 20,000 elements and it seems to me that this is very inefficient. I'm trying to find a way to make the algorithm better but I'm a bit stumped. </p> <p>Edit: Sorry, should have mentioned that the number ranges could overlap (ie. <code>[1, 10000], [1, 100001], [100003, 100005], etc]]</code></p>
-2
2016-08-25T12:43:01Z
39,145,967
<p>Try sets to solve this:</p> <pre><code>test = set(range(1, 100 + 1) + range(102, 200 + 1)) missing = list(set(range(min(test), max(test))) - test) print (missing) </code></pre>
0
2016-08-25T12:55:42Z
[ "python", "python-2.7" ]
Finding Missing Elements among a range of number lines
39,145,665
<p>Let's say I have a list of ranges (ie. <code>[[1,100][102, 200], etc]]</code>. I want to find the number of missing elements in the total range. I have a working algorithm below:</p> <pre><code>def missing(numranges): (minimum, maximum) = (min(map(lambda x: x[0], numranges)), max(map(lambda x: x[1], numranges))) (count, i) = (0, minimum) while i &lt; maximum: if any(j &lt;= i &lt;= k for j, k in numranges): count += 1 i += 1 return maximum - minimum - count </code></pre> <p>The problem is if you have say a number line that say is like <code>[[1, 10000], [10002, 20000]]</code>, then i goes over all 20,000 elements and it seems to me that this is very inefficient. I'm trying to find a way to make the algorithm better but I'm a bit stumped. </p> <p>Edit: Sorry, should have mentioned that the number ranges could overlap (ie. <code>[1, 10000], [1, 100001], [100003, 100005], etc]]</code></p>
-2
2016-08-25T12:43:01Z
39,146,023
<p>See this code </p> <pre><code>l=[[1, 50], [55, 90], [95, 100]] res=[] for item in l : res.extend(range(item[0],item[1])) print [k for k in range(max(res)) if k not in res] </code></pre> <p>Output :</p> <pre><code>[0, 50, 51, 52, 53, 54, 90, 91, 92, 93, 94] </code></pre>
0
2016-08-25T12:58:14Z
[ "python", "python-2.7" ]
numpy ND array: take index'ed elements along a certain axis (ND choose)
39,145,736
<p>I obtain indices along a certain axis. For example like this with 2D and axis=-1 :</p> <pre><code>&gt;&gt;&gt; axis = -1 &gt;&gt;&gt; a = rand(5, 3) - 0.5; a array([[ 0.49970414, -0.14251437, 0.2881351 ], [ 0.3280437 , 0.33766112, 0.4263927 ], [ 0.37377502, 0.05392274, -0.4647834 ], [-0.09461463, -0.25347861, -0.29381079], [-0.09642799, 0.15729681, 0.06048399]]) &gt;&gt;&gt; axisinds = a.__abs__().argmax(axis); axisinds array([0, 2, 2, 2, 1]) </code></pre> <p>Now how can I reduce the array by 1 dimension by taking the indexed elements along that axis?</p> <p>For 2D and axis=-1 it could be done like this (in order to get the absolute max'es of each row the example array):</p> <pre><code>&gt;&gt;&gt; a[arange(len(axisinds)), axisinds] array([ 0.49970414, 0.4263927 , -0.4647834 , -0.29381079, 0.15729681]) </code></pre> <p>But this is very special and limited to 1 or 0 result dimensions. How for any <code>ndim</code> and <code>axis</code> ?</p>
0
2016-08-25T12:46:34Z
39,147,174
<p>Now I found a simple solution myself:</p> <pre><code>def choose_axis(inds, a, axis=-1): return np.choose(inds, np.rollaxis(a, axis)) &gt;&gt;&gt; choose_axis(axisinds, a, -1) array([ 0.49970414, 0.4263927 , -0.4647834 , -0.29381079, 0.15729681]) </code></pre> <p><strong>Edit:</strong> However this approach turned out to be limited to max 31 elements in the axis direction (32bit?) - because of the (undocumented) limitation of <code>np.choose</code>. In many cases this is ok. </p> <p>Yet this is an</p> <h1>Unlimited method:</h1> <pre><code>def choose_axis(inds, a, axis=-1): # handles any number &amp; size of dimensions, and any axis if (axis + 1) % a.ndim: # move axis to last dim a = np.moveaxis(a, axis, -1) # = np.rollaxis(a, axis, a.ndim) shape = a.shape a = a.reshape(-1, shape[-1]) # 2D a = a[np.arange(inds.size), inds.ravel()] # effective reduction return a.reshape(shape[:-1]) </code></pre> <p>Thus an ND absolute min example can be done like:</p> <pre><code>def absminND(a, axis=-1): inds = a.__abs__().argmin(axis) if axis is None: return a.ravel()[inds] return choose_axis(inds, a) </code></pre>
0
2016-08-25T13:50:35Z
[ "python", "arrays", "numpy" ]
masking a series with a boolean array
39,145,795
<p>This has given me a lot of trouble, and I am perplexed by the incompatibility of numpy arrays with pandas series. When I create a boolean array using a series, for instance</p> <pre><code>x = np.array([1,2,3,4,5,6,7]) y = pd.Series([1,2,3,4,5,6,7]) delta = np.percentile(x, 50) deltamask = x- y &gt; delta </code></pre> <p>delta mask creates a boolean pandas series.</p> <p>However, if you do</p> <pre><code>x[deltamask] y[deltamask] </code></pre> <p>You find that the array ignores completely the mask. No error is raised, but you end up with two objects of different length. This means that an operation like</p> <pre><code>x[deltamask]*y[deltamask] </code></pre> <p>results in an error:</p> <pre><code>print type(x-y) print type(x[deltamask]), len(x[deltamask]) print type(y[deltamask]), len(y[deltamask]) </code></pre> <p>Even more perplexing, I noticed that the operator &lt; is treated differently. For instance</p> <pre><code>print type(2*x &lt; x*y) print type(2 &lt; x*y) </code></pre> <p>will give you a pd.series and np.array respectively. </p> <p>Also,</p> <pre><code>5 &lt; x - y </code></pre> <p>results in a series, so it seems that the series takes precedence, whereas the boolean elements of a series mask are promoted to integers when passed to a numpy array and result in a sliced array.</p> <p>What is the reason for this?</p>
6
2016-08-25T12:49:25Z
39,168,021
<p><strong>Fancy Indexing</strong></p> <p>As numpy currently stands, fancy indexing in numpy works as follows:</p> <ol> <li><p>If the thing between brackets is a <code>tuple</code> (whether with explicit parens or not), the elements of the tuple are indices for different dimensions of <code>x</code>. For example, both <code>x[(True, True)]</code> and <code>x[True, True]</code> will raise <code>IndexError: too many indices for array</code> in this case because <code>x</code> is 1D. However, before the exception happens, a telling warning will be raised too: <code>VisibleDeprecationWarning: using a boolean instead of an integer will result in an error in the future</code>.</p></li> <li><p>If the thing between brackets is <strong>exactly</strong> an <code>ndarray</code>, not a subclass or other array-like, and has a boolean type, it will be applied as a mask. This is why <code>x[deltamask.values]</code> gives the expected result (empty array since <code>deltamask</code> is all <code>False</code>.</p></li> <li><p>If the thing between brackets is any array-like, whether a subclass like <code>Series</code> or just a <code>list</code>, or something else, it is converted to an <code>np.intp</code> array (if possible) and used as an integer index. So <code>x[deltamask]</code> yeilds something equivalent to <code>x[[False] * 7]</code> or just <code>x[[0] * 7]</code>. In this case, <code>len(deltamask)==7</code> and <code>x[0]==1</code> so the result is <code>[1, 1, 1, 1, 1, 1, 1]</code>.</p></li> </ol> <p>This behavior is counterintuitive, and the <code>FutureWarning: in the future, boolean array-likes will be handled as a boolean array index</code> it generates indicates that a fix is in the works. I will update this answer as I find out about/make any changes to numpy.</p> <p>This information can be found in Sebastian Berg's response to my initial query on Numpy discussion <a href="https://mail.scipy.org/pipermail/numpy-discussion/2016-August/075908.html" rel="nofollow">here</a>.</p> <p><strong>Relational Operators</strong></p> <p>Now let's address the second part of your question about how the comparison works. Relational operators (<code>&lt;</code>, <code>&gt;</code>, <code>&lt;=</code>, <code>&gt;=</code>) work by calling the corresponding method on one of the objects being compared. For <code>&lt;</code> this is <code>__lt__</code>. However, instead of just calling <code>x.__lt__(y)</code> for the expression <code>x &lt; y</code>, Python actually checks the types of the objects being compared. If <code>y</code> is a subtype of <code>x</code> that implements the comparison, then Python prefers to call <code>y.__gt__(x)</code> instead, regardless of how you wrote the original comparison. The only way that <code>x.__lt__(y)</code> will get called if <code>y</code> is a subclass of <code>x</code> is if <code>y.__gt__(x)</code> returns <code>NotImplemented</code> to indicate that the comparison is not supported in that direction.</p> <p>A similar thing happens when you do <code>5 &lt; x - y</code>. While <code>ndarray</code> is not a subclass of <code>int</code>, the comparison <code>int.__lt__(ndarray)</code> returns <code>NotImplemented</code>, so Python actually ends up calling <code>(x - y).__gt__(5)</code>, which is of course defined and works just fine.</p> <p>A much more succinct explanation of all this can be found in the <a href="https://docs.python.org/3/reference/datamodel.html#object.__lt__" rel="nofollow">Python docs</a>.</p>
1
2016-08-26T13:53:58Z
[ "python", "pandas", "numpy" ]
Append the data to existing json file
39,146,072
<p>I have an existing JSON file and trying to add string into file. But as soon as I write a JSON file the new line characters do disappear in the JSON file and format gets changed.</p> <p>Below is the code:</p> <pre><code>#!/usr/bin/python import json userinput = raw_input('Enter the name of a file a you want to read: ') with open(userinput) as json_data: s = json_data.read() data = json.loads(s) print data['classes'] json_data.close() class_add = raw_input('Enter the name of a class a you want to add: ') if class_add in data['classes']: print "Class %s already exists, doing nothing." % class_add else: data['classes'].append(class_add) print json.dumps(data) print data['classes'] with open(userinput, 'w') as json_data: json_data.write(json.dumps(data)) json_data.close() </code></pre> <hr> <p>One more import thing here is, that the formatting of the JSON file. So by default we will be having the file in the below formatting.</p> <pre><code># cat test.json { "selinux_mode": "enforcing", "cis_manages_auditd_service": true, "classes": [ "basic", "admin", "lvm"] } # </code></pre> <p>But once we add the class it becomes the following.</p> <pre><code># cat test.json {"cis_manages_auditd_service": true, "classes": [ "basic", "admin", "lvm"], "selinux_mode": "enforcing"} </code></pre> <p>Is there any way that I can keep the JSON whitespace and new line character as it is without changing anything.</p>
0
2016-08-25T13:01:01Z
39,146,315
<p>JSON doesn't need a particular layout, but for slightly less bad human readability you can supply <code>indent=2</code></p> <pre><code>import sys import json userinput = raw_input('Enter the name of a file a you want to read: ') with open(userinput) as json_data: data = json.load(json_data) print(data['classes']) class_add = raw_input('Enter the name of a class a you want to add: ') if class_add in data['classes']: print("Class {} already exists, doing nothing.".format(class_add)) else: data['classes'].append(class_add) json.dump(data, sys.stdout, indent=2) print(data['classes']) with open(userinput, 'w') as json_data: json.dump(data, json_data, indent=2) </code></pre> <p>Please note that if you are using the <code>with</code> statement to open a file, you should not close it explicitly (that is done at the end of the block, whether there is an exception or not). </p> <p>If you are writing to a file, instead of processing the JSON as string, you should also refrain from using <code>json.dumps(data)</code> and use <code>json.dump(data, file_pointer)</code> instead. The same holds for <code>json.loads()</code> and <code>json.load()</code>.</p>
0
2016-08-25T13:11:46Z
[ "python", "json", "file-io" ]
Append the data to existing json file
39,146,072
<p>I have an existing JSON file and trying to add string into file. But as soon as I write a JSON file the new line characters do disappear in the JSON file and format gets changed.</p> <p>Below is the code:</p> <pre><code>#!/usr/bin/python import json userinput = raw_input('Enter the name of a file a you want to read: ') with open(userinput) as json_data: s = json_data.read() data = json.loads(s) print data['classes'] json_data.close() class_add = raw_input('Enter the name of a class a you want to add: ') if class_add in data['classes']: print "Class %s already exists, doing nothing." % class_add else: data['classes'].append(class_add) print json.dumps(data) print data['classes'] with open(userinput, 'w') as json_data: json_data.write(json.dumps(data)) json_data.close() </code></pre> <hr> <p>One more import thing here is, that the formatting of the JSON file. So by default we will be having the file in the below formatting.</p> <pre><code># cat test.json { "selinux_mode": "enforcing", "cis_manages_auditd_service": true, "classes": [ "basic", "admin", "lvm"] } # </code></pre> <p>But once we add the class it becomes the following.</p> <pre><code># cat test.json {"cis_manages_auditd_service": true, "classes": [ "basic", "admin", "lvm"], "selinux_mode": "enforcing"} </code></pre> <p>Is there any way that I can keep the JSON whitespace and new line character as it is without changing anything.</p>
0
2016-08-25T13:01:01Z
39,146,317
<p>You can set the <code>indent</code> argument to function <a href="http://fs22.clicknupload.net:182/d/j25yr2vjlvyd7tr7wha4fmcqat5tjxz36erbscvht55bn7tqnpldh3gdc3hrjyvypfd4voij/m.S02E08.480p.u766145.Rapidmoviez.com.rar" rel="nofollow"><code>json.dumps()</code></a> to an integer representing the number of spaces to indent.</p> <p>This will still modify the formatting of the output to something like this:</p> <pre><code>import json s = '''{ "selinux_mode": "enforcing", "cis_manages_auditd_service": true, "classes": [ "basic", "admin", "lvm"] }''' data = json.loads(s) &gt;&gt;&gt; print(json.dumps(data)) {"cis_manages_auditd_service": true, "classes": ["basic", "admin", "lvm"], "selinux_mode": "enforcing"} &gt;&gt;&gt; print(json.dumps(data, indent=4)) { "cis_manages_auditd_service": true, "classes": [ "basic", "admin", "lvm" ], "selinux_mode": "enforcing" } </code></pre> <p>The difference between the original and the updated version is that the <code>classes</code> list is now displayed across multiple lines.</p>
0
2016-08-25T13:11:53Z
[ "python", "json", "file-io" ]
Python pandas grouping issue
39,146,135
<p>Am i doing something wrong here or is there a bug here.</p> <p>df2 is a copy/slice of df1. But the minute i attempt to group it by column A and get the last value of the grouping from column C, creating a new column 'NewMisteryColumn', df1 also gets a new 'NewMisteryColumn'</p> <p>The end result in df2 is correct. I also have different ways on how i can do this, i am not looking for a different method, just wondering on whether i have stumbled upon a bug.</p> <p>My question is, isn't df1 separate from df2, why is df1 also getting the same column?</p> <pre><code>df1 = pd.DataFrame({'A':['some value','some value', 'another value'], 'B':['rthyuyu','truyruyru', '56564'], 'C':['tryrhyu','tryhyteru', '54676']}) df2 = df1 df2['NewMisteryColumn'] = df2.groupby(['A'])['C'].tail(1) </code></pre>
0
2016-08-25T13:03:29Z
39,146,912
<p>The problem is that df2 is just another reference to the DataFrame.</p> <pre><code>df2 = df1 df3 = df1.copy() df1 is df2 # True df1 is df3 # False </code></pre> <p>You can also verify the ids...</p> <pre><code>id(df1) id(df2) # Same as id(df1) id(df3) # Different! </code></pre>
1
2016-08-25T13:38:34Z
[ "python", "pandas", "dataframe", "grouping" ]
Pass just one field via AJAX with Flask
39,146,220
<p>I have a VERY simple HTML form with just one <code>&lt;input type='text'&gt;</code> field, an email address, that I need to pass back to a Python script via AJAX. I can't seem to receive the value on the other end. (And can all the JSON encoding/decoding be avoided, since there's just one field?)</p> <p>Here's the code:</p> <pre><code>from flask import Flask, render_template, request, json import logging app = Flask(__name__) @app.route('/') def hello(): return render_template('index.htm') @app.route('/start', methods=['POST']) def start(): # next line outputs "email=myemail@gmail.com" app.logger.debug(request.json); email = request.json['email']; # next line ALSO outputs "email=myemail@gmail.com" app.logger.debug(email); return json.dumps({ 'status': 'OK', 'email': email }) if __name__ == "__main__": app.run() </code></pre> <p>And the Javascript that sends the AJAX from the HTML side--</p> <pre><code>$( "form" ).on( "submit", function( event ) { event.preventDefault(); d = "email=" + $('#email').val(); // this works correctly // next line outputs 'sending data: myemail@gmail.com' console.log("sending data: "+d); $.ajax({ type: "POST", url: "{{ url_for('start') }}", data: JSON.stringify(d), dataType: 'JSON', contentType: 'application/json;charset=UTF-8', success: function(result) { console.log("SUCCESS: "); // next line outputs 'Object {email: "email=myemail@gmail.com", status: "OK"}' console.log(result); } }); }); </code></pre>
0
2016-08-25T13:07:03Z
39,146,496
<p>JSON.stringify is used to turn an object into a JSON-formatted string, but you don't have an object, just a string. Try this: </p> <pre><code>var d = { email: $('#email').val() }; </code></pre> <p><code>JSON.stringify(d)</code> will now turn that into a JSON-formatted string:</p> <p><code>{email: "myemail@gmail.com"}</code> which can be parsed by flask.</p> <hr> <p>To do this without JSON:</p> <pre><code>var d = { email: $('#email').val() }; ... // AJAX data: d, success: ... </code></pre> <p>This will turn <code>{email: "myemail@gmail.com"}</code> into <code>email=mymail@gmail.com</code> and send that as body of the POST request. In Flask, use <code>request.form['email']</code>.</p>
1
2016-08-25T13:20:27Z
[ "javascript", "jquery", "python", "json", "ajax" ]
rest framework 'user_code' is an invalid keyword argument for this function Request Method: POST Request
39,146,292
<p>I`m trying to create a new BCodes on save BDetail in the same endpoint but when i test, throw framework 'user_code' is an invalid keyword argument for this function Request Method: POST Request.</p> <p>BCodes model</p> <pre><code>class BCodes(models.Model): user_code = models.IntegerField() building_code = models.CharField(max_length=10) oldkey = models.CharField(max_length=32, blank=True, null=True) date_added = models.IntegerField(blank=True, null=True) is_bm = models.IntegerField(blank=True, null=True) bm_src = models.IntegerField(blank=True, null=True) agents = models.ForeignKey(Agents, models.DO_NOTHING, blank=True, null=True) clients = models.ForeignKey('Clients', models.DO_NOTHING, blank=True, null=True) free_property = models.ForeignKey('FreePublishers', models.DO_NOTHING) approve_free_bm = models.IntegerField() class Meta: managed = False db_table = 'b_codes' unique_together = (('user_code', 'building_code'),) </code></pre> <p>BDetail model</p> <pre><code>class BDetail(models.Model): kind_building = models.ForeignKey('Typebuilding', models.DO_NOTHING, db_column='kind_building') kind_offer = models.ForeignKey('Typeoffer', models.DO_NOTHING, db_column='kind_offer') country = models.ForeignKey('Countries', models.DO_NOTHING, db_column='country') city = models.ForeignKey('Cities', models.DO_NOTHING, db_column='city') sector = models.ForeignKey('Sectors', models.DO_NOTHING, db_column='sector') zone = models.ForeignKey('ZonesStandard', models.DO_NOTHING, db_column='zone') address = models.CharField(max_length=100, blank=True, null=True) show_address = models.IntegerField() show_stview = models.IntegerField(blank=True, null=True) lat = models.FloatField(blank=True, null=True) lng = models.FloatField(blank=True, null=True) area_m = models.FloatField(blank=True, null=True) area_um = models.ForeignKey(AreaMetters, models.DO_NOTHING, db_column='area_um', blank=True, null=True) area_built = models.FloatField(blank=True, null=True) area_private = models.FloatField(blank=True, null=True) area_m_front = models.FloatField(blank=True, null=True) area_um_front = models.ForeignKey(AreaMetters, models.DO_NOTHING, db_column='area_um_front', blank=True, null=True) area_m_back = models.FloatField(blank=True, null=True) area_um_back = models.ForeignKey(AreaMetters, models.DO_NOTHING, db_column='area_um_back', blank=True, null=True) area_proximity = models.IntegerField(blank=True, null=True) remade = models.IntegerField(blank=True, null=True) remade_m = models.IntegerField(blank=True, null=True) remade_y = models.IntegerField(blank=True, null=True) is_moblied = models.IntegerField(blank=True, null=True) rooms = models.IntegerField(blank=True, null=True) bathrooms = models.IntegerField(blank=True, null=True) persons = models.IntegerField(blank=True, null=True) garages = models.IntegerField(blank=True, null=True) deposit = models.IntegerField(blank=True, null=True) antiquity = models.ForeignKey('OptionsBuildAntiquity', models.DO_NOTHING, db_column='antiquity', blank=True, null=True) stratum = models.CharField(max_length=50, blank=True, null=True) level = models.IntegerField(blank=True, null=True) title = models.CharField(max_length=60, blank=True, null=True) comments = models.TextField(blank=True, null=True) tags = models.TextField(blank=True, null=True) permalink = models.CharField(max_length=100, blank=True, null=True) catchment = models.IntegerField() date_created = models.IntegerField(blank=True, null=True) date_expire = models.IntegerField(blank=True, null=True) date_lastmodify = models.IntegerField(blank=True, null=True) url360deg = models.CharField(max_length=200, blank=True, null=True) reference = models.CharField(max_length=10, blank=True, null=True) expire = models.IntegerField(blank=True, null=True) is_made = models.IntegerField() is_suspended = models.IntegerField() suspended_date = models.IntegerField(blank=True, null=True) visits = models.IntegerField(blank=True, null=True) b_codes = models.ForeignKey(BCodes, models.DO_NOTHING, unique=True) zoomlevel = models.IntegerField(db_column='zoomLevel', blank=True, null=True) # Field name made lowercase. radius = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'b_detail' </code></pre> <p>BCodes serializer</p> <pre><code>class BCodesSerializer(serializers.ModelSerializer): class Meta: model = BCodes extra_kwargs = { 'building_code': {'read_only': True}, } def create(self, validated_data): code_data = validated_data.pop('building_code') return BCodes.objects.create(building_code='014', **code_data) </code></pre> <p>BDetail serializer</p> <pre><code>bdetailFields = ( 'id', 'lat', 'lng', 'rooms', 'title', 'comments', 'area_m', 'area_um', 'area_built', 'area_private', 'area_m_front', 'area_um_front', 'area_m_back', 'area_um_back', 'area_proximity', 'rooms', 'bathrooms', 'persons', 'garages', 'deposit', 'antiquity', 'stratum', 'level', 'permalink', 'catchment', 'date_created', 'date_expire', 'date_lastmodify', 'reference', 'expire', 'is_made', 'is_suspended', 'suspended_date', 'visits', 'b_codes', 'radius', 'zoomlevel', 'sector', 'country', 'city', 'zone', 'kind_building', 'kind_offer' ) class BDetailSerializerSimple(serializers.ModelSerializer): area_um = serializers.FloatField() area_um_front = serializers.FloatField() area_um_back = serializers.FloatField() antiquity = serializers.IntegerField() b_codes = BCodesSerializer() kind_building = serializers.IntegerField() kind_offer = serializers.IntegerField() country = serializers.IntegerField() city = serializers.IntegerField() sector = serializers.IntegerField() zone = serializers.IntegerField() class Meta: model = BDetail fields = bdetailFields def create(self, validated_data): code = BCodes.objects.create(**validated_data['b_codes']) detail_data = validated_data.pop('b_codes') detail = BDetail.objects.create(b_codes=code, **detail_data) return detail </code></pre> <p>ModelView</p> <pre><code>class BDetailList(viewsets.ModelViewSet): queryset = BDetail.objects.all() def get_object(self): queryset = self.get_queryset() obj = get_object_or_404( queryset, pk=self.kwargs['pk'], ) return obj def get_serializer_class(self): if self.action == 'retrive' or self.action == 'list': return BDetailSerializer if ( self.action == 'create' or self.action == 'update' or self.action == 'destroy' or self.action == 'partial_update' ): return BDetailSerializerSimple </code></pre> <h1>Traceback:</h1> <pre><code>File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/viewsets.py" in view 87. return self.dispatch(request, *args, **kwargs) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 474. response = self.handle_exception(exc) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/views.py" in handle_exception 434. self.raise_uncaught_exception(exc) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/views.py" in dispatch 471. response = handler(request, *args, **kwargs) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/mixins.py" in create 21. self.perform_create(serializer) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/mixins.py" in perform_create 26. serializer.save() File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/rest_framework/serializers.py" in save 192. self.instance = self.create(validated_data) File "./bdetail/serializers.py" in create 113. detail = BDetail.objects.create(b_codes=code, **detail_data) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/db/models/query.py" in create 397. obj = self.model(**kwargs) File "/var/www/verinmuebles/current/Env/api/local/lib/python2.7/site-packages/django/db/models/base.py" in __init__ 555. raise TypeError("'%s' is an invalid keyword argument for this function" % list(kwargs)[0]) Exception Type: TypeError at /v1/propiedades/ Exception Value: 'user_code' is an invalid keyword argument for this function Request information: USER: admin GET: No GET data POST: No POST data FILES: No FILES data COOKIES: tabstyle = 'raw-tab' vi_new_mg = '1' __zlcmid = 'cHfnfGvHfuVXUV' vi_session = 'io2rfnhjhnb6o5mphggrpckhj5' sessionid = 'qpmhbbkm7yzgf4lwsfa5p0mxl8kq1871' vi_login_id = 'd91b6fecb0125ef0bb7172b8ced60ced' vi_login_email = '2c5b1b493b4ed9e648694cf64a1e073a' csrftoken = 'HR1ec1Miobf2c1X7krU82vLEb7Pk1LZtPXQrprRdLzvQrrzfWD2vQOyI5hb3NSyo' META: CONTENT_LENGTH = '481' CONTENT_TYPE = 'application/json' CSRF_COOKIE = 'HR1ec1Miobf2c1X7krU82vLEb7Pk1LZtPXQrprRdLzvQrrzfWD2vQOyI5hb3NSyo' DOCUMENT_ROOT = '/etc/nginx/html' HTTP_ACCEPT = '*/*' HTTP_ACCEPT_ENCODING = 'gzip, deflate' HTTP_ACCEPT_LANGUAGE = 'es,en;q=0.8' HTTP_CACHE_CONTROL = 'no-cache' HTTP_CONNECTION = 'keep-alive' HTTP_CONTENT_LENGTH = '481' HTTP_CONTENT_TYPE = 'application/json' HTTP_COOKIE = 'vi_login_email=2c5b1b493b4ed9e648694cf64a1e073a; vi_new_mg=1; vi_login_id=d91b6fecb0125ef0bb7172b8ced60ced; vi_session=io2rfnhjhnb6o5mphggrpckhj5; sessionid=qpmhbbkm7yzgf4lwsfa5p0mxl8kq1871; tabstyle=raw-tab; __zlcmid=cHfnfGvHfuVXUV; csrftoken=HR1ec1Miobf2c1X7krU82vLEb7Pk1LZtPXQrprRdLzvQrrzfWD2vQOyI5hb3NSyo' HTTP_DNT = '1' HTTP_HOST = 'apiix.verinmuebles.dev' HTTP_ORIGIN = 'chrome-extension://aicmkgpgakddgnaphhhpliifpcfhicfo' HTTP_POSTMAN_TOKEN = 'f5bb5e63-0e7d-f5c7-e2c2-10e495451f7d' HTTP_USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36' HTTP_X_CSRFTOKEN = 'HR1ec1Miobf2c1X7krU82vLEb7Pk1LZtPXQrprRdLzvQrrzfWD2vQOyI5hb3NSyo' PATH_INFO = u'/v1/propiedades/' QUERY_STRING = '' REMOTE_ADDR = '192.168.56.1' REMOTE_PORT = '50090' REQUEST_METHOD = 'POST' REQUEST_SCHEME = 'http' REQUEST_URI = '/v1/propiedades/' SCRIPT_NAME = u'' SERVER_NAME = 'apiix.verinmuebles.dev' SERVER_PORT = '80' SERVER_PROTOCOL = 'HTTP/1.1' uwsgi.node = 'verinmuebles' uwsgi.version = '2.0.13.1' wsgi.errors = &lt;open file 'wsgi_errors', mode 'w' at 0x7f6a392884b0&gt; wsgi.file_wrapper = '' wsgi.input = &lt;uwsgi._Input object at 0x7f6a392c01c8&gt; wsgi.multiprocess = True wsgi.multithread = False wsgi.run_once = False wsgi.url_scheme = 'http' wsgi.version = Settings: Using settings module api.settings ABSOLUTE_URL_OVERRIDES = {} ADMINS = [] ALLOWED_HOSTS = ['*'] APPEND_SLASH = True AUTHENTICATION_BACKENDS = [u'django.contrib.auth.backends.ModelBackend'] AUTH_PASSWORD_VALIDATORS = u'********************' AUTH_USER_MODEL = u'auth.User' BASE_DIR = '/var/www/verinmuebles/current/api' CACHES = {u'default': {u'BACKEND': u'django.core.cache.backends.locmem.LocMemCache'}} CACHE_MIDDLEWARE_ALIAS = u'default' CACHE_MIDDLEWARE_KEY_PREFIX = u'********************' CACHE_MIDDLEWARE_SECONDS = 600 CSRF_COOKIE_AGE = 31449600 CSRF_COOKIE_DOMAIN = None CSRF_COOKIE_HTTPONLY = False CSRF_COOKIE_NAME = u'csrftoken' CSRF_COOKIE_PATH = u'/' CSRF_COOKIE_SECURE = False CSRF_FAILURE_VIEW = u'django.views.csrf.csrf_failure' CSRF_HEADER_NAME = u'HTTP_X_CSRFTOKEN' CSRF_TRUSTED_ORIGINS = [] DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql', 'AUTOCOMMIT': True, 'ATOMIC_REQUESTS': False, 'NAME': 'discover_arkweb', 'CONN_MAX_AGE': 0, 'TIME_ZONE': None, 'PORT': '3306', 'HOST': 'localhost', 'USER': 'discover_ark', 'TEST': {'COLLATION': None, 'CHARSET': None, 'NAME': None, 'MIRROR': None}, 'PASSWORD': u'********************', 'OPTIONS': {}}} DATABASE_ROUTERS = [] DATA_UPLOAD_MAX_MEMORY_SIZE = 2621440 DATA_UPLOAD_MAX_NUMBER_FIELDS = 1000 DATETIME_FORMAT = u'N j, Y, P' DATETIME_INPUT_FORMATS = [u'%Y-%m-%d %H:%M:%S', u'%Y-%m-%d %H:%M:%S.%f', u'%Y-%m-%d %H:%M', u'%Y-%m-%d', u'%m/%d/%Y %H:%M:%S', u'%m/%d/%Y %H:%M:%S.%f', u'%m/%d/%Y %H:%M', u'%m/%d/%Y', u'%m/%d/%y %H:%M:%S', u'%m/%d/%y %H:%M:%S.%f', u'%m/%d/%y %H:%M', u'%m/%d/%y'] DATE_FORMAT = u'N j, Y' DATE_INPUT_FORMATS = [u'%Y-%m-%d', u'%m/%d/%Y', u'%m/%d/%y', u'%b %d %Y', u'%b %d, %Y', u'%d %b %Y', u'%d %b, %Y', u'%B %d %Y', u'%B %d, %Y', u'%d %B %Y', u'%d %B, %Y'] DEBUG = True DEBUG_PROPAGATE_EXCEPTIONS = False DECIMAL_SEPARATOR = u'.' DEFAULT_CHARSET = u'utf-8' DEFAULT_CONTENT_TYPE = u'text/html' DEFAULT_EXCEPTION_REPORTER_FILTER = u'django.views.debug.SafeExceptionReporterFilter' DEFAULT_FILE_STORAGE = u'django.core.files.storage.FileSystemStorage' DEFAULT_FROM_EMAIL = u'webmaster@localhost' DEFAULT_INDEX_TABLESPACE = u'' DEFAULT_TABLESPACE = u'' DISALLOWED_USER_AGENTS = [] EMAIL_BACKEND = u'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = u'localhost' EMAIL_HOST_PASSWORD = u'********************' EMAIL_HOST_USER = u'' EMAIL_PORT = 25 EMAIL_SSL_CERTFILE = None EMAIL_SSL_KEYFILE = u'********************' EMAIL_SUBJECT_PREFIX = u'[Django] ' EMAIL_TIMEOUT = None EMAIL_USE_SSL = False EMAIL_USE_TLS = False FILE_CHARSET = u'utf-8' FILE_UPLOAD_DIRECTORY_PERMISSIONS = None FILE_UPLOAD_HANDLERS = [u'django.core.files.uploadhandler.MemoryFileUploadHandler', u'django.core.files.uploadhandler.TemporaryFileUploadHandler'] FILE_UPLOAD_MAX_MEMORY_SIZE = 2621440 FILE_UPLOAD_PERMISSIONS = None FILE_UPLOAD_TEMP_DIR = None FIRST_DAY_OF_WEEK = 0 FIXTURE_DIRS = [] FORCE_SCRIPT_NAME = None FORMAT_MODULE_PATH = None IGNORABLE_404_URLS = [] INSTALLED_APPS = ['bdetail.apps.BdetailConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework'] INTERNAL_IPS = [] LANGUAGES = [(u'af', u'Afrikaans'), (u'ar', u'Arabic'), (u'ast', u'Asturian'), (u'az', u'Azerbaijani'), (u'bg', u'Bulgarian'), (u'be', u'Belarusian'), (u'bn', u'Bengali'), (u'br', u'Breton'), (u'bs', u'Bosnian'), (u'ca', u'Catalan'), (u'cs', u'Czech'), (u'cy', u'Welsh'), (u'da', u'Danish'), (u'de', u'German'), (u'dsb', u'Lower Sorbian'), (u'el', u'Greek'), (u'en', u'English'), (u'en-au', u'Australian English'), (u'en-gb', u'British English'), (u'eo', u'Esperanto'), (u'es', u'Spanish'), (u'es-ar', u'Argentinian Spanish'), (u'es-co', u'Colombian Spanish'), (u'es-mx', u'Mexican Spanish'), (u'es-ni', u'Nicaraguan Spanish'), (u'es-ve', u'Venezuelan Spanish'), (u'et', u'Estonian'), (u'eu', u'Basque'), (u'fa', u'Persian'), (u'fi', u'Finnish'), (u'fr', u'French'), (u'fy', u'Frisian'), (u'ga', u'Irish'), (u'gd', u'Scottish Gaelic'), (u'gl', u'Galician'), (u'he', u'Hebrew'), (u'hi', u'Hindi'), (u'hr', u'Croatian'), (u'hsb', u'Upper Sorbian'), (u'hu', u'Hungarian'), (u'ia', u'Interlingua'), (u'id', u'Indonesian'), (u'io', u'Ido'), (u'is', u'Icelandic'), (u'it', u'Italian'), (u'ja', u'Japanese'), (u'ka', u'Georgian'), (u'kk', u'Kazakh'), (u'km', u'Khmer'), (u'kn', u'Kannada'), (u'ko', u'Korean'), (u'lb', u'Luxembourgish'), (u'lt', u'Lithuanian'), (u'lv', u'Latvian'), (u'mk', u'Macedonian'), (u'ml', u'Malayalam'), (u'mn', u'Mongolian'), (u'mr', u'Marathi'), (u'my', u'Burmese'), (u'nb', u'Norwegian Bokm\xe5l'), (u'ne', u'Nepali'), (u'nl', u'Dutch'), (u'nn', u'Norwegian Nynorsk'), (u'os', u'Ossetic'), (u'pa', u'Punjabi'), (u'pl', u'Polish'), (u'pt', u'Portuguese'), (u'pt-br', u'Brazilian Portuguese'), (u'ro', u'Romanian'), (u'ru', u'Russian'), (u'sk', u'Slovak'), (u'sl', u'Slovenian'), (u'sq', u'Albanian'), (u'sr', u'Serbian'), (u'sr-latn', u'Serbian Latin'), (u'sv', u'Swedish'), (u'sw', u'Swahili'), (u'ta', u'Tamil'), (u'te', u'Telugu'), (u'th', u'Thai'), (u'tr', u'Turkish'), (u'tt', u'Tatar'), (u'udm', u'Udmurt'), (u'uk', u'Ukrainian'), (u'ur', u'Urdu'), (u'vi', u'Vietnamese'), (u'zh-hans', u'Simplified Chinese'), (u'zh-hant', u'Traditional Chinese')] LANGUAGES_BIDI = [u'he', u'ar', u'fa', u'ur'] LANGUAGE_CODE = 'en-us' LANGUAGE_COOKIE_AGE = None LANGUAGE_COOKIE_DOMAIN = None LANGUAGE_COOKIE_NAME = u'django_language' LANGUAGE_COOKIE_PATH = u'/' LOCALE_PATHS = [] LOGGING = {} LOGGING_CONFIG = u'logging.config.dictConfig' LOGIN_REDIRECT_URL = u'/accounts/profile/' LOGIN_URL = u'/accounts/login/' LOGOUT_REDIRECT_URL = None MANAGERS = [] MEDIA_ROOT = u'' MEDIA_URL = u'' MESSAGE_STORAGE = u'django.contrib.messages.storage.fallback.FallbackStorage' MIDDLEWARE = ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] MIDDLEWARE_CLASSES = [u'django.middleware.common.CommonMiddleware', u'django.middleware.csrf.CsrfViewMiddleware'] MIGRATION_MODULES = {} MONTH_DAY_FORMAT = u'F j' NUMBER_GROUPING = 0 PASSWORD_HASHERS = u'********************' PASSWORD_RESET_TIMEOUT_DAYS = u'********************' PREPEND_WWW = False REST_FRAMEWORK = {'PAGE_SIZE': 10} ROOT_URLCONF = 'api.urls' SECRET_KEY = u'********************' SECURE_BROWSER_XSS_FILTER = False SECURE_CONTENT_TYPE_NOSNIFF = False SECURE_HSTS_INCLUDE_SUBDOMAINS = False SECURE_HSTS_SECONDS = 0 SECURE_PROXY_SSL_HEADER = None SECURE_REDIRECT_EXEMPT = [] SECURE_SSL_HOST = None SECURE_SSL_REDIRECT = False SERVER_EMAIL = u'root@localhost' SESSION_CACHE_ALIAS = u'default' SESSION_COOKIE_AGE = 1209600 SESSION_COOKIE_DOMAIN = None SESSION_COOKIE_HTTPONLY = True SESSION_COOKIE_NAME = u'sessionid' SESSION_COOKIE_PATH = u'/' SESSION_COOKIE_SECURE = False SESSION_ENGINE = u'django.contrib.sessions.backends.db' SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_FILE_PATH = None SESSION_SAVE_EVERY_REQUEST = False SESSION_SERIALIZER = u'django.contrib.sessions.serializers.JSONSerializer' SETTINGS_MODULE = 'api.settings' SHORT_DATETIME_FORMAT = u'm/d/Y P' SHORT_DATE_FORMAT = u'm/d/Y' SIGNING_BACKEND = u'django.core.signing.TimestampSigner' SILENCED_SYSTEM_CHECKS = [] STATICFILES_DIRS = [] STATICFILES_FINDERS = [u'django.contrib.staticfiles.finders.FileSystemFinder', u'django.contrib.staticfiles.finders.AppDirectoriesFinder'] STATICFILES_STORAGE = u'django.contrib.staticfiles.storage.StaticFilesStorage' STATIC_ROOT = '/var/www/verinmuebles/current/api/static' STATIC_URL = '/static/' TEMPLATES = [{'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {'context_processors': ['django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages']}, 'BACKEND': 'django.template.backends.django.DjangoTemplates'}] TEST_NON_SERIALIZED_APPS = [] TEST_RUNNER = u'django.test.runner.DiscoverRunner' THOUSAND_SEPARATOR = u',' TIME_FORMAT = u'P' TIME_INPUT_FORMATS = [u'%H:%M:%S', u'%H:%M:%S.%f', u'%H:%M'] TIME_ZONE = 'UTC' USE_ETAGS = False USE_I18N = True USE_L10N = True USE_THOUSAND_SEPARATOR = False USE_TZ = True USE_X_FORWARDED_HOST = False USE_X_FORWARDED_PORT = False WSGI_APPLICATION = 'api.wsgi.application' X_FRAME_OPTIONS = u'SAMEORIGIN' YEAR_MONTH_FORMAT = u'F Y' </code></pre> <h1>Raw request</h1> <pre><code>{ "lat": 1000, "lng": 1000, "rooms": 2, "catchment": 2, "area_um_back": 2, "area_um_front": 2, "area_um": 2, "zoomlevel": 10, "radius": 10, "is_suspended": 1, "is_made": 1, "antiquity": 1, "sector": 2, "city": "1", "zone": 2, "country": 2, "kind_offer": 3, "kind_building": 3, "b_codes": { "agents": 10, "user_code": 1346, "free_property": 12, "approve_free_bm": 2 } } </code></pre>
0
2016-08-25T13:10:39Z
39,147,231
<p>The error is in create method of BDetailSerializerSimple</p> <p>before</p> <pre><code>def create(self, validated_data): code = BCodes.objects.create(**validated_data['b_codes']) detail_data = validated_data.pop('b_codes') detail = BDetail.objects.create(b_codes=code, **detail_data) return detail </code></pre> <p>after</p> <pre><code>def create(self, validated_data): b_codes_data = validated_data.pop('b_codes') code = BCodes.objects.create(**b_codes_data) detail = BDetail.objects.create(b_codes=code, **validated_data) return detail </code></pre>
0
2016-08-25T13:53:28Z
[ "python", "django", "django-models", "django-rest-framework", "django-rest-framework-gis" ]
How to call a function inside a function ?Odoo9 Validation
39,146,304
<p>I have a added a boolean field in <code>product.pricelist.item</code></p> <pre><code>class product_pricelist_item(models.Model): _inherit = 'product.pricelist.item' myfield = fields.Boolean(string="CheckMark") </code></pre> <p>Now there are multiple lines in <code>product.pricelist.item</code>.</p> <p>(Validation) I want that the user is not allowed to make <code>True</code> multiple <code>myfield</code> one one field can be <code>True</code> at a time.</p> <p>I tried doing this in <code>product.pricelist.item</code> by giving it a counter and passing the counter the number of <code>myfields</code> which are <code>True</code>.</p> <p>But this is giving me error.</p> <blockquote> <p>global name '_get_counter' is not defined</p> </blockquote> <pre><code>def _get_counter(self): for r in self: p=[] p= r.env['product.pricelist.item'].search_read([('myfield', '=', True)], ['myfield']) counter = len(p) return counter @api.constrains('myfield') def _check_myfield(self): counter = _get_counter(self) for r in self: if counter &gt; 1: raise exceptions.ValidationError("Multiple myfield In a PriceList of a Product is not allowed.") </code></pre> <p>Now the second question is :-</p> <p>When you create a pricelist-item and click save in pricelist then it does not reflect the data in the database. When you click the pricelist save it reflects the data...why is this so ?</p>
1
2016-08-25T13:11:14Z
39,149,380
<p>With <code>self</code> we can call method of current class.</p> <p>Try with following code:</p> <p>Replace code </p> <pre><code>counter = _get_counter(self) </code></pre> <p>with</p> <pre><code>counter = self._get_counter() </code></pre>
2
2016-08-25T15:36:17Z
[ "python", "validation", "openerp", "odoo-9" ]
How to call a function inside a function ?Odoo9 Validation
39,146,304
<p>I have a added a boolean field in <code>product.pricelist.item</code></p> <pre><code>class product_pricelist_item(models.Model): _inherit = 'product.pricelist.item' myfield = fields.Boolean(string="CheckMark") </code></pre> <p>Now there are multiple lines in <code>product.pricelist.item</code>.</p> <p>(Validation) I want that the user is not allowed to make <code>True</code> multiple <code>myfield</code> one one field can be <code>True</code> at a time.</p> <p>I tried doing this in <code>product.pricelist.item</code> by giving it a counter and passing the counter the number of <code>myfields</code> which are <code>True</code>.</p> <p>But this is giving me error.</p> <blockquote> <p>global name '_get_counter' is not defined</p> </blockquote> <pre><code>def _get_counter(self): for r in self: p=[] p= r.env['product.pricelist.item'].search_read([('myfield', '=', True)], ['myfield']) counter = len(p) return counter @api.constrains('myfield') def _check_myfield(self): counter = _get_counter(self) for r in self: if counter &gt; 1: raise exceptions.ValidationError("Multiple myfield In a PriceList of a Product is not allowed.") </code></pre> <p>Now the second question is :-</p> <p>When you create a pricelist-item and click save in pricelist then it does not reflect the data in the database. When you click the pricelist save it reflects the data...why is this so ?</p>
1
2016-08-25T13:11:14Z
39,164,970
<p>The loop in <code>_get_counter</code> does not affect the result and the search did not depend on records so you can use: </p> <pre><code>def _get_counter(self): pricelist_obj = self.env['product.pricelist.item'] counter = len(pricelist_obj.search_read([('myfield', '=', True)], ['myfield'])) return counter @api.constrains('myfield') def _check_myfield(self): counter = self._get_counter() if counter &gt; 1: raise exceptions.ValidationError("Multiple myfield In a PriceList of a Product is not allowed.") </code></pre>
1
2016-08-26T11:12:35Z
[ "python", "validation", "openerp", "odoo-9" ]
Trouble sending boto3 filtered data to a list
39,146,327
<p>I've generated a working boto3 instance filter using anaconda python 2.7. I need to assign the IP addresses and instance names to a list for further processing.</p> <p>Code looks like this:</p> <pre><code>for instance in instances: print(instance.id, instance.instance_type, instance.key_name, instance.private_ip_address, instance.public_dns_name ,instance.tags[0].get("Value")) tagged = ec2.instances.filter(Filters=[{'Name': 'tag:My', 'Values': ['tag']}]) for instance in tagged: print(name, instance.id, instance.private_ip_address) object_list={} object_list['requests']=[] for instance in tagged: tagged.collections.OrderedDict() tagged['ip-address'] = instance.private_ip_address tagged['machine'] = name tagged['roles'] = ['tagged',instance.id,name] object_list['requests'].append(tagged) </code></pre> <p>This is the error:</p> <pre><code>AttributeError: 'ec2.instancesCollection' object has no attribute 'collections' </code></pre> <p>Thoughts?</p>
0
2016-08-25T13:12:39Z
39,146,438
<p>this doesn't exist but you have a cryptic error because you are reusing your <code>tagged</code> variable which is an instance of <code>ec2.instancesCollection</code></p> <pre><code> tagged.collections.OrderedDict() </code></pre> <p>(and would do nothing anyway since it's not affected)</p> <p>you (probably) want/wanted:</p> <pre><code>tagged = collections.OrderedDict() </code></pre> <p>but that doesn't make sense since you're already iterating on <code>tagged</code>.</p> <p>You have to declare another variable</p> <pre><code>for instance in tagged: t = collections.OrderedDict() t['ip-address'] = instance.private_ip_address t['machine'] = name t['roles'] = ['tagged',instance.id,name] object_list['requests'].append(t) </code></pre>
0
2016-08-25T13:17:54Z
[ "python", "anaconda", "boto3" ]
scikit-learn joblib: Permission error importing, run in Serial mode
39,146,371
<p>The following permission error occurs when I try importing joblib from script or <code>python -c 'import joblib'</code>:</p> <pre><code>/usr/local/lib/python2.7/dist-packages/joblib//joblib_multiprocessing_helpers.py:29: UserWarning: [Errno 13] Permission denied. joblib will operate in serial mode warnings.warn('%s. joblib will operate in serial mode' % (e,)) </code></pre> <ul> <li>joblib is installed and forcefully reinstalled via pip</li> <li>importing works as superuser</li> <li>I set full permissions on the joblib folder <code>chmod -R 777 /usr/local/lib/python2.7/dist-packages/joblib</code>; to no avail: the permission error remains</li> </ul> <p>So even though every user and group has full rwx permissions on the joblib directory it gives me a permission error. How do I figure out on which directory joblib does the write permission check when importing? Why does it even do the check before I specified a write operation?</p>
0
2016-08-25T13:14:36Z
39,147,538
<p>Found it by looking a in the joblib source code:</p> <p>The problem was that semaphoring was not enabled on my system: Joblib checks for multiprocessing.Semaphore() and it turns out that only root had read/write permission on shared memory in /dev/shm. Fixed it as per <a href="http://stackoverflow.com/questions/2009278/python-multiprocessing-permission-denied">this answer</a> by permanently setting the correct permissions (even after a reboot) by adding the following to your /etc/fstab:</p> <p><code>none /dev/shm tmpfs rw,nosuid,nodev,noexec 0 0</code> and then remount <code>mount /dev/shm -o remount</code></p>
0
2016-08-25T14:07:34Z
[ "python", "permissions", "scikit-learn", "python-import", "joblib" ]
Python - SSL: CERTIFICATE_VERIFY_FAILED
39,146,397
<p>I have a python script that uses the VirusTotal API. It has been working with no problems, but all of a sudden when I run the script I am getting the following error:</p> <blockquote> <pre><code>urllib2.URLError: &lt;urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)&gt; </code></pre> </blockquote> <p>I believe it may be our web proxy that is causing the issue. Is there a way to prevent it from verifying the cert? Here is the portion of the code that uses the API:</p> <pre><code>json_out = [] url = "https://www.virustotal.com/vtapi/v2/file/report" parameters = {"resource": my_list, "apikey": "&lt;MY API KEY&gt;"} data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) json_out.append (response.read()) </code></pre>
0
2016-08-25T13:15:50Z
39,150,585
<blockquote> <p>I believe it may be our web proxy that is causing the issue. Is there a way to prevent it from verifying the cert?</p> </blockquote> <p>If you assume that a SSL intercepting proxy is denying the connection then you have to fix the problem at the proxy, i.e. there is no way to instruct the proxy to not check the certificate from your application.</p> <p>If instead you assume that there is a SSL intercepting proxy and thus the certificate you receive is not signed by a CA you trust then you should get the CA of the proxy and trust it in your application (see <code>cafile</code> parameter in the <a href="https://docs.python.org/2/library/urllib2.html" rel="nofollow">documentation</a>). Disabling validation is almost never the right way. Instead fix it so that validation works.</p>
0
2016-08-25T16:38:56Z
[ "python", "ssl", "certificate" ]
Python - SSL: CERTIFICATE_VERIFY_FAILED
39,146,397
<p>I have a python script that uses the VirusTotal API. It has been working with no problems, but all of a sudden when I run the script I am getting the following error:</p> <blockquote> <pre><code>urllib2.URLError: &lt;urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)&gt; </code></pre> </blockquote> <p>I believe it may be our web proxy that is causing the issue. Is there a way to prevent it from verifying the cert? Here is the portion of the code that uses the API:</p> <pre><code>json_out = [] url = "https://www.virustotal.com/vtapi/v2/file/report" parameters = {"resource": my_list, "apikey": "&lt;MY API KEY&gt;"} data = urllib.urlencode(parameters) req = urllib2.Request(url, data) response = urllib2.urlopen(req) json_out.append (response.read()) </code></pre>
0
2016-08-25T13:15:50Z
39,286,586
<p>There are two possibilities, </p> <ol> <li>You are using a self-signed certificate. Browsers don not trust on such certificate, so be sure that you are using CA-signed trusted certificate. </li> <li>If you are using CA-signed trusted the certificate that you should have to check for install CA chain certificates (Root and Intermediate certificate).</li> </ol> <p>You can refer this article, it may help you. - <a href="https://access.redhat.com/articles/2039753" rel="nofollow">https://access.redhat.com/articles/2039753</a></p>
0
2016-09-02T07:24:17Z
[ "python", "ssl", "certificate" ]
Slicing pandas dataframe by looking for character "in" string
39,146,784
<p>I want to extract a set of rows from a dataframe based on whether a string in that row contains a given substring.</p> <p>For example, say I have</p> <p><code>testdf = pd.DataFrame({'A':['abc','efc','abz'], 'B':[4,5,6]})</code>.</p> <p>I want to get the rows containing the substring <code>'ab'</code> in column <code>'A'</code>.</p> <p>I tried <code>testdf.loc[lambda df: 'ab' in df['A'], :]</code>, but got the following error:</p> <pre><code>--------------------------------------------------------------------------- KeyError Traceback (most recent call last) &lt;ipython-input-12-86c436129f94&gt; in &lt;module&gt;() ----&gt; 1 testdf.loc[lambda df: 'a' in df['A'], :] /Users/justinpounders/anaconda/lib/python2.7/site-packages/pandas/core/indexing.pyc in __getitem__(self, key) 1292 1293 if type(key) is tuple: -&gt; 1294 return self._getitem_tuple(key) 1295 else: 1296 return self._getitem_axis(key, axis=0) /Users/justinpounders/anaconda/lib/python2.7/site-packages/pandas/core/indexing.pyc in _getitem_tuple(self, tup) 782 def _getitem_tuple(self, tup): 783 try: --&gt; 784 return self._getitem_lowerdim(tup) 785 except IndexingError: 786 pass /Users/justinpounders/anaconda/lib/python2.7/site-packages/pandas/core/indexing.pyc in _getitem_lowerdim(self, tup) 906 for i, key in enumerate(tup): 907 if is_label_like(key) or isinstance(key, tuple): --&gt; 908 section = self._getitem_axis(key, axis=i) 909 910 # we have yielded a scalar ? /Users/justinpounders/anaconda/lib/python2.7/site-packages/pandas/core/indexing.pyc in _getitem_axis(self, key, axis) 1465 # fall thru to straight lookup 1466 self._has_valid_type(key, axis) -&gt; 1467 return self._get_label(key, axis=axis) 1468 1469 /Users/justinpounders/anaconda/lib/python2.7/site-packages/pandas/core/indexing.pyc in _get_label(self, label, axis) 91 raise IndexingError('no slices here, handle elsewhere') 92 ---&gt; 93 return self.obj._xs(label, axis=axis) 94 95 def _get_loc(self, key, axis=0): /Users/justinpounders/anaconda/lib/python2.7/site-packages/pandas/core/generic.pyc in xs(self, key, axis, level, copy, drop_level) 1747 drop_level=drop_level) 1748 else: -&gt; 1749 loc = self.index.get_loc(key) 1750 1751 if isinstance(loc, np.ndarray): /Users/justinpounders/anaconda/lib/python2.7/site-packages/pandas/indexes/base.pyc in get_loc(self, key, method, tolerance) 1945 return self._engine.get_loc(key) 1946 except KeyError: -&gt; 1947 return self._engine.get_loc(self._maybe_cast_indexer(key)) 1948 1949 indexer = self.get_indexer([key], method=method, tolerance=tolerance) pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4154)() pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:3977)() pandas/index.pyx in pandas.index.Int64Engine._check_type (pandas/index.c:7634)() KeyError: False </code></pre> <p>What confuses me is that <code>testdf.loc[lambda df: df['A'] == 'abc', :]</code> does not five an error: it returns the one row containing the value <code>abc</code>. So it appears that there something about the <code>'ab' in df['A']</code> boolean that is not correct...</p> <p>I am using python 2.7 and pandas 0.18.1 in a Jupyter (4.0.6) notebook.</p>
2
2016-08-25T13:32:47Z
39,146,805
<p>use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>str.contains</code></a>:</p> <pre><code>In [67]: testdf[testdf['A'].str.contains('ab')] Out[67]: A B 0 abc 4 2 abz 6 </code></pre> <p>What you tried doesn't make sense firstly:</p> <pre><code>In [70]: 'ab' in testdf['A'] Out[70]: False </code></pre> <p>but what you're really trying to do is test 'ab' in each element of that column:</p> <pre><code>In [71]: testdf['A'].apply(lambda x: 'ab' in x) Out[71]: 0 True 1 False 2 True Name: A, dtype: bool </code></pre> <p>However, there is no need for <code>apply</code> here when there is a vectorised method</p> <p>What you tried here:</p> <pre><code>testdf.loc[lambda df: 'ab' in testdf['A']] </code></pre> <p>raised a keyerror because the lambda returned a scalar <code>False</code> which can't be used to index the whole df, but <code>testdf.loc[lambda df: df['A'] == 'abc', :]</code> works because <code>df['A'] == 'abc'</code> returns a boolean mask which can be used to mask the entire df</p> <p>Also the <code>lambda</code> is unnecessary in the <code>loc</code>:</p> <pre><code>testdf.loc[testdf['A'] == 'abc', :] </code></pre> <p>would've worked, if you think about it, all you did was provide a lambda for your df which is no different to the above</p>
3
2016-08-25T13:33:48Z
[ "python", "python-2.7", "pandas" ]
How Do I Build a Class with in a Class in Python
39,146,957
<p>I am trying to model services and I am having some issue. What I am trying to do is I would want something such as this in code:</p> <pre><code>&gt;&gt;&gt; service = Service() &gt;&gt;&gt; service.name = "Instance1" &gt;&gt;&gt; service.name.color = "red" &gt;&gt;&gt; service.name.color.enabled = True </code></pre> <p>I have tried nesting the Classes but I am still having issues. Is this completely against convention. If so I will reevaluate and find another way to do so. </p> <p>EDIT: I decided to do something like the following by just nesting the classes to copy the Hierarchy. </p> <pre><code>class Service(object): _prefix = 'Service' def __init__(self): self.name = Service.Name() class Name(object): _prefix = 'Service' def __init__(self): self.color = Service.Name.Color() class Color(object): _prefix = 'Service' def __init__(self, color="N/A"): self.color = color </code></pre>
-1
2016-08-25T13:40:40Z
39,147,069
<p>You should be looking at composition, not nested classes.</p> <pre><code>class Color: def __init__(self, name): self.name = name class Service: def __init__(self, color_obj): self.color_obj = color_obj service = Service(Color("yellow")) print(service.color_obj.name) &gt;&gt; "yellow" </code></pre>
-1
2016-08-25T13:45:21Z
[ "python", "class" ]
How Do I Build a Class with in a Class in Python
39,146,957
<p>I am trying to model services and I am having some issue. What I am trying to do is I would want something such as this in code:</p> <pre><code>&gt;&gt;&gt; service = Service() &gt;&gt;&gt; service.name = "Instance1" &gt;&gt;&gt; service.name.color = "red" &gt;&gt;&gt; service.name.color.enabled = True </code></pre> <p>I have tried nesting the Classes but I am still having issues. Is this completely against convention. If so I will reevaluate and find another way to do so. </p> <p>EDIT: I decided to do something like the following by just nesting the classes to copy the Hierarchy. </p> <pre><code>class Service(object): _prefix = 'Service' def __init__(self): self.name = Service.Name() class Name(object): _prefix = 'Service' def __init__(self): self.color = Service.Name.Color() class Color(object): _prefix = 'Service' def __init__(self, color="N/A"): self.color = color </code></pre>
-1
2016-08-25T13:40:40Z
39,147,140
<p>It's not against convention to have other objects as values of attributes of your class. </p> <p>The best thing you can do it declare your desired classes - in your example these would be <code>class Color</code>, which would have a boolean attribute <code>enabled</code>.</p>
0
2016-08-25T13:48:58Z
[ "python", "class" ]
How Do I Build a Class with in a Class in Python
39,146,957
<p>I am trying to model services and I am having some issue. What I am trying to do is I would want something such as this in code:</p> <pre><code>&gt;&gt;&gt; service = Service() &gt;&gt;&gt; service.name = "Instance1" &gt;&gt;&gt; service.name.color = "red" &gt;&gt;&gt; service.name.color.enabled = True </code></pre> <p>I have tried nesting the Classes but I am still having issues. Is this completely against convention. If so I will reevaluate and find another way to do so. </p> <p>EDIT: I decided to do something like the following by just nesting the classes to copy the Hierarchy. </p> <pre><code>class Service(object): _prefix = 'Service' def __init__(self): self.name = Service.Name() class Name(object): _prefix = 'Service' def __init__(self): self.color = Service.Name.Color() class Color(object): _prefix = 'Service' def __init__(self, color="N/A"): self.color = color </code></pre>
-1
2016-08-25T13:40:40Z
39,147,510
<p>I'd avoid having nested classes, for example:</p> <pre><code>class Color: def __init__(self, name, enabled=False): self.name = name self.enabled = enabled def __str__(self): return self.name class Service: def __init__(self, name): self.name = name self.palette = None class Palette: def __init__(self): self.colors = [] def __str__(self): return ' - '.join([str(c) for c in self.colors]) if __name__ == "__main__": num_services = 8 num_colors = 256 offset = num_colors / num_services palettes = [Palette() for i in range(num_services)] services = [Service("Service" + str(i)) for i in range(num_services)] colors = [Color("color" + str(i)) for i in range(num_colors)] for i in range(num_services): subcolors = colors[i * offset:(i + 1) * offset] palettes[i].colors = subcolors services[i].palette = palettes[i] print "Palette {0} -&gt; {1}\n".format(i, palettes[i]) </code></pre> <p>Although I'm not sure what's the meaning of enabling a color in this context</p>
0
2016-08-25T14:06:15Z
[ "python", "class" ]
How Do I Build a Class with in a Class in Python
39,146,957
<p>I am trying to model services and I am having some issue. What I am trying to do is I would want something such as this in code:</p> <pre><code>&gt;&gt;&gt; service = Service() &gt;&gt;&gt; service.name = "Instance1" &gt;&gt;&gt; service.name.color = "red" &gt;&gt;&gt; service.name.color.enabled = True </code></pre> <p>I have tried nesting the Classes but I am still having issues. Is this completely against convention. If so I will reevaluate and find another way to do so. </p> <p>EDIT: I decided to do something like the following by just nesting the classes to copy the Hierarchy. </p> <pre><code>class Service(object): _prefix = 'Service' def __init__(self): self.name = Service.Name() class Name(object): _prefix = 'Service' def __init__(self): self.color = Service.Name.Color() class Color(object): _prefix = 'Service' def __init__(self, color="N/A"): self.color = color </code></pre>
-1
2016-08-25T13:40:40Z
39,147,575
<p>If you mean nested <em>instances</em>, you just create them in the relevant <code>__init__</code> code (or subsequently)</p> <pre><code>&gt;&gt;&gt; class LR( object): ... def __init__(self, L=None, R=None): ... self.left = L ... self.right = R &gt;&gt;&gt; class Thing(object): ... def __init__(self): ... self.tree2=LR( LR(1,2), LR(3,4) ) &gt;&gt;&gt; t = Thing() &gt;&gt;&gt; t.tree2.left.right 2 </code></pre> <p>In this context, Python modules <code>collections.namedtuple</code> and <code>attrs</code> may be of use. (<code>attrs</code> is quite awesome: <a href="https://attrs.readthedocs.io/en/stable/" rel="nofollow">https://attrs.readthedocs.io/en/stable/</a>).</p> <p>If you mean some rather deeper magic like Django's nested <code>Meta</code> classes, then the source code is available. (It's clear enough how to use Django, but I can't say I understand the ins and outs of the nested <code>Meta</code> declaration well enough to do anything similar from scratch in my own code). </p> <pre><code>Class Person( models.Model) name = models.CharField( max_length = 100) ... # more field declarations Class Meta: unique_together = (("name", "birthdate"),) .... # more Meta-declarations </code></pre>
0
2016-08-25T14:09:05Z
[ "python", "class" ]
How to print a list without brackets
39,146,973
<p>I have a list with float values. I want to remove the the brackets from the list.</p> <pre><code>Floatlist = [14.715258933890,10.215953824,14.8171645397,10.2458542714719] print (", ".join(Floatlist)) but i am getting an following error : TypeError: sequence item 0: expected string, float found </code></pre> <p>but i want to print the list like:</p> <pre><code>output:14.715258933890,10.215953824,14.8171645397,10.2458542714719 </code></pre>
0
2016-08-25T13:41:24Z
39,147,018
<p>You need to convert the elements to strings.</p> <pre><code>print (", ".join(map(str, Floatlist))) </code></pre> <p>or </p> <pre><code>print (", ".join(str(f) for f in Floatlist))) </code></pre>
3
2016-08-25T13:43:06Z
[ "python" ]
How to print a list without brackets
39,146,973
<p>I have a list with float values. I want to remove the the brackets from the list.</p> <pre><code>Floatlist = [14.715258933890,10.215953824,14.8171645397,10.2458542714719] print (", ".join(Floatlist)) but i am getting an following error : TypeError: sequence item 0: expected string, float found </code></pre> <p>but i want to print the list like:</p> <pre><code>output:14.715258933890,10.215953824,14.8171645397,10.2458542714719 </code></pre>
0
2016-08-25T13:41:24Z
39,147,026
<p><code>.join</code> only operates on iterables that yield strings. It doesn't convert to strings implicitly for you -- You need to do that yourself:</p> <pre><code>','.join([str(f) for f in FloatList]) </code></pre> <hr> <p><sup><sup><code>','.join(str(f) for f in FloatList)</code> also works (notice the missing square brackets), but on CPython, it's pretty well known that the version with the list comprehension performs <em>slightly</em> better.</sup></sup></p>
3
2016-08-25T13:43:16Z
[ "python" ]
How to print a list without brackets
39,146,973
<p>I have a list with float values. I want to remove the the brackets from the list.</p> <pre><code>Floatlist = [14.715258933890,10.215953824,14.8171645397,10.2458542714719] print (", ".join(Floatlist)) but i am getting an following error : TypeError: sequence item 0: expected string, float found </code></pre> <p>but i want to print the list like:</p> <pre><code>output:14.715258933890,10.215953824,14.8171645397,10.2458542714719 </code></pre>
0
2016-08-25T13:41:24Z
39,147,060
<p>You just make a for statement:</p> <pre><code>for i in Floatlist: print(i, ', ', end='') </code></pre> <p>Hope that helps</p> <p>P.S: This snippet code only works in Python3</p>
1
2016-08-25T13:44:41Z
[ "python" ]
How to print a list without brackets
39,146,973
<p>I have a list with float values. I want to remove the the brackets from the list.</p> <pre><code>Floatlist = [14.715258933890,10.215953824,14.8171645397,10.2458542714719] print (", ".join(Floatlist)) but i am getting an following error : TypeError: sequence item 0: expected string, float found </code></pre> <p>but i want to print the list like:</p> <pre><code>output:14.715258933890,10.215953824,14.8171645397,10.2458542714719 </code></pre>
0
2016-08-25T13:41:24Z
39,147,187
<p>Just to print:</p> <pre><code>print(str(Floatlist).strip('[]')) #out: 14.71525893389, 10.215953824, 14.8171645397, 10.2458542714719 </code></pre>
1
2016-08-25T13:51:22Z
[ "python" ]
ArcGIS Raster Calculator Error in Python For-Loop
39,147,079
<p>I am performing a simple for-loop in ArcGIS calculator through python. I want to generate transition maps using cover classes from year one (r2005) to year two (r2009). Here is the code:</p> <pre><code># Importing libraries import arcpy, sys, string, os, arcgisscripting, dircache import numpy as np from arcpy import env from arcpy.sa import * # Creating the geoprocessor object gp = arcgisscripting.create() # Setting environment arcpy.env.compression = "LZW" # Check out the ArcGIS Spatial Analyst extension license arcpy.CheckOutExtension("Spatial") # Reading data classes = np.genfromtxt("Globcover_Legend_Neotropics.txt", dtype="int") r2005 = Raster("2005_Clip.tif") r2009 = Raster("2009_Clip.tif") # Creating transition rasters for i in classes: for j in classes: #OPTION1 #outEqualTo1 = r2005==i #outEqualTo2 = r2009==j #transition_raster = (outEqualTo1) &amp; (outEqualTo2) #OPTION2 transition_raster = (r2005 == i) &amp; (r2009 == j) transition_raster.save(str(i)+"_"+str(j)+".tif") print (str(i)+"_"+str(j)) </code></pre> <p>The object "classes" is a numpy array containing the cover classes to compare:</p> <pre><code>&gt;&gt;&gt; classes array([ 14, 20, 30, 40, 50, 60, 70, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220]) </code></pre> <p>When I run the code using any element in the loop, it runs perfectly. For example:</p> <pre><code>&gt;&gt;&gt; i=j=14 &gt;&gt;&gt; transition_raster = (r2005 == i) &amp; (r2009 == j) &gt;&gt;&gt; transition_raster.save(str(i)+"_"+str(j)+".tif") </code></pre> <p>However, when I run the complete for-loop I get this error:</p> <pre><code>Traceback (most recent call last): File "D:\Cover\GlobCover\transitions.py", line 31, in &lt;module&gt; transition_raster = (r2005 == i) &amp; (r2009 == j) File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\sa\Functions.py", line 3831, in EqualTo in_raster_or_constant2) File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\sa\Utils.py", line 47, in swapper result = wrapper(*args, **kwargs) File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\sa\Functions.py", line 3828, in Wrapper ["EqualTo", in_raster_or_constant1, in_raster_or_constant2]) TypeError: expected a raster or layer name </code></pre> <p>I've tried with the two options in the code (see code) and I get the same error. Any idea about it? Thanks in advance and cheers!</p>
1
2016-08-25T13:45:59Z
39,167,520
<p>You know that the value <code>14</code> works, but you are getting a <code>TypeError</code> with whatever the loop over <code>classes</code> is returning. The type of <code>14</code> is <code>int</code>, so try typecasting <code>i</code> and <code>j</code> to <code>int</code> before making the comparison:</p> <pre><code>for i in classes: for j in classes: transition_raster = ( (r2005 == int(i)) &amp; (r2009 == int(j)) ) # added typecasts: ^^^^ ^ ^^^^ ^ ... </code></pre>
0
2016-08-26T13:28:27Z
[ "python", "for-loop", "arcgis", "raster" ]
Dask: is it safe to pickle a dataframe for later use?
39,147,120
<p>I have a database-like object containing many dask dataframes. I would like to work with the data, save it and reload it on the next day to continue the analysis. </p> <p>Therefore, I tried saving dask dataframes (not computation results, just the "plan of computation" itself) using pickle. Apparently, it works (at least, if I unpickle the objects on the exact same machine) ... but are there some pitfalls? </p>
1
2016-08-25T13:48:07Z
39,147,916
<p>Generally speaking it is <em>usually</em> safe. However there are a few caveats:</p> <ol> <li>If your dask.dataframe contains custom functions, such as with with <code>df.apply(lambda x: x)</code> then the internal function will not be pickleable. However it will still be serializable with <a href="https://github.com/cloudpipe/cloudpickle" rel="nofollow">cloudpickle</a></li> <li>If your dask.dataframe contains references to files that are only valid on your local computer then, while it will still be serializable the re-serialized version on another machine may no longer be useful</li> <li>If your dask.dataframe contains <code>dask.distributed</code> <code>Future</code> objects, such as would occur if you use <code>Executor.persist</code> on a cluster then these are not currently serializable.</li> <li>I recommend using a version >= 0.11.0. </li> </ol>
1
2016-08-25T14:23:27Z
[ "python", "dask" ]
May I display the field from other table in the template in Django 1.10?
39,147,192
<p>May I display the field from other table in the template in Django 1.10?</p> <p>I have 3 tables as the following models.py</p> <pre><code>import datetime from django.db import models from django.forms import ModelForm from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Group(models.Model): group_name = models.CharField(max_length=255) no_of_monk = models.IntegerField() def __str__(self): return self.group_name class Meta: ordering = ['id'] @python_2_unicode_compatible class Tbl_Province(models.Model): province_code = models.CharField(max_length=2) province_name = models.CharField(max_length=150) geo_id = models.IntegerField() def __str__(self): return self.province_name @python_2_unicode_compatible class Contact(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) order = models.IntegerField() name = models.CharField(max_length=255, db_index=True) description = models.TextField(blank=True) amount = models.DecimalField(max_digits=10, decimal_places=2) confirm = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) province = models.ForeignKey(Tbl_Province, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: ordering = ['order', 'province'] </code></pre> <p>and I would like to display tbl_province.province_name where id=contact.id in the following template, is it possible?</p> <pre><code>{% for contact in group.contact_set.all %} &lt;tr&gt; &lt;td width="10%" class="table-text"&gt;&lt;div&gt;&lt;strong&gt;{{ forloop.counter0|mod:5|add:1 }}&lt;/strong&gt;&lt;/div&gt;&lt;/td&gt; &lt;td width="10%" class="table-text"&gt;&lt;div&gt;{{ forloop.counter }}&lt;/div&gt;&lt;/td&gt; &lt;td width="10%" class="table-text"&gt;&lt;div&gt;{{ contact.order }}&lt;/div&gt;&lt;/td&gt; &lt;td class="table-text"&gt;&lt;div&gt;{{ contact.name }}&lt;/div&gt;&lt;/td&gt; {% if contact.province_id %} &lt;td class="table-text"&gt;&lt;div&gt;{{ **Want to display tbl_province.province_name where id=contact.id here** }}&lt;/div&gt;&lt;/td&gt; {% endif %} &lt;td width="13%" class="table-text"&gt;&lt;div&gt;&lt;input type="text" name="ord" id="con-ord" class="form-control" value="{{ contact.amount|intcomma }}"&gt;&lt;/div&gt;&lt;/td&gt; &lt;td width="10%" class="table-text"&gt;&lt;div&gt;บาท&lt;/div&gt;&lt;/td&gt; &lt;td&gt; &lt;form action="{% url 'contribution:contactdel' contact.id %}" method="POST"&gt; {% csrf_token %} &lt;button type="submit" id="delete-group" class="btn btn-danger"&gt; &lt;i class="fa fa-btn fa-trash"&gt;&lt;/i&gt; Delete &lt;/button&gt; &lt;/form&gt; &lt;/td&gt; &lt;/tr&gt; {% endfor %} </code></pre>
2
2016-08-25T13:51:37Z
39,147,302
<p>Templates don't have the access to the database, so they can't execute a query (and that's basically what you want)</p> <p>However, I can see that you have a foreign key to <code>Tbl_Province</code> in <code>Contact</code> and you can use that instead - just write <code>{% contact.province.province_name %}</code> (if I understand correctly what you're trying to achieve)</p> <p>If you need anything more exotic, you'll have to execute your query inside the view function, and then pass it to template context.</p>
0
2016-08-25T13:56:09Z
[ "python", "django" ]
Selenium in Python How use a If - else code if an element is not present
39,147,245
<p>All, I am in need of some serious " dumbed down " examples of how to write code in Python that will do something if a element is there or not there. I'm new to programing and I have reviewed a days worth of posts and I can't seem to figure it out.... </p> <p>Here is what I am trying to do. </p> <pre><code>from selenium.common.exceptions import NoSuchElementException, staleElementReferenceException elem = driver.find_element_by_partial_link_text('Create Activity') print("Searching for Create Activity.") if elem.is_displayed(): elem.click() # this will click the element if it is there print("FOUND THE LINK CREATE ACTIVITY! and Clicked it!") else: print ("NO LINK FOUND") </code></pre> <p>So, Providing that there is a LINK present that is element_by_partial_link_text('Create Activity')</p> <p>I get the proper response ... Searching for Create Activity. FOUND THE LINK CREATE ACTIVITY! and Clicked it!</p> <p>My problem is when there is NOT a link that Matches <code>element_by_partial_link_text('Create Activity')</code></p> <p>I don't get what I would expect that is in my else statement. <code>print ("NO LINK FOUND")</code></p> <p>I get ...</p> <blockquote> <p>Traceback (most recent call last): File "", line 1, in File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 341, in find_element_by_partial_link_text return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 745, in find_element {'using': by, 'value': value})['value'] File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"Create Activity"}</p> </blockquote> <p>How do I get selenium within <code>Python</code> to turn this exception or error to not halt my script and just process the <code>ELSE</code> statement. </p> <p>Thanks,</p>
0
2016-08-25T13:54:01Z
39,147,358
<p>you can catch the exception and act accordingly:</p> <pre><code>try: elem = driver.find_element_by_partial_link_text('Create Activity') if elem.is_displayed(): elem.click() # this will click the element if it is there print("FOUND THE LINK CREATE ACTIVITY! and Clicked it!") except NoSuchElementException: print("...") </code></pre> <p>Also, I would probably modify the test to make sure that the element is indeed "clickable":</p> <pre><code>if elem.is_displayed() and elem.is_enabled(): </code></pre>
5
2016-08-25T13:58:45Z
[ "python", "selenium" ]
Selenium in Python How use a If - else code if an element is not present
39,147,245
<p>All, I am in need of some serious " dumbed down " examples of how to write code in Python that will do something if a element is there or not there. I'm new to programing and I have reviewed a days worth of posts and I can't seem to figure it out.... </p> <p>Here is what I am trying to do. </p> <pre><code>from selenium.common.exceptions import NoSuchElementException, staleElementReferenceException elem = driver.find_element_by_partial_link_text('Create Activity') print("Searching for Create Activity.") if elem.is_displayed(): elem.click() # this will click the element if it is there print("FOUND THE LINK CREATE ACTIVITY! and Clicked it!") else: print ("NO LINK FOUND") </code></pre> <p>So, Providing that there is a LINK present that is element_by_partial_link_text('Create Activity')</p> <p>I get the proper response ... Searching for Create Activity. FOUND THE LINK CREATE ACTIVITY! and Clicked it!</p> <p>My problem is when there is NOT a link that Matches <code>element_by_partial_link_text('Create Activity')</code></p> <p>I don't get what I would expect that is in my else statement. <code>print ("NO LINK FOUND")</code></p> <p>I get ...</p> <blockquote> <p>Traceback (most recent call last): File "", line 1, in File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 341, in find_element_by_partial_link_text return self.find_element(by=By.PARTIAL_LINK_TEXT, value=link_text) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 745, in find_element {'using': by, 'value': value})['value'] File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute self.error_handler.check_response(response) File "C:\Program Files (x86)\Python35-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"partial link text","selector":"Create Activity"}</p> </blockquote> <p>How do I get selenium within <code>Python</code> to turn this exception or error to not halt my script and just process the <code>ELSE</code> statement. </p> <p>Thanks,</p>
0
2016-08-25T13:54:01Z
39,147,742
<p><code>find_element</code> returns either element or throws <code>NoSuchElementException</code>, So for best way to determine element is present with if condition, You should try using <code>find_elements</code> instead of catching exception because it's returns either list of <code>WebElement</code> or empty list, so you just check its length as below :-</p> <pre><code>elems = driver.find_elements_by_partial_link_text('Create Activity') if len(elems) &gt; 0 and elems[0].is_displayed(): elems[0].click() print("FOUND THE LINK CREATE ACTIVITY! and Clicked it!") else: print ("NO LINK FOUND") </code></pre>
1
2016-08-25T14:15:35Z
[ "python", "selenium" ]
Seaborn and plotly violin plots in Jupyter Notebook kill kernel
39,147,350
<p>I am trying to generate a violin plot using seaborn 0.7.1 in a Jupyter notebook. Boxplot works fine for the same data, but violinplot causes the kernel to "die unexpectedly."</p> <p>I have also tried using plotly 1.12.9 to do a violin plot (following the example on the plotly website), but that also kills the kernel.</p> <p>Does anyone have any idea about what the error might be or how I should go about debugging this?</p> <p>This is the code I used for seaborn:</p> <pre><code> import matplotlib.pyplot as plt import seaborn as sns import pandas as pd fig2, ax2 = plt.subplots() sns.violinplot(x="Group", y="Data", data=df, ax=ax2) ax2.set_ylim([0., 1.]) fig2.title = "Data by Group" fig2.show() </code></pre> <p>and this is the code I use for plotly:</p> <pre><code> import plotly.plotly as py from plotly.tools import FigureFactory as FF from plotly.graph_objs import graph_objs from scipy import stats fig = FF.create_violin(bs_df, data_header="Data", group_header="Group", height=500, width=800) fig.show() </code></pre> <p>The error that Jupyter Notebook wasn't showing was:</p> <p><code>Intel MKL FATAL ERROR: Cannot load libmkl_avx2.so or libmkl_def.so.</code></p>
0
2016-08-25T13:58:24Z
39,171,409
<p>Given the error message below:</p> <pre><code>Intel MKL FATAL ERROR: Cannot load libmkl_avx2.so or libmkl_def.so. </code></pre> <p>I was able to resolve it by updating numpy to 1.11.1 and scipy to 0.17.1.</p>
0
2016-08-26T17:06:44Z
[ "python", "matplotlib", "plotly", "seaborn", "violin-plot" ]
Euclidean distance of points coordinates in pandas dataframe
39,147,379
<p>I have a pandas dataframe with six columns, first three columns contain <em>x</em>, <em>y</em> and <em>z</em> reference coordinate, and the next three - coordinates of some point. I want to put euclidean distance between those two points in new column of the dataframe. I think about using <code>numpy.linalg.norm</code> via <code>pandas.apply</code> method, but I don't know what is the best method to parse dataframe row for numpy function. Could you give me some suggestions?</p>
2
2016-08-25T13:59:36Z
39,147,447
<p>You might not need any fancy magic here:</p> <pre><code>df['dist'] = np.sqrt( (df.x1-df.x2)**2 + (df.y1-df.y2)**2 + (df.z1-df.z2)**2) </code></pre>
1
2016-08-25T14:03:00Z
[ "python", "pandas", "numpy", "dataframe" ]
Queryset is returned inside children key
39,147,407
<p>I wanted to list all the reviews along with the replies to specific review of specific restaurant but i could only list the review. While trying to fetch all the replies to its specific review, i called the children() which is defined in Review model. It returned queryset. On the other hand i want all the specific replies with the name of replier. </p> <p><strong>serializers.py</strong></p> <pre><code>class ReviewSeraializer(ModelSerializer): reply_count = SerializerMethodField() children = SerializerMethodField() class Meta: model = Review read_only = ('id',) fields = ('id','content_type','object_id','parent','review','children','reply_count','created') def get_reply_count(self, obj): if obj.is_parent: return obj.children().count() return 0 def get_children(self, obj): obj_children = [] if obj.is_parent: return str(obj.children()) # for obj in obj.children(): # print(obj.review) # obj_children.append(obj.review) # return str(obj_children) return None </code></pre> <p><strong>review/models.py</strong></p> <pre><code>class Review(models.Model): reviewer = models.ForeignKey(User, null=True) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') parent = models.ForeignKey("self", null=True, blank=True, related_name="parent_review") review = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) objects = ReviewManager() def children(self): # replies return Review.objects.filter(parent=self) @property def is_parent(self): if self.parent is not None: return False return True </code></pre> <p><a href="http://i.stack.imgur.com/Gdqqd.png" rel="nofollow"><img src="http://i.stack.imgur.com/Gdqqd.png" alt="enter image description here"></a></p> <p>How to list all the replies and replier name inside children key of a specific review?</p>
0
2016-08-25T14:01:14Z
39,148,108
<p>Add another serializer that can serialize your children.</p> <pre><code>class ReviewSeraializerChild(serializers.ModelSerializer): class Meta: model = Review class ReviewSeraializer(serializers.ModelSerializer): reply_count = serializers.SerializerMethodField() children = ReviewSeraializerChild(many=True) class Meta: model = Review read_only = ('id',) fields = ('id', 'content_type', 'object_id', 'parent', 'review', 'children', 'reply_count', 'created') def get_reply_count(self, obj): if obj.is_parent: return obj.children().count() return 0 </code></pre> <p>But you must write your custom create() and update() functions for nested fields<a href="http://i.stack.imgur.com/SoquZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/SoquZ.png" alt="enter image description here"></a>.</p>
1
2016-08-25T14:32:27Z
[ "python", "django", "python-3.x", "django-rest-framework" ]
How to undo action in OpenAI Gym?
39,147,440
<p>In OpenAI Gym, I would like to know the next states for different actions on the same state. For example, I want to get s_1, s_2 where the dynamics of my environment are:</p> <p>(s, a_1) -> s_1, (s, a_2) -> s_2</p> <p>I can not find a method that undoes an action, or shows me the next state without changing the environment. Is there something obvious that I'm missing?</p> <p>If it helps, I am doing this to differentiate the dynamics and reward for LQR, and using the InvertedPendulum environment.</p>
0
2016-08-25T14:02:33Z
39,158,935
<p>I found a method named set_state that does exactly this. It can be found at: <a href="https://github.com/openai/gym/blob/master/gym/envs/mujoco/mujoco_env.py" rel="nofollow">https://github.com/openai/gym/blob/master/gym/envs/mujoco/mujoco_env.py</a></p>
0
2016-08-26T05:34:50Z
[ "python", "reinforcement-learning" ]
The error says that user_input is undefined, what to do?
39,147,475
<p>The code is below. Please help.</p> <pre><code>num1 = float(raw_input("Enter a number")) num2 = float(raw_input("Enter another number")) while True: print("Select one of the following options") print("'Add' for addition") print("'Subtract' for subtraction") print("'Multiply' for multipication") print("'Divide' for division") print("'Quit' for closing the application") user_input == raw_input("Enter your choice: ") if user_input == 'Add': print num1 + num2 elif user_input == 'Subtract': if num1 &lt; num2: print num2 - num1 else: print num1 - num2 elif user_input == 'Multiply': print num1 * num2 elif user_input == 'Divide': print num1/num2 elif user_input == 'Quit': break </code></pre> <p><a href="http://i.stack.imgur.com/VChyK.png" rel="nofollow">The image shows the code and the error</a></p>
0
2016-08-25T14:04:03Z
39,147,607
<p>you are using incorrect equality assignment. == instead of =</p> <pre><code>user_input == raw_input("Enter your choice: ") </code></pre> <p>should be </p> <pre><code>user_input = raw_input("Enter your choice: ") </code></pre>
1
2016-08-25T14:10:14Z
[ "python" ]
The error says that user_input is undefined, what to do?
39,147,475
<p>The code is below. Please help.</p> <pre><code>num1 = float(raw_input("Enter a number")) num2 = float(raw_input("Enter another number")) while True: print("Select one of the following options") print("'Add' for addition") print("'Subtract' for subtraction") print("'Multiply' for multipication") print("'Divide' for division") print("'Quit' for closing the application") user_input == raw_input("Enter your choice: ") if user_input == 'Add': print num1 + num2 elif user_input == 'Subtract': if num1 &lt; num2: print num2 - num1 else: print num1 - num2 elif user_input == 'Multiply': print num1 * num2 elif user_input == 'Divide': print num1/num2 elif user_input == 'Quit': break </code></pre> <p><a href="http://i.stack.imgur.com/VChyK.png" rel="nofollow">The image shows the code and the error</a></p>
0
2016-08-25T14:04:03Z
39,147,611
<pre><code>user_input == raw_input("Enter your choice: ") </code></pre> <p>should be</p> <pre><code>user_input = raw_input("Enter your choice: ") </code></pre> <p>with only one equal character</p>
1
2016-08-25T14:10:20Z
[ "python" ]
The error says that user_input is undefined, what to do?
39,147,475
<p>The code is below. Please help.</p> <pre><code>num1 = float(raw_input("Enter a number")) num2 = float(raw_input("Enter another number")) while True: print("Select one of the following options") print("'Add' for addition") print("'Subtract' for subtraction") print("'Multiply' for multipication") print("'Divide' for division") print("'Quit' for closing the application") user_input == raw_input("Enter your choice: ") if user_input == 'Add': print num1 + num2 elif user_input == 'Subtract': if num1 &lt; num2: print num2 - num1 else: print num1 - num2 elif user_input == 'Multiply': print num1 * num2 elif user_input == 'Divide': print num1/num2 elif user_input == 'Quit': break </code></pre> <p><a href="http://i.stack.imgur.com/VChyK.png" rel="nofollow">The image shows the code and the error</a></p>
0
2016-08-25T14:04:03Z
39,147,633
<p>Change</p> <pre><code>user_input == raw_input("Enter your choice: ") </code></pre> <p>to</p> <pre><code>user_input = raw_input("Enter your choice: ") </code></pre>
0
2016-08-25T14:11:16Z
[ "python" ]
multiply a number from a list and a number from a text file?
39,147,480
<p>I am currently trying to multiply a number from a list with a number from a text file however I get the error= <code>Can't multiply sequence by non-int of type 'NonType'</code> , </p> <p>Does anyone have a better method for doing this ?</p> <pre><code>text_file =open("read_it.txt", "r") pricetxt=print(text_file.readlines()[2]) price1 = pricetxt*(items2[1]) print(price1) </code></pre>
0
2016-08-25T14:04:35Z
39,147,860
<p>The <code>print()</code> returns None and you are preserving it in <code>pricetxt()</code>. Also you need to convert the result which is a string to <code>int</code> (if it's a correct data). Also note that you better to use a <code>with</code> statement for opening the file, because it will close the file automatically at the end of the block.</p> <pre><code>with open("read_it.txt") as text_file: try: price = int(text_file.readlines()[2]) except ValueError: # do something else else: new_price = price * items2[1] </code></pre> <p>Note that also <code>items2[1]</code> needs to be integer. If it's not you have to convert it to integer, which you can do it in <code>try</code> block after <code>pricetxt</code>.</p>
1
2016-08-25T14:20:48Z
[ "python", "python-3.x", "numbers" ]
Smooth large data in 3D plot
39,147,482
<p>I have made a 3D plot in Python using matplotlib and Axes3D. It looks pretty good, but it has a lot of jagged edges due to how much data I am plotting. I have tried scipy interpolation methods on the data, but the <code>plot_surface</code> command does not like the type given back. I haven't been able to find out much else on the subject.</p> <p>Here is my code so far:</p> <pre><code>import numpy import scipy.io as sio from matplotlib import pyplot import matplotlib from mpl_toolkits.mplot3d import Axes3D import scipy #data pulled from file matFile = sio.loadmat(matFileLocation) data = matFile['data'] [numrows, numcols] = numpy.shape(numpy.atleast_2d(data)) fig = pyplot.figure() ax = fig.gca(projection = '3d') x = range(numcols) y = range(numrows) X, Y = numpy.meshgrid(x,y) hImage = ax.plot_surface(X,Y,data,cmap = 'jet', rstride = 1, cstride = 10, linewidth=0, antialiased = False) fig.colorbar(hImage) hImage.set_clim(mindb, maxdb) pyplot.show() </code></pre> <p>Please note that x, y, and data will change based on different files I run. A point in the right direction would be much appreciated.</p> <p><strong>Edit: methods tried</strong></p> <p>I've tried so many different interpolation methods from too many different examples in the past two days that I can't remember what I have and haven't tried. I think I remember <code>griddata</code>, <code>interp2d</code> and some <code>hImage.imshow(interpolation='gaussian')</code>(or something to that effect). Griddata returned something the <code>plot_surface</code> couldn't understand, interp2d never finished and hImage turned my entire plot yellow with no scaled variations like I was expecting.</p> <p>I have also tried other approaches like convolving my data with a 2D array of ones and dividing by the length of the 2D array. Unfortunately, my data contains a lot of very low values, so the few high values I have get lost in the convolution. <strong>Edit: I forgot to divide by len^2, the values make more sense now.</strong></p> <p>I am essentially looking for <code>shading interp</code> from MatLab.</p>
0
2016-08-25T14:04:42Z
39,153,543
<p>I ended up convolving my data by a 2d array of ones and dividing by the length of the new array.</p> <pre><code>def movingaverage(interval, window_size, mindb): window= numpy.ones((int(window_size),int(window_size)))/(float(window_size)**2) return scipy.signal.convolve2d(interval, window, 'same', fillvalue=mindb) </code></pre> <p>This is a moving average type of function that I discovered while looking for other options. It smooths out my 3d plot, though it does have the trade-off of lowering high peaks because so much of my data has a low z-axis value.</p>
0
2016-08-25T19:43:19Z
[ "python", "matplotlib", "plot", "3d" ]
Annotate seaborn Factorplot
39,147,492
<p>I would like to visualize 2 boolean informations stored as columns in one seaborn FactorPlot.</p> <p>Here is my df :</p> <p><a href="http://i.stack.imgur.com/KTG5j.png" rel="nofollow"><img src="http://i.stack.imgur.com/KTG5j.png" alt="enter image description here"></a></p> <p>I would like to visualize both of <code>actual_group</code> and <code>adviced_group</code> in the same FactorPlot.</p> <p>For now I am only able to plot the <code>adviced_groups</code> using the <code>hue</code> parameter :</p> <p><a href="http://i.stack.imgur.com/5k3kb.png" rel="nofollow"><img src="http://i.stack.imgur.com/5k3kb.png" alt="enter image description here"></a></p> <p>with the code below :</p> <pre><code> _ = sns.factorplot(x='groups', y='nb_opportunities', hue='adviced_groups', size=6, kind='bar', data=df) </code></pre> <p>I tried to use the <code>ax.annotate()</code> from matplotlib without any success, because - for what I understood - Axes are not handled by the <code>sns.FactorPlot()</code> method.</p> <p>It could be an annotation, colorize one of the rectangle's edge or anything that could help visualize the actual group.</p> <p>The result could be for instance something like this : </p> <p><a href="http://i.stack.imgur.com/UZdSv.png" rel="nofollow"><img src="http://i.stack.imgur.com/UZdSv.png" alt="enter image description here"></a></p>
2
2016-08-25T14:05:20Z
39,152,639
<p>You could make use of <a href="http://matplotlib.org/users/annotations_intro.html" rel="nofollow"><code>plt.annotate</code></a> method provided by <code>matplotlib</code> to make annotations for the <code>factorplot</code> as shown:</p> <p><strong>Setup:</strong> </p> <pre><code>df = pd.DataFrame({'groups':['A', 'B', 'C', 'D'], 'nb_opportunities':[674, 140, 114, 99], 'actual_group':[False, False, True, False], 'adviced_group':[False, True, True, True]}) print (df) actual_group adviced_group groups nb_opportunities 0 False False A 674 1 False True B 140 2 True True C 114 3 False True D 99 </code></pre> <p><strong>Data Operations:</strong></p> <p>Choosing the subset of <code>df</code> where the values of <code>actual_group</code> are True. The <code>index</code> value and the <code>nb_opportunities</code> value become the arguments for x and y that become the location of the annotation.</p> <pre><code>actual_group = df.loc[df['actual_group']==True] x = actual_group.index.tolist()[0] y = actual_group['nb_opportunities'].values[0] </code></pre> <p><strong>Plotting:</strong> </p> <pre><code>sns.factorplot(x="groups", y="nb_opportunities", hue="adviced_group", kind='bar', data=df, size=4, aspect=2) </code></pre> <p>Adding some padding to the location of the annotation as well as the location of text to account for the width of the bars being plotted.</p> <pre><code>plt.annotate('actual group', xy=(x+0.2,y), xytext=(x+0.3, 300), arrowprops=dict(facecolor='black', shrink=0.05, headwidth=20, width=7)) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/GZHtJ.png" rel="nofollow"><img src="http://i.stack.imgur.com/GZHtJ.png" alt="Image"></a></p>
2
2016-08-25T18:45:13Z
[ "python", "pandas", "matplotlib", "seaborn" ]
Is there an iterative way to create tk.Frames and configure them?
39,147,545
<p>Right now I have:</p> <pre><code># create window frames self.f1 = tk.Frame(self.root) self.f2 = tk.Frame(self.root) self.f3 = tk.Frame(self.root) self.f4 = tk.Frame(self.root) self.f5 = tk.Frame(self.root) self.f6 = tk.Frame(self.root) # place frames on window for f in (self.f1, self.f2, self.f3, self.f4, self.f5, self.f6): f.configure(bg="white") f.configure(width=self.width, height=self.height, bg="white") f.place(x=0, y=0) </code></pre> <p>I am going to be adding a lot more frames. I was wondering if there was an iterative way to create all the frames, as well as place them in the windows and configure them, without having to type "self.f7, self.f8, self.f9" etc.</p>
1
2016-08-25T14:07:46Z
39,147,561
<p>Add every new <code>Frame</code> to the list and then iterate over list.</p> <pre><code>frames = [] self.f1 = tk.Frame(self.root) frames.append(self.f1) # Do that for all frames for f in frames: f.configure(bg="white") f.configure(width=self.width, height=self.height, bg="white") f.place(x=0, y=0) </code></pre> <p>Edit to answer the comment:</p> <p>Create a method for that:</p> <pre><code>def add_frames(self, how_many_frames): for i in range(how_many_frames): f = tk.Frame(self.root) self.frames[i] = f f.configure(bg="white") f.configure(width=self.width, height=self.height, bg="white") f.place(x=0, y=0) </code></pre> <p>You also need to have <code>self.frames = dict()</code> initialised in <code>__init__</code> method. Now call <code>add_frames(30)</code> to create 30 frames, store then in dictionary under <code>self.frames</code> and configure them at the same time.</p>
2
2016-08-25T14:08:28Z
[ "python", "python-2.7", "tkinter" ]
python - modify part of a masked array inside a function
39,147,576
<p>I need to modify part of a masked array inside a function eg:</p> <pre><code>import numpy.ma as ma arr_2d = ma.masked_all((5,5)) arr_3d = ma.masked_all((5,5,5)) arr_3d[0,1] = 5 def func1(arr, val): arr[:] = val </code></pre> <p>looks simple enough but then...</p> <pre><code>&gt;&gt;&gt; func1(arr_3d[0], 1) &gt;&gt;&gt; arr_3d[0] masked_array(data = [[-- -- -- -- --] [1.0 1.0 1.0 1.0 1.0] [-- -- -- -- --] [-- -- -- -- --] [-- -- -- -- --]], mask = [[ True True True True True] [False False False False False] [ True True True True True] [ True True True True True] [ True True True True True]], fill_value = 1e+20) </code></pre> <p>it seems to be something to do with the sharedmask always being set on a slice of the array so that the mask is passed to the function as a copy</p> <p>I'm hoping there might be some way to fix or get around it other than explicitly passing the mask, returning a copy of the data or passing the larger array with an index. </p>
0
2016-08-25T14:09:06Z
39,150,403
<p>The warning in a recent numpy is:</p> <pre><code>In [738]: func1(A[1],1) /usr/local/bin/ipython3:2: MaskedArrayFutureWarning: setting an item on a masked array which has a shared mask will not copy the mask and also change the original mask array in the future. Check the NumPy 1.11 release notes for more information. </code></pre> <p><a href="http://docs.scipy.org/doc/numpy/release.html#assigning-to-slices-views-of-maskedarray" rel="nofollow">http://docs.scipy.org/doc/numpy/release.html#assigning-to-slices-views-of-maskedarray</a></p> <blockquote> <p>Currently a slice of a masked array contains a view of the original data and a copy-on-write view of the mask. Consequently, any changes to the slice’s mask will result in a copy of the original mask being made and that new mask being changed rather than the original. </p> </blockquote> <p>After this action, row 1 of A is still masked, but the <code>A[</code>,:].data` has been changed.</p> <pre><code>In [757]: B=np.ma.masked_all((5)) ... In [759]: B[0]=5 # direct __setitem__ change to B In [760]: B Out[760]: masked_array(data = [5.0 -- -- -- --], mask = [False True True True True], fill_value = 1e+20) In [761]: func1(B[3:],1) /usr/local/bin/ipython3:2: MaskedArrayFutureWarning: .... In [762]: B # no change to mask Out[762]: masked_array(data = [5.0 -- -- -- --], mask = [False True True True True], fill_value = 1e+20) In [763]: B.data # but data is changed Out[763]: array([ 5., 0., 0., 1., 1.]) </code></pre> <p><code>A[1,:]=1</code> is a direct use of the masked <code>__setitem__</code>, and it can take full responsibility for setting both the <code>data</code> and <code>mask</code>. In your function <code>A</code> is a view of the original, obtained with a <code>A.__getitem__</code> call. Apparently developers have worried about whether changes to this view`s mask should affect the mask of the original or not.</p> <p>We may have to look developers discussions; the warning indicates that something was changed recently.</p> <p>============</p> <p>The issue isn't about use in a function, it's about a view</p> <pre><code>In [764]: B1=B[3:] In [765]: B1[:]=2 /usr/local/bin/ipython3:1: MaskedArrayFutureWarning:... In [766]: B Out[766]: masked_array(data = [5.0 -- -- -- --], mask = [False True True True True], fill_value = 1e+20) In [767]: B.data Out[767]: array([ 5., 0., 0., 2., 2.]) </code></pre> <p>The warning describes what is happening now, and possibly for some time. It's saying that this practice will change.</p> <p>Following the change notes suggestion:</p> <pre><code>In [785]: B1=B[3:] In [787]: B1._sharedmask Out[787]: True In [790]: B1._sharedmask=False In [791]: B1[:]=4 In [792]: B1 Out[792]: masked_array(data = [4.0 4.0], mask = [False False], fill_value = 1e+20) In [793]: B # mask has been changed along with data Out[793]: masked_array(data = [5.0 -- -- 4.0 4.0], mask = [False True True False False], fill_value = 1e+20) </code></pre> <p>So changing </p> <pre><code> def func1(arr,val): arr._sharedmask=False arr[:]=val </code></pre> <p>will stop the warning, and modify the mask of the original array.</p>
0
2016-08-25T16:28:52Z
[ "python", "arrays", "numpy", "masked-array" ]
Set WTForms submit button to icon
39,147,578
<p>I want a submit button that displays an icon rather than text. The button is a field in a WTForms form. I am using Bootstrap and Open Iconic for styling and icons. How do I set the submit field to display an icon?</p> <pre><code>class MyForm(Form): submit = SubmitField('') </code></pre> <pre><code>{{ form.submit }} </code></pre> <p><a href="http://stackoverflow.com/questions/30668029/creating-a-form-with-a-varying-number-of-repeated-subform-in-flask-wtforms">This post</a> refers to an <code>icon</code> method, but I can't find any more information on it.</p>
1
2016-08-25T14:09:09Z
39,150,281
<p>The example you linked is using macros provided by Flask-Bootstrap. The macros make it easy to construct forms with Bootstrap, but might not be flexible. For example, they probably don't support using Open Iconic icons instead.</p> <p>Typically, you don't need to specify the submit button in the form, as it doesn't contribute useful data. Render the submit as a button in the template manually and set whatever content you need.</p> <pre class="lang-html prettyprint-override"><code>&lt;button type=submit class="btn btn-primary"&gt;&lt;span class="oi oi-check" title="Submit"&gt;&lt;/span&gt;&lt;/button&gt; </code></pre> <p>If you do need a <code>SubmitField</code> in your form, you can set the label to a <code>Markup</code> string with the HTML. The <code>Markup</code> is needed to tell Jinja it's safe to render without escaping.</p> <pre><code>from markupsafe import Markup submit_value = Markup('&lt;span class="oi oi-check" title="Submit"&gt;&lt;/span&gt;') submit = SubmitField(submit_value) </code></pre>
0
2016-08-25T16:21:33Z
[ "python", "flask", "jinja2", "wtforms", "iconic" ]
How to append values to a list of lists using other list of lists and doing mathematical operations
39,147,612
<p>I have several lists of lists:</p> <pre><code>crt = [[80, 90, 6, 5.4, 8, 5], [65, 58, 2, 9.7, 1, 1], [83, 60, 4, 7.2, 4, 7], [40, 80, 10, 7.5, 7, 10], [52, 72, 6, 2, 3, 8], [94, 96, 7, 3.6, 5, 6]] nc = [[1, 2, 3, 4, 5, 6], [1, 1, 1, 1, 1, 1], [-1, 1, -1, -1, -1, 1], [2, 3, 5, 6, 1, 6], [10, 0, 0.5, 1, 0, 0], [0, 30, 5, 3, 0, 0], [0, 0, 0, 0, 0, 5]] DivMatrix = [[[0, -15, 3, -40, -28, 14], [15, 0, 18, -25, -13, 29], [-3, -18, 0, -43, -31, 11], [40, 25, 43, 0, 12, 54], [28, 13, 31, -12, 0, 42], [-14, -29, -11, -54, -42, 0]], [[0, 32, 30, 10, 18, -6], [-32, 0, -2, -22, -14, -38], [-30, 2, 0, -20, -12, -36], [-10, 22, 20, 0, 8, -16], [-18, 14, 12, -8, 0, -24], [6, 38, 36, 16, 24, 0]], [[0, -4, -2, 4, 0, 1], [4, 0, 2, 8, 4, 5], [2, -2, 0, 6, 2, 3], [-4, -8, -6, 0, -4, -3], [0, -4, -2, 4, 0, 1], [-1, -5, -3, 3, -1, 0]], [[-0.0, 4.299999999999999, 1.7999999999999998, 2.0999999999999996, -3.4000000000000004, -1.8000000000000003], [-4.299999999999999, -0.0, -2.499999999999999, -2.1999999999999993, -7.699999999999999, -6.1], [-1.7999999999999998, 2.499999999999999, -0.0, 0.2999999999999998, -5.2, -3.6], [-2.0999999999999996, 2.1999999999999993, -0.2999999999999998, -0.0, -5.5, -3.9], [3.4000000000000004, 7.699999999999999, 5.2, 5.5, 0, 1.6], [1.8000000000000003, 6.1, 3.6, 3.9, -1.6, -0.0]], [[0, -7, -4, -1, -5, -3], [7, 0, 3, 6, 2, 4], [4, -3, 0, 3, -1, 1], [1, -6, -3, 0, -4, -2], [5, -2, 1, 4, 0, 2], [3, -4, -1, 2, -2, 0]], [[0, 4, -2, -5, -3, -1], [-4, 0, -6, -9, -7, -5], [2, 6, 0, -3, -1, 1], [5, 9, 3, 0, 2, 4], [3, 7, 1, -2, 0, 2], [1, 5, -1, -4, -2, 0]]] </code></pre> <p>I want to create a list of lists with the same size as <code>DivMatrix</code>. The creation must start with a for loop and then with 6 different if statements, each one of them representing a type equation with <code>nc[3]</code>. I want to build the first if statement and then I will build the others which are more complicated.I have this algorithm so far but it is wrong.</p> <pre><code>pref_indic = [] for x in range(len(crt)): if (nc[3][x] == 1): prolist = [] for y in range(len(DivMatrix[x])): prolist2 = [] for z in range(len(DivMatrix[x])): if (DivMatrix[y][z]&lt;=0): prolist2.append(0) else: prolist2.append(1) prolist.append(prolist2) pref_indic.append(prolist) else: print "wrong function type" print pref_indic </code></pre> <p>If the <code>nc[3][x] = 1</code> which means if the type is type 1, then if the value in <code>DivMatrix[x]&lt;=0</code> then append 0, else append 1.</p> <p>So as a result, for <code>nc[3][4]</code> which is equal to 1, I will get the following list appended:</p> <pre><code>pref_indic[4] = [[0, 0, 0, 0, 0, 0], [1, 0, 1, 1, 1, 1], [1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0], [1, 0, 1, 1, 0, 1], [1, 0, 0, 1, 0, 0]] </code></pre> <p>Sorry for the size of the post.</p>
0
2016-08-25T14:10:27Z
39,148,912
<p>Does this answer your question?</p> <pre><code>pref_indic = [] for x in range(len(crt)): if nc[3][x] == 1: prolist = [] for y in range(len(DivMatrix[x])): prolist2 = [] for z in range(len(DivMatrix[x][y])): if DivMatrix[x][y][z] &lt;= 0: prolist2.append(0) else: prolist2.append(1) prolist.append(prolist2) pref_indic.append(prolist) elif nc[3][x] == 2: # add code here elif nc[3][x] == 3: # add code here elif nc[3][x] == 4: # add code here # ...etc else: print "wrong function type" print pref_indic </code></pre>
0
2016-08-25T15:12:47Z
[ "python", "list", "if-statement", "for-loop", "append" ]
How to append values to a list of lists using other list of lists and doing mathematical operations
39,147,612
<p>I have several lists of lists:</p> <pre><code>crt = [[80, 90, 6, 5.4, 8, 5], [65, 58, 2, 9.7, 1, 1], [83, 60, 4, 7.2, 4, 7], [40, 80, 10, 7.5, 7, 10], [52, 72, 6, 2, 3, 8], [94, 96, 7, 3.6, 5, 6]] nc = [[1, 2, 3, 4, 5, 6], [1, 1, 1, 1, 1, 1], [-1, 1, -1, -1, -1, 1], [2, 3, 5, 6, 1, 6], [10, 0, 0.5, 1, 0, 0], [0, 30, 5, 3, 0, 0], [0, 0, 0, 0, 0, 5]] DivMatrix = [[[0, -15, 3, -40, -28, 14], [15, 0, 18, -25, -13, 29], [-3, -18, 0, -43, -31, 11], [40, 25, 43, 0, 12, 54], [28, 13, 31, -12, 0, 42], [-14, -29, -11, -54, -42, 0]], [[0, 32, 30, 10, 18, -6], [-32, 0, -2, -22, -14, -38], [-30, 2, 0, -20, -12, -36], [-10, 22, 20, 0, 8, -16], [-18, 14, 12, -8, 0, -24], [6, 38, 36, 16, 24, 0]], [[0, -4, -2, 4, 0, 1], [4, 0, 2, 8, 4, 5], [2, -2, 0, 6, 2, 3], [-4, -8, -6, 0, -4, -3], [0, -4, -2, 4, 0, 1], [-1, -5, -3, 3, -1, 0]], [[-0.0, 4.299999999999999, 1.7999999999999998, 2.0999999999999996, -3.4000000000000004, -1.8000000000000003], [-4.299999999999999, -0.0, -2.499999999999999, -2.1999999999999993, -7.699999999999999, -6.1], [-1.7999999999999998, 2.499999999999999, -0.0, 0.2999999999999998, -5.2, -3.6], [-2.0999999999999996, 2.1999999999999993, -0.2999999999999998, -0.0, -5.5, -3.9], [3.4000000000000004, 7.699999999999999, 5.2, 5.5, 0, 1.6], [1.8000000000000003, 6.1, 3.6, 3.9, -1.6, -0.0]], [[0, -7, -4, -1, -5, -3], [7, 0, 3, 6, 2, 4], [4, -3, 0, 3, -1, 1], [1, -6, -3, 0, -4, -2], [5, -2, 1, 4, 0, 2], [3, -4, -1, 2, -2, 0]], [[0, 4, -2, -5, -3, -1], [-4, 0, -6, -9, -7, -5], [2, 6, 0, -3, -1, 1], [5, 9, 3, 0, 2, 4], [3, 7, 1, -2, 0, 2], [1, 5, -1, -4, -2, 0]]] </code></pre> <p>I want to create a list of lists with the same size as <code>DivMatrix</code>. The creation must start with a for loop and then with 6 different if statements, each one of them representing a type equation with <code>nc[3]</code>. I want to build the first if statement and then I will build the others which are more complicated.I have this algorithm so far but it is wrong.</p> <pre><code>pref_indic = [] for x in range(len(crt)): if (nc[3][x] == 1): prolist = [] for y in range(len(DivMatrix[x])): prolist2 = [] for z in range(len(DivMatrix[x])): if (DivMatrix[y][z]&lt;=0): prolist2.append(0) else: prolist2.append(1) prolist.append(prolist2) pref_indic.append(prolist) else: print "wrong function type" print pref_indic </code></pre> <p>If the <code>nc[3][x] = 1</code> which means if the type is type 1, then if the value in <code>DivMatrix[x]&lt;=0</code> then append 0, else append 1.</p> <p>So as a result, for <code>nc[3][4]</code> which is equal to 1, I will get the following list appended:</p> <pre><code>pref_indic[4] = [[0, 0, 0, 0, 0, 0], [1, 0, 1, 1, 1, 1], [1, 0, 0, 1, 0, 1], [1, 0, 0, 0, 0, 0], [1, 0, 1, 1, 0, 1], [1, 0, 0, 1, 0, 0]] </code></pre> <p>Sorry for the size of the post.</p>
0
2016-08-25T14:10:27Z
39,149,268
<p>here is your code, modified just enough to do what you want (I guess, not sure):</p> <pre><code>pref_indic = [] for x in range(len(crt)): if (nc[3][x] == 1): prolist = [] for y in range(len(DivMatrix[x])): prolist2 = [] for z in range(len(DivMatrix[x][y])): if (DivMatrix[x][y][z]&lt;=0): prolist2.append(0) else: prolist2.append(1) prolist.append(prolist2) pref_indic.append(prolist) else: pref_indic.append("wrong function type") print pref_indic </code></pre> <hr> <p>here is now something more readable (but limited because I don't know what kind of data I am manipulating):</p> <pre><code>def process_eq_type_1(div_matrix_element): prolist = [] for element_of_element in div_matrix_element: prolist2 = [] for element_of_element_of_element in element_of_element: if element_of_element_of_element &lt;= 0: prolist2.append(0) else: prolist2.append(1) prolist.append(prolist2) return prolist def process_eq_type_2(div_matrix_element): return "eq type 2 not implemented" def process_eq_type_3(div_matrix_element): return "eq type 3 not implemented" pref_indic = [] for eq_type, unclear_data in zip(nc[3], DivMatrix): if (eq_type == 1): pref_indic.append(process_eq_type_1(unclear_data)) elif (eq_type == 2): pref_indic.append(process_eq_type_2(unclear_data)) elif (eq_type == 3): pref_indic.append(process_eq_type_3(unclear_data)) else: pref_indic.append("wrong function type") print pref_indic </code></pre> <p>it does quite exactly the same thing but:</p> <ol> <li>the main loop is simplified by: <ul> <li>using <a href="https://docs.python.org/2/library/functions.html?highlight=zip#zip" rel="nofollow">zip</a> to link the two list to iterate and retrieving directly the wanted values instead of using an index</li> <li>using <a href="https://docs.python.org/2/tutorial/controlflow.html#defining-functions" rel="nofollow">function</a> for each case to process (only the first kind of process is implemented, but more functions already exist)</li> <li>using "explicit" names for variables</li> </ul></li> <li>the processing code for the case where nc[3] == 1 is extracted in a function, improving readability</li> <li>accessing data by indexes is banished as far as possible</li> </ol> <p>it is far more readable and intelligible in my opinion (hope you will agree).</p> <hr> <p>using some Python tricks you could make the process_eq_type_1 yet more concise:</p> <pre><code>def process_eq_type_1(div_matrix_element): prolist = [] for element_of_element in div_matrix_element: prolist2 = [] for element_of_element_of_element in element_of_element: prolist2.append(int(element_of_element_of_element &gt; 0)) prolist.append(prolist2) return prolist </code></pre> <p>or using <a href="https://docs.python.org/2/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehension</a>:</p> <pre><code>def process_eq_type_1(div_matrix_element): prolist = [] for element_of_element in div_matrix_element: prolist.append([int(element_of_element_of_element &gt; 0) for element_of_element_of_element in element_of_element]) return prolist </code></pre> <hr> <p><strong>final advice</strong>: you may want to read <a href="https://docs.python.org/2/tutorial/" rel="nofollow">the Python tutorial</a></p>
0
2016-08-25T15:31:26Z
[ "python", "list", "if-statement", "for-loop", "append" ]
Profile cpu and memory usage during py.test execution
39,147,678
<p>I am facing the following project. I want to create pictures showing the cpu and memory level during the execution of a set of performance test suites. I would appreciate any suggestion.</p> <p>Currently the only approach I am considering is to use the command top or the python module <a href="https://pypi.python.org/pypi/psutil" rel="nofollow">psutil</a> and execute them in parallel to the tests. However I was wondering whether there exists already a better approach, may be a py.test plugin.</p> <p>A nice to have would be be able to compare those parameters from one execution to another.</p> <p>The tests are executed Under Linux (Ubuntu).</p>
0
2016-08-25T14:13:11Z
39,216,968
<p>There are a whole bunch of ways of doing this, ranging from getting broad system statistics and then averaging them (top), to using processor hardware counters (e.g. using Intel VTune).</p> <p>psutil seems perfectly fine. My only comment is to make sure you take many measurements and then average them to get rid of spurious spikes and such.</p> <p>Some other possible ways of taking these measurements are <a href="http://linux.die.net/man/5/proc" rel="nofollow">/proc/[pid]/stat</a> (see man page), <a href="http://linux.about.com/od/commands/fl/Run-A-Command-And-Return-Time-Statistics-Using-The-time-Command.htm" rel="nofollow">time</a>, or if you get really obsessive, you can use some programatic techniques, e.g. for <a href="http://stackoverflow.com/questions/63166/how-to-determine-cpu-and-memory-consumption-from-inside-a-process">Windows</a>.</p> <p>Here's a <a href="http://nadeausoftware.com/articles/2012/03/c_c_tip_how_measure_cpu_time_benchmarking" rel="nofollow">good discussion</a> about programmatically getting benchmarking values. It also discusses some of the traps you can get into, which you should be familiar with even if you are not using a programmatic method.</p> <p>Intel has a lot of good information about processor benchmarking; it's their bread and butter.</p> <p>The only other comment I can make is that you need to select your benchmark carefully. Intel emphasizes CPU because it is what they are best at. The same is true for other companies. In truth, there are a whole host of <a href="https://en.wikipedia.org/wiki/Benchmark_(computing)" rel="nofollow">other important factors</a> that come into play depending upon the application domain.</p> <p>Look at the different media-based benchmarks. They may be more appropriate than one simply based upon processor time. I can't readily find the benchmarks but bing is a wonder.</p>
1
2016-08-30T00:05:49Z
[ "python", "memory", "cpu-usage", "py.test" ]
Python: ImportError: cannot import name 'BeautifulSoup'
39,147,715
<p>I have always used R and now trying to switch to Python. I'm using Pycharm and found this error when running the following code:</p> <pre><code>import pandas as pd from bs4 import BeautifulSoup example1 = BeautifulSoup(train["review"][0],"lxml") print (example1.get_text()) </code></pre> <p>When I run it I have: </p> <pre><code>ImportError: cannot import name 'BeautifulSoup' </code></pre> <p>But I don't have any problem using the console. The rest of the code works fine both with the Run command/terminal and console.</p> <p>Thank you for your help</p>
0
2016-08-25T14:14:21Z
39,159,068
<p>Oh,I think you should check your file name or folder name.If there is a name that is already used in bs4 module,you will got ImportError.</p> <p>Hope this helps.</p>
0
2016-08-26T05:45:47Z
[ "python", "python-3.x", "console", "pycharm" ]
Selecting audio device for playback via Python
39,147,723
<p>How to get a list of audio devices in linux (like <code>aplay -L</code>) and select audio device for the output? are there any libs to import? Are they already imported? </p>
1
2016-08-25T14:14:47Z
39,148,338
<p>I searched high and low for what you are asking for when writing a sound equaliser and never found a satisfactory answer.<br> There is an alsaaudio library available:</p> <pre><code>import alsaaudio #alternative method pure python for device_number, card_name in enumerate(alsaaudio.cards()): print device_number, card_name </code></pre> <p>I ended up banging <code>pacmd</code> and <code>cat</code> options onto the command line, retrieving and parsing the results to discover what was what.<br> Examples: </p> <pre><code> sink_list = os.popen('cat /proc/asound/cards | grep "\[" | cut -c2').readlines() for s in sink_list: s = s.strip() self.sinks_available.append("hw:"+s) </code></pre> <p>for pulseaudio you need <code>pacmd</code></p> <pre><code># Identify the default sound card device sink = os.popen('pacmd list | grep "device.master_device" | cut --delimiter== -f2').readline() if sink =="": sink = os.popen('pacmd list-cards | grep -C1 sinks | grep pci | cut --delimiter=/ -f1').readline() </code></pre> <p>It's all most unsatisfactory and un-python like but needs must when the devil drives</p>
1
2016-08-25T14:43:56Z
[ "python", "linux", "python-3.x", "audio" ]
SQLalchemy - query by like for float column
39,147,924
<p>I want to query my database for records like a float variable (map coordinates) from an ajax.(querying float column). i'm not sure if the like method can query data types other than strings, because this didn't work...</p> <pre><code>data = json.loads(request.data) markers = session.query(Markers) \ .filter( Markers.lat.like( '%' + data['lat'] + '%' ) ) \ .filter( Markers.lng.like( '%' + data['lng'] + '%' ) ) \ .order_by(func.random()).limit(7).all() if len(markers) &lt;= 0: return jsonify( resp = 'no results' ) else: return jsonify( resp = 'markers', markers = [m.serialize for m in markers] ) </code></pre> <p>i even tried to make it a string with str(), but still get this error:</p> <pre><code> ProgrammingError: (ProgrammingError) operator does not exist: double precision ~~ unknown LINE 3: WHERE markers.lat LIKE '%%' AND markers.lng LIKE '%%' ORDER ... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. 'SELECT markers.id AS markers_id, markers.type AS markers_type, markers.name AS markers_name, markers.location AS markers_location, markers.lat AS markers_lat, markers.lng AS markers_lng, markers.icon AS markers_icon, markers.message AS markers_message, markers.date AS markers_date, markers.place_id AS markers_place_id, markers.owner AS markers_owner \nFROM markers \nWHERE markers.lat LIKE %(lat_1)s AND markers.lng LIKE %(lng_1)s ORDER BY random() \n LIMIT %(param_1)s' {'lng_1': '%%', 'param_1': 7, 'lat_1': '%%'} </code></pre> <p>what's wrong? does the sqlalchemy func module have a way of querying float columns as a string? how do i fix this? Thanks!</p> <p>p.s i am using postgresql</p>
2
2016-08-25T14:23:50Z
39,152,989
<p>You need to cast float to string</p> <pre><code>from sqlalchemy import cast, String markers = session.query(Markers) \ .filter(cast(Markers.lat, String()).like('%' + data['lat'] + '%')) </code></pre>
1
2016-08-25T19:07:41Z
[ "python", "postgresql", "sqlalchemy" ]
Errno 13 Permission denied with Django on a directory I don't want to use
39,147,935
<p>I have this error appearing in my Django app on my production server :</p> <blockquote> <p>[Errno 13] Permission denied: '/var/www/.config'</p> </blockquote> <p>I never asked to access to this unexisting file or directory in my code. The server is running in a different directory defined in my httpd.conf and I haven't defined the use of any <em>/var/www/</em> elements in my Django settings.</p> <p>In my case I'm using the biopython library with Django :</p> <pre><code>from Bio import Entrez Entrez.email = "my@email" handle = Entrez.efetch("taxonomy", id="123, 1") records = Entrez.parse(handle) </code></pre> <p>This code is working in a python console on the server. But the instruction <code>Entrez.parse(handle)</code> return the error in a Django environment.</p> <p><strike>I haven't seen any instruction asking to write or open anything in the source code of the function so it seems to be a problem with Django?</strike></p> <p>Is it a configuration problem? A background Django function trying to access to a file when I call a specific function?</p> <p>My configuration :</p> <ul> <li>Python 3.3</li> <li>Django 1.8</li> <li>Biopython 1.67</li> </ul>
1
2016-08-25T14:24:25Z
39,148,146
<p>Restart the server or restart the service of django.<br> That is important, because the services in the background have to know the new location of the configuration. <br> I guess it works on python, because the library is loading the actual settings and the background service is using the old one.</p> <p>Hope I could help</p>
0
2016-08-25T14:34:11Z
[ "python", "django", "apache", "python-3.x", "biopython" ]
Errno 13 Permission denied with Django on a directory I don't want to use
39,147,935
<p>I have this error appearing in my Django app on my production server :</p> <blockquote> <p>[Errno 13] Permission denied: '/var/www/.config'</p> </blockquote> <p>I never asked to access to this unexisting file or directory in my code. The server is running in a different directory defined in my httpd.conf and I haven't defined the use of any <em>/var/www/</em> elements in my Django settings.</p> <p>In my case I'm using the biopython library with Django :</p> <pre><code>from Bio import Entrez Entrez.email = "my@email" handle = Entrez.efetch("taxonomy", id="123, 1") records = Entrez.parse(handle) </code></pre> <p>This code is working in a python console on the server. But the instruction <code>Entrez.parse(handle)</code> return the error in a Django environment.</p> <p><strike>I haven't seen any instruction asking to write or open anything in the source code of the function so it seems to be a problem with Django?</strike></p> <p>Is it a configuration problem? A background Django function trying to access to a file when I call a specific function?</p> <p>My configuration :</p> <ul> <li>Python 3.3</li> <li>Django 1.8</li> <li>Biopython 1.67</li> </ul>
1
2016-08-25T14:24:25Z
39,148,897
<p>In facts, <code>Entrez.parse</code> is calling the <strong>DataHandler</strong> objects. This objects try to write in the user directory with something like : </p> <pre><code>home = os.path.expanduser('~') directory = os.path.join(home, '.config', 'biopython') local_xsd_dir = os.path.join(directory, 'Bio', 'Entrez', 'XSDs') os.makedirs(local_xsd_dir) </code></pre> <p>Because biopython user is the httpd user, the home directory is <strong>/var/www/</strong>.</p> <p>The solution is here to allow <em>apache</em> to write into <em>/var/www</em> or to move it to a different place.</p>
1
2016-08-25T15:12:16Z
[ "python", "django", "apache", "python-3.x", "biopython" ]
Python, select a specific line
39,147,958
<p>I want to read a textfile using python and print out specific lines. The problem is that I want to print a line which starts with the word "nominal" (and I know how to do it) and the line following this which is not recognizable by some specific string. Could you point me to some lines of code that are able to do that? </p>
0
2016-08-25T14:25:36Z
39,148,098
<p>In good faith and under the assumption that this will help you start coding and showing some effort, here you go:</p> <pre><code>file_to_read = r'myfile.txt' with open(file_to_read, 'r') as f_in: flag = False for line in f_in: if line.startswith('nominal'): print(line) flag = True elif flag: print(line) flag = False </code></pre> <p>it might work out-of-the-box but please try to spend some time going through it and you will definitely get the logic behind it. Note that text comparison in <code>python</code> is case sensitive.</p>
0
2016-08-25T14:32:09Z
[ "python" ]
Python, select a specific line
39,147,958
<p>I want to read a textfile using python and print out specific lines. The problem is that I want to print a line which starts with the word "nominal" (and I know how to do it) and the line following this which is not recognizable by some specific string. Could you point me to some lines of code that are able to do that? </p>
0
2016-08-25T14:25:36Z
39,148,647
<p>If the file isn't too large, you can put it all in a list:</p> <pre><code>def printLines(fname): with open(fname) as f: lines = f.read().split('\n') if len(lines) == 0: return None if lines[0].startswith('Nominal'): print(lines[0]) for i, line in enumerate(lines[1:]): if lines[i-1].startswith('Nominal') or line.startswith('Nominal'): print(line) </code></pre> <p>Then e.g. <code>printLines('test.txt')</code> will do what you want.</p>
0
2016-08-25T14:59:31Z
[ "python" ]
Hex to a String Python
39,147,995
<p>I would like to convert </p> <p>the hex value </p> <pre><code>a = 0x32 </code></pre> <p>to a string <code>d = 32</code></p> <p>Bascially I have a numpy array </p> <pre><code>msg = np.array[2, 50] </code></pre> <p>I need to convert both values to hex --- <code>[0x02 , 0x32]</code> then print the hex values as strings on GUI as 2, 32</p>
-2
2016-08-25T14:27:38Z
39,148,109
<p><code>hex()</code> will give you hex string. Then discard first 2 characters</p> <pre><code>&gt;&gt;&gt; hex(a) '0x32' &gt;&gt;&gt; hex(a)[2:] '32' &gt;&gt;&gt; </code></pre> <p>Looking at the link to duplicate, it seems numpy is giving you the L at the end since you are running 64bit linux. so do this:</p> <pre><code>hex(a)[2:-1] </code></pre>
0
2016-08-25T14:32:29Z
[ "python", "string", "numpy", "hex" ]
Condensing repeat code with a "for" statement using strings - Python
39,148,047
<p>I am very new with "for" statements in Python, and I can't get something that I think should be simple to work. My code that I have is: </p> <pre><code>import pandas as pd df1 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) df2 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) df3 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) DF1 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) DF2 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) DF3 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) </code></pre> <p>Then:</p> <pre><code>A1 = len(df1.loc[df1['Column1'] &lt;= DF1['Column1'].iloc[2]]) Z1 = len(df1.loc[df1['Column1'] &gt;= DF1['Column1'].iloc[3]]) A2 = len(df2.loc[df2['Column1'] &lt;= DF2['Column1'].iloc[2]]) Z2 = len(df2.loc[df2['Column1'] &gt;= DF2['Column1'].iloc[3]]) A3 = len(df3.loc[df3['Column1'] &lt;= DF3['Column1'].iloc[2]]) Z3 = len(df3.loc[df3['Column1'] &gt;= DF3['Column1'].iloc[3]]) </code></pre> <p>As you can see, it is a lot of repeat code with just the identifying numbers being different. So my first attempt at a "for" statement was:</p> <pre><code>Numbers = [1,2,3] for i in Numbers: "A" + str(i) = len("df" + str(i).loc["df" + str(i)['Column1'] &lt;= "DF" + str(i)['Column1'].iloc[2]]) "Z" + str(i) = len("df" + str(i).loc["df" + str(i)['Column1'] &gt;= "DF" + str(i)['Column1'].iloc[3]]) </code></pre> <p>This yielded the SyntaxError: "can't assign to operator". So I tried:</p> <pre><code>Numbers = [1,2,3] for i in Numbers: A = "A" + str(i) Z = "Z" + str(i) A = len("df" + str(i).loc["df" + str(i)['Column1'] &lt;= "DF" + str(i)['Column1'].iloc[2]]) Z = len("df" + str(i).loc["df" + str(i)['Column1'] &gt;= "DF" + str(i)['Column1'].iloc[3]]) </code></pre> <p>This yielded the AttributeError: 'str' object has no attribute 'loc'. I tried a few other things like:</p> <pre><code>Numbers = [1,2,3] for i in Numbers: A = "A" + str(i) Z = "Z" + str(i) df = "df" + str(i) DF = "DF" + str(i) A = len(df.loc[df['Column1'] &lt;= DF['Column1'].iloc[2]]) Z = len(df.loc[df['Column1'] &lt;= DF['Column1'].iloc[3]]) </code></pre> <p>But that just gives me the same errors. Ultimately what I would want is something like:</p> <pre><code>Numbers = [1,2,3] for i in Numbers: Ai = len(dfi.loc[dfi['Column1'] &lt;= DFi['Column1'].iloc[2]]) Zi = len(dfi.loc[dfi['Column1'] &lt;= DFi['Column1'].iloc[3]]) </code></pre> <p>Where the output would be equivalent if I typed:</p> <pre><code>A1 = len(df1.loc[df1['Column1'] &lt;= DF1['Column1'].iloc[2]]) Z1 = len(df1.loc[df1['Column1'] &gt;= DF1['Column1'].iloc[3]]) A2 = len(df2.loc[df1['Column1'] &lt;= DF2['Column1'].iloc[2]]) Z2 = len(df2.loc[df1['Column1'] &gt;= DF2['Column1'].iloc[3]]) A3 = len(df3.loc[df3['Column1'] &lt;= DF3['Column1'].iloc[2]]) Z3 = len(df3.loc[df3['Column1'] &gt;= DF3['Column1'].iloc[3]]) </code></pre>
1
2016-08-25T14:29:38Z
39,151,048
<p>It is "restricted" to generate variables in for loop (you can do that, but it's better to avoid. See other posts: <a href="http://stackoverflow.com/questions/6181935/how-do-you-create-different-variable-names-while-in-a-loop-python">post_1</a>, <a href="http://stackoverflow.com/questions/13603215/using-a-loop-in-python-to-name-variables">post_2</a>).</p> <p>Instead use this code to achieve your goal without generating as many variables as your needs (actually generate only the values in the for loop):</p> <pre><code># Lists of your dataframes Hanimals = [H26, H45, H46, H47, H51, H58, H64, H65] Ianimals = [I26, I45, I46, I47, I51, I58, I64, I65] # Generate your series using for loops iterating through your lists above BPM = pd.DataFrame({'BPM_Base':pd.Series([i_a for i_a in [len(i_h.loc[i_h['EKG-evt'] &lt;=\ i_i[0].iloc[0]]) / 10 for i_h, i_i in zip(Hanimals, Ianimals)]]), 'BPM_Test':pd.Series([i_z for i_z in [len(i_h.loc[i_h['EKG-evt'] &gt;=\ i_i[0].iloc[-1]]) / 30 for i_h, i_i in zip(Hanimals, Ianimals)]])}) </code></pre> <p><strong>UPDATE</strong></p> <p>A more efficient way (iterate over "animals" lists only once):</p> <pre><code># Lists of your dataframes Hanimals = [H26, H45, H46, H47, H51, H58, H64, H65] Ianimals = [I26, I45, I46, I47, I51, I58, I64, I65] # You don't need using pd.Series(), # just create a list of tuples: [(A26, Z26), (A45, Z45)...] and iterate over it BPM = pd.DataFrame({'BPM_Base':i[0], 'BPM_Test':i[1]} for i in \ [(len(i_h.loc[i_h['EKG-evt'] &lt;= i_i[0].iloc[0]]) / 10, len(i_h.loc[i_h['EKG-evt'] &gt;= i_i[0].iloc[-1]]) / 30) \ for i_h, i_i in zip(Hanimals, Ianimals)]) </code></pre>
2
2016-08-25T17:07:16Z
[ "python", "pandas", "for-loop" ]
Condensing repeat code with a "for" statement using strings - Python
39,148,047
<p>I am very new with "for" statements in Python, and I can't get something that I think should be simple to work. My code that I have is: </p> <pre><code>import pandas as pd df1 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) df2 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) df3 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) DF1 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) DF2 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) DF3 = pd.DataFrame({'Column1' : pd.Series([1,2,3,4,5,6])}) </code></pre> <p>Then:</p> <pre><code>A1 = len(df1.loc[df1['Column1'] &lt;= DF1['Column1'].iloc[2]]) Z1 = len(df1.loc[df1['Column1'] &gt;= DF1['Column1'].iloc[3]]) A2 = len(df2.loc[df2['Column1'] &lt;= DF2['Column1'].iloc[2]]) Z2 = len(df2.loc[df2['Column1'] &gt;= DF2['Column1'].iloc[3]]) A3 = len(df3.loc[df3['Column1'] &lt;= DF3['Column1'].iloc[2]]) Z3 = len(df3.loc[df3['Column1'] &gt;= DF3['Column1'].iloc[3]]) </code></pre> <p>As you can see, it is a lot of repeat code with just the identifying numbers being different. So my first attempt at a "for" statement was:</p> <pre><code>Numbers = [1,2,3] for i in Numbers: "A" + str(i) = len("df" + str(i).loc["df" + str(i)['Column1'] &lt;= "DF" + str(i)['Column1'].iloc[2]]) "Z" + str(i) = len("df" + str(i).loc["df" + str(i)['Column1'] &gt;= "DF" + str(i)['Column1'].iloc[3]]) </code></pre> <p>This yielded the SyntaxError: "can't assign to operator". So I tried:</p> <pre><code>Numbers = [1,2,3] for i in Numbers: A = "A" + str(i) Z = "Z" + str(i) A = len("df" + str(i).loc["df" + str(i)['Column1'] &lt;= "DF" + str(i)['Column1'].iloc[2]]) Z = len("df" + str(i).loc["df" + str(i)['Column1'] &gt;= "DF" + str(i)['Column1'].iloc[3]]) </code></pre> <p>This yielded the AttributeError: 'str' object has no attribute 'loc'. I tried a few other things like:</p> <pre><code>Numbers = [1,2,3] for i in Numbers: A = "A" + str(i) Z = "Z" + str(i) df = "df" + str(i) DF = "DF" + str(i) A = len(df.loc[df['Column1'] &lt;= DF['Column1'].iloc[2]]) Z = len(df.loc[df['Column1'] &lt;= DF['Column1'].iloc[3]]) </code></pre> <p>But that just gives me the same errors. Ultimately what I would want is something like:</p> <pre><code>Numbers = [1,2,3] for i in Numbers: Ai = len(dfi.loc[dfi['Column1'] &lt;= DFi['Column1'].iloc[2]]) Zi = len(dfi.loc[dfi['Column1'] &lt;= DFi['Column1'].iloc[3]]) </code></pre> <p>Where the output would be equivalent if I typed:</p> <pre><code>A1 = len(df1.loc[df1['Column1'] &lt;= DF1['Column1'].iloc[2]]) Z1 = len(df1.loc[df1['Column1'] &gt;= DF1['Column1'].iloc[3]]) A2 = len(df2.loc[df1['Column1'] &lt;= DF2['Column1'].iloc[2]]) Z2 = len(df2.loc[df1['Column1'] &gt;= DF2['Column1'].iloc[3]]) A3 = len(df3.loc[df3['Column1'] &lt;= DF3['Column1'].iloc[2]]) Z3 = len(df3.loc[df3['Column1'] &gt;= DF3['Column1'].iloc[3]]) </code></pre>
1
2016-08-25T14:29:38Z
39,749,385
<p>Figured out a better way to do this that fits my needs. This is mainly so that I will be able to find my method.</p> <pre><code># Change/Add animals and conditions here, make sure they match up directly Animal = ['26','45','46','47','51','58','64','65', '69','72','84'] Cond = ['Stomach','Intestine','Stomach','Stomach','Intestine','Intestine','Intestine','Stomach','Cut','Cut','Cut'] d = [] def CuSO4(): for i in Animal: # load in Spike data A = pd.read_csv('TXT/INJ/' + i + '.txt',delimiter=r"\s+", skiprows = 15, header = None, usecols = range(1)) B = pd.read_csv('TXT/EKG/' + i + '.txt', skiprows = 3) C = pd.read_csv('TXT/ESO/' + i + '.txt', skiprows = 3) D = pd.read_csv('TXT/TRACH/' + i + '.txt', skiprows = 3) E = pd.read_csv('TXT/BP/' + i + '.txt', delimiter=r"\s+").rename(columns={"4 BP": "BP"}) # Count number of beats before/after injection, divide by 10/30 minutes for average BPM. F = len(B.loc[B['EKG-evt'] &lt;= A[0].iloc[0]])/10 G = len(B.loc[B['EKG-evt'] &gt;= A[0].iloc[-1]])/30 # Count number of esophogeal events before/after injection H = len(C.loc[C['Eso-evt'] &lt;= A[0].iloc[0]]) I = len(C.loc[C['Eso-evt'] &gt;= A[0].iloc[-1]]) # Find Trach events after injection J = D.loc[D['Trach-evt'] &gt;= A[0].iloc[-1]] # Count number of breaths before/after injection, divide by 10/30 min for average breaths/min K = len(D.loc[D['Trach-evt'] &lt;= A[0].iloc[0]])/10 L = len(J)/30 # Use Trach events from J to find the number of EE M = pd.DataFrame(pybursts.kleinberg(J['Trach-evt'], s=4, gamma=0.1)) N = M.last_valid_index() # Use N and M to determine the latency, set value to MaxTime (1800s)if EE = 0 O = 1800 if N == 0 else M.iloc[1][1] - A[0].iloc[-1] # Find BP value before/after injection, then determine the mean value P = E.loc[E['Time'] &lt;= A[0].iloc[0]] Q = E.loc[E['Time'] &gt;= A[0].iloc[-1]] R = P["BP"].mean() S = Q["BP"].mean() # Combine all factors into one DF d.append({'EE' : N, 'EE-lat' : O, 'BPM_Base' : F, 'BPM_Test' : G, 'Eso_Base' : H, 'Eso_Test' : I, 'Trach_Base' : K, 'Trach_Test' : L, 'BP_Base' : R, 'BP_Test' : S}) CuSO4() # Create shell DF with animal numbers and their conditions. DF = pd.DataFrame({'Animal' : pd.Series(Animal), 'Cond' : pd.Series(Cond)}) # Pull appended DF from CuSO4 and make it a pd.DF Df = pd.DataFrame(d) # Combine the two DF's df = pd.concat([DF, Df], axis=1) df </code></pre>
0
2016-09-28T13:45:40Z
[ "python", "pandas", "for-loop" ]
Python multiprocessing for shared memory with an array of lists
39,148,106
<p>I need to know if there is a way to share memory for an array of bool lists:</p> <pre><code>s = Array( 'x' , range(10000000)) </code></pre> <p>What do I have to write instead of x to make it an array of lists whose size is 64. Then I have to manipulate "s" in two different processes like these:</p> <pre><code>#First for i in range(0,photoCount): db.newDBS.insert_one({ 'photo' : s[i], 'user_id' : ids[i] }) #Second s[photoCount].append = inPhoto </code></pre> <p>What should be the type? Any help or suggestion appreciated. Thank you!</p>
0
2016-08-25T14:32:21Z
39,163,440
<p>Python <code>Multiprocessing</code> module allows 2 types of shared variables : <code>Array</code>, which is a simple 1D array of a single dtype, and <code>Value</code>, which is just a single value.</p> <p>You can design your own shared variables using ctype, if you know your way in C : see the <a href="https://docs.python.org/2/library/multiprocessing.html#shared-ctypes-objects" rel="nofollow">documentation here.</a></p> <p>If you just need a 2D Array and you don't want to use ctype shared objects, maybe you could flatten your array in a single list and use <code>multiprocessing.Array</code> instead? Then just reshape when your processing is done.</p>
0
2016-08-26T09:51:45Z
[ "python", "multiprocessing", "shared-memory", "python-multiprocessing" ]
join polygons without overlay (and plot)
39,148,200
<p>I'm trying to join a set of polygons to create a single polygon. These polygons (they are not closed as in the last point being equal to the first), their edges are exactly equal at some point:</p> <pre><code>poly1 = [(0,0), (1,0), (1,0.25), (1, 0.5), (1,0.75), (1,1), (0,1)] poly2 = [(2,0), (2,0.25), (1,0.25), (1,0.5), (1,0.75), (2,1)] </code></pre> <p>It is visible that the polygons "connect" at: (1,0.25), (1, 0.5), (1,0.75)</p> <p>How do I join these polygons to a single polygon?</p> <p>My current code:</p> <pre><code>from __future__ import division import pandas as pd from shapely.geometry import Polygon,MultiPolygon import os import glob from shapely.ops import cascaded_union import matplotlib.pyplot as plt from descartes import PolygonPatch basePath = os.path.dirname(os.path.realpath(__file__)) # defines the directory where the current file resides files = glob.glob(os.path.join(basePath, '*.txt')) polygons = [] for f in files: data = pd.read_csv(f, sep=';') # file containing a list of x and y points points = [] for index, point in data.iterrows(): points.append((point['x'], point['y'])) polygons.append(Polygon(points)) u = cascaded_union(polygons) fig2 = plt.figure(2, figsize=(10,10), dpi=90) ax2 = fig2.add_subplot(111) patch2b = PolygonPatch(u, fc=BLUE, ec=BLUE, alpha=1, zorder=2) ax2.add_patch(patch2b) </code></pre> <p>When I run the above code it doesn't work. When I try to get the x, y coords from u I cannot (u is a multipolygon)</p>
0
2016-08-25T14:37:32Z
39,153,528
<p>I think the problem is that your second Polygon has a self-join.</p> <pre><code>poly1 = Polygon([(0,0), (1,0), (1,0.25), (1, 0.5), (1,0.75), (1,1), (0,1)]) poly2 = Polygon([(2,0), (2,0.25), (1,0.25), (1,0.5), (1,0.75), (2,1)]) poly2_corrected = Polygon([(2,0), (1,0.25), (1,0.5), (1,0.75), (2,1)]) </code></pre> <p>Then, we have:</p> <pre><code>poly1 </code></pre> <p><a href="http://i.stack.imgur.com/ljoKK.png" rel="nofollow"><img src="http://i.stack.imgur.com/ljoKK.png" alt="enter image description here"></a></p> <pre><code>poly2 </code></pre> <p><a href="http://i.stack.imgur.com/60x7q.png" rel="nofollow"><img src="http://i.stack.imgur.com/60x7q.png" alt="enter image description here"></a></p> <pre><code>poly2_corrected </code></pre> <p><a href="http://i.stack.imgur.com/Y2uus.png" rel="nofollow"><img src="http://i.stack.imgur.com/Y2uus.png" alt="enter image description here"></a></p> <p>We get an error when we try:</p> <pre><code>u = cascaded_union([poly1, poly2]) </code></pre> <p>But not for:</p> <pre><code>u_corrected = cascaded_union([poly1, poly2_corrected]) u_corrected </code></pre> <p><a href="http://i.stack.imgur.com/I7nUE.png" rel="nofollow"><img src="http://i.stack.imgur.com/I7nUE.png" alt="enter image description here"></a></p> <pre><code>print u </code></pre> <p>POLYGON ((1 0.25, 1 0, 0 0, 0 1, 1 1, 1 0.75, 2 1, 2 0, 1 0.25))</p>
0
2016-08-25T19:42:34Z
[ "python", "shapely" ]
Approximating Numerical 2nd Derivative with Python
39,148,258
<p>To preface this question, I understand that it could be done better. But this is a question in a class of mine and I must approach it this way. We cannot use any built in functions or packages.</p> <p>I need to write a function to approximate the numerical value of the second derivative of a given function using finite difference. The function is below we are using. </p> <p><a href="http://i.stack.imgur.com/4QSsT.jpg" rel="nofollow">2nd Derivative Formula</a> (I lost the login info to my old account so pardon my lack of points and not being able to include images).</p> <p>My question is this: </p> <p>I don't understand how to make the python function accept the input function it is to be deriving. If someone puts in the input <code>2nd_deriv(2x**2 + 4, 6)</code> I dont understand how to evaluate 2x^2 at 6. </p> <p>If this is unclear, let me know and I can try again to describe. Python is new to me so I am just getting my feet wet. </p> <p>Thanks</p>
3
2016-08-25T14:39:44Z
39,148,345
<p>you can pass the function as any other "variable":</p> <pre><code>def f(x): return 2*x*x + 4 def d2(fn, x0, h): return (fn(x0+h) - 2*fn(x0) + fn(x0-h))/(h*h) print(d2(f, 6, 0.1)) </code></pre>
3
2016-08-25T14:44:32Z
[ "python" ]
Approximating Numerical 2nd Derivative with Python
39,148,258
<p>To preface this question, I understand that it could be done better. But this is a question in a class of mine and I must approach it this way. We cannot use any built in functions or packages.</p> <p>I need to write a function to approximate the numerical value of the second derivative of a given function using finite difference. The function is below we are using. </p> <p><a href="http://i.stack.imgur.com/4QSsT.jpg" rel="nofollow">2nd Derivative Formula</a> (I lost the login info to my old account so pardon my lack of points and not being able to include images).</p> <p>My question is this: </p> <p>I don't understand how to make the python function accept the input function it is to be deriving. If someone puts in the input <code>2nd_deriv(2x**2 + 4, 6)</code> I dont understand how to evaluate 2x^2 at 6. </p> <p>If this is unclear, let me know and I can try again to describe. Python is new to me so I am just getting my feet wet. </p> <p>Thanks</p>
3
2016-08-25T14:39:44Z
39,148,439
<p>you can't pass a literal expression, you need a function (or a lambda).</p> <pre><code>def d2(f, x0, h = 1e-9): func = f if isinstance(f, str): # quite insecure, use only with controlled input func = eval ("lambda x:%s" % (f,)) return (func(x0+h) - 2*func(x0) + func(x0-h))/(2*h) </code></pre> <p>Then to use it</p> <pre><code>def g(x): return 2*x**2 + 4 # using explicit function, forcing h value print d2(g, 6, 1e-10) </code></pre> <p>Or directly:</p> <pre><code># using lambda and default value for h print d2(lambda x:2x**2+4, 6) </code></pre> <p>EDIT</p> <ul> <li>updated to take into account that f can be a string or a function</li> </ul>
0
2016-08-25T14:48:54Z
[ "python" ]
Using ac2git followed by bitbucket
39,148,266
<p>I am using ac2git to convert my accurev depot to git repository. I am able to successfully make the conversion however when I follow the steps after creating the new repository I am unable to push the changes representing the accurev transactions that are now commits.</p> <p>What I mean is I loose the history, I am only able to see the hist and the diff files when I check the commit options on bitbucket.</p> <p>I followed the following steps:</p> <pre><code>python ac2git.py cd existing-project git add --all git commit -m "Initial Commit" git remote add origin http://****@bitbucket.******.git git push -u origin master </code></pre> <p>I am new to bitbucket so I am not sure what the problem is? Has anyone tried this accurev->git->bitbucket before?</p> <p><strong>In other words, how do I move my git repository on my local created as a result of ac2git to a new repository on bitbucket ?</strong></p> <p><a href="http://i.stack.imgur.com/xemvV.png" rel="nofollow"><img src="http://i.stack.imgur.com/xemvV.png" alt="The commit in bitbucket gives me the diff.xml/hist.xml/stream.xml"></a></p>
0
2016-08-25T14:39:59Z
39,153,982
<p>Your first step is to create a repository in BitBucket. Then you simply need to follow BitBucket's instructions:</p> <pre><code>cd /path/to/my/repo git remote add origin http://****@bitbucket.******.git git push -u origin --all # pushes up the repo and its refs for the first time git push origin --tags # pushes up any tags </code></pre>
1
2016-08-25T20:12:30Z
[ "python", "git", "bitbucket" ]
Using ac2git followed by bitbucket
39,148,266
<p>I am using ac2git to convert my accurev depot to git repository. I am able to successfully make the conversion however when I follow the steps after creating the new repository I am unable to push the changes representing the accurev transactions that are now commits.</p> <p>What I mean is I loose the history, I am only able to see the hist and the diff files when I check the commit options on bitbucket.</p> <p>I followed the following steps:</p> <pre><code>python ac2git.py cd existing-project git add --all git commit -m "Initial Commit" git remote add origin http://****@bitbucket.******.git git push -u origin master </code></pre> <p>I am new to bitbucket so I am not sure what the problem is? Has anyone tried this accurev->git->bitbucket before?</p> <p><strong>In other words, how do I move my git repository on my local created as a result of ac2git to a new repository on bitbucket ?</strong></p> <p><a href="http://i.stack.imgur.com/xemvV.png" rel="nofollow"><img src="http://i.stack.imgur.com/xemvV.png" alt="The commit in bitbucket gives me the diff.xml/hist.xml/stream.xml"></a></p>
0
2016-08-25T14:39:59Z
39,311,340
<p>I'm not 100% certain that this is what has happened but it is worth noting that the <strong>ac2git</strong> script stores a lot of metadata under <code>refs/ac2git/*</code> refs, including a refs that will store a <code>hist.xml</code>, <code>streams.xml</code> and <code>diff.xml</code> in their commit history for each of your stream's transactions. See <a href="https://github.com/NavicoOS/ac2git/blob/master/how_it_works.md" rel="nofollow">how_it_works.md</a> which explains about <code>refs/ac2git/depots/&lt;depot_number&gt;/streams/&lt;stream_number&gt;/info</code>.</p> <p>Though this ref acts as a branch, it shouldn't have been pushed up by invoking <code>git push origin -u -all</code> since the documentation claims that this only pushes things under <code>refs/heads/</code>. However, in case of errors the script may not correctly checkout a branch that was converted and it may leave your local repository in a <em>detached HEAD</em> state where it will have actually checked out one of the internal refs.</p> <p>I don't know what a <code>git push origin -u --all</code> would do in this case for a brand new Bitbucket repo but if it had pushed your HEAD ref up to the repo then you would get this metadata on the remote.</p> <p>However, for now this is just a theory and hopefully someone will be able to use this information to piece together a more clear solution for you.</p>
0
2016-09-03T21:07:57Z
[ "python", "git", "bitbucket" ]
ImportError: No module named _mysql
39,148,410
<p>I'm trying to use the Python module MySQL-python to connect to an external MySQL database from an AWS EC2 instance running amazon linux.</p> <p>This is the code I'm trying to run:</p> <pre><code>db=_mysql.connect(host="hostname",user="dbuser",passwd="dbpassword",db="database") db.query("""SELECT id, field1 FROM test""") r=db.store_result() row = r.fetch_row() print row </code></pre> <p>I have installed the python module with pip:</p> <pre><code>sudo pip install MySQL-python </code></pre> <p>When I run the script I get the following error message:</p> <pre><code>Traceback (most recent call last): File "script.py", line 2, in &lt;module&gt; import _mysql ImportError: No module named _mysql </code></pre> <p>When I research this I keep on digging up a lot of solutions for Ubuntu/Debian linux that don't work for amazon linux.</p> <p>How can I fix this error on amazon linux and run the script?</p> <p>Also, from any experienced linux users observing/answering: Is there any advantage to using amazon linux as I try to learn more linux and pick up AWS or would I be better off using an Ubuntu/Debian image? I'm not an experienced linux user as probably shows from the question.</p> <p><strong>Update</strong></p> <p>I've realised that the installation of the package was unsuccessful on the amazon linux server. Here's the full output when I try to run the install via pip:</p> <pre><code>$ sudo pip install MySQL-Python Collecting MySQL-Python Using cached MySQL-python-1.2.5.zip Installing collected packages: MySQL-Python Running setup.py install for MySQL-Python ... error Complete output from command /usr/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-B1IkvH/MySQL-Python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-RNgtpa-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -&gt; build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -&gt; build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -D_GNU_SOURCE -fPIC -fwrapv -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mysql55 -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o -g -pipe -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -fno-strict-aliasing -fwrapv -fPIC -fPIC -g -static-libgcc -fno-omit-frame-pointer -fno-strict-aliasing -DMY_PTHREAD_FASTMUTEX=1 unable to execute 'gcc': No such file or directory error: command 'gcc' failed with exit status 1 ---------------------------------------- Command "/usr/bin/python2.7 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-B1IkvH/MySQL-Python/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-RNgtpa-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-B1IkvH/MySQL-Python/ </code></pre>
3
2016-08-25T14:47:49Z
39,148,708
<p>Only a workaround, but one that worked for me in situations where I could not easily call "sudo pip install".</p> <p>What you (often, not always) can do:</p> <ol> <li>Turn to a system where that python module you are looking for works</li> <li>Identify its "location", for example, after installing enum34 on my ubuntu, the installation would put files under <em>/usr/lib/python2.7/dist-packages/enum</em></li> <li>Put that directory in an archive</li> <li>On your "target" system, extract that archive locally</li> <li>Manipulate the python path to include the locally extracted archive</li> </ol> <p>As said, this isn't beautiful; but if no better answers come in; you have at least something to try ...</p>
1
2016-08-25T15:02:39Z
[ "python", "linux", "amazon-web-services", "amazon-ec2", "mysql-python" ]
How to replace a list of strings in a text where some of them are substrings of other in python?
39,148,421
<p>I have a text containing some words that I would like to tag, and the words to be tagged are contained in a List. The problem is that some of those words are substrings of others, but I want to tag the longest recognized string from the list.</p> <p>For example, if my text is "foo and bar are different from foo bar." and my list contains "foo", "bar" and "foo bar" the result should be "[tag]foo[/tag] and [tag]bar[/tag] are different from [tag]foo bar[/tag]."</p> <pre><code>text = "foo and bar are different from foo bar." words = ["foo", "bar", "foo bar"] tagged = someFunction(text, words) </code></pre> <p>What should be the code of someFunction in such a way that the value of the string taggedText is <code>"&lt;tag&gt;foo&lt;/tag&gt; and &lt;tag&gt;bar&lt;/tag&gt; are different from &lt;tag&gt;foo bar&lt;/tag&gt;."</code> ?</p>
1
2016-08-25T14:48:16Z
39,149,494
<p>If I understood your problem correctly, then this is something you are looking for :-</p> <pre><code>text = "foo and bar are different from foo bar." words = ["foo", "bar", "foo bar"] add_tag = lambda var : "&lt;tag&gt;"+var+"&lt;/tag&gt;" result = '' # for final string for var in text.split(): if var in words: tmp = add_tag(var) else: tmp = var result += " "+tmp print result return result </code></pre> <p>Here <code>add_tag()</code> method is serving what you are looking in <code>someFunction</code>. </p>
0
2016-08-25T15:41:14Z
[ "python", "regex", "string", "substring" ]
How to replace a list of strings in a text where some of them are substrings of other in python?
39,148,421
<p>I have a text containing some words that I would like to tag, and the words to be tagged are contained in a List. The problem is that some of those words are substrings of others, but I want to tag the longest recognized string from the list.</p> <p>For example, if my text is "foo and bar are different from foo bar." and my list contains "foo", "bar" and "foo bar" the result should be "[tag]foo[/tag] and [tag]bar[/tag] are different from [tag]foo bar[/tag]."</p> <pre><code>text = "foo and bar are different from foo bar." words = ["foo", "bar", "foo bar"] tagged = someFunction(text, words) </code></pre> <p>What should be the code of someFunction in such a way that the value of the string taggedText is <code>"&lt;tag&gt;foo&lt;/tag&gt; and &lt;tag&gt;bar&lt;/tag&gt; are different from &lt;tag&gt;foo bar&lt;/tag&gt;."</code> ?</p>
1
2016-08-25T14:48:16Z
39,150,190
<p>A simple way to achieve that would be to sort <code>words</code> by length in the reversed order and then create a regular expression <code>word1|word2|...</code>. Since the re engine always takes the first match, longer strings will be catched first.</p> <pre><code>import re def tag_it(text, words): return re.sub( '|'.join(sorted(words, key=len, reverse=True)), lambda m: '&lt;tag&gt;' + m.group(0) + '&lt;/tag&gt;', text) text = "foo and bar are different from foo bar." words = ["foo", "bar", "foo bar"] print tag_it(text, words) </code></pre>
0
2016-08-25T16:16:30Z
[ "python", "regex", "string", "substring" ]
What's the correct way to change a value that is imported by other modules?
39,148,446
<p>I have my entry point script take a CLI option argument using <code>argsparser</code> and that looks something like this:</p> <pre><code> import some_module if __name__== "__main__": parser = argparse.ArgumentParser(description='Nemo Node.') parser.add_argument('-t', '--test', dest='testing', action="store_true") # handle CLI params and options # ..... some_module.run() </code></pre> <p>I want the <code>-t</code> option to change a parameter <code>TESTING</code> in a config script <code>settings.py</code>, since my <code>some_module</code> uses things like :</p> <pre><code>from settings import TESTING if TESTING: # do some testing stuff </code></pre> <p>Because of this <code>TESTING</code> is already imported into <code>some_module</code> by the time I handle the args, changes to <code>settings.py</code> can no longer have any effect on <code>some_module</code>. My answer is what's the correct practice in dealing with this:</p> <ol> <li>import <code>some_module</code> inside the <code>__main__</code> after the args have been parsed?</li> <li>replace <code>TESTING</code> by <code>settings.TESTING</code> everywhere?</li> <li>something else? </li> </ol>
0
2016-08-25T14:49:14Z
39,149,169
<p>Since <code>some_module.TESTING</code> is set immediately after import, <em>that's</em> the value you want to update, not <code>settings.TESTING</code>.</p> <pre><code>import some_module if __name__== "__main__": parser = argparse.ArgumentParser(description='Nemo Node.') parser.add_argument('-t', '--test', dest='testing', action="store_true") # handle CLI params and options # ..... some_module.TESTING = args.t some_module.run() </code></pre> <p>If the code using <code>TESTING</code> runs at import time as well, then you only option is to avoid importing <code>some_module</code> before you can change <code>settings.TESTING</code>. It's a bit ugly, though. Module-level globals are best thought of as read-only constants, or private implementation details of the module.</p> <p>It also sounds like you are treating <code>settings.py</code> as a configuration file; you may be better off using something like <code>ConfigParser</code> to read a configuration from <code>settings.conf</code>, then passing that configuration (possibly modified based on command-line arguments) to <code>some_module.run()</code>.</p>
0
2016-08-25T15:25:47Z
[ "python" ]
What is being called when doing int() and float()?
39,148,472
<p>I understand that when I do:</p> <pre><code>&gt;&gt;&gt; int(4.0) &gt;&gt;&gt; int('10') </code></pre> <p>The <code>__init__()</code> method from the class of the argument (in the example, <code>float</code> and <code>str</code>, respectively), will be called.</p> <p>I wonder what will happen if I do <code>int()</code>, I mean, without any argument. It wont call <code>__int__()</code> from class <code>NoneType</code>, because it doesn't implement that method.</p> <p>What will happen?</p> <p>Also, does this mean I can only directly call the constructor of class <code>int</code> if the argument is an <code>int</code>?</p> <p>Thanks,</p>
-2
2016-08-25T14:50:54Z
39,149,008
<p>in python <a href="http://stackoverflow.com/a/865963/3220135">everything is an object</a>, so when you call:</p> <p><code>x = int(y)</code> then constructor <code>int.__new__(cls, value=y)</code> is called.</p> <p>this returns an int object and assigns it to <code>x</code>.</p> <p><code>x</code> may have a method bound to it: <code>x.__init__()</code> to control it's setup after creation, but creating the object in the first place is handled by the method <code>__new__()</code> of the base class.</p> <p>If you provide no value to <code>int()</code>, the default value from the constructor call: </p> <p><code>int.__new__(int, value=0)</code> is substituted. Then as you mentioned, <code>int</code> has no <code>__init__</code> method to modify it's setup after creation..</p>
0
2016-08-25T15:18:10Z
[ "python", "constructor", "int" ]
Python importing modules in CMD
39,148,477
<p>Hello thanks for looking. </p> <p>i am trying to import third party modules but having a hard time. </p> <p>I have already done the edit to the environment variable and i get python to show up in cmd but I can not find the correct syntax to do the install. </p> <p>based on the python org site i should use python -m pip install SomePackage</p> <p>i have also read that i should use pip install SomePackage</p> <p>I have tried both and have not had success. I am in windows 10 below is the command prompt of my attempts. </p> <pre><code>C:\Users\T****J&gt;python Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; -m pip install send2trash File "&lt;stdin&gt;", line 1 -m pip install send2trash ^ SyntaxError: invalid syntax &gt;&gt;&gt; pip install send2trash File "&lt;stdin&gt;", line 1 pip install send2trash ^ SyntaxError: invalid syntax &gt;&gt;&gt; python pip install send2trash File "&lt;stdin&gt;", line 1 python pip install send2trash ^ SyntaxError: invalid syntax &gt;&gt;&gt; python -m pip install requests File "&lt;stdin&gt;", line 1 python -m pip install requests ^ SyntaxError: invalid syntax &gt;&gt;&gt; </code></pre> <p>thanks again. searched the best i could and maybe i am missing something easy. I am new at this . </p>
0
2016-08-25T14:51:14Z
39,148,594
<p>you are trying to give command line arguments within the interpreter...</p> <p>If PIP is installed, you don't need to invoke the interpreter at all. Simply call:</p> <pre><code>C:\Users\T****J&gt;pip install send2trash </code></pre> <p>from the command prompt.</p> <p>otherwise, if you are using the pip module, you need to pass the command line arguments to the command line not to the interpreter...</p> <pre><code>C:\Users\T****J&gt;python -m pip install send2trash </code></pre>
1
2016-08-25T14:57:09Z
[ "python", "python-3.5", "python-3.5.2" ]
Python importing modules in CMD
39,148,477
<p>Hello thanks for looking. </p> <p>i am trying to import third party modules but having a hard time. </p> <p>I have already done the edit to the environment variable and i get python to show up in cmd but I can not find the correct syntax to do the install. </p> <p>based on the python org site i should use python -m pip install SomePackage</p> <p>i have also read that i should use pip install SomePackage</p> <p>I have tried both and have not had success. I am in windows 10 below is the command prompt of my attempts. </p> <pre><code>C:\Users\T****J&gt;python Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; -m pip install send2trash File "&lt;stdin&gt;", line 1 -m pip install send2trash ^ SyntaxError: invalid syntax &gt;&gt;&gt; pip install send2trash File "&lt;stdin&gt;", line 1 pip install send2trash ^ SyntaxError: invalid syntax &gt;&gt;&gt; python pip install send2trash File "&lt;stdin&gt;", line 1 python pip install send2trash ^ SyntaxError: invalid syntax &gt;&gt;&gt; python -m pip install requests File "&lt;stdin&gt;", line 1 python -m pip install requests ^ SyntaxError: invalid syntax &gt;&gt;&gt; </code></pre> <p>thanks again. searched the best i could and maybe i am missing something easy. I am new at this . </p>
0
2016-08-25T14:51:14Z
39,148,711
<p><code>pip</code> is a program itself, similar to how <code>npm</code>, <code>bundler</code> or <code>nuget</code> works.</p> <p>What you are currently doing is firing up the Python interpreter, and writing the call to pip from there, it doesn't work like that.</p> <p>What you're looking to do is to install a package with pip, like this:</p> <pre><code>C:\Users\T****J&gt;pip install send2trash </code></pre> <p>and after that's done you can open the interpreter again and import the module like this:</p> <pre><code>C:\Users\T****J&gt;python &gt;&gt;&gt; import send2trash </code></pre> <p>I strongly suggest, however, that you do a bit of research into <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> and how to use it, it will make your life easier on the long run</p>
0
2016-08-25T15:02:49Z
[ "python", "python-3.5", "python-3.5.2" ]
Parse custom XML to JSON or Pandas DataFrame. (Python)
39,148,524
<p>The following is my xml document.</p> <pre><code>&lt;BizTalk xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;Body&gt; &lt;QUEUE&gt; &lt;FILTER FILTERNAME="CorrectAddress" VALUE="1" /&gt; &lt;FILTER FILTERNAME="DaysSinceLastTracking" VALUE="0" /&gt; &lt;FILTER FILTERNAME="DaysSinceShipped" VALUE="3" /&gt; &lt;FILTER FILTERNAME="DaysUntilDelivered" VALUE="735101" /&gt; &lt;FILTER FILTERNAME="DeliveryStatus" VALUE="IN_TRANSIT" /&gt; &lt;FILTER FILTERNAME="Division" VALUE="71" /&gt; &lt;FILTER FILTERNAME="EmptyBox" VALUE="0" /&gt; &lt;FILTER FILTERNAME="FedVendInstructions" VALUE="" /&gt; &lt;FILTER FILTERNAME="ItemDescription" VALUE="bla bla bla" /&gt; &lt;FILTER FILTERNAME="ItemIssue" VALUE="Damaged" /&gt; &lt;FILTER FILTERNAME="ItemValue" VALUE="50" /&gt; &lt;FILTER FILTERNAME="PiecedSet" VALUE="0" /&gt; &lt;FILTER FILTERNAME="HasProofOfDelivery" VALUE="0" /&gt; &lt;FILTER FILTERNAME="RecievedPOD" VALUE="0" /&gt; &lt;FILTER FILTERNAME="RequestedAction" VALUE="Reship" /&gt; &lt;FILTER FILTERNAME="HasReturntracking" VALUE="0" /&gt; &lt;FILTER FILTERNAME="IsStandardFillLocation" VALUE="1" /&gt; &lt;FILTER FILTERNAME="Tampered" VALUE="0" /&gt; &lt;FILTER FILTERNAME="HasTracking" VALUE="1" /&gt; &lt;FILTER FILTERNAME="ShortName" VALUE="BDD" /&gt; &lt;FILTER FILTERNAME="IsBOPS" VALUE="0" /&gt; &lt;FILTER FILTERNAME="WrongItemType" VALUE="" /&gt; &lt;/QUEUE&gt; &lt;RESPONSEDATA&gt; &lt;ITEMS&gt; &lt;DATA CanReOrder="1" UPC="xxxxxxx" Quantity="1" LineNumber="1" Description="bla bla bla" /&gt; &lt;/ITEMS&gt; &lt;DATA ITEM="Reservation" VALUE="????????" /&gt; &lt;DATA ITEM="ShipmentNumber" VALUE="1" /&gt; &lt;DATA ITEM="ContactedBy" VALUE="Shipping Customer" /&gt; &lt;DATA ITEM="PackageRecieved" VALUE="1" /&gt; &lt;DATA ITEM="CheckedEverywhere" VALUE="0" /&gt; &lt;/RESPONSEDATA&gt; </code></pre> <p> </p> <p>How do I convert this custom XML to Pandas DataFrame?</p> <p>I tried some pre-defined coversions using xmljson which throws up error "str object doesn't have attribute tag"</p> <p>I tried using ELementTree and passing the list of element tree object to Pandas and it throws up empty Dataframe:</p> <pre><code>etree = ET.fromstring(xml_data) df = pd.DataFrame(list(etree)) print(df) </code></pre> <p>I'm currently planning to write custom Parser which takes in <strong>FilterName</strong> as Column name, and Value as its field, but that is hard coding. I want to avoid this thing in future, as if more fields are added, I'll have to manually add them which is hassle.</p> <p>Is there some way where I can iterate through each line (That can be done using Loop with Open). And dynamically add columns to Pandas DataFrame? </p> <p>Or is there some efficient way?</p> <p>Note: I checked the validity of XML on <a href="http://www.w3schools.com/xml/xml_validator.asp" rel="nofollow">W3Schools</a> and It says not errors found, so I believe the XML is valid though.</p> <p>Thanks</p>
0
2016-08-25T14:53:29Z
39,149,617
<p>Cool, I found a solution to this. I did the following:</p> <pre><code>df = pd.DataFrame() etree = ET.fromstring(xml_data) # root = etree.getroot() for node in etree.findall('.//FILTER'): parent = node.attrib.get('FILTERNAME') child = node.attrib.get('VALUE') col_name = parent val = child df[col_name] = [val] </code></pre> <p>print(df)</p> <p>Just wanted to post, so that anyone faces similar issue, it can be of help. Thanks</p>
0
2016-08-25T15:47:40Z
[ "python", "json", "xml", "pandas", "xml-parsing" ]
how to change python version used by apache?
39,148,616
<p>When I launch my CGI (common gateway interface) by using this code: </p> <pre><code># -*- coding: utf-8 -*- import cgi import os import json import cgitb cgitb.enable() from sklearn.feature_extraction.text import CountVectorizer print 'Content-type: text/html' print print '&lt;html&gt;&lt;head&gt;&lt;title&gt;Interface Ticket Recognition&lt;/title&gt;&lt;/head&gt;&lt;body&gt;' formulaire = cgi.FieldStorage() os.chdir("C:\Users\iyacine\Desktop") path= os.getcwd() from subprocess import call call(["Python", "applicationV1.py"]) if path=="C:\Users\iyacine\Desktop": print '''changer''' print '&lt;/body&gt;&lt;/html&gt;' </code></pre> <p>I got an error:</p> <p><a href="http://i.stack.imgur.com/ozazm.png" rel="nofollow"><img src="http://i.stack.imgur.com/ozazm.png" alt="enter image description here"></a></p> <p>I try to change the path in environment variable but this work only in cmd. </p> <p>I installed anaconda i my computer and i can run the module sklearn.feature_extraction.text in Spyder but not from Apache. Do you know how to solve this issue please?</p>
0
2016-08-25T14:58:27Z
39,148,966
<p>You should have a first line like <code>#! /usr/bin/python</code> (called Shebang line) in your script. You have to change that line to point to the python executable you actually want. For Windows have a look at <a href="https://docs.python.org/3/using/windows.html?highlight=shebang#shebang-lines" rel="nofollow">the docs</a> but there also is the possibility to run ".bat" files via CGI so you could use a file (eg <code>runmyscript.bat</code>) containing just</p> <pre><code>@C:\path\to\anaconda\python.exe path\to\script.py </code></pre> <p>which is a hacky workaround (I think) but should work, too.</p> <p>In my experience it is the best to use <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> if possible - this does not fix the path-problem directly but helps keeping different applications isolated.</p>
0
2016-08-25T15:15:53Z
[ "python", "html", "apache", "path", "cgi" ]
How Can I Run Python Class in aws lambda environment?
39,148,782
<p>I have a python class include some methods and I want to run it in Lambda Function and test it. I have a problem with executing in lambda environment .I didn't find any example for using class in Lambda function.I have some error for modifying handler and importing Modules .Is it possible using class in lambda Function? (I also tried to upload my file as a zip file but result is the same.)</p>
-1
2016-08-25T15:06:21Z
39,610,969
<p>I have also the same doubt how to run the below code in aws lambda using function.</p> <hr> <p>import base64 import hashlib</p> <p>from Crypto import Random from Crypto.Cipher import AES</p> <p>class AESCipher(object):</p> <pre><code>def __init__(self, key): self.bs = 32 self.key = hashlib.sha256(AESCipher.str_to_bytes(key)).digest() @staticmethod def str_to_bytes(data): u_type = type(b''.decode('utf8')) if isinstance(data, u_type): return data.encode('utf8') return data def _pad(self, s): return s + (self.bs - len(s) % self.bs) * AESCipher.str_to_bytes(chr(self.bs - len(s) % self.bs)) @staticmethod def _unpad(s): return s[:-ord(s[len(s)-1:])] def encrypt(self, raw): raw = self._pad(AESCipher.str_to_bytes(raw)) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return base64.b64encode(iv + cipher.encrypt(raw)).decode('utf-8') def decrypt(self, enc): enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8') cipher = AESCipher(key='abcd') encrypted = cipher.encrypt("Hello World") print(encrypted) new_cipher = AESCipher(key='abcd') decrypted = new_cipher.decrypt('y1sJ7uJITflG81eKHUWd+JkGlOyj3v/iR5HFyiIJv3u9ZpWFCX/XW+A5HS4iPBVb') print(decrypted) </code></pre>
1
2016-09-21T08:13:12Z
[ "python", "amazon-web-services", "aws-lambda" ]
How to trigger next package installation by "no command line activity" in Python
39,148,826
<p>I build installation wizard to application in Python. Recognising all commands included - requires, prior to running - installing of about 20 different packages (project uses different calculation types, like: SVM, FFT, 3D harmonics, K-nearest neighbours, and additional packages for utilising command line and for GUI).</p> <p>All packages - are needed to be installed one-after-another, sequentially (one installation finishes, then I want to start next package installation). During installation - there are different print status indications, which are automatically printed by installation (not me). </p> <p>Eventually - all command line prints stop, and this "lack of activity of CMD" - I want to become trigger to run (by my project) next command for installation of next Python package. I think I may somehow use "stdout" emptiness, or other system entity. Please tell how to implement it, or provide short example, or link to example. Thanks in advance.</p>
0
2016-08-25T15:08:46Z
39,150,256
<p>The default state of most things in programming is to wait for a function/method/process to return before moving on. For example, if you use <a href="https://docs.python.org/3.5/library/subprocess.html#subprocess.run" rel="nofollow">subprocess.run()</a> to run each command involved in installing, it will wait for the process to return before doing the next thing. The same goes for most other ways of installing.</p> <p>In general, unless you explicitly use some form of <a href="https://docs.python.org/3/library/concurrency.html" rel="nofollow">concurrency</a> (or something else that uses such, which will almost certainly say so in the documentation), it's going to wait.</p> <p>So if your install commands are stored in variables <code>cmd1</code>, <code>cmd2</code>, etc, and none take any input once started:</p> <pre><code># some code subprocess.run(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) subprocess.run(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, check=True) # whatever follows that </code></pre> <p>will run <code>cmd1</code>, then run <code>cmd2</code> when <code>cmd1</code> finishes, putting the <code>stdout</code> output of each to the existing <code>stdout</code>, and raising a <code>CalledProcessError</code> and stopping if either one returns non-zero.</p> <p>Note that if you were to watch <code>stdout</code> instead, the result would probably break if anything was slow - a long blank period without actually being done.</p>
0
2016-08-25T16:20:25Z
[ "python", "installation", "install", "installer", "wizard" ]
How do I send emails using django-simple-email-confirmation?
39,148,845
<p>I have just started using <a href="https://github.com/mfogel/django-simple-email-confirmation" rel="nofollow">django-simple-email-confirmation</a>. They have an example of how to use it, which invokes a <code>send_email</code> method, as below:</p> <pre><code>email = 'original@here.com' user = User.objects.create_user(email, email=email) user.is_confirmed # False send_email(email, 'Use %s to confirm your email' % user.confirmation_key) # User gets email, passes the confirmation_key back to your server </code></pre> <p>I was wondering where this <code>send_email</code> method came from. I can't find it by <a href="https://github.com/mfogel/django-simple-email-confirmation/search?utf8=%E2%9C%93&amp;q=send_email" rel="nofollow">searching the repo</a>, besides when they use it in this example (which does not import anything). Everybody else seems to use the <code>send_mail</code> method in django, so I was wondering what exactly was going on here?</p> <p>Thanks</p>
0
2016-08-25T15:09:52Z
39,149,410
<p>The <code>send_email</code> in the example looks like a typo. It looks to me as if they are using <a href="https://docs.djangoproject.com/en/1.10/topics/email/#send-mail" rel="nofollow"><code>send_mail</code></a> from Django. Try adding the following import:</p> <pre><code>from django.core.mail import send_mail </code></pre> <p>Then change the code in the example to use <code>send_mail</code> instead of <code>send_email</code>.</p> <pre><code>send_email(email, 'Use %s to confirm your email' % user.confirmation_key) </code></pre>
0
2016-08-25T15:37:24Z
[ "python", "django", "email" ]
Regular expression for parsing numbers in python
39,148,905
<p>Could anyone help me with the following scenario? </p> <p>NFL season is approaching and I am working on a python script to scrape spreads off a website for analysis. </p> <p>scenario one: spread comes in the form -3+3</p> <p>scenario two: spread comes in the form -3.5+3.5</p> <pre><code>import re s1 = '-3+3' s2 = '-3.5+3.5' search1 = re.search(r'(.\d)(.*)',s1) search2 = re.search(r'(.\d)(.*)',s2) print search1.group(1),','search1.group(2) print search2.group(1),',',search2.group(2) &gt;-3 , +3 &gt;-3 , .5+3.5 </code></pre> <p>As you can see the output of the second scenario chops off anything after the decimal place and places it in front of the next number. Can anyone help me find a solution that would be applicable to both situations? </p> <p>Thanks!</p>
2
2016-08-25T15:12:29Z
39,149,027
<p>You can use <code>re.findall()</code> with <code>'(.\d(?:\.\d+)?)'</code> as your regex, which uses an optional group for matching the decimal part:</p> <pre><code>&gt;&gt;&gt; re.findall(r'(.\d+(?:\.\d+)?)', s1) ['-3', '+3'] &gt;&gt;&gt; re.findall(r'(.\d+(?:\.\d+)?)', s2) ['-3.5', '+3.5'] </code></pre>
3
2016-08-25T15:18:34Z
[ "python", "regex" ]
Regular expression for parsing numbers in python
39,148,905
<p>Could anyone help me with the following scenario? </p> <p>NFL season is approaching and I am working on a python script to scrape spreads off a website for analysis. </p> <p>scenario one: spread comes in the form -3+3</p> <p>scenario two: spread comes in the form -3.5+3.5</p> <pre><code>import re s1 = '-3+3' s2 = '-3.5+3.5' search1 = re.search(r'(.\d)(.*)',s1) search2 = re.search(r'(.\d)(.*)',s2) print search1.group(1),','search1.group(2) print search2.group(1),',',search2.group(2) &gt;-3 , +3 &gt;-3 , .5+3.5 </code></pre> <p>As you can see the output of the second scenario chops off anything after the decimal place and places it in front of the next number. Can anyone help me find a solution that would be applicable to both situations? </p> <p>Thanks!</p>
2
2016-08-25T15:12:29Z
39,149,743
<p>As I said in the comments, this regular expression will grab any pairs of numbers, optionally preceded by +/-, with a decimal or not. </p> <pre><code>([-+]?\d+(?:\.\d+)?)([-+]?\d+(?:\.\d+)?) </code></pre> <p>Also, if you are going to be using the same regular expression more than once (and especially if you will be using it dozens or more times), you should compile it before use:</p> <pre><code>import re pattern = re.compile(r'([-+]?\d+(?:\.\d+)?)([-+]?\d+(?:\.\d+)?)') s1 = '-3+3' s2 = '-3.5+3.5' search1 = pattern.search(s1) search2 = pattern.search(s2) print search1.group(1), "," , search1.group(2) </code></pre> <p>This will increase performance potentially dozens of times over matching a raw string pattern.</p>
2
2016-08-25T15:53:12Z
[ "python", "regex" ]
Regular expression for parsing numbers in python
39,148,905
<p>Could anyone help me with the following scenario? </p> <p>NFL season is approaching and I am working on a python script to scrape spreads off a website for analysis. </p> <p>scenario one: spread comes in the form -3+3</p> <p>scenario two: spread comes in the form -3.5+3.5</p> <pre><code>import re s1 = '-3+3' s2 = '-3.5+3.5' search1 = re.search(r'(.\d)(.*)',s1) search2 = re.search(r'(.\d)(.*)',s2) print search1.group(1),','search1.group(2) print search2.group(1),',',search2.group(2) &gt;-3 , +3 &gt;-3 , .5+3.5 </code></pre> <p>As you can see the output of the second scenario chops off anything after the decimal place and places it in front of the next number. Can anyone help me find a solution that would be applicable to both situations? </p> <p>Thanks!</p>
2
2016-08-25T15:12:29Z
39,150,108
<p>Here's an example that works with multiple digit numbers:</p> <pre><code>import re NUMBERS_RE = '[\-\+]\d*\.?\d+' s1 = '-3+3' s2 = '-3.5+3.5-12.56+300.9998-.2+5' print re.findall(NUMBERS_RE, s1) print re.findall(NUMBERS_RE, s2) </code></pre> <p>This outputs:</p> <pre><code>['-3', '+3'] ['-3.5', '+3.5', '-12.56', '+300.9998', '-.2', '+5'] </code></pre>
0
2016-08-25T16:12:42Z
[ "python", "regex" ]