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
Large file upload in Flask
38,048,355
<p>I am attempting to implement a flask application for uploading files. This file could be very large. For example, almost 2G in size.</p> <p>I have finished the server side process function like this:</p> <pre><code>@app.route("/upload/&lt;filename&gt;", methods=["POST", "PUT"]) def upload_process(filename): fi...
0
2016-06-27T07:41:02Z
38,054,501
<p>This will be a difficult task for your to figure out on your own. I would suggest a plugin like <a href="https://blueimp.github.io/jQuery-File-Upload/" rel="nofollow">https://blueimp.github.io/jQuery-File-Upload/</a></p> <p>You can see from this projects source code they use a method name which essentially looks a...
1
2016-06-27T12:52:37Z
[ "python", "file-upload", "flask", "large-files" ]
Matplotlib - how to superimpose a contour map with coastlines and countries
38,048,418
<p>I have this python script that plots a contour map of geopotential heights - </p> <pre><code>nc_f = './hgt_500_2014_12_5_00Z.nc' # Your filename nc_fid = Dataset(nc_f, 'r') lats = nc_fid.variables['lat'][:] # extract/copy the data lons = nc_fid.variables['lon'][:] time = nc_fid.variables['time'][:] hgt = nc_fi...
2
2016-06-27T07:44:10Z
38,049,479
<p>Your code is totally broken. Look at the example of hgt data:</p> <pre><code>from netCDF4 import Dataset import scipy.interpolate import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap nc_f = 'hgt_500.nc' nc_fid = Dataset(nc_f, 'r') lats = nc_fid.variables['lat'] lons = nc...
1
2016-06-27T08:46:40Z
[ "python", "matplotlib", "python-3.4", "matplotlib-basemap" ]
How can i add a list to a list in a dictionary
38,048,464
<p>I'm struggling to figure out whats going wrong here I'm trying to append this list to a dictionary key's list but I only ever get the last one.</p> <p>For example:</p> <pre><code>pastmoves =['n','w','s','w'] moves = [1,0,1,0] turnpt = {'pos' : [], 'moves' : [], 'lastmove' : []} pos = [1,1] opt ...
0
2016-06-27T07:47:56Z
38,048,594
<p>Pass a copy of the list <code>pos</code> using <code>pos[:]</code>. When you append <code>pos</code> and then change it, it will also be changed in <code>turnpt</code> because it is a reference to a list and your condition will never be <code>True</code>.</p> <pre><code>while 5 not in opt: if len(pastmoves) &gt...
1
2016-06-27T07:55:46Z
[ "python", "list", "dictionary", "while-loop", "append" ]
How can i add a list to a list in a dictionary
38,048,464
<p>I'm struggling to figure out whats going wrong here I'm trying to append this list to a dictionary key's list but I only ever get the last one.</p> <p>For example:</p> <pre><code>pastmoves =['n','w','s','w'] moves = [1,0,1,0] turnpt = {'pos' : [], 'moves' : [], 'lastmove' : []} pos = [1,1] opt ...
0
2016-06-27T07:47:56Z
38,048,660
<p>Your problem is in </p> <pre><code>if pos not in turnpt['pos']: turnpt['pos'].append(pos) </code></pre> <p>You check if pos in not in turnpt['pos'], then you append it, so after that pos not in turnpt['pos'] is never True. Example to illustrate :</p> <pre><code>a = [1,1] b = [[1,1]] c = [a] a in b == True a ...
0
2016-06-27T08:00:14Z
[ "python", "list", "dictionary", "while-loop", "append" ]
Parsing variable dependency with Pycparser
38,048,478
<p>I'm currently working on a project to find variable dependencies in a given function for I/O, and have chosen to work with Pycparser. My code right now is mostly just one visitor-class, and a few node-classes. What it does is it traverses the AST and creates nodes for each variable assignment, declaration, input, ou...
0
2016-06-27T07:48:31Z
38,068,065
<p>I just found out that what I've been trying to achieve is impossible with the method I have been using. What the AST and Pycparser can provide me with is all variables used to determine the value of a variable.</p> <p>To proceed with my problem, you would have to look into creating a CFG (Control Flow Graph) aswell...
0
2016-06-28T05:55:47Z
[ "python", "c", "static", "analysis", "pycparser" ]
Enter terminal input via Python
38,048,496
<p>I want to switch user using the <code>su</code> command in the terminal via Python:</p> <pre><code>import os os.system("su user") </code></pre> <p>After executing this code, the system asks for a password (obviously).</p> <p>Also, of course I can't add another line like this:</p> <pre><code>import os os.system("...
0
2016-06-27T07:49:32Z
38,049,008
<p>Maybe you need <code>pexpect</code>. My lab as follow:</p> <pre><code>sec@sec-router:/tmp$ uname -a Linux sec-router 3.19.0-59-generic #66~14.04.1-Ubuntu SMP Fri May 13 17:27:10 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux </code></pre> <p><a href="http://i.stack.imgur.com/1EZmo.png" rel="nofollow"><img src="http://i.s...
0
2016-06-27T08:20:42Z
[ "python", "linux", "python-2.7", "terminal", "operating-system" ]
How obtain the real mean & se of my exponential fit?
38,048,529
<p>I'm trying to fit at the same time, a gaussian and an exponential on a histogram on the same plot, but when I try to get the mean of the exponential fit, I get something wrong like mean value : <code>-9.8636992990798974e-07</code>, (I expect to obtain something like <code>70</code>, not <code>-9.8e-07</code>).</p> ...
1
2016-06-27T07:51:15Z
38,051,360
<p>stats.expon.fit returns the tuple (loc, scale). According to the doc, </p> <p>scale = 1 / lambda</p> <p>which is also the mean of the exponential distribution. Therefore, it is the second parameter that you want.</p> <p>If you want to force the location to be 0, you can pass in the floc parameter to fit.</p>
1
2016-06-27T10:17:20Z
[ "python", "matplotlib", "scipy", "histogram", "exponential" ]
Embedding image in gmail
38,048,582
<p>I have to send a HTML report as an email on gmail and it should be inline to avoid further downloads. I have written a python code that fetches data from database, does some analysis, plots graphs and all these results are summarized in a HTML table with one column containing images. Now, I have embedded these imag...
0
2016-06-27T07:55:03Z
38,055,227
<p>The problem is likely Gmail not supporting embedded images (as I <em>think</em> you say in your question). I've never seen it done in an HTML email. <a href="https://sendgrid.com/blog/embedding-images-emails-facts/" rel="nofollow">This article</a> goes into more detail about what's possible, but says while embedding...
0
2016-06-27T13:27:26Z
[ "python", "matplotlib", "gmail", "embed", "html-email" ]
OpenCV grabcut() background color and Contour in Python
38,048,650
<p>I am using Python and OpenCV. I am now using <code>grabcut()</code> to crop out the object I want. Here is my code:</p> <pre><code>img = cv2.imread('test.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) mask = np.zeros(img.shape[:2], np.uint8) bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), n...
1
2016-06-27T07:59:47Z
38,656,941
<p>If you want a single contour like boundary, you can go for edge detection on the output of grabcut and morphology dilation on the edge image to get as a proper connected contour and can get the array of pixels of the boundary.</p> <p>For making the background white, All the pixels outside your bounding box can be d...
-1
2016-07-29T10:48:58Z
[ "python", "image", "opencv", "image-processing" ]
OpenCV grabcut() background color and Contour in Python
38,048,650
<p>I am using Python and OpenCV. I am now using <code>grabcut()</code> to crop out the object I want. Here is my code:</p> <pre><code>img = cv2.imread('test.jpg') img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) mask = np.zeros(img.shape[:2], np.uint8) bgdModel = np.zeros((1, 65), np.float64) fgdModel = np.zeros((1, 65), n...
1
2016-06-27T07:59:47Z
39,351,917
<p>At first, you need to get the background. To this must be subtracted from the original image with the mask image. And then change the black background to white (or any color). And then back to add with the image of the mask.</p> <pre><code>import numpy as np import cv2 cv2.namedWindow(‘image’, cv2.WINDOW_NORMA...
0
2016-09-06T14:47:04Z
[ "python", "image", "opencv", "image-processing" ]
pandas number >mean(), or <mean() , than output a number
38,048,665
<p>I have a dataframe like this:</p> <pre><code>Id F M R 7 1 286 907 12 1 286 907 17 1 186 1271 21 1 296 905 30 1 308 908 32 1 267 905 40 2 591 788 41 1 486 874 47 1 686 906 74 1 230 907 </code></pre> <p>for each row if <code>f&gt; f's mean()</code> and <code>M&gt; M's mean()</code...
1
2016-06-27T08:00:28Z
38,048,781
<pre><code>df.loc[df['f']&gt;df['f'].mean(),['f']] += 1 df.loc[df['m']&gt;df['m'].mean(),['m']] += 1 df.loc[df['r']&gt;df['r'].mean(),['r']] += 1 </code></pre> <p>Have not tested this,please try and comment if works.</p> <p>Or try this one</p> <pre><code>df['f'] = [x+1 for x in df['f'] if x&gt;df['f'].mean()] df['m'...
0
2016-06-27T08:06:42Z
[ "python", "if-statement", "pandas", "dataframe", "mean" ]
pandas number >mean(), or <mean() , than output a number
38,048,665
<p>I have a dataframe like this:</p> <pre><code>Id F M R 7 1 286 907 12 1 286 907 17 1 186 1271 21 1 296 905 30 1 308 908 32 1 267 905 40 2 591 788 41 1 486 874 47 1 686 906 74 1 230 907 </code></pre> <p>for each row if <code>f&gt; f's mean()</code> and <code>M&gt; M's mean()</code...
1
2016-06-27T08:00:28Z
38,048,812
<p>You can use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>numpy.where</code></a> with <code>mask</code> created with comparing 3 columns with their <code>mean</code> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFra...
2
2016-06-27T08:08:53Z
[ "python", "if-statement", "pandas", "dataframe", "mean" ]
How to do validation date_end in odoo
38,048,669
<p>I have two model in my <code>calendar_holidays</code> that is <code>date_start</code> and <code>date_end</code>, I plan to do validation for <code>date_end</code> "<em>date_end must greater than date_start</em>" below is my code odoo python code</p> <pre><code>date_start = fields.Date(string='Date start', required=...
0
2016-06-27T08:00:36Z
38,050,797
<p>You are checking wring condition, I have just update IF condition else everything seems fine.</p> <pre><code>@api.multi @api.constrains('date_start','date_end') def _check_holidays(self): if self.date_start &gt; self.date_end: raise ValidationError('Date end must greater than start date') </code></pre>
0
2016-06-27T09:50:52Z
[ "python", "openerp" ]
File naming inside a for loop
38,048,730
<p>Please have a look on the following Minimal Working Example (MWE)</p> <pre><code>import numpy as np T_val = np.linspace(100,200,15) for i,T in enumerate(T_val): ut_file_name = 'kappaFunction_P_E_%2d.pdf' % i print out_file_name </code></pre> <p>The output for this MWE coming like:</p> <blockquote> <p>.<...
0
2016-06-27T08:03:55Z
38,048,798
<p>Add a <code>0</code> to the format</p> <pre><code>... %02d.pdf' % i </code></pre> <p>that will print 07, 08, 09, etc.</p>
1
2016-06-27T08:07:40Z
[ "python", "python-2.7", "for-loop" ]
File naming inside a for loop
38,048,730
<p>Please have a look on the following Minimal Working Example (MWE)</p> <pre><code>import numpy as np T_val = np.linspace(100,200,15) for i,T in enumerate(T_val): ut_file_name = 'kappaFunction_P_E_%2d.pdf' % i print out_file_name </code></pre> <p>The output for this MWE coming like:</p> <blockquote> <p>.<...
0
2016-06-27T08:03:55Z
38,048,821
<p>You don't need to use <code>enumerate</code> since your are only using the index. And for your format to work as expected, you need to use <code>%02d</code> to get the <code>0</code> before:</p> <pre><code>import numpy as np T_val = np.linspace(100,200,15) for i in range(len(T_val)): ut_file_name = 'kappaFuncti...
1
2016-06-27T08:09:22Z
[ "python", "python-2.7", "for-loop" ]
File naming inside a for loop
38,048,730
<p>Please have a look on the following Minimal Working Example (MWE)</p> <pre><code>import numpy as np T_val = np.linspace(100,200,15) for i,T in enumerate(T_val): ut_file_name = 'kappaFunction_P_E_%2d.pdf' % i print out_file_name </code></pre> <p>The output for this MWE coming like:</p> <blockquote> <p>.<...
0
2016-06-27T08:03:55Z
38,048,868
<pre><code>ut_file_name = 'kappaFunction_P_E_{:0&gt;2}.pdf'.format(i) </code></pre> <p>Your should use format(). You can reference from <a href="https://pyformat.info/" rel="nofollow">https://pyformat.info/</a> or docs from <a href="https://docs.python.org/2/library/string.html" rel="nofollow">https://docs.python.org/...
2
2016-06-27T08:12:25Z
[ "python", "python-2.7", "for-loop" ]
Marshmallow: Dict of nested Schema
38,048,775
<p>I'm wondering how to serialize a dict of nested <code>Schema</code>.</p> <p>Naively, I would expect syntaxes like this to work:</p> <pre><code>fields.List(Schema) fields.Dict(Schema) </code></pre> <p>or maybe</p> <pre><code>fields.List(fields.Nested(Schema)) fields.Dict(fields.Nested(Schema)) </code></pre> <p>S...
0
2016-06-27T08:06:30Z
39,193,467
<p>This is not possible right now, but it is a feature request:</p> <ul> <li><a href="https://github.com/marshmallow-code/marshmallow/issues/483" rel="nofollow">https://github.com/marshmallow-code/marshmallow/issues/483</a></li> <li><a href="https://github.com/marshmallow-code/marshmallow/issues/496" rel="nofollow">ht...
0
2016-08-28T16:34:29Z
[ "python", "serialization", "marshmallow" ]
How to turn warnings into errors when building sphinx documentation with setuptools?
38,048,945
<p>I am using setuptools to build my sphinx documentation of a python project (<code>python setup.py build_sphinx</code>).</p> <p>As found on, e.g., <a href="https://webmynd.wordpress.com/2009/01/28/building-sphinx-documentation-with-setuptools/" rel="nofollow">this site</a>, I have configured the build process using ...
2
2016-06-27T08:17:42Z
38,110,753
<p>The only solution I can manage is both simple and sub-optimal.</p> <p>Change from:</p> <pre><code>python setup.py build_sphinx </code></pre> <p>to:</p> <pre><code>python -W error setup.py build_sphinx </code></pre> <p>That will turn <strong>all</strong> warnings into errors, including errors from setuptools, et...
1
2016-06-29T21:58:08Z
[ "python", "python-sphinx", "setuptools" ]
How to use pydicom in jython
38,048,988
<p>When I tried to import dicom in pydicom package I got error. I performed the following steps. Downloaded the pydicom-0.9.9.tar file,extracted and performed 'jython setup.py install' in cmd.But its not working. Is this due to compatability of jython with python? How to make pydicom is working in jython?</p>
1
2016-06-27T08:19:43Z
38,078,205
<p>There is a bug in Jython on the bytecode files size. That is, Jython can’t compile the file if a module have huge bytecode size and unfortunately PyDicom have 2 such files. So, The work around is to split the files into junks and try installing.</p> <p>This is a temporary work around and this issue has been resol...
0
2016-06-28T13:54:57Z
[ "python", "jython-2.7" ]
How to set ReferenceField value of mongoengine in mongodb shell?
38,049,057
<p>this is my 2nd day with mongo. I am working with django + mongoengine. structure of my article document is like this:</p> <pre><code>class Article(Document): title = StringField(required=True) content = StringField(required=True) comments = ListField(ReferenceField(Comment)) author = ReferenceField(...
1
2016-06-27T08:23:43Z
38,049,272
<p>In Mongo shell we cannot use sub-queries in a kind os SQL like syntax.</p> <p>To solve that we could do:</p> <pre><code>var author = db.m_user.find({ 'email' : 'vsp@gmail.com' }).limit(1).toArray() db.article.update({ 'title' : 'asdasdasdasd' }, { $set : { 'author' ...
1
2016-06-27T08:35:40Z
[ "python", "django", "mongodb", "shell" ]
ansible throwing error on argument list for os_network
38,049,087
<p>we have installed ansible version 2.1.0 in ubuntu 14.04. </p> <p>While using os_network module we are getting this error. </p> <pre><code>root@ubuntu:/home/admin-nfv/Nuage_Automation/nuage_vm_creation/playbooks# ansible-playbook create_or_delete_network.yml [WARNING]: provided hosts list is empty, only localhost ...
2
2016-06-27T08:24:59Z
38,053,116
<p>Ansible uses the <code>shade</code> pip package inside the <code>os_network</code> module. The interface inside that package, especially around the <code>create_network</code> method has changed in recent versions, and newer versions of ansible are now dependent on the new features.</p> <p>You should make sure you ...
1
2016-06-27T11:44:49Z
[ "python", "ansible" ]
Why with CSV file it loads first column as a dtype64[ns], but a txt as a object
38,049,144
<p>Thanks to this forum someone else on here I have this code:</p> <pre><code>names=['Date','Wind Speed','Wind Direction'] df2 = pd.read_csv('test_met.csv', index_col=0, names=names, parse_dates=[0]) aethalometer=['Date','Conc'] df1=pd.read_csv('BC_2012_1min.csv', index_col=0, names=aethalometer, parse_dates=[0]) df1...
1
2016-06-27T08:28:37Z
38,051,156
<p>OK, your file looks like it's been foo-ed by whatever method you've done to create it, you have the header repeated on lines:</p> <p>43202, 87843, 132482, 174243, 186697, 231338, 274539, 319180, 363821, 407022, 448389</p> <p>like the following:</p> <pre><code>2012/4/30 23:59:00 -16.00 TimeW_1min CONC_1min 2012...
1
2016-06-27T10:07:03Z
[ "python", "pandas" ]
Replace string in line without adding new line?
38,049,188
<p>I want to replace string in a line which contain patternB, something like this:</p> <p>from:</p> <pre><code>some lines line contain patternA some lines line contain patternB more lines </code></pre> <p>to:</p> <pre><code>some lines line contain patternA some lines line contain patternB xx oo more lines </code></...
0
2016-06-27T08:31:13Z
38,049,263
<p>You can use <a href="https://docs.python.org/3.5/library/stdtypes.html#str.replace" rel="nofollow">str.replace</a>:</p> <pre><code>s = '''some lines line contain patternA some lines line contain patternB more lines''' print(s.replace('patternB', 'patternB xx oo')) </code></pre>
0
2016-06-27T08:35:25Z
[ "python", "python-2.7" ]
Replace string in line without adding new line?
38,049,188
<p>I want to replace string in a line which contain patternB, something like this:</p> <p>from:</p> <pre><code>some lines line contain patternA some lines line contain patternB more lines </code></pre> <p>to:</p> <pre><code>some lines line contain patternA some lines line contain patternB xx oo more lines </code></...
0
2016-06-27T08:31:13Z
38,049,287
<p>The simplest will be: 1. Read all File into string 2. Call string.replace 3. Dump string to file</p>
0
2016-06-27T08:36:29Z
[ "python", "python-2.7" ]
Replace string in line without adding new line?
38,049,188
<p>I want to replace string in a line which contain patternB, something like this:</p> <p>from:</p> <pre><code>some lines line contain patternA some lines line contain patternB more lines </code></pre> <p>to:</p> <pre><code>some lines line contain patternA some lines line contain patternB xx oo more lines </code></...
0
2016-06-27T08:31:13Z
38,049,316
<p>Of course it is, since you append line to dummy in the beginning of the for loop and then the modified version again in the "if" statement. Also why check for Pattern A if you treat is as you treat everything else?</p> <pre><code>inputfile = open("d:\myfile.abc", "r") outputfile = open("d:\myfile_renew.abc", "w") o...
0
2016-06-27T08:38:14Z
[ "python", "python-2.7" ]
Replace string in line without adding new line?
38,049,188
<p>I want to replace string in a line which contain patternB, something like this:</p> <p>from:</p> <pre><code>some lines line contain patternA some lines line contain patternB more lines </code></pre> <p>to:</p> <pre><code>some lines line contain patternA some lines line contain patternB xx oo more lines </code></...
0
2016-06-27T08:31:13Z
38,049,365
<p>If you want to keep line by line iterator (for a big file)</p> <pre><code>for line in inputfile: if line.find("patternB") != -1: dummy = line.replace('patternB', 'patternB xx oo') outputfile.write(dummy) else: outputfile.write(line) </code></pre> <p>This is slower than other respons...
0
2016-06-27T08:41:10Z
[ "python", "python-2.7" ]
Replace string in line without adding new line?
38,049,188
<p>I want to replace string in a line which contain patternB, something like this:</p> <p>from:</p> <pre><code>some lines line contain patternA some lines line contain patternB more lines </code></pre> <p>to:</p> <pre><code>some lines line contain patternA some lines line contain patternB xx oo more lines </code></...
0
2016-06-27T08:31:13Z
38,049,490
<p><strong>This should work</strong></p> <pre><code>import os def replace(): f1 = open("d:\myfile.abc","r") f2 = open("d:\myfile_renew.abc","w") ow = raw_input("Enter word you wish to replace:") nw = raw_input("Enter new word:") for line in f1: templ = line.split() for i in templ:...
0
2016-06-27T08:47:16Z
[ "python", "python-2.7" ]
New row based on other's row past value to current value
38,049,357
<p>I'm trying to create a new column called <code>move</code> in <code>df</code> that gives the value of <code>1</code> if the value in <code>x is higher</code> than its previous value and a <code>0</code> if the <code>value is lower</code>, so the first value in <code>move</code> should be a <code>NaN</code>.</p> <pr...
1
2016-06-27T08:40:37Z
38,049,434
<p>You can compare using <code>shift</code> with a slice of the column using <code>iloc</code> and cast the boolean series to numeric dtype using <code>astype</code>:</p> <pre><code>In [82]: df['move'] = (df['x'].iloc[1:] &gt; df['x'].iloc[1:].shift()).astype(int) df Out[82]: x move 0 1 NaN 1 0 0.0 2 2 1...
2
2016-06-27T08:44:51Z
[ "python", "pandas", "dataframe", "condition", "shift" ]
New row based on other's row past value to current value
38,049,357
<p>I'm trying to create a new column called <code>move</code> in <code>df</code> that gives the value of <code>1</code> if the value in <code>x is higher</code> than its previous value and a <code>0</code> if the <code>value is lower</code>, so the first value in <code>move</code> should be a <code>NaN</code>.</p> <pr...
1
2016-06-27T08:40:37Z
38,049,436
<p>I think you need compare with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.shift.html" rel="nofollow"><code>shift</code></a>ed values in column <code>x</code> and last you can change first value to <code>NaN</code> (if necessary):</p> <pre><code>df['move'] = (df.x &gt; df.x.shift())....
0
2016-06-27T08:44:53Z
[ "python", "pandas", "dataframe", "condition", "shift" ]
How to get the public ip's using boto3
38,049,391
<p>I need to extract all the RUNNING PUBLIC Ip's from AWS and i am using the following code:</p> <pre><code>def gather_public_ip(): regions = ['us-west-2', 'eu-central-1', 'ap-southeast-1'] combined_list = [] ##This needs to be returned for region in regions: instance_information = [] # I assume ...
-1
2016-06-27T08:42:31Z
38,049,902
<p>Use <code>get()</code> instead of <code>dict[key]</code>. <code>get()</code> will not raise a <code>KeyError</code>. Here are some examples which will explain. </p> <pre><code>&gt;&gt;&gt; test = {'xxx':123} &gt;&gt;&gt; test['xxx'] 123 &gt;&gt;&gt; test['yyy'] KeyError: 'yyy' &gt;&gt;&gt; test.get('yyy') &gt;&gt;&...
2
2016-06-27T09:06:56Z
[ "python", "boto3" ]
Need help understanding the behavior of a for loop
38,049,470
<p>I am working through a tutorial on sets in Python 2.7, and I have run into a behavior using a <code>for</code> loop that I do not understand, and I am trying to find out what the reason for the difference in outputs might be.</p> <p>The object of the exercise is to produce a set, cities, from a dictionary that cont...
0
2016-06-27T08:46:19Z
38,049,645
<p>The expression:</p> <pre><code>cities = set() cities = cities.union(pair for pair in flight_distances) </code></pre> <p>will take the union of the empty set <code>{}</code> with another set</p> <pre><code>{pair_0, pair_1, pair_2, ..., pair_n} </code></pre> <p>leaving you with a set of sets. </p> <p>In contrast,...
1
2016-06-27T08:55:17Z
[ "python", "for-loop", "set-comprehension" ]
Need help understanding the behavior of a for loop
38,049,470
<p>I am working through a tutorial on sets in Python 2.7, and I have run into a behavior using a <code>for</code> loop that I do not understand, and I am trying to find out what the reason for the difference in outputs might be.</p> <p>The object of the exercise is to produce a set, cities, from a dictionary that cont...
0
2016-06-27T08:46:19Z
38,049,723
<p>In the first version, <code>pair</code> is a <code>frozenset</code> at each loop, so you can do a <code>union</code> with it, while in your version, you try do a union with a <code>set</code> of <code>frozenset</code>.</p> <p>The first case comes down to (union with a <code>frozenset</code> at each iteration):</p> ...
0
2016-06-27T08:58:56Z
[ "python", "for-loop", "set-comprehension" ]
How to merge two columns into one in csv format (Python Pandas)?
38,049,548
<p>I crawled a table from html and parsed it into a csv file. Yet the format of the table on the web changed in the middle, yet they didn't update the previous rows, so some of the columns are deprecated. Looks something like this: <a href="http://i.stack.imgur.com/FtJfy.png" rel="nofollow"><img src="http://i.stack.img...
-2
2016-06-27T08:49:52Z
38,050,192
<p>I've met a similar problem, and solved it outside of pandas, and then merged the dataframes corresponding to the two kind of rows:</p> <pre><code>A = [] B = [] with open(your_file) as f: for line in f: if len(line.split(your_separator)) == expected_number_of_columns: A.append(line.split(you...
2
2016-06-27T09:21:56Z
[ "python", "csv", "pandas" ]
In Visual Studio Code can I force the file type for a non-standard file extension?
38,049,649
<p>I have a buildbot master configuration file:</p> <pre><code>master.cfg </code></pre> <p>The file is a python file. With a python identifier as the first line:</p> <pre><code># -*- python -*- </code></pre> <p>However VSCode reads it as plain text and I have to manually change it. Is there a way to get VSCode to d...
0
2016-06-27T08:55:29Z
38,074,278
<p>As Kenny Ostrom indicated, VSCode has section on "Adding a file extension to a Language":</p> <p><a href="https://code.visualstudio.com/docs/languages/overview#_adding-a-file-extension-to-a-language" rel="nofollow">https://code.visualstudio.com/docs/languages/overview#_adding-a-file-extension-to-a-language</a></p>
1
2016-06-28T10:55:37Z
[ "python", "vscode" ]
How to map/assign/replace values of one dictionary to another dictionary?
38,049,743
<p>Say I have the following 3 dictionaries:</p> <pre><code>General case: d1 = {'c_choice1': '1.10', 'c_choice2': '1.20',...} d2 = {'John': {'strength': 'choice1', 'agility': 'choice2',...},...} d3 = {'John': {'choice1': 'c_choice1', 'choice2': 'c_choice2',...},...} d2 and d3 can be: d2 = {'John': {'strength': 'choi...
0
2016-06-27T08:59:57Z
38,049,988
<p>You could do this as a single nested dict comprehension:</p> <pre><code>d4 = {name: {stat: d1[d3[name][choice]] for name, choices in d2.items() for stat, choice in stats.items()} for name, stats in d2.items()} </code></pre> <p>but that's almost impossible to understand. Instead, a l...
1
2016-06-27T09:11:12Z
[ "python", "python-2.7", "dictionary" ]
How to map/assign/replace values of one dictionary to another dictionary?
38,049,743
<p>Say I have the following 3 dictionaries:</p> <pre><code>General case: d1 = {'c_choice1': '1.10', 'c_choice2': '1.20',...} d2 = {'John': {'strength': 'choice1', 'agility': 'choice2',...},...} d3 = {'John': {'choice1': 'c_choice1', 'choice2': 'c_choice2',...},...} d2 and d3 can be: d2 = {'John': {'strength': 'choi...
0
2016-06-27T08:59:57Z
38,049,994
<p>You need to iterate over the keys and use then to extract data. for example:</p> <p><strong>In order to extract the names from d2:</strong></p> <pre><code>for name in d2: print name </code></pre> <blockquote> <p><strong>output</strong>:<br> John</p> </blockquote> <p><strong>Extract the dictionary for ea...
0
2016-06-27T09:11:41Z
[ "python", "python-2.7", "dictionary" ]
How to map/assign/replace values of one dictionary to another dictionary?
38,049,743
<p>Say I have the following 3 dictionaries:</p> <pre><code>General case: d1 = {'c_choice1': '1.10', 'c_choice2': '1.20',...} d2 = {'John': {'strength': 'choice1', 'agility': 'choice2',...},...} d3 = {'John': {'choice1': 'c_choice1', 'choice2': 'c_choice2',...},...} d2 and d3 can be: d2 = {'John': {'strength': 'choi...
0
2016-06-27T08:59:57Z
38,050,024
<p>Updated version: Based on the info given in the comments, I have modified my solution to handle multiple instances of the same choice value, or missing instances, in <code>d2</code>. Here is the new solution, which I believe will do what was requested. I have modified the sample data to exercise the new functiona...
2
2016-06-27T09:13:02Z
[ "python", "python-2.7", "dictionary" ]
Django included urls doesn't work
38,049,753
<p>Can't figure out why included urls isn't working. Project has 1 my app. So in myproject/mysite/urls.py i have:</p> <pre><code>urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), ...... url(r'^sub/', include('subscription.urls')), url(r'^', include('cms.urls')), ) </code></pre>...
1
2016-06-27T09:00:20Z
38,050,051
<blockquote> <p>if i try localhost:8000/sub/subscribe, it appends url with /lt/</p> </blockquote> <p>Thats because your url pattern requires a trailing slash, which you haven't provided</p> <pre><code>r'^subscribe/' # Shouldn't have the slash or should be optional </code></pre> <p>Normally this wouldn't be a prob...
1
2016-06-27T09:14:20Z
[ "python", "django" ]
Django included urls doesn't work
38,049,753
<p>Can't figure out why included urls isn't working. Project has 1 my app. So in myproject/mysite/urls.py i have:</p> <pre><code>urlpatterns = i18n_patterns('', url(r'^admin/', include(admin.site.urls)), ...... url(r'^sub/', include('subscription.urls')), url(r'^', include('cms.urls')), ) </code></pre>...
1
2016-06-27T09:00:20Z
38,051,609
<p>You have an error in calling the <a href="https://docs.djangoproject.com/en/1.9/ref/urls/#patterns" rel="nofollow"><code>patterns()</code></a> function:</p> <pre><code>urlpatterns = patterns( url(r'^subscribe/', subscribe), ) </code></pre> <p><code>patterns()</code> accepts a view prefix as the first argument,...
1
2016-06-27T10:28:31Z
[ "python", "django" ]
Shift images to the right in TensorFlow
38,049,787
<p>I've made a learning on Tensorflow (MNIST) and I've saved the weights in a .ckpt. Now I want to test my neural network on this weights, with the same images translated of a few pixels to the right and bottom. The loading weigths works well, but when I print an eval, Tensorflow display always the same results (0.9630...
0
2016-06-27T09:01:57Z
38,050,217
<p>You function <code>translate_right</code> doesn't work, because <code>images[i, j]</code> is just one pixel (containing 1 value if you have greyscale images).</p> <p>You should use the argument <code>axis</code> of <code>np.roll</code>:</p> <pre class="lang-py prettyprint-override"><code>def translate_right(images...
0
2016-06-27T09:23:13Z
[ "python", "neural-network", "tensorflow" ]
How to get the index of non-zero value in a numpy array quickly?
38,049,793
<p>Now I am writing a function which is to get the index of the non-zero values with following rules:</p> <ol> <li>The expected result is a list. Each element denotes the index of a continue slice of non-zero values. So for a list of <code>[0,0,0,1,1,1,0,1,1,0]</code>, it should get the list <code>[[3,4,5], [7,8]]</co...
0
2016-06-27T09:02:07Z
38,049,928
<p>With <code>arr</code> as input array and to have a list of arrays as output, you could do something like this -</p> <pre><code># Store non-zero element indices idx = np.where(arr)[0] # Get indices where the shifts occur, i.e. positions where groups of identical # elements are separated. For this we perform diffe...
2
2016-06-27T09:07:50Z
[ "python", "algorithm", "numpy", "data-structures" ]
What is the reason for this Cython compile error when declaring a cpdef enum?
38,049,841
<p>I am working on a Raspberry PI using Python 3.4.2 with Cython 0.24 and GCC 4.9.1.<br> I want to use a <code>cpdef enum</code> which creates a <a href="https://www.python.org/dev/peps/pep-0435/" rel="nofollow">PEP 435</a> style Python Enum (available since Python 3.4). This feature was introduced in <a href="https://...
0
2016-06-27T09:04:19Z
38,051,705
<p>An enum can be declared with either <code>ctypedef</code> or <code>cdef.</code><br> Try defining your enum like:</p> <pre><code>cdef enum Test: A, B, C, D </code></pre> <p>or </p> <pre><code>ctypedef enum Test: A, B, C, D </code></pre>
0
2016-06-27T10:33:04Z
[ "python", "python-3.x", "enums", "compiler-errors", "cython" ]
What is the reason for this Cython compile error when declaring a cpdef enum?
38,049,841
<p>I am working on a Raspberry PI using Python 3.4.2 with Cython 0.24 and GCC 4.9.1.<br> I want to use a <code>cpdef enum</code> which creates a <a href="https://www.python.org/dev/peps/pep-0435/" rel="nofollow">PEP 435</a> style Python Enum (available since Python 3.4). This feature was introduced in <a href="https://...
0
2016-06-27T09:04:19Z
38,059,038
<p>I think you might have the semicolon in the wrong place in your header? Also in the header you define <code>test</code>, but then in the cython you only refer to <code>Test</code>. Depending on what it's actually supposed to be something like below should work. Tested on a Raspberry Pi running Arch Linux.</p> <p><e...
0
2016-06-27T16:35:46Z
[ "python", "python-3.x", "enums", "compiler-errors", "cython" ]
How to select an integer randomly from a list containing integers as well as other objects?
38,049,898
<p>I have a list</p> <pre><code>data=['_','_','A','B','C',1,2,3,4,5] </code></pre> <p>I need to randomly get an integer among 1,2,3,4,5 The list keeps getting modified so i cant just simply choose from the last 5 members</p> <p>Here's what i tried but it throws an error retrieving the other members:</p> <pre><code...
1
2016-06-27T09:06:47Z
38,049,969
<p>You can filter the non-integer items; </p> <pre><code>inp2 = ramdom.choice([x for x in data if isinstance(x, int)]) </code></pre>
4
2016-06-27T09:10:28Z
[ "python", "list", "random" ]
How to select an integer randomly from a list containing integers as well as other objects?
38,049,898
<p>I have a list</p> <pre><code>data=['_','_','A','B','C',1,2,3,4,5] </code></pre> <p>I need to randomly get an integer among 1,2,3,4,5 The list keeps getting modified so i cant just simply choose from the last 5 members</p> <p>Here's what i tried but it throws an error retrieving the other members:</p> <pre><code...
1
2016-06-27T09:06:47Z
38,050,000
<p>To create a list of last 5 elements.</p> <pre><code>&gt;&gt;&gt; from random import choice &gt;&gt;&gt; data=['_','_','A','B','C',1,2,3,4,5] &gt;&gt;&gt; l = len(data) &gt;&gt;&gt; data[(l-5):l] [1, 2, 3, 4, 5] &gt;&gt;&gt; k = data[(l-5):l] &gt;&gt;&gt; choice(k) 5 &gt;&gt;&gt; choice(k) 2 &gt;&gt;&gt; </code></p...
0
2016-06-27T09:12:02Z
[ "python", "list", "random" ]
How to select an integer randomly from a list containing integers as well as other objects?
38,049,898
<p>I have a list</p> <pre><code>data=['_','_','A','B','C',1,2,3,4,5] </code></pre> <p>I need to randomly get an integer among 1,2,3,4,5 The list keeps getting modified so i cant just simply choose from the last 5 members</p> <p>Here's what i tried but it throws an error retrieving the other members:</p> <pre><code...
1
2016-06-27T09:06:47Z
38,050,092
<pre><code>random.choice([i for i in data[-5:] if isinstance(x, int)]) </code></pre> <p>It is more safe for check type of data[-5:] by isinstance().</p>
0
2016-06-27T09:16:17Z
[ "python", "list", "random" ]
How to select an integer randomly from a list containing integers as well as other objects?
38,049,898
<p>I have a list</p> <pre><code>data=['_','_','A','B','C',1,2,3,4,5] </code></pre> <p>I need to randomly get an integer among 1,2,3,4,5 The list keeps getting modified so i cant just simply choose from the last 5 members</p> <p>Here's what i tried but it throws an error retrieving the other members:</p> <pre><code...
1
2016-06-27T09:06:47Z
38,050,115
<p>Though it is almost similar to the answer of Neo, you can also try this:</p> <pre><code>inp2 = random.choice(filter(lambda d: isinstance(d, int), data)) </code></pre>
2
2016-06-27T09:17:31Z
[ "python", "list", "random" ]
How to select an integer randomly from a list containing integers as well as other objects?
38,049,898
<p>I have a list</p> <pre><code>data=['_','_','A','B','C',1,2,3,4,5] </code></pre> <p>I need to randomly get an integer among 1,2,3,4,5 The list keeps getting modified so i cant just simply choose from the last 5 members</p> <p>Here's what i tried but it throws an error retrieving the other members:</p> <pre><code...
1
2016-06-27T09:06:47Z
38,050,184
<p>Try this.</p> <pre><code>import operator inp2 = random.choice(filter(operator.isNumberType, data)) </code></pre> <p>For this specific problem selecting last 5 elements also a good solution. </p> <pre><code>inp2 = random.choice(data[5:]) </code></pre>
0
2016-06-27T09:21:42Z
[ "python", "list", "random" ]
How to select an integer randomly from a list containing integers as well as other objects?
38,049,898
<p>I have a list</p> <pre><code>data=['_','_','A','B','C',1,2,3,4,5] </code></pre> <p>I need to randomly get an integer among 1,2,3,4,5 The list keeps getting modified so i cant just simply choose from the last 5 members</p> <p>Here's what i tried but it throws an error retrieving the other members:</p> <pre><code...
1
2016-06-27T09:06:47Z
38,055,635
<p>I think the best solution would be creating another list, where would be just int values you want to pick from. I don't know your specified assignment, but for example if you have a method for adding to your list, just add there:</p> <pre><code>def add(self, element): self.data.append(element) if type(element...
0
2016-06-27T13:46:27Z
[ "python", "list", "random" ]
Userview with no return statement
38,049,932
<p>I am told that this piece of code works in django.</p> <pre><code>class UserDetailView(LoginRequiredMixin, DetailView): model = User # These next two lines tell the view to index lookups by username slug_field = 'username' slug_url_kwarg = 'username' </code></pre> <p>As i am new to Django. There is...
-1
2016-06-27T09:08:16Z
38,050,038
<p>You are using generic views (<a href="https://docs.djangoproject.com/es/1.9/ref/class-based-views/generic-display/" rel="nofollow">https://docs.djangoproject.com/es/1.9/ref/class-based-views/generic-display/</a>). Your view is child of DetailView. Take a look at the docs and you will sort things out.</p>
1
2016-06-27T09:13:32Z
[ "python", "django" ]
Python: Adding boundary values in while loops
38,049,996
<p>As the question says. I'm trying to get 4 'practical' grades from a student, while keeping the boundaries of each grade within 0-40. However i keep getting an error with my following code:</p> <pre><code>while True: try: mark = int(input("What was your first mark out of the four? ")) if mark &lt...
-1
2016-06-27T09:11:49Z
38,050,216
<p>This is because you're first adding and then checking and therefor <code>mark</code> will never be <code>&gt; 40+mark</code> or <code>&lt; 0-mark</code>.</p> <pre><code>mark += int(input("And the next mark? ")) # The next line is where the problem is if mark &lt; 0-mark or mark &gt; 40+mark : # mark will never be &...
0
2016-06-27T09:23:12Z
[ "python" ]
Uninstalling Python3.5 from Linux RHEL
38,050,053
<p>I installed Python3.5 in Linux machine using <code>configure</code>, <code>make</code>, <code>make install</code> and made it default over existing Python2.6 . Now I want to uninstall Python 3.5 as it is not supporting <code>zlib</code>. How do I uninstall default Python 3.5. Linux is RHEL6.7.</p>
0
2016-06-27T09:14:28Z
38,050,633
<p>you probably can remove the directory that contain the new installation. but the main thing is to remove it from the $PATH.</p>
0
2016-06-27T09:43:16Z
[ "python", "linux", "python-3.x", "rhel", "make-install" ]
Uninstalling Python3.5 from Linux RHEL
38,050,053
<p>I installed Python3.5 in Linux machine using <code>configure</code>, <code>make</code>, <code>make install</code> and made it default over existing Python2.6 . Now I want to uninstall Python 3.5 as it is not supporting <code>zlib</code>. How do I uninstall default Python 3.5. Linux is RHEL6.7.</p>
0
2016-06-27T09:14:28Z
38,384,497
<p>To re-add Python 3.x, go here to use a software collection which installs "along side" the original 2.6 - so no collisions/corruption. <a href="http://developers.redhat.com/products/softwarecollections/get-started-rhel6-python/" rel="nofollow">http://developers.redhat.com/products/softwarecollections/get-started-rh...
0
2016-07-14T21:22:52Z
[ "python", "linux", "python-3.x", "rhel", "make-install" ]
Uninstalling Python3.5 from Linux RHEL
38,050,053
<p>I installed Python3.5 in Linux machine using <code>configure</code>, <code>make</code>, <code>make install</code> and made it default over existing Python2.6 . Now I want to uninstall Python 3.5 as it is not supporting <code>zlib</code>. How do I uninstall default Python 3.5. Linux is RHEL6.7.</p>
0
2016-06-27T09:14:28Z
38,384,650
<p>Because python is integral into the RHEL OS, please explain what you mean by: "and made it default over existing Python2.6 ." Otherwise attempts to "uninstall" your working python install might leave you with a broken RHEL install.</p>
0
2016-07-14T21:35:39Z
[ "python", "linux", "python-3.x", "rhel", "make-install" ]
Unbound method must be called with X instance as first argument (got str instance instead)
38,050,084
<p>I am playing with <a href="https://github.com/yann2192/pyelliptic" rel="nofollow">pyelliptic</a>, but I can't use the method <code>raw_get_ecdh_key</code> defined in the file <em>ecc.py</em>.</p> <p>Here's my example code:</p> <pre><code>&gt;&gt;&gt; import pyelliptic &gt;&gt;&gt; pubkey1="0453eb8248f42b00d057bc1a...
0
2016-06-27T09:15:57Z
38,051,294
<p>It's a very obvious bug in pyelliptic - if you look at the code, the part where <code>own_key</code> is defined (ecc.py line 301) is wrapped in huge try/finally block. If an exception is raised (and not managed) before line 301 (which is obviously what happened to you), then the execution flow jumps to the <code>fin...
0
2016-06-27T10:13:46Z
[ "python", "class", "methods" ]
NodeJS streaming JSON from python
38,050,095
<p>I'm creating an API with NodeJS. Every request returns a JSON. Some requests call to a python script and I want to send the JSON generated by python to the user. The code would look like:</p> <pre><code>child = child_process.spawn(cmd, args); child.stdout.on('data', (chunk) =&gt; { res.write(chunk); }); child...
0
2016-06-27T09:16:23Z
38,051,608
<p>Instead of using <code>spawn</code>, you probably want to use <a href="https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback" rel="nofollow"><code>exec</code></a>, which will wait for the Python process to exit and provide you with its output (which you can subsequently ...
1
2016-06-27T10:28:31Z
[ "python", "json", "node.js" ]
NodeJS streaming JSON from python
38,050,095
<p>I'm creating an API with NodeJS. Every request returns a JSON. Some requests call to a python script and I want to send the JSON generated by python to the user. The code would look like:</p> <pre><code>child = child_process.spawn(cmd, args); child.stdout.on('data', (chunk) =&gt; { res.write(chunk); }); child...
0
2016-06-27T09:16:23Z
38,053,478
<p>So you need a streaming JSON verifier in NodeJS. The problem is that if you start streaming the json data over the network, and find an error in the JSON halfways, you cannot rollback the traffic to the http headers and change <code>200 ok</code> to <code>500 ise</code>. If you want to check the output first you hav...
0
2016-06-27T12:02:52Z
[ "python", "json", "node.js" ]
Why is my Spark DataFrame much slower than RDD?
38,050,140
<p>I have a very simple Spark DataFrame, and when running a DataFrame groupby, the performance is terrible - about 8x slower than the (in my head) equivalent RDD reduceByKey...</p> <p>My cached DF is just two columns, customer and name with only 50k rows:</p> <pre><code>== Physical Plan == InMemoryColumnarTableScan [...
3
2016-06-27T09:19:09Z
38,052,035
<p>Both numbers seem to be relatively high and it is not exactly clear how you create <code>DataFrame</code> or measure the time but in general difference like this can be explained by a low number of records compared to the number of partitions.</p> <p>Default value for <code>spark.sql.shuffle.partitions</code> is 20...
2
2016-06-27T10:49:46Z
[ "python", "apache-spark", "pyspark", "spark-dataframe" ]
efficient way to operate on JSON type file
38,050,199
<p>So, I have a JSON file something which is a large one and keep on increasing. So, I am showing a simpler version here.</p> <pre><code>{ "b0:47:bf:af:c1:42": { "No. of visits": 10, "cities": { "Mumbai": {"count": 5,"last_visited": "5/22/2016"}, "Kolkata": {"count": 2,"last_visited": "5/22/2016"},...
2
2016-06-27T09:22:28Z
38,050,780
<p>You implement like this. It's implement with the basic dictionary operations. The concept is created a list of list with the no.of visit and city name. And it's sorted with using key <code>itemgetter</code>. Get the max visited city from there and get the percent with simple math operations.</p> <pre><code>from ope...
2
2016-06-27T09:50:05Z
[ "python", "json", "mongodb", "bigdata", "data-analysis" ]
efficient way to operate on JSON type file
38,050,199
<p>So, I have a JSON file something which is a large one and keep on increasing. So, I am showing a simpler version here.</p> <pre><code>{ "b0:47:bf:af:c1:42": { "No. of visits": 10, "cities": { "Mumbai": {"count": 5,"last_visited": "5/22/2016"}, "Kolkata": {"count": 2,"last_visited": "5/22/2016"},...
2
2016-06-27T09:22:28Z
38,051,184
<p>You can use the <code>json</code> library in Python. It takes a string, and gives back a <code>dict</code> which you can then parse. </p> <p>While I have no disagreement with Rahul's answer, I think it's neater to use the max function instead, and the basic data structure from the json.</p> <pre><code>import json ...
1
2016-06-27T10:08:22Z
[ "python", "json", "mongodb", "bigdata", "data-analysis" ]
How to predict a simple sequence using seq2seq from tensorflow?
38,050,333
<p>I've recently started working with tensorflow so I'm still struggling with basics.</p> <p>I wanted to create simple seq2seq prediction. </p> <ul> <li>Input is list of numbers between 0 and 1. </li> <li>Output is first number from list and the rest of the numbers multiplied by first.</li> </ul> <p>I managed to eva...
5
2016-06-27T09:28:20Z
38,067,223
<p>When you're training, you give the decoder input at each decoder timestep as the desired output. When testing, you do not have the desired output, so the best you can do is sample an output. This will be the input to the next timestep.</p> <p>TLDR; Feed in the decoder output at each timestep as the input for the ne...
2
2016-06-28T04:45:22Z
[ "python", "tensorflow", "lstm" ]
send custom mail makes memory leaks in python loop?
38,050,374
<p>I think this question is not good for understand, but i have to guess about it.</p> <p>Status:</p> <ul> <li>send mail for over then 20,000 users.</li> <li>send mail that has custom html for every users.</li> <li>mail will be sent on production Server.</li> </ul> <p>I expect, memory usage will be bigger then usual...
0
2016-06-27T09:30:49Z
38,050,551
<p>Given the example code, those variables will be garbage collected. There is no need to free them. </p> <p>If you're nervous, you could simply split the contents of the loop into a function taking the user as a parameter. It is easy to reason that a local variable within a function that is never passed out of the fu...
1
2016-06-27T09:39:02Z
[ "python", "memory", "memory-leaks" ]
send custom mail makes memory leaks in python loop?
38,050,374
<p>I think this question is not good for understand, but i have to guess about it.</p> <p>Status:</p> <ul> <li>send mail for over then 20,000 users.</li> <li>send mail that has custom html for every users.</li> <li>mail will be sent on production Server.</li> </ul> <p>I expect, memory usage will be bigger then usual...
0
2016-06-27T09:30:49Z
38,051,449
<p>Python uses garbage collection. That means that when a variable has no references on it, it <em>can</em> be freed by the garbage collector. <code>del</code> does not free memory: it just remove the indentifier pointing to the actual variable.</p> <p>Example:</p> <pre><code>a = [1,2,3] b = a del a </code></pre> <p...
2
2016-06-27T10:20:38Z
[ "python", "memory", "memory-leaks" ]
Adding spark-csv package in PyCharm IDE
38,050,380
<p>I have successfully loaded spark-csv library in python standalone mode through</p> <pre><code>$ --packages com.databricks:spark-csv_2.10:1.4.0 </code></pre> <p><a href="http://i.stack.imgur.com/HwciJ.png" rel="nofollow">Running the above command</a></p> <p>While running the above command, it creates two folders(j...
1
2016-06-27T09:31:05Z
38,054,229
<ul> <li><p>sqlContext.read.format('com.databricks.spark.csv') on your console does not garantee that the package is actually installed until you execute a proper command on it. In fact the command </p> <pre><code>sqlContext.read.format('com.dummy.csv') </code></pre></li> </ul> <p>will not return any error either</p...
0
2016-06-27T12:38:23Z
[ "python", "apache-spark", "pycharm", "pyspark", "spark-csv" ]
Adding spark-csv package in PyCharm IDE
38,050,380
<p>I have successfully loaded spark-csv library in python standalone mode through</p> <pre><code>$ --packages com.databricks:spark-csv_2.10:1.4.0 </code></pre> <p><a href="http://i.stack.imgur.com/HwciJ.png" rel="nofollow">Running the above command</a></p> <p>While running the above command, it creates two folders(j...
1
2016-06-27T09:31:05Z
38,267,679
<p>The solution is to add an environment variable named as "PYSPARK_SUBMIT_ARGS" and set its value to "--packages com.databricks:spark-csv_2.10:1.4.0 pyspark-shell". It will work fine.</p>
1
2016-07-08T13:15:22Z
[ "python", "apache-spark", "pycharm", "pyspark", "spark-csv" ]
Is there another way in python to remove a key,value pair from a dictionary other than del key[value]?
38,050,407
<p>I have a function that works fine on its own, but raises a key error when I try to use it inside another function. Rather than try to explain the larger context, I thought it would be easier to just change the <em>del hand[letter]</em>, which is where the error is raised. In some cases I could just change hand[lette...
0
2016-06-27T09:32:22Z
38,050,419
<p>Use <code>.pop</code>, so in the case the key does not exist, it does not throw any error when you use a default, say <code>None</code>:</p> <pre><code>hand.pop(letter, None) # ^ pops None when the key letter does not exist </code></pre> <p>Since you already have a check for the existence of the s...
5
2016-06-27T09:33:09Z
[ "python", "dictionary" ]
Is there another way in python to remove a key,value pair from a dictionary other than del key[value]?
38,050,407
<p>I have a function that works fine on its own, but raises a key error when I try to use it inside another function. Rather than try to explain the larger context, I thought it would be easier to just change the <em>del hand[letter]</em>, which is where the error is raised. In some cases I could just change hand[lette...
0
2016-06-27T09:32:22Z
38,051,680
<p>If your function "works fine on it's own but raises when called from another function" then the very first thing to do would be to find out <em>why</em> you have a problem in the second case. Else it's a canonical example of <a href="https://en.wikipedia.org/wiki/Programming_by_permutation" rel="nofollow">programmin...
0
2016-06-27T10:31:52Z
[ "python", "dictionary" ]
How to deal with the boolean operator when their length don't match in pandas?
38,050,596
<p>Given such a data frame <code>a</code> and <code>idx</code>:</p> <pre><code>import pandas as pd import numpy as np idx = np.array([False, False, True, True, False]) a = pd.Dataframe(np.full((5),0)) </code></pre> <p>I want to add <code>n</code> to <code>a</code> and the <code>n</code> denotes the number of <code>Tr...
0
2016-06-27T09:41:15Z
38,050,700
<p>IIUC you want <code>cumsum</code>:</p> <pre><code>In [106]: pd.DataFrame(idx).cumsum() Out[106]: 0 0 0 1 0 2 1 3 2 4 2 </code></pre> <p>your question is a little unclear but you can use the boolean array itself and call <code>cumsum</code> which will convert the <code>True</code> to <code>1</code></p>
0
2016-06-27T09:47:13Z
[ "python", "pandas" ]
Wagtail SnippetChooserBlock in Streamfield
38,050,609
<p>I am having some trouble getting the values from a snippet, that I have included into a streamfield using a Snippet Chooser Block.</p> <p>BioSnippet:</p> <pre><code>@register_snippet class BioSnippet(models.Model): name = models.CharField(max_length=200, null=True) job_title = models.CharField(max_length=2...
1
2016-06-27T09:41:52Z
38,051,221
<p><code>bios</code> here is defined as a list of <code>BioInline</code> values, and so <code>b</code> in your template would be a <code>BioInline</code> value - which has a single property, <code>bio</code> (giving you the actual <code>BioSnippet</code> object). To get the name, you'd therefore have to use: <code>{{ b...
1
2016-06-27T10:10:14Z
[ "python", "django", "wagtail", "wagtail-streamfield", "wagtail-snippet" ]
Getting "Expected string, got None" error on Model.get_by_id()
38,050,616
<p>When running this code, with the <em>same site_id</em>:</p> <pre><code>int_id= int(self.request.get("site_id")) site_draft = SiteDraft.get_by_id(int_id) </code></pre> <p>I'm getting this error:</p> <pre><code>INFO 2016-06-27 12:39:19,040 module.py:788] minisites: "GET /edit/5891733057437696 HTTP/1.1" 500 - ...
0
2016-06-27T09:42:11Z
38,064,279
<p>As request</p> <p>Looking at the stack trace in detail and paying attention to the operations performed, </p> <p>we see </p> <pre><code> _get_by_id get_result _help_tasklet_al get _to_pb _serialize _get_base_value _get_base_value _apply_to_values _opt_call_to_base _call_to_base_type call _validate BadValu...
2
2016-06-27T22:35:56Z
[ "python", "google-app-engine", "google-cloud-datastore" ]
Local scope for numpy set_printoptions
38,050,643
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.set_printoptions.html" rel="nofollow">np.set_printoptions</a> allows to customize the <em>pretty printing</em> of numpy arrays. For different use cases, however, I would like to have different printing options. </p> <p>Ideally, this would be done w...
0
2016-06-27T09:43:52Z
38,054,473
<p>Try</p> <pre><code> np.array_repr(x, precision=6, suppress_small=True) </code></pre> <p>Or one of the related functions that take keywords like <code>precision</code>. Looks like it can control many, if not all, of the print options. </p>
1
2016-06-27T12:51:13Z
[ "python", "arrays", "numpy", "pretty-print" ]
Getting a Python function's source code without the definition lines
38,050,649
<p>Using the <code>inspect.getsourcelines</code> function, I have been able to get a Python function's source code like this:</p> <pre><code>import inspect def some_decorator(x): return x @some_decorator def foo(): print("bar") print(inspect.getsourcelines(foo)[0]) </code></pre> <p>This code will corre...
1
2016-06-27T09:44:17Z
38,050,845
<p>You can find that the code you want all have blank before, so you can try this</p> <pre><code>print filter(lambda x:x.startswith(' '), inspect.getsourcelines(foo)[0]) </code></pre>
2
2016-06-27T09:53:11Z
[ "python", "function" ]
Getting a Python function's source code without the definition lines
38,050,649
<p>Using the <code>inspect.getsourcelines</code> function, I have been able to get a Python function's source code like this:</p> <pre><code>import inspect def some_decorator(x): return x @some_decorator def foo(): print("bar") print(inspect.getsourcelines(foo)[0]) </code></pre> <p>This code will corre...
1
2016-06-27T09:44:17Z
38,050,969
<p>Using <code>re</code> to handle <code>def</code> and <code>async def</code>:</p> <pre><code>def_regexp = r"^(\s*)(?:async\s+)?def foobar\s*?\:" def get_func_code(func): lines = inspect.getsourcelines(foo)[0] for idx in range(len(lines)): # in py2.X, use range def_match = re.match(line, def_regexp) ...
1
2016-06-27T09:59:11Z
[ "python", "function" ]
Getting a Python function's source code without the definition lines
38,050,649
<p>Using the <code>inspect.getsourcelines</code> function, I have been able to get a Python function's source code like this:</p> <pre><code>import inspect def some_decorator(x): return x @some_decorator def foo(): print("bar") print(inspect.getsourcelines(foo)[0]) </code></pre> <p>This code will corre...
1
2016-06-27T09:44:17Z
38,051,289
<p>You can do something like this:</p> <pre><code>import inspect from itertools import dropwhile def get_function_body(func): source_lines = inspect.getsourcelines(func)[0] source_lines = dropwhile(lambda x: x.startswith('@'), source_lines) def_line = next(source_lines).strip() if def_line.startswith...
2
2016-06-27T10:13:32Z
[ "python", "function" ]
Why XmlNode.SelectNodes returns empty list when XPath validator returns correct result?
38,050,733
<p>The code is in IronPython and here it is:</p> <pre><code>for systemNode in csResultXML.SelectNodes("Response/SubSystems/SubSystem"): itemNodes = systemNode.SelectNodes('/SubSystem/Items/Item') </code></pre> <p>The value of systemNode in the single loop cycle is:</p> <pre><code>&lt;SubSystem ID="0"&gt; &lt;...
1
2016-06-27T09:48:21Z
38,050,795
<p>You need to use <code>systemNode.SelectNodes('Items/Item')</code> as you want to select the <code>Items</code> child element of the context node (your <code>systemNode</code> variable) and not the <code>Items</code> child element of the document node <code>/</code>.</p>
2
2016-06-27T09:50:50Z
[ "python", ".net", "xpath", "ironpython", "xmlnode" ]
How to get the element id when I browse a webpage
38,050,759
<p>I want to get the element id when I click a button or something else in a webpage . How can i get it by Python or js?</p>
-1
2016-06-27T09:49:10Z
38,051,369
<p>If by "get the element id when I click a button" you mean the id of the button then this is how you do it in javascript</p> <pre><code> &lt;button onclick="myFunction(event)" id="testBtn"&gt;Click me&lt;/button&gt; </code></pre> <p>And inside your script tag</p> <pre><code> function myFunction(event) { console....
0
2016-06-27T10:17:43Z
[ "python", "webpage" ]
Heapq module losing elements on heappop
38,050,849
<p>I was playing around with the heapq module and experienced awkward behaviour, though I only use the built in functions modifying it. I created a sample to show the behaviour. My Python version is 3.5.1+. In the sample I would expect 6 elements in the final output, but somehow it looses 3 of them.</p> <pre><code>fro...
0
2016-06-27T09:53:13Z
38,076,571
<p>I figured out the problem now on my own and want to give an explanation. The problem is not related with the heapq module, but rather with modifying the list while iterating over it. With the heappop function we remove the first element from the list and return it. I am showing the influence of this on the list and ...
0
2016-06-28T12:41:06Z
[ "python", "python-3.x" ]
Can two Python argparse objects be combined?
38,050,873
<p>I have an object A which contains parserA - an argparse.ArgumentParser object There is also object B which contains parserB - another argparse.ArgumentParser</p> <p>Object A contains an instance of object B, however object B's arguments now need to be parsed by the parser in object A (since A is the one being calle...
2
2016-06-27T09:54:02Z
38,053,253
<p>You can't use one <code>ArgumentParser</code> inside another. But there is a way around. You need to extract to method code that add arguments to parser. Then you will be able to use them to merge arguments in parser. Also it will be easer to group arguments (related to their parsers). But you must be shore that set...
2
2016-06-27T11:51:56Z
[ "python", "python-2.7", "argparse" ]
Can two Python argparse objects be combined?
38,050,873
<p>I have an object A which contains parserA - an argparse.ArgumentParser object There is also object B which contains parserB - another argparse.ArgumentParser</p> <p>Object A contains an instance of object B, however object B's arguments now need to be parsed by the parser in object A (since A is the one being calle...
2
2016-06-27T09:54:02Z
38,058,315
<p><code>argparse</code> was developed around objects. Other than a few constants and utility functions it is all class definitions. The documentation focuses on use rather than that class structure. But it may help to understand a bit of that.</p> <pre><code>parser = argparse.ArgumentParser(...) </code></pre> <p>...
2
2016-06-27T15:53:01Z
[ "python", "python-2.7", "argparse" ]
Number of features in dictionary
38,050,896
<p>I am working on loading a dataset from a pickle file like this</p> <pre><code>""" Load the dictionary containing the dataset """ with open("final_project_dataset.pkl", "r") as data_file: data_dict = pickle.load(data_file) </code></pre> <p>It works fine and loads the data correctly. This is an example of one ro...
1
2016-06-27T09:55:20Z
38,050,935
<p>Apply <code>sum</code> to the <code>len</code> of each nested dictionary:</p> <pre><code>sum(len(v) for _, v in data_dict.items()) </code></pre> <p><code>v</code> represents a nested dictionary object.</p> <p>Dictionaries will <em>naturally</em> return their keys when you call an iterator on them (or something of...
1
2016-06-27T09:57:08Z
[ "python", "python-2.7", "dictionary" ]
Number of features in dictionary
38,050,896
<p>I am working on loading a dataset from a pickle file like this</p> <pre><code>""" Load the dictionary containing the dataset """ with open("final_project_dataset.pkl", "r") as data_file: data_dict = pickle.load(data_file) </code></pre> <p>It works fine and loads the data correctly. This is an example of one ro...
1
2016-06-27T09:55:20Z
38,050,940
<p>Try this.</p> <pre><code>no_of_features = len(data_dict[data_dict.keys()[0]]) </code></pre> <p>This will work only if all your keys in <code>data_dict</code> have same number of features.</p> <p><strike>or simply</p> <pre><code>no_of_features = len(data_dict['GLISAN JR BEN F']) </code></pre> <p></strike></p...
0
2016-06-27T09:57:26Z
[ "python", "python-2.7", "dictionary" ]
Number of features in dictionary
38,050,896
<p>I am working on loading a dataset from a pickle file like this</p> <pre><code>""" Load the dictionary containing the dataset """ with open("final_project_dataset.pkl", "r") as data_file: data_dict = pickle.load(data_file) </code></pre> <p>It works fine and loads the data correctly. This is an example of one ro...
1
2016-06-27T09:55:20Z
38,050,986
<pre><code>""" Load the dictionary containing the dataset """ with open("final_project_dataset.pkl", "r") as data_file: data_dict = pickle.load(data_file) print len(data_dict) </code></pre>
1
2016-06-27T09:59:56Z
[ "python", "python-2.7", "dictionary" ]
Number of features in dictionary
38,050,896
<p>I am working on loading a dataset from a pickle file like this</p> <pre><code>""" Load the dictionary containing the dataset """ with open("final_project_dataset.pkl", "r") as data_file: data_dict = pickle.load(data_file) </code></pre> <p>It works fine and loads the data correctly. This is an example of one ro...
1
2016-06-27T09:55:20Z
38,051,302
<p>I think you want to find out the size of the set of all unique field names used in the row dictionaries. You can find that like this:</p> <pre><code>data_dict = { 'red':{'alpha':1,'bravo':2,'golf':3,'kilo':4}, 'green':{'bravo':1,'delta':2,'echo':3}, 'blue':{'foxtrot':1,'tango':2} } unique_features = ...
1
2016-06-27T10:14:09Z
[ "python", "python-2.7", "dictionary" ]
Reading a line's number in a file
38,050,912
<p>Currently I have: </p> <pre><code>for line in f: if line == promble: print("check") </code></pre> <p>I want to make the program print the line after the line I have selected. Help. </p>
-2
2016-06-27T09:56:18Z
38,051,333
<p>If you want to test a line in a file, and if it matches print the next line in the file, try:</p> <pre><code>selected = False for line in f: if selected: print line selected = False if line == promble: selected = True </code></pre>
0
2016-06-27T10:16:07Z
[ "python", "file" ]
Reading a line's number in a file
38,050,912
<p>Currently I have: </p> <pre><code>for line in f: if line == promble: print("check") </code></pre> <p>I want to make the program print the line after the line I have selected. Help. </p>
-2
2016-06-27T09:56:18Z
38,051,454
<p>Use <code>enumerate</code></p> <pre><code>for index,line in enumerate(f): if line == promble: print f[index+1] </code></pre>
0
2016-06-27T10:20:45Z
[ "python", "file" ]
Reading a line's number in a file
38,050,912
<p>Currently I have: </p> <pre><code>for line in f: if line == promble: print("check") </code></pre> <p>I want to make the program print the line after the line I have selected. Help. </p>
-2
2016-06-27T09:56:18Z
38,051,542
<p>Your <code>file</code> object <code>f</code> has an <code>__iter__</code> attribute, so you can apply <code>next</code> to get the next item in your loop:</p> <pre><code>for line in f: if line == promble: print(next(f)) # prints next line after the current one </code></pre> <p>If <code>f</code> is neit...
0
2016-06-27T10:25:25Z
[ "python", "file" ]
python dictionary assignment using map and lambda
38,050,928
<p>I was just curious to know if the following loop is doable with the map() rather than using for loop ? If yes please be kind enough to show how ? or what's the most efficient way to do the following ?</p> <pre><code>f = open('sample_list.txt').read().split('\n') val = lambda x: re.match('[a-zA-z0-9]+',x).group...
3
2016-06-27T09:56:46Z
38,051,197
<p>Better to use <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dict comprehension</a> than <code>map</code>.</p> <p>Can be done like this:</p> <pre><code>my_dict = { val(line) : 0 if line.find('XYZ') == -1 else 1 for line in f } </code></pre> <p>Some notes and improvements:</p> <ol> <li...
4
2016-06-27T10:09:03Z
[ "python", "dictionary", "lambda" ]
python dictionary assignment using map and lambda
38,050,928
<p>I was just curious to know if the following loop is doable with the map() rather than using for loop ? If yes please be kind enough to show how ? or what's the most efficient way to do the following ?</p> <pre><code>f = open('sample_list.txt').read().split('\n') val = lambda x: re.match('[a-zA-z0-9]+',x).group...
3
2016-06-27T09:56:46Z
38,051,400
<p>With a lambda:</p> <pre><code>dict(map(lambda x: (x[0], int(x[1] == 'XYZ')), map(str.split, f))) </code></pre> <p>Or:</p> <pre><code>dict(map(lambda k, v: (k, int(v == 'XYZ')), *map(str.split, f))) </code></pre> <p>Dictionary comprehension:</p> <pre><code>{k: int(v == 'XYZ') for k, v in map(str.split, f)} </cod...
1
2016-06-27T10:18:34Z
[ "python", "dictionary", "lambda" ]
How do I change the properties of a child widget by having a method in the root widget?
38,050,945
<p>I am trying to do the following.</p> <p>-i have 'GameScreen' as the root widget.</p> <p>-When I click a button,I want its color to be changed to green if it is red in color.At the same time,I also want the value of the 'Label' to be incremented by 1.I want to do it by having a method in the GameScreen class.But I ...
0
2016-06-27T09:57:56Z
38,052,636
<p>You can use ternary operator in kv language and by using the ';' character you can run multiple statements in one line.</p> <pre><code>&lt;Button&gt;: size_hint:0.33,0.8/3 &lt;GameScreen@BoxLayout&gt;: Button: name:"1" text:self.name color:(0,1,0,1) if self.pressed else (1,0,0,1) ...
1
2016-06-27T11:20:57Z
[ "python", "kivy" ]
Pyro4 Serialize Error : unsupported serialized class
38,051,005
<p>I'm new to Pyro4 and need to get into it, and what better way is there than trying out the examples contained in the Pyro4 package? So my first move was to simply make one work, it's the example "warehouse". The idea is to have a person visit the warehouse and choose items to take or store. The file "warehouse.py" ...
0
2016-06-27T10:00:30Z
38,064,805
<p>Your source files are wrong. Did you type them in yourself? Where did you get them from? Because the ones you show us here are very old versions of those example files (3 years old!) Those old versions indeed won't work anymore with recent versions of Pyro4 due to some changes to the serializer mechanism that have ...
0
2016-06-27T23:32:13Z
[ "python", "windows", "serialization", "pyro" ]
Retrieving current user inside Serializer Method in Django Rest API
38,051,145
<p>I have a serializer for user profiles in Django Rest: </p> <pre><code>class UserProfileSerializer(serializers.ModelSerializer): ...................... ...................... status = serializers.SerializerMethodField() def get_status(self, obj): user = self.context['request'].user ...
0
2016-06-27T10:06:36Z
38,051,268
<p>Since <strong>you are manually instantiating the <code>UserProfileSerializer</code> in your <code>APIView</code> class without passing the <code>context</code></strong>, <code>KeyError</code> exception gets raised.</p> <p>You should pass the <code>request</code> in <code>context</code> parameter when instantiating ...
1
2016-06-27T10:12:36Z
[ "python", "django", "serialization", "django-rest-framework" ]
Permissions manager
38,051,218
<p>In Django Admin, I'm developing a permissions manager which consist in:</p> <blockquote> <p>Permissions - Role - Group - Users</p> </blockquote> <ul> <li>You can group users to assign roles to groups.</li> <li>A group can have multiple roles.</li> <li>The roles are composed of different permissions.</li> </ul> ...
0
2016-06-27T10:10:12Z
38,099,579
<p>Django has an authentication system with permissions </p> <p><a href="https://docs.djangoproject.com/en/1.9/topics/auth/default/" rel="nofollow">https://docs.djangoproject.com/en/1.9/topics/auth/default/</a></p> <p>then for better permission system on object level you can use django-guardian <a href="https://gith...
0
2016-06-29T12:29:27Z
[ "python", "django", "django-models", "django-admin" ]
python - How to click "next" in Selenium until it's no longer available?
38,051,418
<p>I would like to scrape some data on a page and extract table from each page to a dataframe, then click on the "next" button and scrape some data on the second page until it's no longer available. How can I make it with this html structure:</p> <pre><code>&lt;div class="dataTables_paginate paging_bootstrap paginatio...
-2
2016-06-27T10:19:28Z
38,055,650
<p>You should use <code>looping</code> as below :-</p> <pre><code>from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) while True: # scrape some data on a page and extract ...
0
2016-06-27T13:47:05Z
[ "python", "selenium", "selenium-webdriver", "pagination" ]
Reading a csv with a very bad header
38,051,651
<p>I am reading CSVs from files. I am having some trouble with bad headers.</p> <p>Suppose I have:</p> <pre><code>CUSTOMER_NO;CASEWHENDWH_ADM.DIM_CUSTOMER_EXT.CUSTOMER_ACT_STATE='0'THENDECODE(DWH_ADM.DIM_CUSTOMER_EXT.CUSTOMER_STATE,'XX','UNKNOWN',DWH_ADM.DIM_CUSTOMER_EXT.CUSTOMER_STATE)ELSEDWH_ADM.DIM_CUSTOMER_EXT.CU...
-1
2016-06-27T10:30:20Z
38,051,742
<p>I'm sorry. I have already solved in the simplest way:</p> <pre><code>pandas.read_csv('myFile.csv', delimiter = ';') </code></pre> <p>That parameter works both for the file and for the header. I thought that the "comma separator" was the default but it probably is not.</p>
0
2016-06-27T10:34:58Z
[ "python", "io", "header" ]
Reading a csv with a very bad header
38,051,651
<p>I am reading CSVs from files. I am having some trouble with bad headers.</p> <p>Suppose I have:</p> <pre><code>CUSTOMER_NO;CASEWHENDWH_ADM.DIM_CUSTOMER_EXT.CUSTOMER_ACT_STATE='0'THENDECODE(DWH_ADM.DIM_CUSTOMER_EXT.CUSTOMER_STATE,'XX','UNKNOWN',DWH_ADM.DIM_CUSTOMER_EXT.CUSTOMER_STATE)ELSEDWH_ADM.DIM_CUSTOMER_EXT.CU...
-1
2016-06-27T10:30:20Z
38,051,890
<p>I thinks you can try <a href="http://opencsv.sourceforge.net/" rel="nofollow">OpenCSV</a>.</p> <p>But instead of using its default delimiter ([,]) you can set the delimiter as ([;]) for your data.</p> <p>Example code:</p> <pre><code>try (final CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), ';', ...
0
2016-06-27T10:42:37Z
[ "python", "io", "header" ]
How do I reliably scale matplotlib pcolormesh plots for large data sets?
38,051,662
<p>I'm trying to plot some data using a <code>pcolormesh</code> from the <code>matplotlib.pyplot</code> but I'm having some difficulty when saving the output (specifically, in scaling the image appropriately).</p> <p>I'm using Python v3.4 with matplotlib v1.51 if that makes a difference.</p> <p>This is what my code c...
0
2016-06-27T10:31:04Z
38,077,408
<p>Thanks to the prompt from @Dusch, this seems to solve things rather neatly:</p> <pre><code>import numpy as np import pandas as pd from matplotlib import pyplot as plt def GetData(data_entries, num_of_channels): data_dict = {'timestamp' : np.linspace(1, data_entries*21, data_entries, endpoint=True)} for ch...
0
2016-06-28T13:19:18Z
[ "python", "python-3.x", "matplotlib" ]
Saving videos doesnt work in opencv2-python
38,051,664
<p>I am trying to run this example code for saving a video:</p> <pre><code>cap = cv2.VideoCapture('input.mp4') fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480)) while(cap.isOpened()): ret, frame = cap.read() if ret==True: out.write(frame) cv2...
1
2016-06-27T10:31:11Z
38,054,063
<p>For OpenCV 2.4.X, you’ll need to change cv2.VideoWriter_fourcc(*'XVID') </p> <p>function to cv2.cv.FOURCC(*'XVID') .</p>
0
2016-06-27T12:30:17Z
[ "python", "python-2.7", "opencv", "video-processing", "opencv3.0" ]
Pymongo - MongoDB : Error "The _id field cannot be changed from _id: ObjectId to _id: ObjectId
38,051,826
<p>thanks for reading my question.</p> <p>In my database have two collection and every collections have >4k records.</p> <p>This is two collection :</p> <p><strong>collection_ResultRecord</strong> and <strong>collection_RecordNextDay</strong></p> <p>This is one record from <strong>collection_ResultRecord</strong>:...
0
2016-06-27T10:39:31Z
38,052,421
<p>I'm not sure, But I think it can work for you.</p> <pre><code>collection_ResultRecord.update( {"sessionId":record_Result["sessionId"]}, {"$push":{"objects":{"$each": record_nextDay['objects']}}}, upsert = True) </code></pre>
0
2016-06-27T11:09:39Z
[ "python", "mongodb", "pymongo" ]
python close file automatically like context manager
38,051,862
<p>How to close this file or does the file automatically gets closed like a context manager <code>with</code></p> <pre><code>lines = open(file_name).readlines() </code></pre> <p>I wanted to avoid the <code>with</code> statement as the above statement is a one liner, but now i see that the above said statement is of n...
0
2016-06-27T10:41:25Z
38,051,992
<p>you can use <code>with</code></p> <p>This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.</p> <pre><code>with open(file_name, 'r') as readfile: lines = readfile.readlines() </code></pre>
0
2016-06-27T10:47:10Z
[ "python" ]
python close file automatically like context manager
38,051,862
<p>How to close this file or does the file automatically gets closed like a context manager <code>with</code></p> <pre><code>lines = open(file_name).readlines() </code></pre> <p>I wanted to avoid the <code>with</code> statement as the above statement is a one liner, but now i see that the above said statement is of n...
0
2016-06-27T10:41:25Z
38,052,101
<p>if you tend to use <code>open(filename)</code> in your expressions, rather than the <code>with</code> statement, wrap the with statement in your own function, and use it in the expression.</p> <pre><code>def open_readlines_and_close(filename, *args, **kwargs): with open(filename, *args, **kwargs) as file: ...
2
2016-06-27T10:53:13Z
[ "python" ]