title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python: Comparing the speed of NumPy and SymPy ufuncified functions
39,118,096
<p>Just wrote a code for comparison of speed of calculation for a function which is in written as <code>numpy</code> and a function which uses <code>ufuncify</code> from <code>sympy</code>:</p> <pre><code>import numpy as np from sympy import symbols, Matrix from sympy.utilities.autowrap import ufuncify u,v,e,a1,a0 = s...
-1
2016-08-24T08:24:41Z
39,121,609
<p>After further exploration it seems that <code>ufuncify</code> and regular <code>numpy</code> functions will give more or less the same speed of computation. Using <code>numba</code> or printing to <code>theano</code> function did not result in a faster code. So the other option to make things faster is either <code>...
0
2016-08-24T11:06:27Z
[ "python", "python-2.7", "numpy", "sympy" ]
python type error after third time in loop in line """print (seql, seq)""" following line with """seql = len(seq)"""
39,118,135
<pre><code>&gt;&gt;&gt; run Python 3.5.1 (default, Dec 2015, 13:05:11) [GCC 4.8.2] on linux 1 [1] 2 [1, 1] Traceback (most recent call last): File "python", line 45, in &lt;module&gt; File "python", line 38, in conwayseq File "python", line 10, in newseq TypeError: object of type 'NoneType' has no len() </code><...
0
2016-08-24T08:26:23Z
39,118,441
<p>The issue is with the logic of your code. Check below line:</p> <pre><code>nseq = newseq(nseq) </code></pre> <p>Function <code>newseq()</code> do not have any return type. So, <code>nseq</code> is getting set as <code>None</code> (<em>default return type</em>). Next time when your <code>for</code> loop makes a cal...
0
2016-08-24T08:41:42Z
[ "python", "types" ]
Django form in the base template. How to display validation error?
39,118,136
<p>I use Django 1.8.14. I have <code>Search</code> form on every page of my website. I pass <code>Search</code> form to base template through context processor. Each time form sends data to <code>/search/</code> view. And there is a problem. Django raises <code>ValidationError</code> on form, but it doesn't display any...
0
2016-08-24T08:26:26Z
39,118,312
<p>You need to pass the form once it is bound to the data (the POST request) and validated; right now your context only has a blank form which is why no errors are being displayed.</p> <pre><code>from django.shortcuts import redirect def search(request, template): search_form = SearchForm(request.POST or None, re...
1
2016-08-24T08:35:41Z
[ "python", "django", "python-2.7", "django-forms" ]
Django form in the base template. How to display validation error?
39,118,136
<p>I use Django 1.8.14. I have <code>Search</code> form on every page of my website. I pass <code>Search</code> form to base template through context processor. Each time form sends data to <code>/search/</code> view. And there is a problem. Django raises <code>ValidationError</code> on form, but it doesn't display any...
0
2016-08-24T08:26:26Z
39,122,019
<p>If you Django is raising <code>validation error</code> how you want it to and now all you need is to <strong>display</strong> that validation error on your <code>html templates</code> then i suppose what you are looking for is <strong>Django Messages</strong></p> <p>See the official documentation for the same -> <a...
1
2016-08-24T11:25:11Z
[ "python", "django", "python-2.7", "django-forms" ]
wsdl file parsing results in 'Unable to resolve type {http://schemas.xmlsoap.org/soap/encoding/}Array.'
39,118,241
<p>First of all, I don't understand the XML and can't figure what problem I am having. I tried using couple of python libraries but most of them resulted in this error. For current setup I am using 'zeep' python library. Using the command for validating file:</p> <pre><code>python -mzeep ss.xml </code></pre> <p>I am ...
1
2016-08-24T08:31:36Z
39,123,839
<p>For anyone who is having the same problem(and it's a known problem), the wsdl needs to import the soap encoding, but it doesn't happen. So see the snippet and use the <code>&lt;types&gt;</code> declaration in the file/response of the server:</p> <pre><code>&lt;definitions targetNamespace="TARGET_NAMESPACE" ...&gt; ...
0
2016-08-24T12:51:03Z
[ "python", "xml", "soap", "wsdl" ]
Resample a 'tidy' dataframe with pandas
39,118,308
<p>I have timestamped data with two columns of interest: a 'label' and a count. I would like to create a time series with the sums per label per, say, day. Can I use <code>resample</code> to achieve this?</p> <p>Concrete example:</p> <pre><code>import pandas as pd import numpy as np from itertools import cycle idx =...
2
2016-08-24T08:35:25Z
39,118,413
<p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.DataFrameGroupBy.resample.html" rel="nofollow"><code>DataFrameGroupBy.resample...
2
2016-08-24T08:40:33Z
[ "python", "pandas" ]
How to distinguish processes in Multiprocessing.Pool?
39,118,353
<p>I'm using python <code>multiprocessing</code> to fork some child processes to run my jobs. There are two demands:</p> <ol> <li>I need to know the pid of the child process in case of killing it if I want.</li> <li>I need callback to do some stuffs after job has finished. Because those stuffs use a lock in parent pro...
0
2016-08-24T08:37:52Z
39,158,063
<p>Finally I find a solution: use <code>multiprocessing.Event</code> instead.</p> <p>Since <code>multiprocessing.Pool</code> can't tell me which process is allocated, I can't record it so that I can kill it according to job id whenever I want.</p> <p>Fortunately, <code>multiprocessing</code> provides <code>Event</cod...
0
2016-08-26T03:58:36Z
[ "python", "linux", "multiprocessing", "fork", "python-multiprocessing" ]
Sorting a list of xy-coordinates in python
39,118,367
<p>I have a long list of xy coordinates like the following:</p> <pre><code>&gt;&gt;&gt; data = [(x1,y1),(x2,y2),(x3,y3),...] </code></pre> <p>Every pair of coordinates represents a point of a contour in an image and I would like to sort them like they are arranged along the contour (shortest path). The shape of the c...
-2
2016-08-24T08:38:43Z
39,118,898
<p>If your shape is 'simple' as your example, you can compute the center of your cloud of points (average of X and Y). Sort your points by the angle from the center to the points and if two of them share the same angle, sort them by their distance from the center. That should do the trick.</p> <pre><code>center = func...
0
2016-08-24T09:02:30Z
[ "python", "sorting", "coordinates", "shortest-path" ]
Sorting a list of xy-coordinates in python
39,118,367
<p>I have a long list of xy coordinates like the following:</p> <pre><code>&gt;&gt;&gt; data = [(x1,y1),(x2,y2),(x3,y3),...] </code></pre> <p>Every pair of coordinates represents a point of a contour in an image and I would like to sort them like they are arranged along the contour (shortest path). The shape of the c...
-2
2016-08-24T08:38:43Z
39,118,932
<p>The problem you described is similar to finding a convex hull. You can have a look <a href="http://tomswitzer.net/2009/12/jarvis-march/" rel="nofollow">here</a></p>
0
2016-08-24T09:04:40Z
[ "python", "sorting", "coordinates", "shortest-path" ]
Sorting a list of xy-coordinates in python
39,118,367
<p>I have a long list of xy coordinates like the following:</p> <pre><code>&gt;&gt;&gt; data = [(x1,y1),(x2,y2),(x3,y3),...] </code></pre> <p>Every pair of coordinates represents a point of a contour in an image and I would like to sort them like they are arranged along the contour (shortest path). The shape of the c...
-2
2016-08-24T08:38:43Z
39,120,360
<p>You can do this by selecting a random point and find the next points from there like</p> <pre><code>def distance(a,b): pass #propably something with math.hypot for euclidean norm points=set([(1,2),(2,3)]) current=points.pop() path=[current] while points: current=min(points,key=(lambda p: distance(curre...
0
2016-08-24T10:09:25Z
[ "python", "sorting", "coordinates", "shortest-path" ]
Sorting a list of xy-coordinates in python
39,118,367
<p>I have a long list of xy coordinates like the following:</p> <pre><code>&gt;&gt;&gt; data = [(x1,y1),(x2,y2),(x3,y3),...] </code></pre> <p>Every pair of coordinates represents a point of a contour in an image and I would like to sort them like they are arranged along the contour (shortest path). The shape of the c...
-2
2016-08-24T08:38:43Z
39,243,504
<p>Update: meanwhile I solved it by using OpenCV's findContours - that outputs the coordinates like I whished! </p>
0
2016-08-31T07:39:17Z
[ "python", "sorting", "coordinates", "shortest-path" ]
slice operation for numpy in python2
39,118,401
<p>If I have a <em>numpy</em> array <strong>X</strong>:</p> <pre><code>array([[ 0.13263767, 0.23149757, 0.57097612], [ 0.49629958, 0.67507182, 0.6758823 ]]) </code></pre> <p>And an index array <strong>Y</strong>:</p> <pre><code>array([1, 2, 1]) </code></pre> <p>I could use <strong>X[0:,Y]</strong> to ind...
2
2016-08-24T08:40:06Z
39,118,614
<p>You can use fancy indexing to achieve that:</p> <pre><code>&gt;&gt;&gt; X[[[0], [1]], Z] array([[ 0.23149757, 0.57097612, 0.23149757], [ 0.49629958, 0.67507182, 0.6758823 ]]) </code></pre> <p>The trick is that the array indexing the first dimension must broadcast with the one indexing the second one. In...
3
2016-08-24T08:50:13Z
[ "python", "arrays", "numpy" ]
How to count rows that share a unique field in pandas
39,118,521
<p>Imagine I have a dataframe that stores the books that individual people have read and their scores for them:</p> <pre><code>df = pd.DataFrame({ 'person' : [1,1,2,2,3,3], 'book' : ['dracula', 'frankenstein', 'dracula', 'frankenstein', 'dracula', 'rebecca'], 'score':[10,11,12,13,14,15] }) df book pe...
3
2016-08-24T08:45:08Z
39,118,598
<p>You can construct a pivot table and multiply it with its transpose:</p> <pre><code>pvt = pd.pivot_table(df, index='book', columns='person', aggfunc=len, fill_value=0) pvt.dot(pvt.T) Out: book dracula frankenstein rebecca book dracula 3 2 ...
3
2016-08-24T08:49:30Z
[ "python", "pandas", "pivot", "pivot-table" ]
How to count rows that share a unique field in pandas
39,118,521
<p>Imagine I have a dataframe that stores the books that individual people have read and their scores for them:</p> <pre><code>df = pd.DataFrame({ 'person' : [1,1,2,2,3,3], 'book' : ['dracula', 'frankenstein', 'dracula', 'frankenstein', 'dracula', 'rebecca'], 'score':[10,11,12,13,14,15] }) df book pe...
3
2016-08-24T08:45:08Z
39,118,642
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.crosstab.html" rel="nofollow"><code>crosstab</code></a>:</p> <pre><code>df = pd.crosstab(df.book, df.person) print (df.dot(df.T)) book dracula frankenstein rebecca book drac...
2
2016-08-24T08:51:27Z
[ "python", "pandas", "pivot", "pivot-table" ]
edit: how to design and implement an experiment to do benchmark comparisons of the two queue implementations in python
39,118,587
<p>I am looking for pointers on how to design an experiment to compare the behaviour of <code>queue</code> implementations one done with <code>python list</code> and the other <code>python queue abstract data type</code> using a benchmark.</p> <p>Here is some code I could put up based on the how I understood <code>amo...
0
2016-08-24T08:48:53Z
39,118,788
<p>You could use Python time.time() to measure execution time for each queue. the test should be run multiple times with at least 1000 elements in the structure to have a "decent" execution time.</p> <pre><code>import time t1 = time.time() for i in range(1, 50000): m.enqueue(i) t2 = time.time() exec_time = t2-t1 </...
0
2016-08-24T08:57:15Z
[ "python", "amortized-analysis", "amortization" ]
Pandas disassemble column
39,118,689
<p>From the documentaiton of pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html</a> a assembly of multiple columns e.g. date columns to a single one is explained.</p> <pre><code>&gt;...
2
2016-08-24T08:53:08Z
39,118,825
<p>You can access the constituent parts of a datetime using the <a href="http://pandas.pydata.org/pandas-docs/stable/api.html#datetimelike-properties" rel="nofollow"><code>dt</code></a> accessor, note that <code>to_datetime</code> returns a <code>Series</code> so I'm converting to a df in order to add columns:</p> <pr...
2
2016-08-24T08:59:27Z
[ "python", "date", "pandas", "dataframe", "split" ]
Pandas disassemble column
39,118,689
<p>From the documentaiton of pandas <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html</a> a assembly of multiple columns e.g. date columns to a single one is explained.</p> <pre><code>&gt;...
2
2016-08-24T08:53:08Z
39,119,245
<p><code>.dt.strftime('%Y %-m %-d').str.split()</code> will reverse the operation</p> <pre><code>df = pd.DataFrame({'year': [2015, 2016], 'month': [2, 3], 'day': [4, 5]}) pd.to_datetime(df) 0 2015-02-04 1 2016-03-05 dtype: datetime64[ns] </code></pre> <hr> <pre><c...
2
2016-08-24T09:19:56Z
[ "python", "date", "pandas", "dataframe", "split" ]
Division of two dataframe with Group by of a Column Pandas
39,118,708
<p>I have a dataframe df_F1 : </p> <pre><code>df_F1.info() </code></pre> <blockquote> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; Int64Index: 2 entries, 0 to 1 Data columns (total 7 columns): class_energy 2 non-null object ACT_TIME_AERATEUR_1_F1 2 non-null float64 ACT_TIME_AERATEUR_1_F3 ...
0
2016-08-24T08:53:42Z
39,118,883
<p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.divide.html" rel="nofollow"><code>DF.divide</code></a> to divide the required columns with their <code>sum</code> along the same columns as shown:</p> <pre><code>df.iloc[:,1:4] = df.iloc[:,1:4].divide(df.sum(axis=1), axis=...
2
2016-08-24T09:02:01Z
[ "python", "pandas", "dataframe", "group-by" ]
insert special characters in mysql database using python angularjs
39,118,967
<p>How do I insert a value in MySQL that consist of single quotes. i.e</p> <p>"I am joy's brother and trying to get a 'job' "</p> <p>The single quote is creating a problems.When I am trying to write some text using single quotes in text field. I am getting an error in the console i.e,.</p> <p>SyntaxError: Unexpect...
-1
2016-08-24T09:06:41Z
39,119,023
<p>You're looking for: </p> <pre><code>conn.escape_string() </code></pre> <p>Look into what escape_string does. In a nutshell it takes your string and replaces the special characters with ex \x00. </p> <p>See: <a href="http://mysql-python.sourceforge.net/MySQLdb.html" rel="nofollow">http://mysql-python.sourceforge.n...
0
2016-08-24T09:09:26Z
[ "python", "mysql", "angularjs" ]
My gauss filter is too slow
39,119,008
<p>I am making a simple gauss blur, and since I could not make scipy's convolve work, I made my own:</p> <pre><code>def Convolve(matr_, ker_): output = matr_.astype(np.float64) for x in range(len(matr_)): for y in range(len(matr_[x])): sum = 0 count = 0 width = int(l...
0
2016-08-24T09:08:42Z
39,119,089
<p>You should never use loops in Python if you can avoid it. Use Numpy or Pandas and work on vectors.</p> <p>If you <em>have</em> to use loops (which doesn't seem to be the case in your example), use the Numba package.</p>
0
2016-08-24T09:12:26Z
[ "python", "scipy" ]
Converting string to date/hour at the 24hour mark: ValueError unconverted data remains: 4
39,119,093
<p>I am trying to extract the date and hour from the following string:</p> <pre><code>string = '3/24/2016 24' # 24 is the hour </code></pre> <p>Using the following code:</p> <pre><code>result = datetime.strptime(string, '%m/%d/%Y %H') </code></pre> <p>However I am running into the following error message: Value...
0
2016-08-24T09:12:32Z
39,119,268
<p>I suppose to handle the corner case of 24, you can parse the date part as a date, then replace the "hour" mod 24, eg:</p> <pre><code>d, t = '3/24/2016 24'.partition(' ')[::2] dt = datetime.strptime(d, '%m/%d/%Y').replace(hour=int(t) % 24) # datetime.datetime(2016, 3, 24, 0, 0) </code></pre>
2
2016-08-24T09:21:11Z
[ "python", "date", "type-conversion", "extract", "strptime" ]
psutil: get cpu of all processes
39,119,119
<p>Maybe I'm overlooking something, but I can't figure out how to get <code>current_process.cpu_percent(interval=0.1)</code> for all processes at once without iterating over them. Currently iteration will take <code>process_count * interval</code> seconds to finish. Is there a way around this?</p> <p>So far I'm doing:...
1
2016-08-24T09:13:39Z
39,121,160
<p>This is a kind of measuring CPU time of each process, so, you cannot avoid <code>process_count * interval</code> seconds in a single Python interpreter process. Maybe, you could reduce the time by means of multiprocessing.</p> <p><a href="https://docs.python.org/3/library/multiprocessing.html" rel="nofollow">https:...
1
2016-08-24T10:45:28Z
[ "python", "python-2.7", "psutil" ]
psutil: get cpu of all processes
39,119,119
<p>Maybe I'm overlooking something, but I can't figure out how to get <code>current_process.cpu_percent(interval=0.1)</code> for all processes at once without iterating over them. Currently iteration will take <code>process_count * interval</code> seconds to finish. Is there a way around this?</p> <p>So far I'm doing:...
1
2016-08-24T09:13:39Z
39,138,890
<p>In order to calculate CPU% you necessarily have to wait. You don't have to wait 0.1 secs <strong>for each process/iteration</strong> though. Instead, iterate over all processes, call cpu_percent() with interval=0, ignore the return value then wait 0.1 secs (or more). The second time you iterate over all processes...
2
2016-08-25T07:12:41Z
[ "python", "python-2.7", "psutil" ]
How to plot bar graph interactively based on value of dropdown widget in bokeh python?
39,119,140
<p>I want to plot the bar graph based value of dropdown widget.</p> <p><strong>Code</strong></p> <pre><code>import pandas as pd from bokeh.io import output_file, show from bokeh.layouts import widgetbox from bokeh.models.widgets import Dropdown from bokeh.plotting import curdoc from bokeh.charts import Bar, output_fi...
0
2016-08-24T09:14:48Z
39,127,871
<p>For 1.) you are referencing it before assigning it. Look at the <code>df['item']==dropdown.value</code> inside the square brackets. That happens <em>first</em> before the assignment. As to why this matters, that's how Python works. All assignments in a function by default create <em>local</em> variables. But before ...
0
2016-08-24T15:52:03Z
[ "python", "matplotlib", "plot", "data-visualization", "bokeh" ]
List Accumulation with Append
39,119,300
<p>I want to generate or return an append-accumulated list from a given list (or iterator). For a list like <code>[1, 2, 3, 4]</code>, I would like to get, <code>[1]</code>, <code>[1, 2]</code>, <code>[1, 2, 3]</code> and <code>[1, 2, 3, 4]</code>. Like so:</p> <pre><code>&gt;&gt;&gt; def my_accumulate(iterable): ... ...
3
2016-08-24T09:22:25Z
39,119,482
<p>The easiest way to use <code>accumulate</code> is to make each item in the iterable a list with a single item and then the default function works as expected:</p> <pre><code>from itertools import accumulate acc = accumulate([el] for el in range(1, 5)) res = list(acc) # [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]] </code>...
8
2016-08-24T09:32:02Z
[ "python", "list" ]
Raspberry pi Jasper speech recognition not working
39,119,471
<p>I follow this tutorial <a href="http://jasperproject.github.io/documentation/" rel="nofollow">http://jasperproject.github.io/documentation/</a> I use Debian Jessie so most off them I have to compile. When I want to run jasper.py I get this error: Does anyone knows what the problem can be.</p> <blockquote> <p>DEBU...
-1
2016-08-24T09:31:15Z
39,120,672
<p>I paste my stt.py script on pastebin. <a href="http://pastebin.com/Cy6ziGPk" rel="nofollow">http://pastebin.com/Cy6ziGPk</a> Because I could not manage this on this forum.</p>
0
2016-08-24T10:24:16Z
[ "python", "linux" ]
How to I list down the results of a function (python)
39,119,500
<p>I want to list down the sums taken from numberA. </p> <p>The function "add" prompts the user if he wants to add. If he selects yes, then it will go to the function "numberA". This part will loop. </p> <p>I want to list down the list of the sums when the user selects "N" in the function "add". And finally sum up a...
0
2016-08-24T09:32:53Z
39,119,569
<pre><code>total = [] def numberA(): num1=int(input("Enter First Number")) num2=int(input("Enter Second Number")) total.append(num1+num2) def add(): userSelect = input("Do You Want to Add?" "\n(Y) Yes ; (N) No" "\n") while userSelect != "Y" and userSelect != "N": pr...
0
2016-08-24T09:35:46Z
[ "python" ]
How to I list down the results of a function (python)
39,119,500
<p>I want to list down the sums taken from numberA. </p> <p>The function "add" prompts the user if he wants to add. If he selects yes, then it will go to the function "numberA". This part will loop. </p> <p>I want to list down the list of the sums when the user selects "N" in the function "add". And finally sum up a...
0
2016-08-24T09:32:53Z
39,120,536
<p>This help</p> <pre><code>def add(): ask = True res = [] while ask : num1=int(input("Enter First Number : ")) num2=int(input("Enter Second Number : ")) total = num1+num2 userSelect = input("Do You Want to Add?" "\n(Y) Yes ; (N) No" "\n") if userSele...
0
2016-08-24T10:18:13Z
[ "python" ]
button on press being called before button press
39,119,567
<p>I am trying to add a set of buttons to a grid layout scroll view using for loop. But the on press event is being triggered for all the buttons even before pressing the buttons. How can I fix this?</p> <pre><code>from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.scrollview ...
0
2016-08-24T09:35:42Z
39,119,701
<p>because you are actually calling your callback when passing args:</p> <pre><code>btn.bind(on_press =btnsclicked('b'+str(i), url)) </code></pre> <p>Doc example says:</p> <pre><code>def callback(instance): print('The button &lt;%s&gt; is being pressed' % instance.text) btn1 = Button(text='Hello world 1') btn1.b...
1
2016-08-24T09:40:53Z
[ "python", "button", "event-handling", "kivy", "buttonclick" ]
button on press being called before button press
39,119,567
<p>I am trying to add a set of buttons to a grid layout scroll view using for loop. But the on press event is being triggered for all the buttons even before pressing the buttons. How can I fix this?</p> <pre><code>from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.scrollview ...
0
2016-08-24T09:35:42Z
39,119,790
<p>For <code>on_press</code>, you call the function instead of specifying the function to use. Try:</p> <pre><code>btn.bind(on_press=lambda x: btnsclicked('b' + str(i), url)) </code></pre> <p>If you want to deal with arguments, see <a href="https://kivy.org/docs/api-kivy.event.html" rel="nofollow">Event dispatcher</a...
2
2016-08-24T09:45:31Z
[ "python", "button", "event-handling", "kivy", "buttonclick" ]
django bootstrap modal form redirect on validation failed
39,119,619
<p>I have Bootstrap Modal which contains form. When validation form is failed redirect to the original form page. The question is how to make that server send me response with errors in my bootstrap modal?</p> <p>urls.py</p> <pre><code>url(r'^add/$', CreateCarView.as_view(), name='add_auto'), </code></pre> <p>views....
0
2016-08-24T09:37:44Z
39,121,419
<p>this may look like a hack but you could manually launch the modal if there are errors on the form, something like</p> <pre><code>&lt;form id="add_item" class="form" role="form" action="{% url 'add_auto' %}" method="post"&gt; &lt;div class="modal-header"&gt; &lt;button type="button" class="close" data-dismiss="m...
0
2016-08-24T10:57:44Z
[ "python", "django", "bootstrap-modal" ]
django bootstrap modal form redirect on validation failed
39,119,619
<p>I have Bootstrap Modal which contains form. When validation form is failed redirect to the original form page. The question is how to make that server send me response with errors in my bootstrap modal?</p> <p>urls.py</p> <pre><code>url(r'^add/$', CreateCarView.as_view(), name='add_auto'), </code></pre> <p>views....
0
2016-08-24T09:37:44Z
39,122,111
<p>when you are submitting, normal form submitting is happening, instead you can post using ajax, this is an example ajax code.</p> <pre><code>$(document).on('submit', '#add_item', function() { $.ajax({ type: $(this).attr('method'), url: this.action, data: $(this).serialize(), cont...
0
2016-08-24T11:29:17Z
[ "python", "django", "bootstrap-modal" ]
Import functions on-the-fly without loading all "sibling" modules
39,119,681
<p>I have the following package structure:</p> <pre><code>pkg/ __init__.py f1.py f2.py </code></pre> <p>Each of the <code>fX.py</code> files contains a function with the same name as the file (e.g. <code>f1.py</code> contains the definition of <code>f1</code>). Inside <code>__init__.py</code>, I do the fo...
1
2016-08-24T09:40:04Z
39,120,507
<p>Python import only what you instruct it to import. The correct syntax here would be:</p> <pre><code>from pkg.module import object </code></pre> <p>Then if you remove all the code from <code>__init__.py</code>, the following happens:</p> <pre><code>&gt;&gt;&gt; from pkg.f1 import f1 I am in f1. &gt;&gt;&gt; f1 &lt...
0
2016-08-24T10:16:57Z
[ "python", "python-3.x" ]
How to change the structure of output.xml from Robot Framework output
39,119,873
<p>We are passing three text files to pybot and the output generated is in the hierarchical format. For Example, in Test Statistics section of the report.html file, under Statistics by Suite, <strong>Test 1 &amp; Test 2 &amp; Test 3.Test 1</strong> is observed. It was changed to display just Test 1 by editing the repor...
0
2016-08-24T09:49:03Z
39,122,581
<p>There is no way to modify the format of the output.xml file that was generated by robot. You have a couple of choices. </p> <p>First, you can post-process output.xml with xslt or any other tool to transform it into whatever format you want. It's a very simple structure that is easy to parse. </p> <p>Your second op...
2
2016-08-24T11:52:40Z
[ "python", "xml", "robotframework" ]
Saving a Video in OpenCV (Linux, Python)
39,119,893
<p>There is an example that works on Windows (<a href="https://pythonprogramming.net/loading-video-python-opencv-tutorial/" rel="nofollow">original</a>):</p> <pre><code>import numpy as np import cv2 cap = cv2.VideoCapture(0) fourcc = cv2.VideoWriter_fourcc(*'XDIV') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (64...
1
2016-08-24T09:49:58Z
39,120,292
<p>I didn't try but this should work : </p> <pre><code>fourcc = cv2.cv.CV_FOURCC(*'XVID') </code></pre>
0
2016-08-24T10:06:31Z
[ "python", "linux", "opencv" ]
Celery tasks with the same name
39,119,949
<p>I am implementing a file tree walking script that calls tasks based on the file extension or directory name.</p> <p>My walking code looks like this:</p> <pre><code>from celery import Celery import os app = Celery('tasks', broker='amqp://guest@localhost//') app.conf.update( CELERY_DEFAULT_EXCHANGE = 'path_wal...
0
2016-08-24T09:52:25Z
39,121,211
<p>Answering my own question:</p> <p>It's not possible to have two tasks with the same name in a single celery app. I could split the above into two separate apps and run them with different workers, or provide unique names for the tasks.</p> <p>The key bit of code in celery is here:</p> <p><a href="https://github.c...
0
2016-08-24T10:47:45Z
[ "python", "celery" ]
How can I combine two FITS tables into a single table in new fits file?
39,120,050
<p>I have two fits file data (file1.fits and file2.fits). The first one (file1.fits) consists of 80,700 important rows of data and another one is 140,000 rows. The both of them have the same Header. </p> <pre><code>$ python &gt;&gt;&gt; import pyfits &gt;&gt;&gt; f1 = pyfits.open('file1.fits') &gt;&gt;&gt; f2 = pyfit...
0
2016-08-24T09:57:10Z
39,123,896
<p>I tried with <a href="http://www.astropy.org/" rel="nofollow">astropy</a>:</p> <pre><code>from astropy.table import Table, hstack t1 = Table.read('file1.fits', format='fits') t2 = Table.read('file2.fits', format='fits') new = hstack([t1, t2]) new.write('combined.fits') </code></pre> <p>It seems to work with sampl...
1
2016-08-24T12:53:03Z
[ "python", "fits", "pyfits" ]
Except for non gmail addresses, how do i make gmail addresses to be strictly ending with '@gmail.com' (and not something as '@gmail.com.au', etc)
39,120,263
<p>How to validate an email address in a form to be only as 'gmail.com' but raise an error if the domain name and extension is anything other than 'gmail.com'? I get an error if the email address ends with @gmail.au.com for example</p> <pre><code>from django import forms from .models import User class RegisterForm(f...
-2
2016-08-24T10:05:20Z
39,120,504
<p>You can just check whether or not the email includes <code>@gmail</code> and ends with <code>@gmail.com</code>, theres no need to split it at all</p> <pre><code>if '@gmail' in email and not email.endswith('@gmail.com'): </code></pre>
4
2016-08-24T10:16:54Z
[ "python", "django" ]
Except for non gmail addresses, how do i make gmail addresses to be strictly ending with '@gmail.com' (and not something as '@gmail.com.au', etc)
39,120,263
<p>How to validate an email address in a form to be only as 'gmail.com' but raise an error if the domain name and extension is anything other than 'gmail.com'? I get an error if the email address ends with @gmail.au.com for example</p> <pre><code>from django import forms from .models import User class RegisterForm(f...
-2
2016-08-24T10:05:20Z
39,121,174
<p>There are multiple ways to achieve it. Below are the changes in your code which will make it run. Code further, explore, and let us know for issues :)</p> <pre><code>&gt;&gt;&gt; provider = 'gmail.com.au' &gt;&gt;&gt; provider_list = provider.split('.') &gt;&gt;&gt; domain, extension = provider_list[0], ''.join(pro...
0
2016-08-24T10:46:11Z
[ "python", "django" ]
Organise large dataset into separate lines
39,120,276
<p>I have a large raw data set which I want to organise into separate lines. The data is delimited. I want to organise so there are 8 delimiters in one line followed by a location, then the new line. </p> <p>Raw Data:</p> <p>468|2016-06-17||Mobile|responsive|sport|sport.football.england||London 468|2016-06-16||Mobile...
0
2016-08-24T10:05:48Z
39,122,413
<p>You may try this :</p> <pre><code>data = '''468|2016-06-17||Mobile|responsive|sport|sport.football.england||london 468|2016-06-16||Mobile|responsive|sport|sport.football.european||west midlands 468|2016-06-17||Mobile|responsive|sport|sport.football.england||india''' new = [] for i in data.split(' '): if '|' in...
0
2016-08-24T11:44:00Z
[ "python", "token" ]
Removing non-alphanumeric characters with bash or python
39,120,328
<p>I have much files like these(please see the screenshot): </p> <pre><code>30.230201521829.jpg Mens-Sunglasses_L.180022111040.jpg progressive-sunglasses.180041285287.jpg Atmosphere.222314222509.jpg Womens-Sunglasses-L.180023271958.jpg DAILY ESSENTIALS.211919012115.jpg aviator-l.Sunglasses.24020221675...
0
2016-08-24T10:08:12Z
39,120,374
<pre><code>#!/bin/bash/ echo "test: " echo "" &gt; 30.230201521829.jpg echo "" &gt; Mens-Sunglasses_L.180022111040.jpg echo "" &gt; progressive-sunglasses.180041285287.jpg echo "" &gt; Atmosphere.222314222509.jpg echo "" &gt; Womens-Sunglasses-L.180023271958.jpg echo "" &gt; DAILY\ ESSENTIALS.2119190121...
-2
2016-08-24T10:10:19Z
[ "python", "bash", "sed" ]
Removing non-alphanumeric characters with bash or python
39,120,328
<p>I have much files like these(please see the screenshot): </p> <pre><code>30.230201521829.jpg Mens-Sunglasses_L.180022111040.jpg progressive-sunglasses.180041285287.jpg Atmosphere.222314222509.jpg Womens-Sunglasses-L.180023271958.jpg DAILY ESSENTIALS.211919012115.jpg aviator-l.Sunglasses.24020221675...
0
2016-08-24T10:08:12Z
39,120,513
<p>Using command substitution for renaming the file. Following code will loop to the current directory's (unless path is modified) jpg files. </p> <p>Awk is used to filter out the penultimate and last column of file name which are separated by "." . </p> <pre><code>for file in *.jpg do mv "$file" $(echo "$file...
1
2016-08-24T10:17:19Z
[ "python", "bash", "sed" ]
Removing non-alphanumeric characters with bash or python
39,120,328
<p>I have much files like these(please see the screenshot): </p> <pre><code>30.230201521829.jpg Mens-Sunglasses_L.180022111040.jpg progressive-sunglasses.180041285287.jpg Atmosphere.222314222509.jpg Womens-Sunglasses-L.180023271958.jpg DAILY ESSENTIALS.211919012115.jpg aviator-l.Sunglasses.24020221675...
0
2016-08-24T10:08:12Z
39,121,119
<p>Using <a href="http://www.unix.com/man-page/linux/1/prename/" rel="nofollow">perl rename</a> one-liner:</p> <pre><code>$ touch 30.230201521829.jpg Mens-Sunglasses_L.180022111040.jpg progressive-sunglasses.180041285287.jpg Atmosphere.222314222509.jpg Womens-Sunglasses-L.180023271958.jpg Womens-Eyeglasses-R.172254027...
0
2016-08-24T10:43:40Z
[ "python", "bash", "sed" ]
Removing non-alphanumeric characters with bash or python
39,120,328
<p>I have much files like these(please see the screenshot): </p> <pre><code>30.230201521829.jpg Mens-Sunglasses_L.180022111040.jpg progressive-sunglasses.180041285287.jpg Atmosphere.222314222509.jpg Womens-Sunglasses-L.180023271958.jpg DAILY ESSENTIALS.211919012115.jpg aviator-l.Sunglasses.24020221675...
0
2016-08-24T10:08:12Z
39,124,055
<p>You can use parameter expansion to strip off the extension, then remove all but the last <code>.</code>-delimited field from the remaining name. After than, you can reapply the extension.</p> <pre><code>for f in *; do ext=${f##*.} base=${f%.$ext} mv -- "$f" "${base##*.}.$ext" done </code></pre> <p>The ...
0
2016-08-24T13:00:30Z
[ "python", "bash", "sed" ]
Removing non-alphanumeric characters with bash or python
39,120,328
<p>I have much files like these(please see the screenshot): </p> <pre><code>30.230201521829.jpg Mens-Sunglasses_L.180022111040.jpg progressive-sunglasses.180041285287.jpg Atmosphere.222314222509.jpg Womens-Sunglasses-L.180023271958.jpg DAILY ESSENTIALS.211919012115.jpg aviator-l.Sunglasses.24020221675...
0
2016-08-24T10:08:12Z
39,136,580
<p>I use python </p> <p>examp.</p> <pre><code>import os import sys import glob pth = "C:\Users\Test" dir_show = os.listdir(pth) for list_file in dir_show: if list_file.endswith(".JPG"): (shrname, exts) = os.path.splitext(list_file) path = os.path.join(pth, list_file) newname=os.path.join...
1
2016-08-25T04:09:50Z
[ "python", "bash", "sed" ]
Python regex match until certain word after identaion
39,120,346
<p>Given the following string or similar:</p> <pre><code>baz: bar key: &gt; lorem ipsum 1213 __ ^123 lorem ipsum foo:bar anotherkey: &gt; lorem ipsum 1213 __ ^123 lorem ipsum </code></pre> <p>I am trying to build a REGEX which captures all values after a key followed by a <code>&gt;</code> sign. </...
0
2016-08-24T10:08:59Z
39,120,436
<p>You can tweak your regex to this:</p> <pre><code>(\w+:\s+&gt;\n\s+[\S\s]+?)(?=\n\w+:\w+\n|\Z) </code></pre> <p><a href="https://regex101.com/r/fU7wC3/1" rel="nofollow">RegEx Demo</a></p> <p>Lookahead <code>(?=\n\w+:\w+\n|\Z)</code> will assert presence of <code>key:value</code> or end of input (<code>\Z</code>) a...
1
2016-08-24T10:13:26Z
[ "python", "regex" ]
Python regex match until certain word after identaion
39,120,346
<p>Given the following string or similar:</p> <pre><code>baz: bar key: &gt; lorem ipsum 1213 __ ^123 lorem ipsum foo:bar anotherkey: &gt; lorem ipsum 1213 __ ^123 lorem ipsum </code></pre> <p>I am trying to build a REGEX which captures all values after a key followed by a <code>&gt;</code> sign. </...
0
2016-08-24T10:08:59Z
39,121,755
<h2>One</h2> <p>If you are <strong>not sure about indentations</strong> whether or not they exist, then this is the <em>simplest</em> way you can achieve desired result:</p> <pre><code>^\w+:\s+&gt;(?:\s?[^:]*$)* </code></pre> <p><a href="https://regex101.com/r/rM1qZ5/1" rel="nofollow">Live demo</a></p> <p>Explanati...
0
2016-08-24T11:12:14Z
[ "python", "regex" ]
Python regex match until certain word after identaion
39,120,346
<p>Given the following string or similar:</p> <pre><code>baz: bar key: &gt; lorem ipsum 1213 __ ^123 lorem ipsum foo:bar anotherkey: &gt; lorem ipsum 1213 __ ^123 lorem ipsum </code></pre> <p>I am trying to build a REGEX which captures all values after a key followed by a <code>&gt;</code> sign. </...
0
2016-08-24T10:08:59Z
39,122,367
<p>(As per request ;)</p> <p>You could use something like</p> <pre><code>^\w+:\s*&gt;\n(?:[ \t].*\n?)+ </code></pre> <p>(This is without the groups. If you decide you wan't them, see the comments to the question.)</p> <p>It matches the start of a line (<code>^</code>) followed by at least one word character (<code>...
2
2016-08-24T11:41:54Z
[ "python", "regex" ]
Python Argparse: Raw string input
39,120,363
<p>Apologies if this has been asked before, I did search for it but all hits seemed to be about python raw strings in general rather than regarding argparse.</p> <p>Anyways, I have a code where the user feeds in a string and then this string is processed. However, I have a problem as I want my code to be able to diffe...
0
2016-08-24T10:09:34Z
39,120,610
<p>Here's a possible solution to your problem:</p> <pre><code>import argparse parser = argparse.ArgumentParser(description='Test.') parser.add_argument('text', action='store', type=str, help='The text to parse.') args = parser.parse_args() print '-' * 80 raw_text = eval('"' + args.text.replace('"', '\\"') + '"') pr...
1
2016-08-24T10:21:21Z
[ "python", "string", "argparse", "rawstring" ]
Python Argparse: Raw string input
39,120,363
<p>Apologies if this has been asked before, I did search for it but all hits seemed to be about python raw strings in general rather than regarding argparse.</p> <p>Anyways, I have a code where the user feeds in a string and then this string is processed. However, I have a problem as I want my code to be able to diffe...
0
2016-08-24T10:09:34Z
39,128,697
<p>As noted in the comments, <code>argparse</code> works with <code>sys.argv</code>, a list which is produced by the shell and Python interpreter. </p> <p>With a simple <code>argv</code> echo script:</p> <pre><code>0928:~/mypy$ cat echo_argv.py import sys print(sys.argv) </code></pre> <p>I get (with a bash shell):<...
0
2016-08-24T16:34:13Z
[ "python", "string", "argparse", "rawstring" ]
Convert current time to WebKit/Chrome 17-digit timestamp
39,120,437
<p>I'm writing some bash script that parses and modifies multiple preferences and bookmarks of Google Chrome in OS X. Some of the values require 17-digit WebKit timestamp to be provided. For now I've hardcoded it with <code>13116319200000000</code> which corresponds to beginning of my workday this Monday in CEST, but i...
0
2016-08-24T10:13:29Z
39,121,470
<p>Something like this?</p> <pre><code>from datetime import datetime, timedelta def date_from_webkit(webkit_timestamp): epoch_start = datetime(1601, 1, 1) delta = timedelta(microseconds=int(webkit_timestamp)) return epoch_start + delta def date_to_webkit(date_string): epoch_start = datetime(1601, 1...
0
2016-08-24T11:00:10Z
[ "javascript", "python", "bash", "google-chrome", "webkit" ]
Convert current time to WebKit/Chrome 17-digit timestamp
39,120,437
<p>I'm writing some bash script that parses and modifies multiple preferences and bookmarks of Google Chrome in OS X. Some of the values require 17-digit WebKit timestamp to be provided. For now I've hardcoded it with <code>13116319200000000</code> which corresponds to beginning of my workday this Monday in CEST, but i...
0
2016-08-24T10:13:29Z
39,131,589
<p>So after great solution provided by <a href="http://stackoverflow.com/a/39121470/6751451">Tiger-222</a> I've found out about python's <code>datetime</code> microseconds (<code>%f</code>) and added it to my final bash script to get full available time resolution and, as a result, the precise WebKit timestamp. Might b...
0
2016-08-24T19:28:48Z
[ "javascript", "python", "bash", "google-chrome", "webkit" ]
Put variable inside string + hardcoded %d value
39,120,538
<p>I'm trying to put into string variables and hardcoded '%d' value - which is not variable (unfornatelly python take it as intiger variable). Example:</p> <pre><code>Error="""awk -v col="%s" -F"," '{ if(NF != col) printf("Index: %d, NR, NF-1); }' "%s" &gt; %s"""%(variable1,variable2,variable3) </code></pre> <p>Now I...
0
2016-08-24T10:18:16Z
39,120,627
<p>Try this:</p> <pre><code>Error="""awk -v col="%s" -F"," '{ if(NF != col) printf("Index: %%d, NR, NF-1); }' "%s" &gt; %s"""%(variable1,variable2,variable3) </code></pre> <p>This uses <code>%%</code>, which resolves to <code>%</code>. Another solution:</p> <pre><code>Error="""awk -v col="{}" -F"," '{ if(NF != col) ...
2
2016-08-24T10:22:05Z
[ "python" ]
catching CTRL-C and manipulating clipboard data with wxpython
39,120,616
<p>My wxpython application must respond everytime user hits CTRL-C, no matter if applications frame is on top/visible but unfocussed/minimalized/under other window etc. Basically I want to know that user copied something into clipboard using CTRL-C combination - other changes in clipboard (like mouse r-click + "copy" s...
1
2016-08-24T10:21:35Z
39,125,066
<p>Took me a while to figure it out but did it!</p> <p>Just change key down event to key up and it works. Your callback is called when CTRL+C is released, so clipboard is already correct since CTRL+C has been processed.</p> <p>(also fixed the callback returned <code>True</code> else I get a lot of exception messages)...
1
2016-08-24T13:45:06Z
[ "python", "wxpython", "clipboard" ]
Finding list of index corresponding to list of element of a dataframe in Python
39,120,667
<p>I have a dataframe with millions of lines. I need to get the corresponding indexes of hundreds of thousands of elements that are present in the original dataframe.</p> <p>I currently use this code:</p> <pre><code>df[df['processed_col'] == element.index[0] </code></pre> <p>to find the position of <code>'element'</...
1
2016-08-24T10:24:05Z
39,120,806
<p>IIUC you need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>isin</code></a> if find first value of index:</p> <pre><code>df[df['processed_col'].isin([element1, element2,..., elementN])].index[0] </code></pre> <p>or if want all values of index, remove <...
0
2016-08-24T10:30:06Z
[ "python", "list", "pandas", "indexing", "dataframe" ]
Sublime Text 3 API reload file after opening
39,120,699
<p>I've written a simple Sublime Text 3 plugin which let me open a log file with a keybord shortcut : </p> <pre><code>class OpenFilesCommand(sublime_plugin.TextCommand): def run(self, edit, var_str): str_date = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d') path_file = '/home/user/l...
1
2016-08-24T10:25:16Z
39,130,907
<p>If the file is already open, and you want Sublime Text to refresh the view from the file, you can use the <code>revert</code> command to reload it from the disk.</p> <pre><code>self.view.window().run_command('revert') </code></pre>
1
2016-08-24T18:47:30Z
[ "python", "sublimetext3" ]
Replacing all numeric value to formatted string
39,120,783
<p>What I am trying to do is:</p> <p>Find out all the numeric values in a string.</p> <pre><code>input_string = "高露潔光感白輕悅薄荷牙膏100 79.80" numbers = re.finditer(r'[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?',input_string) for number in numbers: print ("{} start &gt; {}, end &gt; {}".forma...
4
2016-08-24T10:28:56Z
39,121,003
<p>Use <code>re.sub</code> and a callback method inside where you can perform various manipulations on the match:</p> <pre><code>import re def repl(match): chunks = match.group(1).split(".") if len(chunks) == 2: return "FLT_{}".format(len(chunks[1])) else: return "INT_{}".format(len(chunks[...
4
2016-08-24T10:39:14Z
[ "python", "regex", "string", "replace" ]
Replacing all numeric value to formatted string
39,120,783
<p>What I am trying to do is:</p> <p>Find out all the numeric values in a string.</p> <pre><code>input_string = "高露潔光感白輕悅薄荷牙膏100 79.80" numbers = re.finditer(r'[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?',input_string) for number in numbers: print ("{} start &gt; {}, end &gt; {}".forma...
4
2016-08-24T10:28:56Z
39,121,239
<p>You need to group the parts of your regex possibly like this</p> <pre><code>import re def repl(m): if m.group(1) is None: #int return ("INT_%i"%len(m.group(2))) else: #float return ("FLT_%i"%(len(m.group(2)))) input_string = "高露潔光感白輕悅薄荷牙膏100 79.80" number...
2
2016-08-24T10:49:12Z
[ "python", "regex", "string", "replace" ]
Replacing all numeric value to formatted string
39,120,783
<p>What I am trying to do is:</p> <p>Find out all the numeric values in a string.</p> <pre><code>input_string = "高露潔光感白輕悅薄荷牙膏100 79.80" numbers = re.finditer(r'[-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)?',input_string) for number in numbers: print ("{} start &gt; {}, end &gt; {}".forma...
4
2016-08-24T10:28:56Z
39,121,356
<p>You probably are looking for something like the code below (of course there are other ways to do it). This one just starts with what you were doing and show how it can be done.</p> <pre><code>import re input_string = u"高露潔光感白輕悅薄荷牙膏100 79.80" numbers = re.finditer(r'[-+]?[0-9]*\.?[0-9]+(?:...
1
2016-08-24T10:54:59Z
[ "python", "regex", "string", "replace" ]
converting an HTML table in Pandas Dataframe
39,120,853
<p>I am reading an HTML table with pd.read_html but the result is coming in a list, I want to convert it inot a pandas dataframe, so I can continue further operations on the same. I am using the following script</p> <pre><code>import pandas as pd import html5lib data=pd.read_html('http://www.espn.com/nhl/statistics/pl...
0
2016-08-24T10:32:35Z
39,120,889
<p>I think you need add <code>[0]</code> if need select first item of list, because <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html" rel="nofollow"><code>read_html</code></a> return <code>list of DataFrames</code>:</p> <p>So you can use:</p> <pre><code>import pandas as pd data1 =...
3
2016-08-24T10:34:27Z
[ "python", "html", "pandas", "dataframe" ]
Comparison operator in PySpark (not equal/ !=)
39,120,934
<p>I am trying to obtain all rows in a dataframe where two flags are set to '1' and subsequently all those that where only one of two is set to '1' and the other <strong>NOT EQUAL</strong> to '1'</p> <p>With the following schema (three columns),</p> <pre><code>df = sqlContext.createDataFrame([('a',1,'null'),('b',1,1)...
1
2016-08-24T10:36:05Z
39,121,002
<p>To filter null values try:</p> <p><code>foo_df = df.filter( (df.foo==1) &amp; (df.bar.isNull()) )</code></p> <p><a href="https://spark.apache.org/docs/1.6.2/api/python/pyspark.sql.html#pyspark.sql.Column.isNull" rel="nofollow">https://spark.apache.org/docs/1.6.2/api/python/pyspark.sql.html#pyspark.sql.Column.isNul...
2
2016-08-24T10:39:13Z
[ "python", "apache-spark", "pyspark", "pyspark-sql" ]
Comparison operator in PySpark (not equal/ !=)
39,120,934
<p>I am trying to obtain all rows in a dataframe where two flags are set to '1' and subsequently all those that where only one of two is set to '1' and the other <strong>NOT EQUAL</strong> to '1'</p> <p>With the following schema (three columns),</p> <pre><code>df = sqlContext.createDataFrame([('a',1,'null'),('b',1,1)...
1
2016-08-24T10:36:05Z
39,121,638
<blockquote> <p>Why is it not filtering</p> </blockquote> <p>Because it is SQL and <code>NULL</code> indicates missing values. Because of that any comparison to <code>NULL</code>, other than <code>IS NULL</code> and <code>IS NOT NULL</code> is undefined. You need either:</p> <pre><code>col("bar").isNull() | (col("b...
1
2016-08-24T11:07:31Z
[ "python", "apache-spark", "pyspark", "pyspark-sql" ]
Error in changing to directory using os.chdir in for loop - python
39,121,006
<p>Hey i've got this script which converts all the flv video files in a directory to mp4 format. </p> <p>I got it to work with just having all the files placed in one directory but am now needing to modify it so it goes into folders within that directory and converts the files within each folder it comes across.</p> ...
0
2016-08-24T10:39:20Z
39,121,099
<p>The <code>dirpath</code> is a <em>single</em> string. When you iterate over it using <code>for</code> loop (<code>for z in dirpath</code>), you're iterating over each individual character in string <code>'/home/dubit/Desktop/test/'</code>! First <code>z</code> is set to <code>'/'</code>, then <code>'h'</code>... and...
4
2016-08-24T10:42:53Z
[ "python", "python-2.7" ]
Error in changing to directory using os.chdir in for loop - python
39,121,006
<p>Hey i've got this script which converts all the flv video files in a directory to mp4 format. </p> <p>I got it to work with just having all the files placed in one directory but am now needing to modify it so it goes into folders within that directory and converts the files within each folder it comes across.</p> ...
0
2016-08-24T10:39:20Z
39,121,217
<p>The error you're getting is due to the fact that <code>dirpath</code> is actually a string, not a list of strings. <code>os.walk()</code> returns a tuple, where <code>dirpath</code> being current directory being walked by, <code>dirnames</code> and <code>filenames</code> being <code>dirpath</code>'s contents.</p> <...
1
2016-08-24T10:47:59Z
[ "python", "python-2.7" ]
How to make simple graphs in python 2.7
39,121,235
<p>I would like to make simple graphs for my web page in python/django, but I do not know, which library (and how) to use.</p> <p>I DO NOT WANT CHARTS, I SEEK A WAY TO CREATE IMAGE FROM PRIMITIVES LIKE RECTANGLES.</p> <p>Each such graph is probabely generated and used only one time, as next time the values would diff...
2
2016-08-24T10:48:57Z
39,121,646
<p>You should check Pillow out. Here is a sample how it works:</p> <pre><code>from PIL import Image, ImageDraw im = Image.open("lena.pgm") draw = ImageDraw.Draw(im) draw.line((0, 0) + im.size, fill=128) draw.line((0, im.size[1], im.size[0], 0), fill=128) del draw # write to stdout im.save(sys.stdout, "PNG") </code>...
2
2016-08-24T11:08:03Z
[ "python", "django", "python-2.7" ]
How to make simple graphs in python 2.7
39,121,235
<p>I would like to make simple graphs for my web page in python/django, but I do not know, which library (and how) to use.</p> <p>I DO NOT WANT CHARTS, I SEEK A WAY TO CREATE IMAGE FROM PRIMITIVES LIKE RECTANGLES.</p> <p>Each such graph is probabely generated and used only one time, as next time the values would diff...
2
2016-08-24T10:48:57Z
39,121,890
<p><a href="http://matplotlib.org/" rel="nofollow">http://matplotlib.org/</a> permits to generate plenty of great graphs. You should be able to save it as an image and integrate it to your webpage</p>
0
2016-08-24T11:18:58Z
[ "python", "django", "python-2.7" ]
How to make simple graphs in python 2.7
39,121,235
<p>I would like to make simple graphs for my web page in python/django, but I do not know, which library (and how) to use.</p> <p>I DO NOT WANT CHARTS, I SEEK A WAY TO CREATE IMAGE FROM PRIMITIVES LIKE RECTANGLES.</p> <p>Each such graph is probabely generated and used only one time, as next time the values would diff...
2
2016-08-24T10:48:57Z
39,121,971
<p>What about <a href="https://plot.ly/python/gantt/" rel="nofollow">plotly</a>? Never used in a project, but by reading the examples it seems very powerful and easy to use. It has a <a href="https://plot.ly/python/static-image-export/" rel="nofollow">static image export</a> (as most graphic libraries probably have).<...
0
2016-08-24T11:22:20Z
[ "python", "django", "python-2.7" ]
How to create a specific type of object for type .hdf5?
39,121,367
<p>My question is about creating an object type or document for .hdf5 files. The object will have three attributes, an id, a user_id and a boolean array of size 64. I have to create them about 10000000 (Ten millions) many. </p> <p>Imagine mongodb, I have to use them like that. I have to make queries for some particula...
0
2016-08-24T10:55:18Z
39,121,705
<p>I would go ahead and use a dictionary for this case. I feel dictionaries do scale up well. Since the query would be on user_id, I would make it the key.</p> <p>The structure would be like </p> <pre><code>{ 'user_id-xyz': { 'id':'id-1212', 'boolarray':[True,False,..], }, 'user_id-abc':...
0
2016-08-24T11:10:10Z
[ "python", "mongodb", "hdf5", "h5py" ]
How do I ignore the "redundant parentheses" feature in PyCharm?
39,121,432
<p>PyCharm decides that certain parenthesis in my Python code are 'redundant'. I want to keep them anyway. So PyCharm started annoying me with green lines under them. I don't want to give in to PyCharm's quirks.</p> <p>I was able to ignore other warnings in the following way:</p> <blockquote> <p>File > Settings > E...
-1
2016-08-24T10:58:23Z
39,121,575
<p>There is <code>redundant parenthesis</code> under Inspections (PyCharm 2016.1.4). Look closer.</p> <p>If you still can't find it, there is a search bar on the top left corner of the settings menu. Search for <code>redun</code> and the <code>redundant parenthesis</code> inspection should come up.</p>
4
2016-08-24T11:04:51Z
[ "python", "pycharm" ]
How do I ignore the "redundant parentheses" feature in PyCharm?
39,121,432
<p>PyCharm decides that certain parenthesis in my Python code are 'redundant'. I want to keep them anyway. So PyCharm started annoying me with green lines under them. I don't want to give in to PyCharm's quirks.</p> <p>I was able to ignore other warnings in the following way:</p> <blockquote> <p>File > Settings > E...
-1
2016-08-24T10:58:23Z
39,121,691
<p>redundant parenthesis is a <em>weak warning</em>. You can just uncheck the box there.</p> <p><a href="http://i.stack.imgur.com/QTCwM.png" rel="nofollow"><img src="http://i.stack.imgur.com/QTCwM.png" alt="enter image description here"></a></p>
3
2016-08-24T11:09:47Z
[ "python", "pycharm" ]
Saving functions using shelve
39,121,587
<p>I'm trying to use the shelve python module to save my session output and reload it later, but I have found that if I have defined functions then I get an error in the reloading stage. Is there a problem with the way I am doing it? I based my code on an answer at <a href="http://stackoverflow.com/questions/2960864/ho...
0
2016-08-24T11:05:22Z
39,121,645
<p>You can't use <code>shelve</code> (or <a href="https://docs.python.org/2/library/pickle.html#module-pickle" rel="nofollow"><code>pickle</code></a>, the actual protocol used by <code>shelve</code>) to store <em>executable code</em>, no.</p> <p>What is stored is a <em>reference</em> to the function (just the location...
3
2016-08-24T11:07:59Z
[ "python", "python-2.7" ]
Updating messages with inline keyboards using callback queries
39,121,678
<p>I want to update message in chat with inline keyboard but can't understand how to receive a <em>inline_message_id</em> or if it only for inline queries how I can determine <em>chat_id</em> and <em>message_id</em> for using it on <a href="https://pythonhosted.org/python-telegram-bot/telegram.bot.html" rel="nofollow">...
0
2016-08-24T11:09:16Z
39,127,669
<p>You should pass <code>message_id</code> instead of <code>inline_message_id</code> to <code>editMessageText</code>.</p> <p>So the solution for you is this:</p> <pre class="lang-python prettyprint-override"><code>bot.editMessageText( message_id = update.callback_query.message.message_id, chat_id = update.cal...
1
2016-08-24T15:41:16Z
[ "python", "telegram", "telegram-bot", "python-telegram-bot" ]
Setting with enlargement - updating transaction DF
39,121,709
<p>Looking for ways to achieve following updates on a dataframe:</p> <ul> <li><code>dfb</code> is the base dataframe that I want to update with <code>dft</code> transactions.</li> <li>Any common index rows should be updated with values from <code>dft</code>. </li> <li>Indexes only in <code>dft</code> should be appende...
1
2016-08-24T11:10:27Z
39,121,833
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.combine_first.html" rel="nofollow"><code>combine_first</code></a> with renaming columns, last convert <code>float</code> columns to <code>int</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Dat...
1
2016-08-24T11:16:10Z
[ "python", "pandas", "dataframe", "multiple-columns", "insert-update" ]
decoding base64 images from rtf
39,121,875
<p>In my rtf document, I want to extract image from string: The string is like this:</p> <pre><code> \pard\pard\qc{\*\shppict{\pict\pngblip\picw320\pich192\picwgoal0\pichgoal0 89504e470d0a1a0a0000000d4948445200000140000000c00802000000fa352d9100000e2949444[.....]6c4f0000000049454e44ae426082 }} </code></pre> <p...
0
2016-08-24T11:18:07Z
39,121,955
<p>No, that's not Base64-encoded data. It is <em>hexadecimal</em>. From the <a href="https://en.wikipedia.org/wiki/Rich_Text_Format#Pictures" rel="nofollow">Wikipedia article on the RTF format</a>:</p> <blockquote> <p>RTF supports inclusion of JPEG, Portable Network Graphics (PNG), Enhanced Metafile (EMF), Windows M...
4
2016-08-24T11:21:21Z
[ "python", "base64", "rtf" ]
Why is Python regex slower 5 times on aws instance than my local mac OS X with similar specs?
39,122,067
<p>I have the following regex code. </p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- import time import re start_time = time.time() input_string = """သီဟိုဠ်မှ ဉာဏ်ကြီးရှင်သည် အာယုဝဍ်ဎနဆေးညွှန်းစာကို ဇလွ...
2
2016-08-24T11:27:21Z
39,122,978
<p>The problem is that I was using python 2.7.3 on my aws instance. After I updated to 2.7.10, it is now as fast as my other machines.</p> <p>Cheers.</p>
3
2016-08-24T12:11:30Z
[ "python", "regex", "amazon-web-services" ]
How to remove spacing from an input
39,122,117
<p>Hi I am new to programming and I am trying to write a code that will add a hashtag from the users input and remove spacing.</p> <p>For example if the input is </p> <pre><code>Enter text: </code></pre> <p>and I was to write "Sam is cool". I would want it to print "#Samiscool"</p> <p>This is my program so far:</p>...
-4
2016-08-24T11:29:29Z
39,122,168
<p>You can use <code>string.replace</code> to remove the whitespace, then simply use concatenation to put the <code>'#'</code> symbol in front</p> <pre><code>def hashify(s): return '#' + s.replace(' ', '') &gt;&gt;&gt; hashify('Sam is cool') '#Samiscool' </code></pre>
3
2016-08-24T11:31:54Z
[ "python" ]
How to remove spacing from an input
39,122,117
<p>Hi I am new to programming and I am trying to write a code that will add a hashtag from the users input and remove spacing.</p> <p>For example if the input is </p> <pre><code>Enter text: </code></pre> <p>and I was to write "Sam is cool". I would want it to print "#Samiscool"</p> <p>This is my program so far:</p>...
-4
2016-08-24T11:29:29Z
39,122,193
<p>Here's a possible solution, it'll get rid not only of spaces but also tabs:</p> <pre><code>a = input("Enter text: ") print('#' + "".join(a.split())) </code></pre>
4
2016-08-24T11:33:10Z
[ "python" ]
How to remove spacing from an input
39,122,117
<p>Hi I am new to programming and I am trying to write a code that will add a hashtag from the users input and remove spacing.</p> <p>For example if the input is </p> <pre><code>Enter text: </code></pre> <p>and I was to write "Sam is cool". I would want it to print "#Samiscool"</p> <p>This is my program so far:</p>...
-4
2016-08-24T11:29:29Z
39,122,370
<p>I propose one more option</p> <pre><code>def hashify(s): return '#' + s.title().replace(' ', '') &gt;&gt;&gt; hashify('Sam is cool') '#SamIsCool' </code></pre>
1
2016-08-24T11:41:55Z
[ "python" ]
How to remove spacing from an input
39,122,117
<p>Hi I am new to programming and I am trying to write a code that will add a hashtag from the users input and remove spacing.</p> <p>For example if the input is </p> <pre><code>Enter text: </code></pre> <p>and I was to write "Sam is cool". I would want it to print "#Samiscool"</p> <p>This is my program so far:</p>...
-4
2016-08-24T11:29:29Z
39,122,649
<p>And if you really want to know why Python is cool (#PythonIsCool):</p> <pre><code>&gt;&gt;&gt; s = 'Python is cool' &gt;&gt;&gt; print( '#' + ''.join( x[0:1].upper() + x[1:len(x)] for x in s.split() )) PythonIsCool </code></pre>
0
2016-08-24T11:55:19Z
[ "python" ]
Interpolating backwards with multiple consecutive nan's in Pandas/Python?
39,122,196
<p>I have an array with missing values in various places.</p> <pre><code>import numpy as np import pandas as pd x = np.arange(1,10).astype(float) x[[0,1,6]] = np.nan df = pd.Series(x) print(df) 0 NaN 1 NaN 2 3.0 3 4.0 4 5.0 5 6.0 6 NaN 7 8.0 8 9.0 dtype: float64 </code></pre> <p>For each <...
3
2016-08-24T11:33:21Z
39,122,277
<p>You can do something like this:</p> <pre><code>import numpy as np import pandas as pd x = np.arange(1,10).astype(float) x[[0,1,6]] = np.nan df = pd.Series(x) prev = 0 new_list = [] for i in df.values[::-1]: if np.isnan(i): new_list.append(prev/2.) prev = prev / 2. else: new_list...
2
2016-08-24T11:37:50Z
[ "python", "pandas", "numpy", "dataframe", "interpolation" ]
Interpolating backwards with multiple consecutive nan's in Pandas/Python?
39,122,196
<p>I have an array with missing values in various places.</p> <pre><code>import numpy as np import pandas as pd x = np.arange(1,10).astype(float) x[[0,1,6]] = np.nan df = pd.Series(x) print(df) 0 NaN 1 NaN 2 3.0 3 4.0 4 5.0 5 6.0 6 NaN 7 8.0 8 9.0 dtype: float64 </code></pre> <p>For each <...
3
2016-08-24T11:33:21Z
39,122,684
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a> with method <code>ffill</code>, what it same as <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.ffill.html" rel="nofollow"><code>ffill()<...
3
2016-08-24T11:57:17Z
[ "python", "pandas", "numpy", "dataframe", "interpolation" ]
Multiprocessing - Shared Array
39,122,270
<p>So I'm trying to implement multiprocessing in python where I wish to have a Pool of 4-5 processes running a method in parallel. The purpose of this is to run a total of thousand Monte simulations (250-200 simulations per process) instead of running 1000. I want each process to write to a common shared array by acqui...
0
2016-08-24T11:37:10Z
39,122,466
<p>Not tested, but something like that should work. The array and lock are shared between processes.</p> <pre><code>from multiprocessing import Process def f(array,lock): lock.acquire() #modify array here lock.release() if __name__ == '__main__': size=100 multiprocessing.Array('i', size) #c type ...
0
2016-08-24T11:46:49Z
[ "python", "multiprocessing", "shared" ]
Multiprocessing - Shared Array
39,122,270
<p>So I'm trying to implement multiprocessing in python where I wish to have a Pool of 4-5 processes running a method in parallel. The purpose of this is to run a total of thousand Monte simulations (250-200 simulations per process) instead of running 1000. I want each process to write to a common shared array by acqui...
0
2016-08-24T11:37:10Z
39,124,004
<p>Since you're only returning state from the child process to the parent process, then using a shared array and explicity locks is overkill. You can use <code>Pool.map</code> or <code>Pool.starmap</code> to accomplish exactly what you need. For example:</p> <pre><code>from multiprocessing import Pool class Adder: ...
0
2016-08-24T12:58:04Z
[ "python", "multiprocessing", "shared" ]
BitVector performance issues
39,122,376
<p>I need to use bits for operations in a crypto scheme, however, when I transform variables and functions into BitVector(bitstring/int/textstrings="") the result is a very long bitvector, at times of length in the thousands. Now, this slows my encryption and operations on these BitVectors a LOT. How can I overcome thi...
0
2016-08-24T11:42:12Z
39,122,656
<p>Your question does not have much information. Nonetheless, the documentation says that you can set the size of your BitVector.</p> <pre><code>bv = BitVector( intVal = 0, size = 8 ) </code></pre> <p>Hope that helps!</p>
0
2016-08-24T11:55:44Z
[ "python", "encryption", "bitvector" ]
BitVector performance issues
39,122,376
<p>I need to use bits for operations in a crypto scheme, however, when I transform variables and functions into BitVector(bitstring/int/textstrings="") the result is a very long bitvector, at times of length in the thousands. Now, this slows my encryption and operations on these BitVectors a LOT. How can I overcome thi...
0
2016-08-24T11:42:12Z
39,123,978
<p>This is shameless self-advertising but I made <a href="https://pypi.python.org/pypi/BytesOp" rel="nofollow">https://pypi.python.org/pypi/BytesOp</a> exactly for this.</p> <p>You could use it like this</p> <pre><code>from BytesOp import op_xor msg=b"asdf" h1=b"1234" msgxored=op_xor(msg,h1) print(msgxored,op_xor(msg...
1
2016-08-24T12:56:55Z
[ "python", "encryption", "bitvector" ]
Change Dyno types through the Heroku API
39,122,456
<p>I have an app running in Heroku; I'm using the <a href="https://elements.heroku.com/addons/scheduler" rel="nofollow">Heroku scheduler</a> to run a python script that scales the number of dynos at particular times of the day, using the <a href="https://github.com/heroku/heroku.py" rel="nofollow">python API</a> (follo...
-1
2016-08-24T11:46:21Z
39,288,180
<p>A chat with the Heroku support has confirmed that the python API has no command to perform this operation; I have therefore resorted to add the following script to the app (following <a href="http://stackoverflow.com/a/27153236/1237531">this answer</a>):</p> <pre><code>#!/bin/bash curl -s https://s3.amazonaws.com/...
0
2016-09-02T08:51:14Z
[ "python", "heroku" ]
Pass data from django middleware.process_view to the template context
39,122,541
<p>I have a custom middleware and during its process_view I get some token. And I need to pass this token to the rendered result html.</p> <p>I thought that context_processor is a good place to modify context, but looks like it's hard to pass some data from middleware into processor.</p> <p>But it seems that the only...
0
2016-08-24T11:50:52Z
39,122,722
<p>That error is raised when you try and use dictionary item assignment:</p> <pre><code>request['my_key'] = 'my_value' </code></pre> <p>But the request is not a dictionary, it is an object. As with all objects - like the Django models which you must be familiar with - you need to set attributes, not items.</p> <pre>...
1
2016-08-24T11:59:11Z
[ "python", "django" ]
Django-taggit tags with whitespace in name?
39,122,552
<p>How can I use tags with whitespace char in their name with django-taggit? For example, "Some simple tag"? Because if I ctrl-c=>ctrl-v some phrase to tags field in my admin panel, on page with this tag i get something like this:</p> <pre><code>Reverse for 'posts_by_tag' with arguments '()' and keyword arguments '{u'...
0
2016-08-24T11:51:21Z
39,128,388
<p>Multi-word tags in Wagtail need to be quoted, e.g. "my tag". </p> <p>There are two pull requests open that address this topic:</p> <ul> <li><a href="https://github.com/torchbox/wagtail/issues/1874" rel="nofollow">https://github.com/torchbox/wagtail/issues/1874</a> to improve documentation and explain users that at...
1
2016-08-24T16:18:06Z
[ "python", "django", "django-taggit", "wagtail" ]
Setting axis values in numpy/matplotlib.plot
39,122,554
<p>I am in the process of learning numpy. I wish to plot a graph of Planck's law for different temperatures and so have two <code>np.array</code>s, <code>T</code> and <code>l</code> for temperature and wavelength respectively. </p> <pre><code>import scipy.constants as sc import numpy as np import matplotlib.pyplot as ...
2
2016-08-24T11:51:23Z
39,122,887
<p>The problem is that you're not giving your wavelength values to <code>plt.plot()</code>, so Matplotlib puts the index into the array on the horizontal axis as a default. Quick solution:</p> <pre><code>plt.plot(l, B) </code></pre> <p>Without explicitly setting tick labels, that gives you this:</p> <p><a href="http...
3
2016-08-24T12:07:07Z
[ "python", "numpy", "matplotlib" ]
Setting axis values in numpy/matplotlib.plot
39,122,554
<p>I am in the process of learning numpy. I wish to plot a graph of Planck's law for different temperatures and so have two <code>np.array</code>s, <code>T</code> and <code>l</code> for temperature and wavelength respectively. </p> <pre><code>import scipy.constants as sc import numpy as np import matplotlib.pyplot as ...
2
2016-08-24T11:51:23Z
39,122,897
<p>You need to use same size lists at the <code>xtick</code>. Try setting the axis values separately from the plot value as below.</p> <pre><code>import scipy.constants as sc import numpy as np import matplotlib.pyplot as plt lhinm = 10000 # Highest wavelength in nm T = np.linspace(200, 1000, ...
0
2016-08-24T12:07:48Z
[ "python", "numpy", "matplotlib" ]
Setting axis values in numpy/matplotlib.plot
39,122,554
<p>I am in the process of learning numpy. I wish to plot a graph of Planck's law for different temperatures and so have two <code>np.array</code>s, <code>T</code> and <code>l</code> for temperature and wavelength respectively. </p> <pre><code>import scipy.constants as sc import numpy as np import matplotlib.pyplot as ...
2
2016-08-24T11:51:23Z
39,122,917
<p>You can supply the <code>x</code> values to <code>plt.plot</code>, and let matplotlib take care of setting the tick labels.</p> <p>In your case, you could plot <code>plt.plot(l, B)</code>, but then you still have the ticks in m, not nm.</p> <p>You could therefore convert your <code>l</code> array to nm before plot...
3
2016-08-24T12:09:04Z
[ "python", "numpy", "matplotlib" ]
Python client for free SOAP service using socket giving error?
39,122,569
<p>This is the code that I'm trying to use:</p> <pre><code>import os import socket import httplib packet=''' &lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema"xmlns:soap12="http://www.w3.org/2003/05/soap-en...
0
2016-08-24T11:52:05Z
39,122,884
<p>You ought to use <a href="https://fedorahosted.org/suds/wiki/Documentation" rel="nofollow">suds</a> to consume SOAP web service.</p> <p><strong>EDIT: Example</strong></p> <pre><code>import suds import suds.transport from suds.transport.http import HttpAuthenticated class MyException(Exception): pass servic...
0
2016-08-24T12:07:05Z
[ "python", "web-services", "sockets", "soap", "python-sockets" ]
Python: reducing cyclomatic complexity
39,122,645
<p>I need help in reducing the cyclomatic complexity of the following code: </p> <pre><code>def avg_title_vec(record, lookup): avg_vec = [] word_vectors = [] for tag in record['all_titles']: titles = clean_token(tag).split() for word in titles: if word in lookup.value: ...
0
2016-08-24T11:55:12Z
39,126,639
<p>It probably doesn't count as a correct answer really, as in the end cyclomatic complexity isn't reduced.</p> <p>This variant is a little bit shorter, but I can't see any way it can be generalized in. And it seems that you need those <code>if</code>s you have.</p> <pre><code>def avg_title_vec(record, lookup): w...
0
2016-08-24T14:50:38Z
[ "python", "code-review", "cyclomatic-complexity" ]
Django 1.8.7 get_readonly_fields seems like have a bug
39,122,829
<p>I try something with readonly field in Django 1.8.7, let say I have some code like the following:</p> <pre><code>class MyAdmin(admin.ModelAdmin): readonly_fields = ('a', 'b') def get_readonly_fields(self, request, obj=None): if not request.user.is_superuser: self.readonly_fields += ('c'...
0
2016-08-24T12:04:18Z
39,123,123
<p>The bug is not in Django, but in your code. In your <code>get_readonly_fields</code> method you <em>modify</em> the <code>readonly_fields</code> attribute; those modifications persist, since the admin object lives for the lifetime of the process.</p> <p>Don't do that. <code>get_readonly_fields</code> is supposed to...
1
2016-08-24T12:17:54Z
[ "python", "django", "get", "field", "readonly" ]
How do I remove blank elements from an AstroPy table?
39,122,843
<p>I'm trying to remove any elements from an astropy table that have blank fields. However, all the help I have found so far just tells me how to replace it. I have tried replacing these blank fields (denoted by '--') with zeroes. However, whenever I try to filter them out with traditional python loops, they stay put. ...
-1
2016-08-24T12:05:07Z
39,125,554
<p>You cannot!</p> <p>Removing single fields from a <code>astropy.table.Table</code> is impossible because it is based on <code>numpy</code>. Therefore you can only remove whole columns or rows but not single elements.</p> <p>For example you have such a Table:</p> <pre><code>&gt;&gt;&gt; from astropy.table import Ta...
1
2016-08-24T14:04:44Z
[ "python", "pandas", "python-3.5", "astropy" ]
Get read of ['\n'] in python3 with paramiko
39,122,910
<p>I've just started to do some monitoring tool in python3 and I wondered, if I can get 'clear' number output through ssh. I've made some script:</p> <pre><code>import os import paramiko command = 'w|grep \"load average\"|grep -v grep|awk {\'print ($10+$11+$12)/3*100\'};' ssh = paramiko.SSHClient() ssh.set_missing_ho...
0
2016-08-24T12:08:29Z
39,122,949
<p>Instead of <code>print(stdout.readlines())</code> you should iterate over each element in the list that is returned by <code>stdout.readlines()</code> and <code>strip</code> it, possibly converting it to <code>float</code> as well (depends what you are planning to do with this data later).</p> <p>You can use list c...
1
2016-08-24T12:10:19Z
[ "python", "python-3.x", "output", "special-characters", "paramiko" ]
Get read of ['\n'] in python3 with paramiko
39,122,910
<p>I've just started to do some monitoring tool in python3 and I wondered, if I can get 'clear' number output through ssh. I've made some script:</p> <pre><code>import os import paramiko command = 'w|grep \"load average\"|grep -v grep|awk {\'print ($10+$11+$12)/3*100\'};' ssh = paramiko.SSHClient() ssh.set_missing_ho...
0
2016-08-24T12:08:29Z
39,122,954
<p><code>.readlines()</code> returns a <em>list</em> of separate lines. In your case there is just one line, you can just extract it by indexing the list, then strip of the whitespace at the end:</p> <pre><code>firstline = stdout.readlines()[0].rstrip() </code></pre> <p>This is still a string, however. If you expecte...
3
2016-08-24T12:10:29Z
[ "python", "python-3.x", "output", "special-characters", "paramiko" ]
Pyspark error for java heap space error
39,122,955
<p>I am new to spark using <strong>Spark 1.6.1</strong> with <strong>two workers</strong> each having <strong>Memory 1GB</strong> and <strong>5 Cores</strong> assigned, running this code on a 33MB file. </p> <p>This Code is used to Index word in spark.</p> <pre><code>from textblob import TextBlob as tb from textblob_...
0
2016-08-24T12:10:32Z
39,124,549
<p>That's because of the .collect(). You lose everything when you transform your rdd into a classic python variable (or np.array), all data is collected on the same place.</p>
0
2016-08-24T13:21:50Z
[ "python", "numpy", "optimization", "pyspark" ]
How do you pass multiple arguments to a Luigi subtask?
39,123,021
<p>I have a Luigi task that <code>requires</code> a subtask. The subtask depends on parameters passed through by the parent task (i.e. the one that is doing the <code>require</code>ing). I know you can specify a parameter that the subtask can use by setting...</p> <pre><code>def requires(self): return subTask(some...
0
2016-08-24T12:13:41Z
39,126,080
<p>Ok, so I found that this works as expected in python 3.5 (and the problem is still there in 3.4).</p> <p>Don't have the time to get to the bottom of this today so no further details.</p>
0
2016-08-24T14:27:36Z
[ "python", "luigi" ]
How do you pass multiple arguments to a Luigi subtask?
39,123,021
<p>I have a Luigi task that <code>requires</code> a subtask. The subtask depends on parameters passed through by the parent task (i.e. the one that is doing the <code>require</code>ing). I know you can specify a parameter that the subtask can use by setting...</p> <pre><code>def requires(self): return subTask(some...
0
2016-08-24T12:13:41Z
39,512,474
<blockquote> <p>What is the best way to send through an arbitrary number of parameters, of whatever types I want?</p> </blockquote> <p>The best way is to use named parameters, e.g.,</p> <pre><code>#in requires return MySampleSubTask(x=local_x, y=local_y) class MySampleSubTask(luigi.Task): x = luigi.Parameter...
0
2016-09-15T13:34:52Z
[ "python", "luigi" ]