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
sequencelengths
1
5
Dstream output to Rabbitmq
40,112,170
<p>I am using spark 2.0 (python). I am trying to send the output stream to Rabbitmq. Following is my implemetation, </p> <pre><code>def sendPartition(iter): connection = pika.BlockingConnection(pika.URLParameters('amqp://user:pass@ip:5672/')) channel = connection.channel() for record in iter: channel.basic_publish(exchange='ExchangePostingUpdate', routing_key='PostingUpdate', body=json.dumps(record) ) channel.close() data_stream.foreachRDD(lambda rdd: rdd.foreachPartition(lambda partition:sendPartition(partition,rabbitconnection))) </code></pre> <p>It is working fine. But as we see here it is estabilshing connection and closing it for every partition. Is there any better way to do this ?</p> <p>i tried to estabilsh a connection and pass to <code>sendPartition(iter,conn)</code> but i did not work. </p>
1
2016-10-18T15:23:58Z
40,114,972
<p>What you have right now is probably close to the optimum in a general case. Python workers don't share state so you cannot reuse connections between partitions in the same batch.</p> <p>It should be possible to reuse connections for each worker between batches by creating a singleton wrapping a connection pool (there are well established patterns you can use like Borg pattern or using module as a singleton) but this will work only under certain assumptions:</p> <ul> <li><code>spark.python.worker.reuse</code> is set to true.</li> <li>Disabled dynamic allocation (<code>spark.dynamicAllocation.enabled</code>).</li> </ul> <p>If resources are created dynamically and / or not reused keeping persistent pool won't be helpful.</p>
0
2016-10-18T17:56:17Z
[ "python", "apache-spark", "rabbitmq", "spark-streaming" ]
EOF Error with ftplib only when connecting to GoDaddy hosted server
40,112,202
<p>I'm having problems with FTP_TLS (ftplib) in Python 2.7.3.</p> <p>Summary of findings (all connection attempts performed over the internet):</p> <ul> <li>FileZilla to home web server - works</li> <li>FileZilla to GoDaddy shared hosting server - works</li> <li>Python to home web server - works</li> <li>Python to GoDaddy shared hosting server - fails (see stack trace below)</li> </ul> <p>The following code shows how I reproduce the problem. When connecting to my home server, this code generates an identical log on my personal FTP as FileZilla. (Only when connecting to the GoDaddy site does it result in an EOF exception).</p> <pre><code>from ftplib import FTP_TLS o = FTP_TLS(ftpServer,ftpUsername,ftpPassword,ftpPort) o.voidcmd('SYST') o.voidcmd('FEAT') o.prot_p() o.voidcmd('PWD') o.retrbinary('MLSD', open('OUTTEST', 'wb').write) &gt;&gt;&gt; o.retrbinary('MLSD', open('OUTTEST', 'wb').write) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.7/ftplib.py", line 703, in retrbinary return self.voidresp() File "/usr/lib/python2.7/ftplib.py", line 225, in voidresp resp = self.getresp() File "/usr/lib/python2.7/ftplib.py", line 211, in getresp resp = self.getmultiline() File "/usr/lib/python2.7/ftplib.py", line 197, in getmultiline line = self.getline() File "/usr/lib/python2.7/ftplib.py", line 187, in getline if not line: raise EOFError </code></pre> <p>I read that the EOF error is given when the server closes the pipe. It's also similar to what happens if you change to prot_p and then try to issue a plain text command (although as far as I can tell, this isn't the case here).</p> <p>I don't understand what's different between my code and FileZilla. The fact that all attempts are performed over the internet reassures me that it isn't related to firewalls. Furthermore, FileZilla works, so from a technical perspective the connection is possible, I'm just having a hard time achieving it with Python.</p> <p>My code works with the GoDaddy FTP if I don't issue the prot_p switch.</p> <p>Additional information:</p> <ul> <li>GoDaddy doesn't provide technical FTP logs (only usage logs)</li> <li>My code has been working flawlessly for over a year, this just started happening two months ago.</li> <li>The GoDaddy FTP server identifies as "Pure-FTPd [privsep] [TLS]"</li> </ul> <p>Typical FileZilla Server Log after running my code.</p> <pre><code>(000132)18/10/2016 15:44:19 - (not logged in) (IP_ADDRESS)&gt; Connected on port 21, sending welcome message... (000132)18/10/2016 15:44:19 - (not logged in) (IP_ADDRESS)&gt; 220-FileZilla Server 0.9.57 beta (000132)18/10/2016 15:44:19 - (not logged in) (IP_ADDRESS)&gt; 220-written by Tim Kosse (Tim.Kosse@gmx.de) (000132)18/10/2016 15:44:19 - (not logged in) (IP_ADDRESS)&gt; 220 Please visit https://filezilla-project.org/ (000132)18/10/2016 15:44:19 - (not logged in) (IP_ADDRESS)&gt; AUTH TLS (000132)18/10/2016 15:44:19 - (not logged in) (IP_ADDRESS)&gt; 234 Using authentication type TLS (000132)18/10/2016 15:44:19 - (not logged in) (IP_ADDRESS)&gt; SSL connection established (000132)18/10/2016 15:44:19 - (not logged in) (IP_ADDRESS)&gt; USER ******************** (000132)18/10/2016 15:44:19 - (not logged in) (IP_ADDRESS)&gt; 331 Password required for USER_NAME (000132)18/10/2016 15:44:19 - (not logged in) (IP_ADDRESS)&gt; PASS ******************** (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; 230 Logged on (000131)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; disconnected. (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; SYST (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; 215 UNIX emulated by FileZilla (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; FEAT (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; 211-Features: (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; MDTM (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; REST STREAM (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; SIZE (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; MODE Z (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; MLST type*;size*;modify*; (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; MLSD (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; AUTH SSL (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; AUTH TLS (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; PROT (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; PBSZ (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; UTF8 (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; CLNT (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; MFMT (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; EPSV (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; EPRT (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; 211 End (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; PBSZ 0 (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; 200 PBSZ=0 (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; PROT P (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; 200 Protection level set to P (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; PWD (000132)18/10/2016 15:44:19 - USER_NAME (IP_ADDRESS)&gt; 257 "/" is current directory. (000132)18/10/2016 15:44:22 - USER_NAME (IP_ADDRESS)&gt; TYPE I (000132)18/10/2016 15:44:22 - USER_NAME (IP_ADDRESS)&gt; 200 Type set to I (000132)18/10/2016 15:44:22 - USER_NAME (IP_ADDRESS)&gt; PASV (000132)18/10/2016 15:44:22 - USER_NAME (IP_ADDRESS)&gt; 227 Entering Passive Mode (xxx,xxx,xxx,xxx,xxx,xxx) (000132)18/10/2016 15:44:22 - USER_NAME (IP_ADDRESS)&gt; MLSD (000132)18/10/2016 15:44:22 - USER_NAME (IP_ADDRESS)&gt; 150 Opening data channel for directory listing of "/" (000132)18/10/2016 15:44:22 - USER_NAME (IP_ADDRESS)&gt; SSL connection for data connection established (000132)18/10/2016 15:44:22 - USER_NAME (IP_ADDRESS)&gt; 226 Successfully transferred "/" </code></pre>
1
2016-10-18T15:25:48Z
40,112,354
<p>I think you need to set the FTP mode to passive, here's a <a href="http://www.perlmonks.org/?node_id=175281" rel="nofollow">similar error but in Perl</a></p> <p>The difference is explained in <a href="http://stackoverflow.com/questions/1699145/what-is-the-difference-between-active-and-passive-ftp">what-is-the-difference-between-active-and-passive-ftp</a></p>
0
2016-10-18T15:32:20Z
[ "python", "python-2.7", "ftplib" ]
panda dataframe iterate and adding to set issue
40,112,223
<p>I have a dataframe that looks like this:</p> <pre><code> name 0 [somename1, somename2, n... 1 [name1, someothername, ... 2 [name, name, s... 3 [somename1, name3, s... 4 [name2, name2, s... 5 [somename2, name2, s... 6 [somename1, somename, s... </code></pre> <p>I am trying to iterate through the dataframe and save the data in the dataframe as a sequence in a set. Therefore I have done this:</p> <pre><code>events = set([]) for index, row in datarame.iterrows(): session = row['name'] print len(session) for x in session: events.add(x) print events length total: print len(events) </code></pre> <p>What I get as an output here is:</p> <pre><code> 24 80 15 60 76 66 83 32 100 73 13 3 2 9 57 2 2 4 1 events length total: 108 </code></pre> <p>Which does not make sense. Normally it should add all the contents in the sessions and the length should be the summary of the numbers above, which obviously is not.</p>
0
2016-10-18T15:26:51Z
40,115,924
<p>A <code>set</code> in python is an </p> <blockquote> <p>unordered collection of <strong>unique</strong> elements.</p> </blockquote> <p>It does not allow duplicates.</p> <p>You should define <code>event</code> as a <code>list</code> instead.</p> <pre><code>events = [] for index, row in datarame.iterrows(): session = row['name'] print len(session) for x in session: events.append(x) print events length total: print len(events) </code></pre>
1
2016-10-18T18:53:03Z
[ "python", "dataframe", "set", "iteration" ]
creating package with setuptools not installing properly
40,112,269
<p>I'm using setuptools to try and create a module for python.</p> <p>I have tried installing locally and from git with pip (version 3.5). pip says that the package is installed and it is listed in the installed packages with "pip list" and "pip freeze". When I try to import the module in my script I get an import error "ImportError: No module named 'jackedCodeTimerPY' ". I've been banging my head on the wall for a while now and I think that is a really simple problem and I'm just missing something.</p> <p>You can find my repo at <a href="https://github.com/BebeSparkelSparkel/jackedCodeTimerPY" rel="nofollow">https://github.com/BebeSparkelSparkel/jackedCodeTimerPY</a></p> <p>My setup.py looks like this:</p> <pre><code>from setuptools import setup setup(name='jackedCodeTimerPY', version='0.0.0', license='MIT', description='Simple but powerful code timer that can measure execution time of one line, functions, imports and gives statistics (min/max/mean/total time, number of executions).', author='William Rusnack', author_email='williamrusnack@gmail.com', url='https://github.com/BebeSparkelSparkel/jackedCodeTimerPY', classifiers=['Development Status :: 2 - Pre-Alpha', 'Programming Language :: Python :: 3'], py_modules=["jackedCodeTimerPY"], install_requires=['tabulate==0.7.5'], ) </code></pre> <p>My directory looks like this:</p> <pre><code>LICENSE.md jackedCodeTimerPY.py README.md jackedCodeTimerPY.pyc __pycache__ setup.py build small.jpg dist t2.py example.py tests.py jackedCodeTimerPY.egg-info </code></pre>
0
2016-10-18T15:28:46Z
40,112,574
<p>Seems to work for me:</p> <pre><code>pip3 install git+git://github.com/BebeSparkelSparkel/jackedCodeTimerPY.git@master Cloning git://github.com/BebeSparkelSparkel/jackedCodeTimerPY.git (to master) to /tmp/pip-lq07iup9-build Collecting tabulate==0.7.5 (from jackedCodeTimerPY==0.0.0) Downloading tabulate-0.7.5.tar.gz Installing collected packages: tabulate, jackedCodeTimerPY Running setup.py install for tabulate ... done Running setup.py install for jackedCodeTimerPY ... done Successfully installed jackedCodeTimerPY-0.0.0 tabulate-0.7.5 python3 -c 'from jackedCodeTimerPY import JackedTiming; print(JackedTiming)' &lt;class 'jackedCodeTimerPY.JackedTiming'&gt; </code></pre>
0
2016-10-18T15:41:33Z
[ "python", "setuptools", "setup.py" ]
Accelerate or decelerate a movie clip
40,112,284
<p>I am trying to accelerate and/or decelerate a movie clip with the help of Python's moviepy module, but I can't seem to work it out properly. The script runs quite smoothly, and without any errors, but I do not see any effects. Might be my script is wrong and I can't detect the problem. Looking for help/tips from you. I do not need a complete solution, any hints will be of great help. I have been working on this solution for sometime and I think I should post my problem here. Any help, tips, guidance will be greatly appreciated. Thank you. </p> <pre><code>from moviepy.editor import * from moviepy.video.tools.drawing import color_split import os dir = os.path.split(os.path.realpath(__file__))[0] img = os.path.join('tmp', 'stock.jpg') folder = 'tmp' def f_accel_decel(t, old_d, new_d, abruptness=1, soonness=1.0): """ abruptness negative abruptness (&gt;-1): speed up down up zero abruptness : no effect positive abruptness: speed down up down soonness for positive abruptness, determines how soon the speedup occurs (0&lt;soonness &lt; inf) """ a = 1.0+abruptness def _f(t): f1 = lambda t: (0.5)**(1-a)*(t**a) f2 = lambda t: (1-f1(1-t)) return (t&lt;.5)*f1(t) + (t&gt;=.5)*f2(t) return old_d*_f((t/new_d)**soonness) def accel_decel(clip, new_duration=None, abruptness=1.0, soonness=1.0): """ new_duration If None, will be that of the current clip. abruptness negative abruptness (&gt;-1): speed up down up zero abruptness : no effect positive abruptness: speed down up down soonness for positive abruptness, determines how soon the speedup occurs (0&lt;soonness &lt; inf) """ if new_duration is None: new_duration = clip.duration fl = lambda t : f_accel_decel(t, clip.duration, new_duration, abruptness, soonness) return clip.fl_time(fl).set_duration(new_duration) duration = 30 main_clip = ImageClip(img, duration=30) W,H = main_clip.size print W,H clip1 = (main_clip .subclip(0,duration) .set_pos(lambda t:(max((0), (int(W-0.5*W*t))), "center")) ) modifiedClip1 = accel_decel(clip1, abruptness=5, soonness=1.3) cc = CompositeVideoClip([modifiedClip1], size=(1920,1080), bg_color=(232,54,18)).resize(0.5) cc.preview(fps=24) #cc.write_videofile("mask.avi", fps=25, codec="libx264", bitrate="1000K", threads=3) </code></pre>
0
2016-10-18T15:29:22Z
40,136,932
<p>I think the best way of accelerating and decelerating clip objects is using <strong>easing functions</strong>.</p> <p>Some reference sites:</p> <ul> <li><a href="http://easings.net" rel="nofollow">http://easings.net</a></li> <li><a href="http://www.gizma.com/easing/" rel="nofollow">http://www.gizma.com/easing/</a></li> <li><a href="http://gsgd.co.uk/sandbox/jquery/easing/" rel="nofollow">http://gsgd.co.uk/sandbox/jquery/easing/</a></li> </ul> <p>Here's part of a script I made when trying to understand these functions. Maybe you can use some of this concepts to solve your issue.</p> <pre><code>from __future__ import division from moviepy.editor import TextClip, CompositeVideoClip import math def efunc(x0, x1, dur, func='linear', **kwargs): # Return an easing function. # It will control a single dimention of the clip movement. # http://www.gizma.com/easing/ def linear(t): return c*t/d + b def out_quad(t): t = t/d return -c * t*(t-2) + b def in_out_sine(t): return -c/2 * (math.cos(math.pi*t/d) - 1) + b def in_quint(t): t = t/d return c*t*t*t*t*t + b def in_out_circ(t): t /= d/2; if t &lt; 1: return -c/2 * (math.sqrt(1 - t*t) - 1) + b t -= 2; return c/2 * (math.sqrt(1 - t*t) + 1) + b; def out_bounce(t): # http://gsgd.co.uk/sandbox/jquery/easing/jquery.easing.1.3.js t = t/d if t &lt; 1/2.75: return c*(7.5625*t*t) + b elif t &lt; 2/2.75: t -= 1.5/2.75 return c*(7.5625*t*t + .75) + b elif t &lt; 2.5/2.75: t -= 2.25/2.75 return c*(7.5625*t*t + .9375) + b else: t -= 2.625/2.75 return c*(7.5625*t*t + .984375) + b # Kept the (t, b, c, d) notation found everywhere. b = x0 c = x1 - x0 d = dur return locals()[func] def particle(x0, x1, y0, y1, d, func='linear', color='black', **kwargs): # Dummy clip for testing. def pos(t): return efunc(x0, x1, d, func=func)(t), efunc(y0, y1, d, func=func)(t) return ( TextClip('*', fontsize=80, color=color) .set_position(pos) .set_duration(d) ) # Make a gif to visualize the behaviour of the functions: easing_functions = [ ('linear', 'red'), ('in_out_sine', 'green'), ('in_out_circ', 'violet'), ('out_quad', 'blue'), ('out_bounce', 'brown'), ('in_quint', 'black'), ] d = 4 x0, x1 = 0, 370 clips = [] for i, (func, c) in enumerate(easing_functions): y = 40*i clips.append(particle(x0, x1, y, y, d=d, func=func, color=c)) clips.append(particle(x1, x0, y, y, d=d, func=func, color=c).set_start(d)) clip = CompositeVideoClip(clips, size=(400,250), bg_color=(255,255,255)) clip.write_gif('easing.gif', fps=12) </code></pre> <p><br></p> <p>The output of the script:</p> <p><a href="https://i.stack.imgur.com/73oVB.gif" rel="nofollow"><img src="https://i.stack.imgur.com/73oVB.gif" alt="Easing functions demo"></a></p>
1
2016-10-19T16:29:18Z
[ "python", "numpy", "moviepy" ]
How can I make automatize fetchall() calling in pyodbc without exception handling?
40,112,321
<p>I want to do automatic results fetching after every <strong>pyodbc</strong> query. In usual situation <code>cursor.fetchall()</code> calling raises a <code>ProgrammingError</code> exception if no SQL has been executed or if it did not return a result set (e.g. was not a SELECT statement). I want to do something like this:</p> <pre><code>def execute(query, data): cursor.execute(query, data) cursor.commit() try: result = cursor.fetchall() except pyodbc.ProgrammingError: result = None return result </code></pre> <p>Is there some way to make it possible without using exception handling (it works too slow if it used)?</p>
1
2016-10-18T15:31:11Z
40,119,325
<p>Here's an example that might work for you, with a list of samples queries to run:</p> <pre><code>sql_to_run = [ "SELECT 10000", "SELECT 2 + 2", "", "SELECT 'HELLO WORLD'", ] for sql in sql_to_run: rows = cursor.execute(sql) if cursor.rowcount: for row in rows: print(row) </code></pre> <p>Output:</p> <pre><code>(10000, ) (4, ) ('HELLO WORLD', ) </code></pre> <p>Will that do the trick? Good luck!</p>
1
2016-10-18T22:47:40Z
[ "python", "pyodbc" ]
Python Create List of Words Per Sentence and Calculate Mean and Place in CSV File
40,112,365
<p>I'm looking to count the number of words per sentence, calculate the mean words per sentence, and put that info into a CSV file. Here's what I have so far. I probably just need to know how to count the number of words before a period. I might be able to figure it out from there.</p> <pre><code>#Read the data in the text file as a string with open("PrideAndPrejudice.txt") as pride_file: pnp = pride_file.read() #Change '!' and '?' to '.' for ch in ['!','?']: if ch in pnp: pnp = pnp.replace(ch,".") #Remove period after Dr., Mr., Mrs. (choosing not to include etc. as that often ends a sentence although in can also be in the middle) pnp = pnp.replace("Dr.","Dr") pnp = pnp.replace("Mr.","Mr") pnp = pnp.replace("Mrs.","Mrs") </code></pre>
0
2016-10-18T15:32:28Z
40,112,538
<p>You might be interested in the split() function for strings. It seems like you're editing your text to make sure all sentences end in a period and every period ends a sentence.</p> <p>Thus,</p> <pre><code>pnp.split('.') </code></pre> <p>is going to give you a list of all sentences. Once you have that list, for each sentence in the list,</p> <pre><code>sentence.split() # i.e., split according to whitespace by default </code></pre> <p>will give you a list of words in the sentence.</p> <p>Is that enough of a start?</p>
0
2016-10-18T15:39:38Z
[ "python", "csv" ]
Python Create List of Words Per Sentence and Calculate Mean and Place in CSV File
40,112,365
<p>I'm looking to count the number of words per sentence, calculate the mean words per sentence, and put that info into a CSV file. Here's what I have so far. I probably just need to know how to count the number of words before a period. I might be able to figure it out from there.</p> <pre><code>#Read the data in the text file as a string with open("PrideAndPrejudice.txt") as pride_file: pnp = pride_file.read() #Change '!' and '?' to '.' for ch in ['!','?']: if ch in pnp: pnp = pnp.replace(ch,".") #Remove period after Dr., Mr., Mrs. (choosing not to include etc. as that often ends a sentence although in can also be in the middle) pnp = pnp.replace("Dr.","Dr") pnp = pnp.replace("Mr.","Mr") pnp = pnp.replace("Mrs.","Mrs") </code></pre>
0
2016-10-18T15:32:28Z
40,112,548
<p>To split a string into a list of strings on some character:</p> <pre><code>pnp = pnp.split('.') </code></pre> <p>Then we can split each of those sentences into a list of strings (words)</p> <pre><code>pnp = [sentence.split() for sentence in pnp] </code></pre> <p>Then we get the number of words in each sentence</p> <pre><code>pnp = [len(sentence) for sentence in pnp] </code></pre> <p>Then we can use <code>statistics.mean</code> to calculate the mean:</p> <pre><code>statistics.mean(pnp) </code></pre> <p>To use <code>statistics</code> you must put <code>import statistics</code> at the top of your file. If you don't recognize the ways I'm reassigning <code>pnp</code>, look up list comprehensions.</p>
2
2016-10-18T15:40:00Z
[ "python", "csv" ]
Python Create List of Words Per Sentence and Calculate Mean and Place in CSV File
40,112,365
<p>I'm looking to count the number of words per sentence, calculate the mean words per sentence, and put that info into a CSV file. Here's what I have so far. I probably just need to know how to count the number of words before a period. I might be able to figure it out from there.</p> <pre><code>#Read the data in the text file as a string with open("PrideAndPrejudice.txt") as pride_file: pnp = pride_file.read() #Change '!' and '?' to '.' for ch in ['!','?']: if ch in pnp: pnp = pnp.replace(ch,".") #Remove period after Dr., Mr., Mrs. (choosing not to include etc. as that often ends a sentence although in can also be in the middle) pnp = pnp.replace("Dr.","Dr") pnp = pnp.replace("Mr.","Mr") pnp = pnp.replace("Mrs.","Mrs") </code></pre>
0
2016-10-18T15:32:28Z
40,112,960
<p>You can try the code below.</p> <pre><code>numbers_per_sentence = [len(element) for element in (element.split() for element in pnp.split("."))] mean = sum(numbers_per_sentence)/len(numbers_per_sentence) </code></pre> <p>However, for real natural language processing I would probably recommend a more robust solution such as <a href="http://www.nltk.org/" rel="nofollow">NLTK</a>. The text manipulation you perform (replacing "?" and "!", removing commas after "Dr.","Mr." and "Mrs.") is probably not enough to be 100% sure that comma is always a sentence separator (and that there are no other sentence separators in your text, even if it happens to be true for Pride And Prejudice)</p>
0
2016-10-18T16:01:18Z
[ "python", "csv" ]
How to classify new documents with tf-idf?
40,112,373
<p>If I use the <code>TfidfVectorizer</code> from <code>sklearn</code> to generate feature vectors as:</p> <p><code>features = TfidfVectorizer(min_df=0.2, ngram_range=(1,3)).fit_transform(myDocuments)</code></p> <p>How would I then generate feature vectors to classify a new document? Since you cant calculate the tf-idf for a single document. </p> <p>Would it be a correct approach, to extract the feature names with:</p> <p><code>feature_names = TfidfVectorizer.get_feature_names()</code></p> <p>and then count the term frequency for the new document according to the <code>feature_names</code> ?</p> <p>But then I wont get the weights that has the information of a words importnance.</p>
0
2016-10-18T15:32:44Z
40,122,073
<p>You need to save the instance of the TfidfVectorizer, it will remember the term frequencies and vocabulary that was used to fit it. It may make things clearer sense if rather than using <code>fit_transform</code>, you use <code>fit</code> and <code>transform</code> separately:</p> <pre><code>vec = TfidfVectorizer(min_df=0.2, ngram_range=(1,3)) vec.fit(myDocuments) features = vec.transform(myDocuments) new_features = fec.transform(myNewDocuments) </code></pre>
0
2016-10-19T04:21:12Z
[ "python", "scikit-learn", "text-mining", "tf-idf", "text-analysis" ]
How do I access request metadata for a java grpc service I am defining?
40,112,374
<p>For some background, I am attempting to use <a href="http://www.grpc.io/docs/guides/auth.html#authenticate-with-google-4" rel="nofollow">grpc auth</a> in order to provide security for some services I am defining.</p> <p>Let's see if I can ask this is a way that makes sense. For my python code, it was pretty easy to implement the server side code. </p> <pre><code>class TestServiceServer(service_pb2.TestServiceServer): def TestHello(self, request, context): ## credential metadata for the incoming request metadata = context.invocation_metadata() ## authenticate the user using the metadata </code></pre> <p>So, as you can tell, I am able to get the metadata from "context" quite easily. What is harder for me is to do the same thing in java.</p> <pre><code>public class TestImpl extends TestServiceGrpc.TestServiceImplBase { @Override public void testHello(TestRequest req, StreamObserver&lt;TestResponse&gt; responseObserver) { // How do I get access to similar request metadata here? // from the parameter positions, it looks like it should be // "responseObserver" but that doesn't seem similar to "context" } } </code></pre> <p>I'll admit my problem comes from a few directions.</p> <p>1) I am not well versed in Java</p> <p>2) I heavily used python's "pdb" in order to debug the classes and see what methods are available to me. I don't know of/am not proficient at a similar tool for java.</p> <p>3) The documentation seems rather sparse at this point. It shows you how to set up an ssl connection on the server side, but I can't find an example of the server taking a look at request metadata, as I have shown in python.</p> <p>Could someone please give me an idea of how to do this, or perhaps show me a useful debugging tool for java in the same vein of python's pdb?</p> <p>EDIT/ANSWER :</p> <p>I needed to first write a definition implementing the interface ServerInterceptor.</p> <pre><code>private class TestInterceptor implements ServerInterceptor { .... </code></pre> <p>Then, before actually binding my service and building my server, I needed to do this.</p> <pre><code>TestImpl service = new TestImpl(); ServerServiceDefinition intercepted = ServerInterceptors.intercept(service, new TestInterceptor()); </code></pre> <p>Now I was able to create the server.</p> <pre><code>server = NettyServerBuilder.forPort(port) // enable tls .useTransportSecurity( new File(serverCert), new File(serverKey) ) .addService( intercepted // had been "new TestImpl()" ) .build(); server.start(); </code></pre> <p>This allowed my ServerInterceptor to actually be called when I fired off a client side request.</p> <p><a href="https://github.com/grpc/grpc-java/blob/16c07ba434787f68e256fc50cece1425f421b03e/core/src/test/java/io/grpc/ServerInterceptorsTest.java" rel="nofollow">This link</a> was quite helpful in figuring this out.</p>
0
2016-10-18T15:32:58Z
40,113,309
<p>Use a <code>ServerInterceptor</code> and then propagate the identity via <code>Context</code>. This allows you to have a central policy for authentication.</p> <p>The interceptor can retrieve the identity from <code>Metadata headers</code>. It <em>should then validate</em> the identity. The validated identity can then be communicated to the application (i.e., <code>testHello</code>) via <code>io.grpc.Context</code>:</p> <pre><code>/** Interceptor that validates user's identity. */ class MyAuthInterceptor implements ServerInterceptor { public static final Context.Key&lt;Object&gt; USER_IDENTITY = Context.key("identity"); // "identity" is just for debugging @Override public &lt;ReqT, RespT&gt; ServerCall.Listener&lt;ReqT&gt; interceptCall( ServerCall&lt;ReqT, RespT&gt; call, Metadata headers, ServerCallHandler&lt;ReqT, RespT&gt; next) { // You need to implement validateIdentity Object identity = validateIdentity(headers); if (identity == null) { // this is optional, depending on your needs // Assume user not authenticated call.close(Status.UNAUTENTICATED.withDescription("some more info"), new Metadata()); return new ServerCall.Listener() {}; } Context context = Context.current().withValue(USER_IDENTITY, identity); return Contexts.interceptCall(context, call, headers, next); } } public class TestImpl extends TestServiceGrpc.TestServiceImplBase { @Override public void testHello(TestRequest req, StreamObserver&lt;TestResponse&gt; responseObserver) { // Access to identity. Object identity = MyAuthInterceptor.USER_IDENTITY.get(); ... } } // Need to use ServerInterceptors to enable the interceptor Server server = ServerBuilder.forPort(PORT) .addService(ServerInterceptors.intercept(new TestImpl(), new MyAuthInterceptor())) .build() .start(); </code></pre>
2
2016-10-18T16:17:35Z
[ "java", "python", "request", "metadata", "grpc" ]
Django KeyError kwargs.pop('pk')
40,112,448
<p>I'm using CBV in Django 1.9 and in CreateView when I try to pass an additional parameter ('pk') to my form using self.kwargs.pop('pk') i got "Key Error" but if I get the parameter by index it works, here is my code:</p> <pre><code>def get_form(self, form_class=None, **kwargs): self.project_version_pk = self.kwargs.pop('pk') form = super(HRCreateView, self).get_form(form_class) form.fields['project_version'].queryset = form.fields['project_version'].queryset.filter(pk=self.project_version_pk) form.fields['project_version'].initial = self.project_version_pk return form def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class, pk=self.kwargs['pk']) return self.render_to_response( self.get_context_data(form=form) </code></pre> <p>And I get this error:</p> <p>builtins.KeyError KeyError: 'pk'</p> <pre><code>File "RelationView.py", line 65, in get_form self.project_version_pk = self.kwargs.pop('pk') KeyError: 'pk' </code></pre> <p>But if i read the key this way it works:</p> <pre><code>def get_form(self, form_class=None, **kwargs): self.project_version_pk = self.kwargs['pk'] form = super(HRCreateView, self).get_form(form_class) form.fields['project_version'].queryset = form.fields['project_version'].queryset.filter(pk=self.project_version_pk) form.fields['project_version'].initial = self.project_version_pk return form </code></pre> <p>I don't really understand why the parameter is missing on pop() or which is the best practice for this.</p>
-1
2016-10-18T15:35:52Z
40,112,767
<p>Firstly, you shouldn't be overriding <code>get</code>. In a CreateView, Django already calls <code>get_form</code> for you - inside <code>get_context_data</code>. This is the cause of the issue you are having; you call <code>get_form</code> and pop the pk so that it is no longer in kwargs; but Django calls it again in get_context_data, but this second time it can't find the pk because you removed it the first time.</p> <p>So don't use pop; but, as I said, don't do this at all. The only thing you actually need to override is <code>get_form</code>.</p>
1
2016-10-18T15:51:04Z
[ "python", "django", "django-class-based-views", "class-based-views" ]
AttributeError: 'numpy.ndarray' object has no attribute 'median'
40,112,487
<p>I can perform a number of statistics on a numpy array but "median" returns an attribute error. When I do a "dir(np)" I do see the median method listed.</p> <pre><code>(newpy2) 7831c1c083a2:src scaldara$ python Python 2.7.12 |Continuum Analytics, Inc.| (default, Jul 2 2016, 17:43:17) [GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.11.00)] on darwin Type "help", "copyright", "credits" or "license" for more information. Anaconda is brought to you by Continuum Analytics. Please check out: http://continuum.io/thanks and https://anaconda.org &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; print(np.version.version) 1.11.2 &gt;&gt;&gt; a = np.array([1,2,3,4,5,6,7,8,9,10]) &gt;&gt;&gt; print(a) [ 1 2 3 4 5 6 7 8 9 10] &gt;&gt;&gt; print(a.min()) 1 &gt;&gt;&gt; print(a.max()) 10 &gt;&gt;&gt; print(a.mean()) 5.5 &gt;&gt;&gt; print(a.std()) 2.87228132327 &gt;&gt;&gt; print(a.median()) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'numpy.ndarray' object has no attribute 'median' &gt;&gt;&gt; </code></pre>
2
2016-10-18T15:37:21Z
40,112,611
<p>Although <code>numpy.ndarray</code> has a <code>mean</code>, <code>max</code>, <code>std</code> etc. method, it does not have a <code>median</code> method. For a list of all methods available for an <code>ndarray</code>, see the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html" rel="nofollow"><code>numpy</code> documentation for <code>ndarray</code></a>.</p> <p>It is available as a function that takes the array as an argument:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; a = np.array([1,2,3,4,5,6,7,8,9,10]) &gt;&gt;&gt; np.median(a) 5.5 </code></pre> <p>As you will see in <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.mean.html#numpy.ndarray.mean" rel="nofollow">the documentation for <code>ndarray.mean</code></a>, <code>ndarray.mean</code> and <code>np.mean</code> are "equivalent functions," so this is just a matter of semantics.</p>
3
2016-10-18T15:43:24Z
[ "python", "numpy" ]
TypeError: 'float' object is not callable (finding averages of a list of numbers)
40,112,537
<pre><code>sales = [49.99, 20, 155.20, 71.65, 91.07] length = len(sales) max_value = max(sales) min_value = min(sales) sum_of_values = sum(sales) print(length, max_value, min_value, sum_value) average = float(sum_of_values/length) answer = round(average,2) print(answer) </code></pre> <p>I'm trying to get a sum of the numbers in the list and then find the average, round the average to 2 decimal places, and then print it. how would I fix this error?</p>
-1
2016-10-18T15:39:34Z
40,112,692
<p>Your code is working fine on my machine.</p> <p>But as a suggestion: In Python 3.4 the statistics module was introduced, which enables you to do</p> <pre><code>&gt;&gt;&gt; from statistics import mean &gt;&gt;&gt; mean([1, 2, 3, 4, 4]) 2.8 &gt;&gt;&gt; mean([49.99, 20, 155.20, 71.65, 91.07]) 77.582 </code></pre> <p>For more infos refer to: <a href="https://docs.python.org/3/library/statistics.html#function-details" rel="nofollow">https://docs.python.org/3/library/statistics.html#function-details</a></p>
0
2016-10-18T15:47:25Z
[ "python" ]
Using nested dictionaries to store user defined graph
40,112,545
<p>I am trying to get the user to enter a graph manually as opposed to using it 'pre-existing' in the code, for use in my Dijkstra's Algorithm. </p> <p>I have done this but would like some feedback on its implementation and user friendliness. In addition is there a more efficient way of entering a graph into a nested dictionary ? If so how ?.</p> <p>Key points about code</p> <ul> <li>Data must be stored using nested dictionaries </li> <li>A loop would be a zero e.g b-b is 0 not left blank, but this only occurs if a loop is present in user graph otherwise its ignored.</li> <li>Ideally I would not like to use anything inside existing libraries before coding it myself to get a better understanding of what is happening</li> </ul> <p>Many Thanks. Edit: repeat requirement no longer needed.</p> <pre><code>{'A': {'C': 1, 'B': 5}, 'D': {}, 'B': {'D': 2}, 'C': {'D': 9}} </code></pre> <p>^ Desired output for nodes also current output.</p> <pre><code>nodes = {} def add_node(): entered_graph = False while not entered_graph: source_node = input("Enter a source node: ") num_neighbours = int(input("Enter how many neighbours this node has" "including previously entered nodes: ")) nodes[source_node] = {} for neighbour in range(num_neighbours): neighbour = input("Enter neighbor node: ") distance = int(input("Enter distance from source node to this neighbor node: ")) nodes[source_node][neighbour] = distance end_loop = input("Enter y to finish graph entry: ") end_loop = end_loop.lower() if end_loop == "y": entered_graph = True add_node() print(nodes) </code></pre>
1
2016-10-18T15:39:51Z
40,112,814
<p>You really only want users to enter every edge once, then you can just store it twice.</p> <pre><code>edges = {} while True: edge = input('Enter an edge as Node names separated by a space followed by a number ("exit" to exit): ') if edge == 'exit': break node1, node2, weight = edge.split() weight = float(weight) if node1 not in edges: edges[node1] = {} if node2 not in edges: edges[node2] = {} edges[node1][node2] = weight edges[node2][node1] = weight </code></pre> <p>User enters each edge once as <code>"A B 3.5"</code></p>
0
2016-10-18T15:53:15Z
[ "python", "dictionary" ]
Using nested dictionaries to store user defined graph
40,112,545
<p>I am trying to get the user to enter a graph manually as opposed to using it 'pre-existing' in the code, for use in my Dijkstra's Algorithm. </p> <p>I have done this but would like some feedback on its implementation and user friendliness. In addition is there a more efficient way of entering a graph into a nested dictionary ? If so how ?.</p> <p>Key points about code</p> <ul> <li>Data must be stored using nested dictionaries </li> <li>A loop would be a zero e.g b-b is 0 not left blank, but this only occurs if a loop is present in user graph otherwise its ignored.</li> <li>Ideally I would not like to use anything inside existing libraries before coding it myself to get a better understanding of what is happening</li> </ul> <p>Many Thanks. Edit: repeat requirement no longer needed.</p> <pre><code>{'A': {'C': 1, 'B': 5}, 'D': {}, 'B': {'D': 2}, 'C': {'D': 9}} </code></pre> <p>^ Desired output for nodes also current output.</p> <pre><code>nodes = {} def add_node(): entered_graph = False while not entered_graph: source_node = input("Enter a source node: ") num_neighbours = int(input("Enter how many neighbours this node has" "including previously entered nodes: ")) nodes[source_node] = {} for neighbour in range(num_neighbours): neighbour = input("Enter neighbor node: ") distance = int(input("Enter distance from source node to this neighbor node: ")) nodes[source_node][neighbour] = distance end_loop = input("Enter y to finish graph entry: ") end_loop = end_loop.lower() if end_loop == "y": entered_graph = True add_node() print(nodes) </code></pre>
1
2016-10-18T15:39:51Z
40,112,860
<p><a href="https://www.khanacademy.org/computing/computer-science/algorithms/graph-representation/a/representing-graphs" rel="nofollow">Khanacademy</a> has a pretty good page on different ways to represent graphs.</p> <p>For an undirected graph (a => b and b => a) I would personally look at using an edge list. It can be sorted to improve lookup efficiency, and it is more memory efficient than other methods such as an adjacency table</p>
0
2016-10-18T15:55:27Z
[ "python", "dictionary" ]
Using nested dictionaries to store user defined graph
40,112,545
<p>I am trying to get the user to enter a graph manually as opposed to using it 'pre-existing' in the code, for use in my Dijkstra's Algorithm. </p> <p>I have done this but would like some feedback on its implementation and user friendliness. In addition is there a more efficient way of entering a graph into a nested dictionary ? If so how ?.</p> <p>Key points about code</p> <ul> <li>Data must be stored using nested dictionaries </li> <li>A loop would be a zero e.g b-b is 0 not left blank, but this only occurs if a loop is present in user graph otherwise its ignored.</li> <li>Ideally I would not like to use anything inside existing libraries before coding it myself to get a better understanding of what is happening</li> </ul> <p>Many Thanks. Edit: repeat requirement no longer needed.</p> <pre><code>{'A': {'C': 1, 'B': 5}, 'D': {}, 'B': {'D': 2}, 'C': {'D': 9}} </code></pre> <p>^ Desired output for nodes also current output.</p> <pre><code>nodes = {} def add_node(): entered_graph = False while not entered_graph: source_node = input("Enter a source node: ") num_neighbours = int(input("Enter how many neighbours this node has" "including previously entered nodes: ")) nodes[source_node] = {} for neighbour in range(num_neighbours): neighbour = input("Enter neighbor node: ") distance = int(input("Enter distance from source node to this neighbor node: ")) nodes[source_node][neighbour] = distance end_loop = input("Enter y to finish graph entry: ") end_loop = end_loop.lower() if end_loop == "y": entered_graph = True add_node() print(nodes) </code></pre>
1
2016-10-18T15:39:51Z
40,112,980
<p>You could be more modular in your source, as in "add_node" should only add a node. I think entering all neighbors with costs immediately in one line would be more user friendly, so using the data structure you insist on:</p> <pre><code>from itertools import tee #For pairwise iteration from collection import defaultdict #To add arcs to non-existing nodes def add_node(graph): source = input("Please enter node ('quit' to stop):") if node == 'quit': return False for neighbor,dist in zip(tee(input("Please enter neighbors [neighbor distance neighbor distance ...]").split())): graph[source][neighbor] = int(dist) graph[neighbor][source] = int(dist) return True def add_graph(self): graph = defaultdict(dict) while add_node(graph): pass print add_graph() </code></pre> <p>The defaultdict saves you checking, and I think inputting this way is easier rather than neighbor by neighbor. You could even make this [source neighbor cost neighbor cost ...] - [source ...] - ... for a one line input.</p> <p>Being modular makes it easier to add code to the 'graph' or to the 'node', if you insist on not making a class out of this.</p>
0
2016-10-18T16:02:03Z
[ "python", "dictionary" ]
removing a number from a list
40,112,774
<p>I'm stuck on a part of a looping question. I have to remove from list1 all instances of "number". So lets say list1 is (1,2,3) and num is 2. The list I would have to return would be (1,3)</p> <pre><code>def remove(list1,num) list1=list1 num = num </code></pre> <p>This is what is given. So far, I have this:</p> <pre><code>def remove(list1,num) list1=list1 num=num if num in list1: </code></pre> <p>This is where I'm stuck because I don't know how to say in coding "remove num from list" I am not allowed to use .remove either. </p> <p>Would appreciate the help.</p>
-2
2016-10-18T15:51:36Z
40,112,866
<p>Use list comprehension:</p> <pre><code>list1 = [1,2,3] num = 2 new_list = [i for i in list1 if i != num] print(new_list) &gt;&gt; [1,3] </code></pre>
1
2016-10-18T15:55:35Z
[ "python", "loops", "for-loop" ]
removing a number from a list
40,112,774
<p>I'm stuck on a part of a looping question. I have to remove from list1 all instances of "number". So lets say list1 is (1,2,3) and num is 2. The list I would have to return would be (1,3)</p> <pre><code>def remove(list1,num) list1=list1 num = num </code></pre> <p>This is what is given. So far, I have this:</p> <pre><code>def remove(list1,num) list1=list1 num=num if num in list1: </code></pre> <p>This is where I'm stuck because I don't know how to say in coding "remove num from list" I am not allowed to use .remove either. </p> <p>Would appreciate the help.</p>
-2
2016-10-18T15:51:36Z
40,112,892
<pre><code>def remove(item,given_list): new_list = [] for each in given_list: if item != each: new_list.append(each) return new_list print(remove(2,[1,2,3,1,2,1,2,2,4])) #outputs [1, 3, 1, 1, 4] </code></pre> <p>While my answer as strong as others, I feel this is the fundamental way of thinking on how to remove an item from a list. It allows people to understand at a basic level of what's happening. </p> <p>Basically we are taking 2 inputs, the item to remove and the list to remove it from. It loops through the <code>input_list</code> and checks if the <code>item</code> is equal to the <code>item</code> we want to remove, if it's not the same we <code>append</code> it to the new list, and return the new list. </p> <p>We don't want to remove items in place in the list while looping because it could cause undesirable looping. For example if we have the <code>example_list=[1,2,3]</code> and we are on the second iteration of the <code>for loop</code> and we remove 2 in place, it will try to go somewhere we don't want it to go. <a class='doc-link' href="http://stackoverflow.com/documentation/python/3553/common-pitfalls/12259/list-multiplication-and-common-references#t=201610181559287156669">See this for more detailed example</a></p>
0
2016-10-18T15:56:46Z
[ "python", "loops", "for-loop" ]
removing a number from a list
40,112,774
<p>I'm stuck on a part of a looping question. I have to remove from list1 all instances of "number". So lets say list1 is (1,2,3) and num is 2. The list I would have to return would be (1,3)</p> <pre><code>def remove(list1,num) list1=list1 num = num </code></pre> <p>This is what is given. So far, I have this:</p> <pre><code>def remove(list1,num) list1=list1 num=num if num in list1: </code></pre> <p>This is where I'm stuck because I don't know how to say in coding "remove num from list" I am not allowed to use .remove either. </p> <p>Would appreciate the help.</p>
-2
2016-10-18T15:51:36Z
40,112,900
<p>Taking into account:</p> <pre><code>list=[1,2,3,2] </code></pre> <p>You can check if the element is in the list with:</p> <pre><code>if num in list </code></pre> <p>And then remove with:</p> <pre><code>list.remove(num) </code></pre> <p>And iterate through it</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; list=[1,2,3] &gt;&gt;&gt; list.remove(2) &gt;&gt;&gt; print list [1, 3] </code></pre>
0
2016-10-18T15:57:16Z
[ "python", "loops", "for-loop" ]
removing a number from a list
40,112,774
<p>I'm stuck on a part of a looping question. I have to remove from list1 all instances of "number". So lets say list1 is (1,2,3) and num is 2. The list I would have to return would be (1,3)</p> <pre><code>def remove(list1,num) list1=list1 num = num </code></pre> <p>This is what is given. So far, I have this:</p> <pre><code>def remove(list1,num) list1=list1 num=num if num in list1: </code></pre> <p>This is where I'm stuck because I don't know how to say in coding "remove num from list" I am not allowed to use .remove either. </p> <p>Would appreciate the help.</p>
-2
2016-10-18T15:51:36Z
40,112,990
<p>It sounds like this is a homework problem, especially since you can't use <code>.remove</code>.</p> <p>Given that, your teacher probably wants you to take a manual approach that looks something like this:</p> <ol> <li>Create a new list</li> <li>For each item in the previous list... <ol> <li>If it's not the value you want to filter out, <code>.append</code> it to your new list</li> </ol></li> <li>Return your new list</li> </ol> <p>(mouseover if you don't want to write the code yourself)</p> <blockquote class="spoiler"> <p><pre> def remove(list1, num): new_list = [] for item in list1: if item != num: new_list.append(item) return new_list</pre></p> </blockquote>
2
2016-10-18T16:02:31Z
[ "python", "loops", "for-loop" ]
removing a number from a list
40,112,774
<p>I'm stuck on a part of a looping question. I have to remove from list1 all instances of "number". So lets say list1 is (1,2,3) and num is 2. The list I would have to return would be (1,3)</p> <pre><code>def remove(list1,num) list1=list1 num = num </code></pre> <p>This is what is given. So far, I have this:</p> <pre><code>def remove(list1,num) list1=list1 num=num if num in list1: </code></pre> <p>This is where I'm stuck because I don't know how to say in coding "remove num from list" I am not allowed to use .remove either. </p> <p>Would appreciate the help.</p>
-2
2016-10-18T15:51:36Z
40,113,176
<p>To go with pure loops and delete with list index:</p> <pre><code>#!/usr/bin/env python from __future__ import print_function def remove(item, old_list): while True: try: # find the index of the item index = old_list.index(item) # remove the item found del old_list[index] except ValueError as e: # no more items, return return old_list a_list = [1, 2, 3, 2, 1, 3, 2, 4, 2] print(remove(2, a_list)) </code></pre> <p>If possible, of course, you should use list comprehension, which is pythonic and much easier!</p>
0
2016-10-18T16:11:02Z
[ "python", "loops", "for-loop" ]
Different output after decode and encode data (base64)
40,112,796
<p>If i run:</p> <pre><code>import base64 data = open('1.dat', 'rb').read() decoded = base64.b64decode(data) encoded = base64.b64encode(decoded) data == encoded </code></pre> <p>I get "False" as result? How to decode/encode to get the original result?</p>
0
2016-10-18T15:52:35Z
40,112,912
<p>You have to <code>b64encode()</code> the data before you <code>b64decode()</code> it:</p> <pre><code>&gt;&gt;&gt; import base64 &gt;&gt;&gt; data = b"qwertzuiop" &gt;&gt;&gt; encoded = base64.b64encode(data) &gt;&gt;&gt; decoded = base64.b64decode(encoded) &gt;&gt;&gt; data == decoded True </code></pre> <p>If your input file is already base64, you need to <code>b64decode()</code> it first, not encode. So your code should be this: </p> <pre><code>import base64 data = open('1.dat', 'rb').read() # base64 encoded string decoded = base64.b64decode(data) encoded = base64.b64encode(decoded) data == encoded </code></pre> <p>If you are getting False as a result, your <code>data</code> is Base64 encoded differently than what the <code>base64</code> module does.</p>
0
2016-10-18T15:58:14Z
[ "python", "base64" ]
Different output after decode and encode data (base64)
40,112,796
<p>If i run:</p> <pre><code>import base64 data = open('1.dat', 'rb').read() decoded = base64.b64decode(data) encoded = base64.b64encode(decoded) data == encoded </code></pre> <p>I get "False" as result? How to decode/encode to get the original result?</p>
0
2016-10-18T15:52:35Z
40,112,940
<p>Base64 is not base64 unfortunately. There may be differences in the implementations. Some implementation for example insert line breaks every 76 characters when encoding, some don't.</p>
1
2016-10-18T15:59:55Z
[ "python", "base64" ]
Different output after decode and encode data (base64)
40,112,796
<p>If i run:</p> <pre><code>import base64 data = open('1.dat', 'rb').read() decoded = base64.b64decode(data) encoded = base64.b64encode(decoded) data == encoded </code></pre> <p>I get "False" as result? How to decode/encode to get the original result?</p>
0
2016-10-18T15:52:35Z
40,113,080
<p>There is some flexibility in the way base64 is encoded, for example the insertion of newlines. There may also be some alternate characters which the <a href="https://docs.python.org/2/library/base64.html" rel="nofollow"><code>base64</code> module</a> allows you to specify when encoding and decoding. It's up to you to make sure the proper alternate characters are specified, but otherwise it's easy to compare two strings while ignoring any newlines or whitespace:</p> <pre><code>''.join(data.split()) == ''.join(encoded.split()) </code></pre>
0
2016-10-18T16:06:28Z
[ "python", "base64" ]
How can I append a numpy array of N-Length to another array of N-dimensions?
40,113,072
<p><strong>Situation</strong></p> <p>I assumed this would be easy - but turns out there are a few restrictions. I have an empty array, that at this point, is empty and has unknown dimensions.</p> <pre><code>mainArray = np.array([]) </code></pre> <p>later on, I want to append arrays to my main array, which are of different lengths.</p> <p><strong>I have tried</strong></p> <p>*Please assume all arrays I have attempted to append are the result of <code>np.zeros(n)</code></p> <p>I have tried <code>np.append()</code> but this does not maintain the correct dimensions (assumes I want a linear array).</p> <p>I have tried <code>np.concatenate()</code> however, this error </p> <pre><code>TypeError: only length-1 arrays can be converted to Python scalars </code></pre> <p>implies I cannot concatenate to an empty array...?</p> <p>I have tried <code>np.vstack()</code> but get</p> <pre><code>ValueError: all the input array dimensions except for the concatenation axis must match exactly </code></pre> <p>...which implies I cannot have added arrays of different lengths?</p> <p><strong>Question</strong></p> <p>How can I append n-length arrays to an empty n-dimensional array?</p> <p><strong>update</strong></p> <p>Here is an example of an output:</p> <pre><code>[[0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0]] </code></pre> <p>Where length of 3 is a variable</p>
2
2016-10-18T16:06:08Z
40,113,201
<p>Your starting array is not empty (ok, it does have 0 elements), and not of unknown dimensions. It has a well defined shape and number of dimensions (1d).</p> <pre><code>In [704]: a=np.array([]) In [705]: a.shape Out[705]: (0,) In [706]: a.ndim Out[706]: 1 </code></pre> <p>Some examples on concatenate that work with <code>a</code></p> <pre><code>In [708]: np.concatenate((a,a,a,a)).shape Out[708]: (0,) In [709]: np.concatenate((a,np.zeros(3))).shape Out[709]: (3,) </code></pre> <p>As a general rule, don't start with an 'empty' array and try to append to it repeatedly. That's a <code>list</code> approach, and is not efficient with arrays. And because of the dimensionality issue, might not work.</p> <p>A correct way of doing a repeated append is something like:</p> <pre><code>alist = [] for i in range(3): alist.append([1,2,3]) np.array(alist) </code></pre> <p>Are the sublists all the same length or not? In your last example, they differ, and the array version is <code>dtype=object</code>. It is 1d, with pointers to lists else where in memory - i.e. glorified list.</p> <pre><code>In [710]: np.array([[0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0]]) Out[710]: array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0]], dtype=object) </code></pre> <p>This is a very different thing from what you'd get by <code>vstack</code> of 3 arrays of the same length.</p> <p>I think you need more practice with basic array construction, and the meaning of <code>shape</code> and dimensions. The title itself shows some confusion - <code>array of length N</code> <code>array of N-dimensions</code>. Those are very different descriptions.</p> <p>============</p> <p>The basic point with <code>concatenate</code> is that a <code>(n1,m)</code> array can be joined with a <code>(n2,m)</code> array to produce a <code>(n1+n2,m)</code> array. Similarly for other dimensions. If one array is 1d <code>(m,)</code> it needs to be expanded to <code>(1,m)</code> to perform this concatenation. <code>vstack</code> does this kind of expansion for you.</p> <p>This means that a <code>(0,)</code> shape array can be concatenated horizontally with other 1d arrays, but can't participate in a 2d vertical concatenation except with a <code>(n2,0)</code> array. A dimension may have size 0, but this is rarely useful, since it doesn't contain any data.</p>
4
2016-10-18T16:12:22Z
[ "python", "arrays", "numpy" ]
How can I append a numpy array of N-Length to another array of N-dimensions?
40,113,072
<p><strong>Situation</strong></p> <p>I assumed this would be easy - but turns out there are a few restrictions. I have an empty array, that at this point, is empty and has unknown dimensions.</p> <pre><code>mainArray = np.array([]) </code></pre> <p>later on, I want to append arrays to my main array, which are of different lengths.</p> <p><strong>I have tried</strong></p> <p>*Please assume all arrays I have attempted to append are the result of <code>np.zeros(n)</code></p> <p>I have tried <code>np.append()</code> but this does not maintain the correct dimensions (assumes I want a linear array).</p> <p>I have tried <code>np.concatenate()</code> however, this error </p> <pre><code>TypeError: only length-1 arrays can be converted to Python scalars </code></pre> <p>implies I cannot concatenate to an empty array...?</p> <p>I have tried <code>np.vstack()</code> but get</p> <pre><code>ValueError: all the input array dimensions except for the concatenation axis must match exactly </code></pre> <p>...which implies I cannot have added arrays of different lengths?</p> <p><strong>Question</strong></p> <p>How can I append n-length arrays to an empty n-dimensional array?</p> <p><strong>update</strong></p> <p>Here is an example of an output:</p> <pre><code>[[0,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0]] </code></pre> <p>Where length of 3 is a variable</p>
2
2016-10-18T16:06:08Z
40,117,273
<p>One of the key concepts of numpy's ndarray is that it is rectangular: all elements at a given depth have the same length. This allows simple indexing with a tuple of positions in each dimension to be mapped onto a single flat array:</p> <pre><code>array[x,y,z] #where array.shape = (a,b,c) #is equivalent to: array.flat[b*c*x + c*y + z] </code></pre> <p>This allows very fast and efficient operation in c for many algorithms.</p> <p>Numpy does technically support what you want to do, but the implementation is basically reverting functionality back to native lists. The way to do it with numpy is to specify the array <code>dtype=object</code>.</p> <h2>;TLDR</h2> <p>Arrays are intended to be created the correct size ahead of time and never change size. The functionality does exist, but it bypasses some of the advantages of using numpy arrays in the first place.</p>
1
2016-10-18T20:13:46Z
[ "python", "arrays", "numpy" ]
Django rest framework pagination
40,113,089
<p>I am trying to add pagination into my project, couldn't find any clear documentation or tutorial.</p> <p>I have a list of offices</p> <p>models Office.py</p> <pre><code>class Office(Model): name = CharField(_("name"), default=None, max_length=255, null=True) email = EmailField(_("email"), default=None, max_length=255, null=True) description = TextField(_("description"), default=None, null=True) </code></pre> <p>Serializer</p> <pre><code>class OfficeSerializer(ModelSerializer): id = IntegerField(read_only=True) name = CharField(read_only=True) email = URLField(read_only=True) description = CharField(read_only=True) class Meta: model = Office fields = ("id", "name", "email", "description") </code></pre> <p>views.py</p> <pre><code>@api_view(["GET"]) @permission_classes((AllowAny,)) def offices(request): instance = Office.objects.filter()[:10] serializer = OfficeSerializer(instance, many=True) return Response(serializer.data) </code></pre> <p>Any help with returning Office list with pagination ?</p>
0
2016-10-18T16:06:58Z
40,113,418
<p><a href="http://www.django-rest-framework.org/api-guide/pagination/" rel="nofollow">http://www.django-rest-framework.org/api-guide/pagination/</a></p> <pre><code>GET https://api.example.org/accounts/?limit=100&amp;offset=400 </code></pre> <p>Response:</p> <pre><code>HTTP 200 OK { "count": 1023 "next": "https://api.example.org/accounts/?limit=100&amp;offset=500", "previous": "https://api.example.org/accounts/?limit=100&amp;offset=300", "results": [ … ] } </code></pre> <p>Example of <code>settings.py</code></p> <pre><code>REST_FRAMEWORK = { 'PAGE_SIZE': 10, 'EXCEPTION_HANDLER': 'rest_framework_json_api.exceptions.exception_handler', 'DEFAULT_PAGINATION_CLASS': 'rest_framework_json_api.pagination.PageNumberPagination', 'DEFAULT_PARSER_CLASSES': ( 'rest_framework_json_api.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser' ), 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework_json_api.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) } </code></pre>
0
2016-10-18T16:24:13Z
[ "python", "django", "pagination", "django-rest-framework" ]
Django rest framework pagination
40,113,089
<p>I am trying to add pagination into my project, couldn't find any clear documentation or tutorial.</p> <p>I have a list of offices</p> <p>models Office.py</p> <pre><code>class Office(Model): name = CharField(_("name"), default=None, max_length=255, null=True) email = EmailField(_("email"), default=None, max_length=255, null=True) description = TextField(_("description"), default=None, null=True) </code></pre> <p>Serializer</p> <pre><code>class OfficeSerializer(ModelSerializer): id = IntegerField(read_only=True) name = CharField(read_only=True) email = URLField(read_only=True) description = CharField(read_only=True) class Meta: model = Office fields = ("id", "name", "email", "description") </code></pre> <p>views.py</p> <pre><code>@api_view(["GET"]) @permission_classes((AllowAny,)) def offices(request): instance = Office.objects.filter()[:10] serializer = OfficeSerializer(instance, many=True) return Response(serializer.data) </code></pre> <p>Any help with returning Office list with pagination ?</p>
0
2016-10-18T16:06:58Z
40,114,426
<p><a href="http://www.django-rest-framework.org/api-guide/pagination/" rel="nofollow">http://www.django-rest-framework.org/api-guide/pagination/</a></p> <blockquote> <p>Pagination is only performed automatically if you're using the generic views or viewsets. If you're using a regular APIView, you'll need to call into the pagination API yourself to ensure you return a paginated response. See the source code for the mixins.ListModelMixin and generics.GenericAPIView classes for an example.</p> </blockquote> <p><a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py#L35" rel="nofollow">https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py#L35</a> <a href="https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py#L166" rel="nofollow">https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/generics.py#L166</a></p> <p>so I would suggest something like:</p> <pre><code>@api_view(["GET"]) @permission_classes((AllowAny,)) def offices(request): pagination_class = api_settings.DEFAULT_PAGINATION_CLASS paginator = pagination_class() queryset = Office.objects.all() page = paginator.paginate_queryset(queryset, request) serializer = OfficeSerializer(page, many=True) return paginator.get_paginated_response(serializer.data) </code></pre>
0
2016-10-18T17:24:27Z
[ "python", "django", "pagination", "django-rest-framework" ]
Python - asking the user for a text and printing out specific number of times
40,113,128
<p>We've been doing python in school so the stuff that we've done so far is pretty basic but we got this homework and we're meant to ask the user to input a text and then a number and then print out the text the number of times the user requested. I though it'd be something like this, </p> <pre><code>text=input("Enter your text: ") number=input("Enter the times you want the text to be printed: ") for i in range (number): print (text) </code></pre> <p>But it doesn't work. Any help would be appreciated. It'd also help if the code was quite simple since we started doing python a couple of weeks ago.</p>
-3
2016-10-18T16:08:43Z
40,113,376
<pre><code>text=raw_input("Enter your text: ") number=input("Enter the times you want the text to be printed: ") for i in range(number): print (text) </code></pre> <p>This code is written in python2.7. raw_input() take strings wherein input() take integers.</p>
-1
2016-10-18T16:21:19Z
[ "python", "input", "range" ]
Do i have to use try: and except ValueError?
40,113,217
<p>I'm still new to python. Do I have to use try: and except ValueError? If not when would and should I use them? Some parts work with and without it E.g</p> <pre><code>Def Main_Menu(): Main_menu_op = input("A.Start \nB.Options \nC.Exit") Try: if Main_menu_op == "A" or "a": Start() elif Maim_menu_op == "B" or "b": Options() elif Main_menu_op == "C" or "c": Exit() except ValueError: print("error") Main_menu() </code></pre> <p>I just typed this since I'm on my tablet and not my pc so just ignore any mistakes </p> <p>P.s this is part of a text based game I'm working on </p>
-2
2016-10-18T16:13:14Z
40,113,355
<p>You should only use <code>try</code> and <code>except ...Error</code> (<a href="https://docs.python.org/2.7/tutorial/errors.html" rel="nofollow">documentation</a>) when you know you can safely handle a specific known error.</p> <p>So if you are expecting a certain error, like a <code>ValueError</code>, you can catch it and handle it instead of having you application crash. Let's say you have a user's input and expect a number:</p> <pre><code>... a = raw_input('Please give me a number: ') # input(...) on Python 3. try: number = float(a) except ValueError: print 'You have not given me a valid number, defaulting to 0.' number = 0. # do stuff with number ... </code></pre> <p>If you are not expecting an error or are not prepared to handle it (or there's no proper way to handle), you might want to see the error and its trace on the console so you can debug it.</p> <p>In your example you can use an 'else' to say the command given is not recognised, and ask for another.</p>
0
2016-10-18T16:20:35Z
[ "python" ]
Do i have to use try: and except ValueError?
40,113,217
<p>I'm still new to python. Do I have to use try: and except ValueError? If not when would and should I use them? Some parts work with and without it E.g</p> <pre><code>Def Main_Menu(): Main_menu_op = input("A.Start \nB.Options \nC.Exit") Try: if Main_menu_op == "A" or "a": Start() elif Maim_menu_op == "B" or "b": Options() elif Main_menu_op == "C" or "c": Exit() except ValueError: print("error") Main_menu() </code></pre> <p>I just typed this since I'm on my tablet and not my pc so just ignore any mistakes </p> <p>P.s this is part of a text based game I'm working on </p>
-2
2016-10-18T16:13:14Z
40,113,433
<p><code>try</code> <code>except</code> blocks are to enclose code that might produce a runtime error. The optional argument of Error type (in this case you have input <code>ValueError</code>) will change the block so that it will only catch that type of exception. In your example it looks like you are trying to produce an error message if none of the given options are correctly chosen.</p> <p>As written, none of the if statements will pass if a different input is received, but no exception will be generated. Instead of try:except, you should likely just use an additional <code>else</code> block onto your <code>if</code> statement. True exceptions are generally reserved for exiting the code when it tries to do something illegal like divide by 0. If you wanted to <a href="https://docs.python.org/3/tutorial/errors.html#user-defined-exceptions" rel="nofollow">create your own</a> custom exception to mimic illegal behavior, you would have to test for when it should be raised (likely with an if statement) then call <code>raise</code> with your custom exception.</p> <p>I would also like to point out that in your <code>if</code> and <code>elif</code> conditions, I think you are mistaking the operator precedence of <code>==</code> and <code>or</code>. the equivalence operator: == will be called first because of operator precedence producing either a true or false value then the or will be evaluated. the true or false value will be compared to a non-empty string (<code>'a'</code>, <code>'b'</code>, or <code>'c'</code>) which will always evaluate to true. Instead you could add another == comparison for something like: <code>if Main_menu_op == "A" or Main_menu_op == "a":</code></p>
1
2016-10-18T16:24:58Z
[ "python" ]
Return last character of string in python
40,113,223
<p>I want to print the last character of string in python reading from the file. I am calling as <code>str[-1]</code> But not working. </p> <p><strong>t.txt contains</strong></p> <pre><code>Do not laugh please! 9 Are you kidding me? 4 </code></pre> <p>My code is </p> <pre><code>with open('t.txt', 'r') as f: for line in f: print(line ) print(line[-1]) #break </code></pre> <p>But it is not printing anything. </p>
1
2016-10-18T16:13:40Z
40,113,264
<p>The last character of every line is a <em>newline character</em>. You can <a href="https://docs.python.org/2/library/string.html#string.strip" rel="nofollow">strip</a> it:</p> <pre><code>print(line.strip()[-1]) # or print(line.rstrip()[-1]) </code></pre>
6
2016-10-18T16:15:15Z
[ "python" ]
Return last character of string in python
40,113,223
<p>I want to print the last character of string in python reading from the file. I am calling as <code>str[-1]</code> But not working. </p> <p><strong>t.txt contains</strong></p> <pre><code>Do not laugh please! 9 Are you kidding me? 4 </code></pre> <p>My code is </p> <pre><code>with open('t.txt', 'r') as f: for line in f: print(line ) print(line[-1]) #break </code></pre> <p>But it is not printing anything. </p>
1
2016-10-18T16:13:40Z
40,113,366
<p>Simple take the string and clear it's leading and trailing spaces. Then return the last character in your case. Otherwise simply return last character.</p> <pre><code>line=line.strip() return line[-1] </code></pre>
0
2016-10-18T16:20:57Z
[ "python" ]
How to check if file is currently existing using os.path
40,113,224
<p>I am currently having a problem while checking if a file name entered by user already exists. This is the code that i am currently running, however when i run the code properly and go to save the data with a name that already exists. It prints the correct error caption "This file already exists" and returns them back to the menu of the program. I was wondering how i could have it. Is there a way so the program can ask the user to re-input the file name again?</p> <pre><code>if Menuchoice =='4': if popJuveniles ==0: print("please take part in option 1 before running option 4") else: if csvdata ==1: print("please take part in option 3 before trying to save the file") else: import csv #file_name=input("What would you like to call your file?") filename1=input("what would you like to call your file?") if os.path.isfile(filename1): print("This file already exists") csvext='.csv' filename=filename1+csvext with open(filename,'a') as genfile: insects_writer = csv.writer(genfile) insects_writer.writerow(csvdata) </code></pre>
0
2016-10-18T16:13:40Z
40,113,378
<p>If you want a quick answer, I would use a <code>while</code> loop until the name is correct.</p> <p>For example:</p> <pre><code>while os.path.isfile(filename1): print("This file already exists") filename1=input("what would you like to call your file?") </code></pre> <p>Keep in mind though that you should not use <code>while</code> very frequently for various reasons.</p>
1
2016-10-18T16:21:29Z
[ "python" ]
Producing multi-level dictionary from word and part-of-speech
40,113,276
<p>Given some Penn Treebank tagged text in this format:</p> <p>"David/NNP Short/NNP will/MD chair/VB the/DT meeting/NN ./. The/DT boy/NN sits/VBZ on/IN the/DT chair/NN ./."</p> <p>I would like to produce a multi-level dictionary that has the word as a key and counts the frequency it appears tagged as each POS so we have ['Chair, VB : 1, NN : 1', 'The, DT : 3',] etc. </p> <p>I figure I can use regexes to extract the word and the corresponding POS.</p> <pre><code>r'[A+Za+z]+/' and r'/[A+Z]+' </code></pre> <p>But can't work out how to put this together to make an entry for a word and its corresponding POS occurences. </p> <p>Thoughts?</p>
1
2016-10-18T16:15:48Z
40,113,387
<p>You don't have to use regular expressions in this case.</p> <p>What you can do is to split by space and then by slash collecting the results into a <a href="https://docs.python.org/2/library/collections.html#collections.defaultdict" rel="nofollow"><code>defaultdict</code></a> of <code>defaultdict</code> of <code>int</code>:</p> <pre><code>In [1]: import re In [2]: from collections import defaultdict In [3]: s = "David/NNP Short/NNP will/MD chair/VB the/DT meeting/NN ./. The/DT boy/NN sits/VBZ on/IN the/DT chair/NN ...: ./." In [4]: d = defaultdict(lambda: defaultdict(int)) In [5]: for item in s.split(): ...: word, tag = item.split("/") ...: word = word.lower() ...: d[word][tag] += 1 </code></pre> <p>Now the <code>d</code> would be:</p> <pre><code>In [6]: for word, word_data in d.items(): ...: for tag, count in word_data.items(): ...: print(word, tag, count) ...: ('boy', 'NN', 1) ('short', 'NNP', 1) ('on', 'IN', 1) ('david', 'NNP', 1) ('will', 'MD', 1) ('sits', 'VBZ', 1) ('chair', 'VB', 1) ('chair', 'NN', 1) ('.', '.', 2) ('meeting', 'NN', 1) ('the', 'DT', 3) </code></pre>
2
2016-10-18T16:22:11Z
[ "python", "regex", "dictionary", "part-of-speech" ]
How do I run a single function over a loop parallely? Python 2.7.12
40,113,343
<p>I'm trying to parallelize a program which uses a single function in a for loop which updates a global list/variable parallely. How do I go about this and how can I pass values to the function?</p> <p>The sample code looks like this,</p> <pre><code>#python 2.7.12 import random sum=0 #sample function to take a random integer between 0 to i and add it to global variable sum def hello(i): print "Thread Id :",i #instead of i it should be the threadID sum=sum+random.randrange(0,i) #main function i=1 for i in range(10): hello(i) #how to parallelize this function over a loop? </code></pre> <p>Edit 1 : Tried using the Process from multiprocessing but don't know how to pass values to the functions and how to run it parallely over a loop.</p> <pre><code>from multiprocessing import Process sum=0 def Hello(): print 'hello: starting' sum=sum+i #Don't know how to pass values here print 'hello: finishing' if name == 'main': p1 = Process(target=func1) p1.start() p1.join() print sum </code></pre>
0
2016-10-18T16:19:40Z
40,113,774
<p>You can use multiprocessing.dummy.Pool, which takes the function followed by your parameters (see below).</p> <p>You'll also need to worry about synchronization on your global variable (see below for an example of how to use Lock).</p> <p>Also, unless you use "global sum" the sum inside your function is referring to a local sum variable (see below for global sum example).</p> <p>threading.current_thread() gives you the thread id.</p> <pre><code>#python 2.7.12 from multiprocessing.dummy import Pool as ThreadPool import threading import random lock = threading.Lock() sum = 0 #sample function to take a random integer between 0 to i and add it to global variable sum def hello(i): if (i == 0): return global sum print threading.current_thread() #instead of i it should be the threadID r = random.randrange(0,i) lock.acquire() try: sum = sum + r finally: lock.release() ThreadPool().map(hello, list(range(1, 11))) print sum </code></pre>
1
2016-10-18T16:45:02Z
[ "python", "parallel-processing" ]
How do I run a single function over a loop parallely? Python 2.7.12
40,113,343
<p>I'm trying to parallelize a program which uses a single function in a for loop which updates a global list/variable parallely. How do I go about this and how can I pass values to the function?</p> <p>The sample code looks like this,</p> <pre><code>#python 2.7.12 import random sum=0 #sample function to take a random integer between 0 to i and add it to global variable sum def hello(i): print "Thread Id :",i #instead of i it should be the threadID sum=sum+random.randrange(0,i) #main function i=1 for i in range(10): hello(i) #how to parallelize this function over a loop? </code></pre> <p>Edit 1 : Tried using the Process from multiprocessing but don't know how to pass values to the functions and how to run it parallely over a loop.</p> <pre><code>from multiprocessing import Process sum=0 def Hello(): print 'hello: starting' sum=sum+i #Don't know how to pass values here print 'hello: finishing' if name == 'main': p1 = Process(target=func1) p1.start() p1.join() print sum </code></pre>
0
2016-10-18T16:19:40Z
40,113,825
<p>Pass the parameters as a tuple to the args kwarg of the Process function: Here is the example from the docs:</p> <pre><code>if __name__ == '__main__': p = Process(target=f, args=('bob',)) p.start() p.join() </code></pre> <p><a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">https://docs.python.org/2/library/multiprocessing.html</a></p> <p>Also what John Gordon said in his comment is true too. You will need to have the master process (which will be running the loop) handle the summing. What you are basically trying to do is a simple map/reduce job. </p> <p>The map part is your hello function and the reduce is the sum. There are lots of examples of doing map/reduce jobs in python.</p> <p>Look at using a Pipe or Shared Memory for handling the sum, both are detailed in the multiprocessing docs mentioned above.</p>
0
2016-10-18T16:47:23Z
[ "python", "parallel-processing" ]
UnicodeEncodeError in python3
40,113,507
<p>Some of my application's libraries are depending on being able to print UTF-8 characters to stdout and stderr. Therefore this must not fail:</p> <pre><code>print('\u2122') </code></pre> <p>On my local machine it works, but on my remote server it raises <code>UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in position 0: ordinal not in range(128)</code></p> <p>I tried <code>$ PYTHONIOENCODING=utf8</code> with no apparent effect.</p> <pre><code>sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) </code></pre> <p>works for a while, then stalls and finally fails with <code>ValueError: underlying buffer has been detached</code></p> <p><code>sys.getdefaultencoding()</code> returns <code>'utf-8'</code>, and <code>sys.stdout.encoding</code> returns <code>'ANSI_X3.4-1968'</code></p> <p>What can I do? I don't want to edit third-party libraries.</p>
0
2016-10-18T16:29:39Z
40,114,051
<p>I'm guessing you're on a UNIX-like system, and your environment set <code>LANG</code> (or <code>LC_ALL</code> or whatever) to <code>C</code>.</p> <p>Try editing your default shell's startup file to set <code>LANG</code> to something like <code>en_US.utf-8</code> (or whatever locale makes sense for you)? For example, in bash, edit <code>~/.bash_profile</code> (or <code>~/.profile</code> if you're using that instead for <code>sh</code> compatibility) and add:</p> <pre><code>export LANG="en_US.utf-8" </code></pre> <p>For (t)csh, edit <code>~/.cshrc</code> (or <code>~/.tcshrc</code> if that's what you're using) to add:</p> <pre><code>setenv LANG "en_US.utf-8" </code></pre> <p>Making the changes "live" doesn't work, because your shell is likely hosted in a terminal that has configured itself solely for ASCII display, based on the <code>LANG=C</code> in effect when it was launched (and many terminals do session coalescence, so even if you changed <code>LANG</code> and then launched a new terminal, it would coalesce with the shared terminal process with the out-of-date <code>LANG</code>). So after you change <code>~/.bash_profile</code>, log out and then log back in so your root shell will set <code>LANG</code> correctly for every other process (since they all ultimately <code>fork</code> from the root shell).</p>
0
2016-10-18T16:59:36Z
[ "python", "python-3.x", "unicode", "utf-8", "locale" ]
UnicodeEncodeError in python3
40,113,507
<p>Some of my application's libraries are depending on being able to print UTF-8 characters to stdout and stderr. Therefore this must not fail:</p> <pre><code>print('\u2122') </code></pre> <p>On my local machine it works, but on my remote server it raises <code>UnicodeEncodeError: 'ascii' codec can't encode character '\u2122' in position 0: ordinal not in range(128)</code></p> <p>I tried <code>$ PYTHONIOENCODING=utf8</code> with no apparent effect.</p> <pre><code>sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) </code></pre> <p>works for a while, then stalls and finally fails with <code>ValueError: underlying buffer has been detached</code></p> <p><code>sys.getdefaultencoding()</code> returns <code>'utf-8'</code>, and <code>sys.stdout.encoding</code> returns <code>'ANSI_X3.4-1968'</code></p> <p>What can I do? I don't want to edit third-party libraries.</p>
0
2016-10-18T16:29:39Z
40,114,882
<p>From @ShadowRanger's comment on my question,</p> <blockquote> <p><code>PYTHONIOENCODING=utf8</code> won't work unless you <code>export</code> it (or prefix the Python launch with it). Otherwise, it's a local variable in <code>bash</code> that isn't inherited in the environment of child processes. <code>export PYTHONIOENCODING=utf-8</code> would both set and export it in <code>bash</code>.</p> </blockquote> <p><code>export PYTHONIOENCODING=utf-8</code> did the trick, UTF-8 characters no longer raise UnicodeEncodeError</p>
1
2016-10-18T17:50:34Z
[ "python", "python-3.x", "unicode", "utf-8", "locale" ]
Setting up proxy with selenium / python
40,113,514
<p>I am using selenium with python. I need to configure a proxy.</p> <p>It is working for HTTP but not for HTTPS.</p> <p>The code I am using is:</p> <pre><code># configure firefox profile = webdriver.FirefoxProfile() profile.set_preference("network.proxy.type", 1) profile.set_preference("network.proxy.http", '11.111.11.11') profile.set_preference("network.proxy.http_port", int('80')) profile.update_preferences() # launch driver = webdriver.Firefox(firefox_profile=profile) driver.get('https://www.iplocation.net/find-ip-address') </code></pre> <p>Also. Is there a way for me to completely block any outgoing traffic from my IP and restrict it ONLY to the proxy IP so that I don't accidently mess up the test/stats by accidently switching from proxy to direct connection?</p> <p>Any tips would help! Thanks :)</p>
0
2016-10-18T16:29:58Z
40,113,706
<p>Check out <a href="https://github.com/AutomatedTester/browsermob-proxy-py" rel="nofollow">browsermob proxy</a> for setting up a proxies for use with <code>selenium</code></p> <pre><code>from browsermobproxy import Server server = Server("path/to/browsermob-proxy") server.start() proxy = server.create_proxy() from selenium import webdriver profile = webdriver.FirefoxProfile() profile.set_proxy(proxy.selenium_proxy()) driver = webdriver.Firefox(firefox_profile=profile) proxy.new_har("google") driver.get("http://www.google.co.uk") proxy.har # returns a HAR JSON blob server.stop() driver.quit() </code></pre> <p>You can use a remote proxy server with the <code>RemoteServer</code> class.</p> <blockquote> <p>Is there a way for me to completely block any outgoing traffic from my IP and restrict it ONLY to the proxy IP</p> </blockquote> <p>Yes, just look up how to setup proxies for whatever operating system you're using. Just use caution because some operating systems will ignore proxy rules based on certain conditions, for example, if using a VPN connection.</p>
0
2016-10-18T16:41:35Z
[ "python", "selenium", "proxy" ]
Find missing data indices using python
40,113,520
<p>What is the optimum way to return indices where 1-d array has missing data. The missing data is represented by zeros. The data may be genuinely zero but not missing. We only want to return indices where data is zero for more than or equal to 3 places at a time. For example for array [1,2,3,4,0,1,2,3,0,0,0,1,2,3] the function should only return indices for second segment where there are zeros and not the first instance.</p> <p>This is actually an interview question :) challenge is to do most effeciently in one line</p>
-3
2016-10-18T16:30:14Z
40,113,890
<p>Keep track of the count of zeros in the current run. Then if a run finishes that has at least three zeros calculate the indexes.</p> <pre><code>def find_dx_of_missing(a): runsize = 3 # 3 or more, change to 4 if your need "more than 3" zcount = 0 for i, n in enumerate(a): if n == 0: zcount += 1 else: if zcount &gt;= runsize: for j in range(i - zcount, i): yield j zcount = 0 if zcount &gt;= runsize: # needed if sequence ends with missing i += 1 for j in range(i - zcount, i): yield j </code></pre> <p>Examples:</p> <pre><code>&gt;&gt;&gt; a = [1,2,3,4,0,1,2,3,0,0,0,1,2,3] &gt;&gt;&gt; list(find_dx_of_missing(a)) [8, 9, 10] &gt;&gt;&gt; a = [0,0,0,3,0,5,0,0,0,0,10,0,0,0,0,0] &gt;&gt;&gt; list(find_dx_of_missing(a)) [0, 1, 2, 6, 7, 8, 9, 11, 12, 13, 14, 15] </code></pre> <p><strong>Edit:</strong> Since you need a one liner here are two candidates assuming <code>a</code> is your list and <code>n</code> is the smallest run of zeros that count as missing data:</p> <pre><code>[v for vals in (list(vals) for iszeros, vals in itertools.groupby(xrange(len(a)), lambda dx, a=a: a[dx]==0) if iszeros) for v in vals if len(vals) &gt;= n] </code></pre> <p>Or</p> <pre><code>sorted({dx for i in xrange(len(a)-n+1) for dx in xrange(i, i+n) if set(a[i:i+n]) == {0}}) </code></pre>
0
2016-10-18T16:50:38Z
[ "python", "python-2.7" ]
Pandas: Create another column while splitting each row from the first column
40,113,552
<p>Goal create a second column from the first column</p> <pre><code>column1, column2 Hello World, #HelloWord US Election, #USElection </code></pre> <p>I have a simple file that has a one column</p> <pre><code>columnOne Hello World US Election Movie Night </code></pre> <p>I wrote following function</p> <pre><code>&gt;&gt;&gt; def newColumn(row): ... r = "#" + "".join(row.split(" ")) ... return r </code></pre> <p>then I did following to create the second column using pandas</p> <pre><code>df['column2'] = df.apply (lambda row: newColumn(row),axis=1) </code></pre> <p>But I end up with following error: </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 3972, in apply return self._apply_standard(f, axis, reduce=reduce) File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 4064, in _apply_standard results[i] = func(v) File "&lt;stdin&gt;", line 1, in &lt;lambda&gt; File "&lt;stdin&gt;", line 2, in newColumn File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/generic.py", line 2360, in __getattr__ (type(self).__name__, name)) AttributeError: ("'Series' object has no attribute 'split'", u'occurred at index 0') </code></pre> <p>so I change the split to following: </p> <pre><code>r = "".join(row.str.split(" ")) </code></pre> <p>But that didn't help</p>
3
2016-10-18T16:32:01Z
40,113,775
<p>This should do the trick</p> <pre><code>df['new_column'] = df['old_column'].apply(lambda x: "#"+x.replace(' ', '')) </code></pre> <p>Example</p> <pre><code>&gt;&gt;&gt; names = ['Hello World', 'US Election', 'Movie Night'] &gt;&gt;&gt; df = pd.DataFrame(data = names, columns=['Names']) &gt;&gt;&gt; df Names 0 Hello World 1 US Election 2 Movie Night &gt;&gt;&gt; df['Names2'] = df['Names'].apply(lambda x: "#"+x.replace(' ', '')) &gt;&gt;&gt; df Names Names2 0 Hello World #HelloWorld 1 US Election #USElection 2 Movie Night #MovieNight </code></pre>
3
2016-10-18T16:45:02Z
[ "python", "pandas" ]
Pandas: Create another column while splitting each row from the first column
40,113,552
<p>Goal create a second column from the first column</p> <pre><code>column1, column2 Hello World, #HelloWord US Election, #USElection </code></pre> <p>I have a simple file that has a one column</p> <pre><code>columnOne Hello World US Election Movie Night </code></pre> <p>I wrote following function</p> <pre><code>&gt;&gt;&gt; def newColumn(row): ... r = "#" + "".join(row.split(" ")) ... return r </code></pre> <p>then I did following to create the second column using pandas</p> <pre><code>df['column2'] = df.apply (lambda row: newColumn(row),axis=1) </code></pre> <p>But I end up with following error: </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 3972, in apply return self._apply_standard(f, axis, reduce=reduce) File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 4064, in _apply_standard results[i] = func(v) File "&lt;stdin&gt;", line 1, in &lt;lambda&gt; File "&lt;stdin&gt;", line 2, in newColumn File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/generic.py", line 2360, in __getattr__ (type(self).__name__, name)) AttributeError: ("'Series' object has no attribute 'split'", u'occurred at index 0') </code></pre> <p>so I change the split to following: </p> <pre><code>r = "".join(row.str.split(" ")) </code></pre> <p>But that didn't help</p>
3
2016-10-18T16:32:01Z
40,113,784
<p>Try a list comprehesion:</p> <pre><code>df = pandas.DataFrame({'columnOne': ['Hello World', 'US Election', 'Movie Night']}) df['column2'] = ['#' + item.replace(' ', '') for item in df.columnOne] In [2]: df </code></pre> <p><a href="https://i.stack.imgur.com/iiwuK.png" rel="nofollow"><img src="https://i.stack.imgur.com/iiwuK.png" alt="enter image description here"></a></p>
2
2016-10-18T16:45:25Z
[ "python", "pandas" ]
Pandas: Create another column while splitting each row from the first column
40,113,552
<p>Goal create a second column from the first column</p> <pre><code>column1, column2 Hello World, #HelloWord US Election, #USElection </code></pre> <p>I have a simple file that has a one column</p> <pre><code>columnOne Hello World US Election Movie Night </code></pre> <p>I wrote following function</p> <pre><code>&gt;&gt;&gt; def newColumn(row): ... r = "#" + "".join(row.split(" ")) ... return r </code></pre> <p>then I did following to create the second column using pandas</p> <pre><code>df['column2'] = df.apply (lambda row: newColumn(row),axis=1) </code></pre> <p>But I end up with following error: </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 3972, in apply return self._apply_standard(f, axis, reduce=reduce) File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 4064, in _apply_standard results[i] = func(v) File "&lt;stdin&gt;", line 1, in &lt;lambda&gt; File "&lt;stdin&gt;", line 2, in newColumn File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/generic.py", line 2360, in __getattr__ (type(self).__name__, name)) AttributeError: ("'Series' object has no attribute 'split'", u'occurred at index 0') </code></pre> <p>so I change the split to following: </p> <pre><code>r = "".join(row.str.split(" ")) </code></pre> <p>But that didn't help</p>
3
2016-10-18T16:32:01Z
40,114,137
<p>Your general approach is totally fine, you just have a few problems. When you use apply on an entire dataframe, it will pass either a row or a column to the function it is applying. In your case, you don't want a row or a column - you want the string that is within each cell in the first column. So, instead of running <code>df.apply</code>, you want <code>df['columnOne'].apply</code>.</p> <p>Here's what I would do: </p> <pre><code>import pandas as pd df = pd.DataFrame(['First test here', 'Second test'], columns=['A']) # Note that this function expects a string, and returns a string def new_string(s): # Get rid of the spaces s = s.replace(' ','') # Add the hash s = '#' + s return s # The, apply it to the first column, and save it in the second, new column df['B'] = df['A'].apply(new_string) </code></pre> <p>Or, if you really want it in a one-liner:</p> <pre><code>df['B'] = df['A'].apply(lambda x: '#' + x.replace(' ','')) </code></pre>
3
2016-10-18T17:04:34Z
[ "python", "pandas" ]
Pandas: Create another column while splitting each row from the first column
40,113,552
<p>Goal create a second column from the first column</p> <pre><code>column1, column2 Hello World, #HelloWord US Election, #USElection </code></pre> <p>I have a simple file that has a one column</p> <pre><code>columnOne Hello World US Election Movie Night </code></pre> <p>I wrote following function</p> <pre><code>&gt;&gt;&gt; def newColumn(row): ... r = "#" + "".join(row.split(" ")) ... return r </code></pre> <p>then I did following to create the second column using pandas</p> <pre><code>df['column2'] = df.apply (lambda row: newColumn(row),axis=1) </code></pre> <p>But I end up with following error: </p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 3972, in apply return self._apply_standard(f, axis, reduce=reduce) File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/frame.py", line 4064, in _apply_standard results[i] = func(v) File "&lt;stdin&gt;", line 1, in &lt;lambda&gt; File "&lt;stdin&gt;", line 2, in newColumn File "/Users/anuradha_uduwage/anaconda2/lib/python2.7/site-packages/pandas/core/generic.py", line 2360, in __getattr__ (type(self).__name__, name)) AttributeError: ("'Series' object has no attribute 'split'", u'occurred at index 0') </code></pre> <p>so I change the split to following: </p> <pre><code>r = "".join(row.str.split(" ")) </code></pre> <p>But that didn't help</p>
3
2016-10-18T16:32:01Z
40,114,562
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html" rel="nofollow"><code>str.replace</code></a> as commented <a href="http://stackoverflow.com/questions/40113552/pandas-create-another-column-while-splitting-each-row-from-the-first-column/40114562#comment67498560_40113552">MaxU</a> or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.replace.html" rel="nofollow"><code>Series.replace</code></a> with parameter <code>regex=True</code> for replacing all whitespaces by empty strings:</p> <pre><code>df['column2'] = '#' + df.column1.str.replace('\s+','') df['column3'] = '#' + df.column1.replace('\s+','', regex=True) print (df) column1 column2 column3 0 Hello World #HelloWorld #HelloWorld 1 US Election #USElection #USElection </code></pre>
3
2016-10-18T17:32:39Z
[ "python", "pandas" ]
finding new line characters in a text file
40,113,785
<p>I have an assignment that involves creating a tail to find the last <code>K</code> lines in a file. We have been given a buffer to use for this. For now, I'm trying to write small things and search for <code>"\n"</code> characters within a file. I am running into a few problems. In <code>python</code> my code spits back <strong>6</strong> and in <code>python3</code> its a <strong>0</strong>. The text file has WAY more than this though. Can someone please tell me why this isn't working as I would like? </p> <pre><code>def new(): try: f = open("test.txt", "r") count = 0 for i in f: if i == "\n": count = count + 1 return count f.close() except(FileNotFoundError): print("No file") </code></pre> <p>What I would like to do is use seek to go backwards in the file and every so often search for the new line characters but this doesn't even seem to work for me. </p>
0
2016-10-18T16:45:28Z
40,113,878
<p><code>for i in f:</code> isn't doing what you think it is. The default iterator for a file gives you <code>lines</code>, not <code>characters</code>. So you're saying "Does the entire line equal just a return?"</p> <p>Try instead doing <code>if i[-1] == "\n":</code> as this says "Is the last character in the line a newline?"</p> <p>You might notice that this is trivially true, as each "line" is ended by a newline, so simply counting the lines is sufficient.</p> <hr> <p>If you want to iterate through the individual characters, I would do:</p> <pre><code>for line in file: for char in line: dostuff() </code></pre> <p>Naming the variables what you think they are will also help to troubleshoot if they end up not being what you thought.</p> <hr> <p>Example on <a href="https://repl.it/Dzaf/0" rel="nofollow">repl.it</a>. The variables are named <code>line</code> and <code>char</code> just to show what they are, they could be <code>banana</code> and <code>henry</code> just as easily, although then it would be less clear what was happening. <code>raven</code> simulates a file for the purposes of this example.</p>
1
2016-10-18T16:49:41Z
[ "python", "file", "newline" ]
finding new line characters in a text file
40,113,785
<p>I have an assignment that involves creating a tail to find the last <code>K</code> lines in a file. We have been given a buffer to use for this. For now, I'm trying to write small things and search for <code>"\n"</code> characters within a file. I am running into a few problems. In <code>python</code> my code spits back <strong>6</strong> and in <code>python3</code> its a <strong>0</strong>. The text file has WAY more than this though. Can someone please tell me why this isn't working as I would like? </p> <pre><code>def new(): try: f = open("test.txt", "r") count = 0 for i in f: if i == "\n": count = count + 1 return count f.close() except(FileNotFoundError): print("No file") </code></pre> <p>What I would like to do is use seek to go backwards in the file and every so often search for the new line characters but this doesn't even seem to work for me. </p>
0
2016-10-18T16:45:28Z
40,113,895
<p>A much simpler approach would be to</p> <ul> <li>use Python's built-in ability to split a file into a list of lines</li> <li>create your tail from the last K elements of that list</li> </ul> <p>If keeping the whole file in an array is a problem, you could instead read the file line-by-line, but only retain the last K lines read, so that when you reach the end of the file, you have the tail you want.</p>
0
2016-10-18T16:51:14Z
[ "python", "file", "newline" ]
finding new line characters in a text file
40,113,785
<p>I have an assignment that involves creating a tail to find the last <code>K</code> lines in a file. We have been given a buffer to use for this. For now, I'm trying to write small things and search for <code>"\n"</code> characters within a file. I am running into a few problems. In <code>python</code> my code spits back <strong>6</strong> and in <code>python3</code> its a <strong>0</strong>. The text file has WAY more than this though. Can someone please tell me why this isn't working as I would like? </p> <pre><code>def new(): try: f = open("test.txt", "r") count = 0 for i in f: if i == "\n": count = count + 1 return count f.close() except(FileNotFoundError): print("No file") </code></pre> <p>What I would like to do is use seek to go backwards in the file and every so often search for the new line characters but this doesn't even seem to work for me. </p>
0
2016-10-18T16:45:28Z
40,113,896
<p>Why not simplify the logic and use a Python built-in?</p> <pre><code>def new(): # not a good function name! try: with open('data1.txt') as f: return f.read().count('\n') except FileNotFoundError: print ("No file") </code></pre>
0
2016-10-18T16:51:21Z
[ "python", "file", "newline" ]
Django ImportError: No module named... but module is visible in Project Interpreter settings
40,113,835
<p>I am developing a Django app and I am experiencing a strange problem. I've installed a few modules using pip and I can see them in "project interpreter settings":</p> <p><a href="https://i.stack.imgur.com/NWeYS.png" rel="nofollow"><img src="https://i.stack.imgur.com/NWeYS.png" alt="enter image description here"></a></p> <p>However, when I try to import any of these modules I get errors like this:</p> <pre><code>File "/Users/Franek/Documents/testy/testy/testysearch/views.py", line 4, in &lt;module&gt; from sumy.summarizers.text_rank import TextRankSummarizer ImportError: No module named sumy.summarizers.text_rank </code></pre> <p>I am using <code>virtualenv</code>, but I don't think this can be an issue, because when I try to run some of these modules from console (bypassing Django) they work properly. What am I doing wrong?</p>
0
2016-10-18T16:47:51Z
40,116,359
<p>Did u activate your virtualenv, with the command:</p> <pre><code>source &lt;virtualenv_name&gt;/bin/ativate </code></pre>
0
2016-10-18T19:20:40Z
[ "python", "django", "python-2.7", "python-import", "python-module" ]
Bind Key to Stop Script
40,113,868
<p>I have a URL in a while loop which repeats the process. Is it possible to bind a key to stop a selenium python script from running while still keeping chromedriver open?</p>
0
2016-10-18T16:49:12Z
40,113,918
<p>You can use a try/except block that catches a <code>KeyboardInterrupt</code> exception (IE when you input <code>ctrl + c</code> to the terminal/command prompt)</p> <pre><code>try: while True: #dostuff except KeyboardInterrupt: print("Loop stopped!") </code></pre> <p>You may also want to consider launching your script in interactive mode, which will prevent the console from closing and will keep the interpreter open after the completion (or failure) of the script, thereby preventing the teardown/cleanup that closes the webdriver instance.</p>
1
2016-10-18T16:52:38Z
[ "python", "selenium", "webdriver", "selenium-chromedriver" ]
Build successive condition to when
40,113,905
<p>I'm trying to build a sql request of consecutive <code>when</code>.</p> <pre><code>def build_modify_function(df, ids_colname, modified_colname, modification_list): if len(modification_list) == 0: pass # Small optimization id_col = df[ids_colname] modif_col = df[modified_colname] # There is no "identity element" so : ret = None for (row_ids, new_value) in modification_list: if type(row_ids) != type(list()): row_ids = list(row_ids) if ret == None: ret = when(id_col.isin(row_ids), new_value) # .isin(row_ids) else: ret = ret.when(id_col.isin(row_ids), new_value) return modif_col if ret == None else ret.otherwise(modif_col) </code></pre> <p><code>df</code> is a dataframe,</p> <p><code>ids_colname</code> is the column name of my ids,</p> <p><code>modified_colname</code> is the column name I want to modify,</p> <p><code>modification_list</code> is a list of tuple <code>[(list_of_ids, new_value)]</code></p> <p>I am having this error:</p> <pre><code>ValueError: Cannot convert column into bool: please use '&amp;' for 'and', '|' for 'or', '~' for 'not' when building DataFrame boolean expressions. </code></pre> <p>I don't understand why. When I build a very simple function returning :</p> <pre><code> tmp = when(id_col.isin(row_ids), new_value) return tmp\ .when(id_col.isin(row_ids), new_value)\ .otherwise(modif_col) </code></pre> <p>It perfectly works. Any suggestions?</p>
0
2016-10-18T16:52:02Z
40,114,735
<p>I believe that the problem is here:</p> <pre><code>if ret == None: ... </code></pre> <p>In general you should never use equality operators to compare to singleton objects in Python and always use <code>is</code> or <code>is not</code>:</p> <pre><code>if ret is None: ... </code></pre> <p>In this particular case equality operator for column returns a <code>Column</code> and <code>Column</code> object explicitly forbids conversion to bool.</p>
0
2016-10-18T17:42:07Z
[ "python", "apache-spark", "apache-spark-sql" ]
Issue adding request headers for Django Tests
40,113,921
<p>I need to add a header to a request in a Django test. I have browsed a few pages on both Stack Overflow and elsewhere, following various suggestions. I can add the headers to PUTs and GETs successfully, but having an issue with POSTs. Any advice would be greatly appreciated.</p> <p>For PUT and GET I have used the following [passing successfully]:</p> <pre><code>resp = self.client.put(resource_url, res_params, **{'HTTP_SSL_CLIENT_CERT': self.client_cert}) </code></pre> <p>For POST, I tried the same thing but am receiving the error: "'str' object has no attribute 'items'"</p> <p>I have tried the following:</p> <pre><code>resp = self.client.post(resource_url, res_params, **{'HTTP_SSL_CLIENT_CERT': self.client_cert}) resp = self.client.post(resource_url, res_params, HTTP_SSL_CLIENT_CERT=self.client_cert) resp = self.client.post(resource_url, res_params, HTTP_SSL_CLIENT_CERT='1234567890') </code></pre>
0
2016-10-18T16:52:39Z
40,127,734
<p>For anybody that finds themselves looking at this page with a similar issue, I was able to get this working with the following:</p> <pre><code>resp = self.client.post(resource_url, data=res_params, content_type='application/json', HTTP_SSL_CLIENT_CERT=self.client_cert) </code></pre>
0
2016-10-19T09:44:32Z
[ "python", "django", "django-testing" ]
Python - creating multiple objects for a class
40,113,998
<p>In python I need to create 43 instances of a class 'Student' that includes the variables first_name, middle_name, last_name, student_id by reading in a file (Students.txt) and parsing it. The text file appears like this: </p> <pre><code>Last Name Midle Name First Name Student ID ---------------------------------------------- Howard Moe howar1m Howard Curly howar1c Fine Lary fine1l Howard Shemp howar1s Besser Joe besse1j DeRita Joe Curly derit1cj Tiure Desilijic Jaba tiure1jd Tharen Bria thare1b Tai Besadii Durga tai1db Hego Damask hego1d Lannister Tyrion lanni1t Stark Arya stark1a Clegane Sandor clega1s Targaryen Daenerys targa1d Bombadil Tom bomba1t Brandybuck Meriadoc brand1m Took Pregrin took1p McCoy Leonard mccoy1l Scott Montgomery scott1m Crusher Wesley crush1w Montoya Inigo monto1i Rugen Tyrone rugen1t Solo Han solo1h Corey Carl corey1c Flaumel Evelyn flaum1e Taltos Vlad talto1v e'Drien Morrolan edrie1m Watson John watso1j McCoy Ebenezar mccoy1e Carpenter Molly carpe1m Graystone Zoe grays1z Adama William adama1w Adama Joseph Leland adama1l Roslin Laura rosli1l Baltar Gaius balta1g Tigh Ellen tigh1e Tigh Saul tigh1s Cottle Sherman cottl1s Zarek Thomas zarek1t Murphy James Alexander murph1a Sobchak Walter sobch1w Dane Alexander dane1a Gruber Hans grube1h Biggs John Gil biggs1gj </code></pre> <p>The class student is:</p> <pre><code>class Student (object): def __init__(self, first_name, middle_name, last_name, student_id): self.__first_name = first_name self.__middle_name = middle_name self.__last_name = last_name self.__student_id = student_id </code></pre> <p>What would be the easiest way to read into 'Students.txt' and create each instance of student?</p>
0
2016-10-18T16:57:00Z
40,114,173
<pre><code>list_of_students = [] with open('students.txt') as f: for line in f: data = line.split() if len(data) == 3: firstname, lastname, id = data list_of_students.append(Student(firstname, '', lastname, id)) elif len(data) == 4: list_of_students.append(Student(*data)) else: raise ValueError </code></pre> <p>I'm not usre exactly how your input file is laid out, so there's a little processing here to handle the cases where there is no middle name.</p>
0
2016-10-18T17:06:15Z
[ "python", "class", "object", "object-oriented-analysis" ]
Python - creating multiple objects for a class
40,113,998
<p>In python I need to create 43 instances of a class 'Student' that includes the variables first_name, middle_name, last_name, student_id by reading in a file (Students.txt) and parsing it. The text file appears like this: </p> <pre><code>Last Name Midle Name First Name Student ID ---------------------------------------------- Howard Moe howar1m Howard Curly howar1c Fine Lary fine1l Howard Shemp howar1s Besser Joe besse1j DeRita Joe Curly derit1cj Tiure Desilijic Jaba tiure1jd Tharen Bria thare1b Tai Besadii Durga tai1db Hego Damask hego1d Lannister Tyrion lanni1t Stark Arya stark1a Clegane Sandor clega1s Targaryen Daenerys targa1d Bombadil Tom bomba1t Brandybuck Meriadoc brand1m Took Pregrin took1p McCoy Leonard mccoy1l Scott Montgomery scott1m Crusher Wesley crush1w Montoya Inigo monto1i Rugen Tyrone rugen1t Solo Han solo1h Corey Carl corey1c Flaumel Evelyn flaum1e Taltos Vlad talto1v e'Drien Morrolan edrie1m Watson John watso1j McCoy Ebenezar mccoy1e Carpenter Molly carpe1m Graystone Zoe grays1z Adama William adama1w Adama Joseph Leland adama1l Roslin Laura rosli1l Baltar Gaius balta1g Tigh Ellen tigh1e Tigh Saul tigh1s Cottle Sherman cottl1s Zarek Thomas zarek1t Murphy James Alexander murph1a Sobchak Walter sobch1w Dane Alexander dane1a Gruber Hans grube1h Biggs John Gil biggs1gj </code></pre> <p>The class student is:</p> <pre><code>class Student (object): def __init__(self, first_name, middle_name, last_name, student_id): self.__first_name = first_name self.__middle_name = middle_name self.__last_name = last_name self.__student_id = student_id </code></pre> <p>What would be the easiest way to read into 'Students.txt' and create each instance of student?</p>
0
2016-10-18T16:57:00Z
40,115,729
<h2>Step by step tutorial</h2> <p>To read the file content, use <code>io.open</code>. Don't forget to specify the file encoding if any name has accentuated characters.</p> <pre><code>with io.open('students.txt', mode="r", encoding="utf8") as fd: content = fd.read() </code></pre> <p>Here, you read the whole content and store it in memory (amount of data is small). You can also use an iterator.</p> <p>Then, you can split the content line by line with <code>str.splitlines()</code>:</p> <pre><code>lines = content.splitlines() # print(lines) </code></pre> <p>You get something like:</p> <pre><code>['Last Name Midle Name First Name Student ID ', '----------------------------------------------', 'Howard Moe howar1m ', 'Howard Curly howar1c ', 'Fine Lary fine1l ', 'Howard Shemp howar1s ', 'Besser Joe besse1j ', 'DeRita Joe Curly derit1cj ', 'Tiure Desilijic Jaba tiure1jd ', 'Tharen Bria thare1b '] </code></pre> <p>You have (nearly) fixed-length lines, so you can use slices to extract the fields.</p> <p>Here is what you can do for the header:</p> <pre><code>header = lines.pop(0) fields = header[0:8], header[11:21], header[23:33], header[36:46] # print(fields) </code></pre> <p>You get:</p> <pre><code>('Last Nam', 'Midle Name', 'First Name', 'Student ID') </code></pre> <p>You can drop the line of hyphens:</p> <pre><code>lines.pop(0) </code></pre> <p>For each line, you can extract values using slices too. Note: slice indices are slightly different:</p> <pre><code>for line in lines: record = line[0:8], line[12:21], line[23:34], line[36:46] # print(record) </code></pre> <p>You'll get values with trailing space:</p> <pre><code>('Howard ', ' ', ' Moe ', 'howar1m ') ('Howard ', ' ', ' Curly ', 'howar1c ') ('Fine ', ' ', ' Lary ', 'fine1l ') ('Howard ', ' ', ' Shemp ', 'howar1s ') ('Besser ', ' ', ' Joe ', 'besse1j ') ('DeRita ', 'Joe ', ' Curly ', 'derit1cj ') ('Tiure ', 'Desilijic', ' Jaba ', 'tiure1jd ') ('Tharen ', ' ', ' Bria ', 'thare1b ') </code></pre> <p>To avoid trailing spaces, use <code>str.strip()</code> function:</p> <pre><code>for line in lines: record = line[0:8], line[12:21], line[23:34], line[36:46] record = [v.strip() for v in record] # print(record) </code></pre> <p>You get:</p> <pre><code>['Howard', '', 'Moe', 'howar1m'] ['Howard', '', 'Curly', 'howar1c'] ['Fine', '', 'Lary', 'fine1l'] ['Howard', '', 'Shemp', 'howar1s'] ['Besser', '', 'Joe', 'besse1j'] ['DeRita', 'Joe', 'Curly', 'derit1cj'] ['Tiure', 'Desilijic', 'Jaba', 'tiure1jd'] ['Tharen', '', 'Bria', 'thare1b'] </code></pre> <p>At this point, I recommend you to store your record as a <code>dict</code> in a list:</p> <pre><code>records = [] for line in lines: record = line[0:8], line[12:21], line[23:34], line[36:46] record = [v.strip() for v in record] records.append(dict(zip(header, record))) </code></pre> <p>You get:</p> <pre><code>[{'First Name': 'Moe', 'Last Nam': 'Howard', 'Midle Name': '', 'Student ID': 'howar1m'}, {'First Name': 'Curly', 'Last Nam': 'Howard', 'Midle Name': '', 'Student ID': 'howar1c'}, {'First Name': 'Lary', 'Last Nam': 'Fine', 'Midle Name': '', 'Student ID': 'fine1l'}, {'First Name': 'Shemp', 'Last Nam': 'Howard', 'Midle Name': '', 'Student ID': 'howar1s'}, {'First Name': 'Joe', 'Last Nam': 'Besser', 'Midle Name': '', 'Student ID': 'besse1j'}, {'First Name': 'Curly', 'Last Nam': 'DeRita', 'Midle Name': 'Joe', 'Student ID': 'derit1cj'}, {'First Name': 'Jaba', 'Last Nam': 'Tiure', 'Midle Name': 'Desilijic', 'Student ID': 'tiure1jd'}, {'First Name': 'Bria', 'Last Nam': 'Tharen', 'Midle Name': '', 'Student ID': 'thare1b'}] </code></pre> <p>But you can also use a class:</p> <pre><code>class Student(object): def __init__(self, first_name, middle_name, last_name, student_id): self.first_name = first_name self.middle_name = middle_name self.last_name = last_name self.student_id = student_id def __repr__(self): fmt = "&lt;Student('{first_name}', '{middle_name}', '{last_name}', '{student_id}')&gt;" return fmt.format(first_name=self.first_name, middle_name=self.middle_name, last_name=self.last_name, student_id=self.student_id) </code></pre> <p>And construct a list of students:</p> <pre><code>students = [] for line in lines: record = line[0:8], line[12:21], line[23:34], line[36:46] record = [v.strip() for v in record] students.append(Student(*record)) </code></pre> <p>You get:</p> <pre><code>[&lt;Student('Howard', '', 'Moe', 'howar1m')&gt;, &lt;Student('Howard', '', 'Curly', 'howar1c')&gt;, &lt;Student('Fine', '', 'Lary', 'fine1l')&gt;, &lt;Student('Howard', '', 'Shemp', 'howar1s')&gt;, &lt;Student('Besser', '', 'Joe', 'besse1j')&gt;, &lt;Student('DeRita', 'Joe', 'Curly', 'derit1cj')&gt;, &lt;Student('Tiure', 'Desilijic', 'Jaba', 'tiure1jd')&gt;, &lt;Student('Tharen', '', 'Bria', 'thare1b')&gt;] </code></pre>
0
2016-10-18T18:41:54Z
[ "python", "class", "object", "object-oriented-analysis" ]
Precise Python 2.7 calculation including Pi
40,114,115
<p>I am working on a small program that calculates different things related to orbital mechanics, such as the semi-major axis of an orbit, velocity etc. (No experience in this subject is required to answer this).</p> <p>Everything worked out well, until I tried to calculate the orbital period (a formula where I had to use Pi):</p> <p>T = 2π √ a<sup>3</sup> / µ <a href="https://i.stack.imgur.com/cyS2I.png" rel="nofollow">(Click for image)</a></p> <p>Where <em>T</em> is <em>time in seconds</em>, <em>a</em> is the <em>semi-major axis</em>, and <em>µ</em> is the <em>standard gravitational parameter</em>.</p> <p>Now, my problem is that my program does not calculate it very precise, as the result of the formula is a bit off; for example: a circular orbit at an altitude of 160km should take approx 88 minutes, but my program tells me an approx of 90 minutes and 37 seconds.</p> <p><strong>My code:</strong></p> <pre><code>#the standard gravitational parameter of the Earth gravPara = 3.986004418*10**14 #the semi-major axis of the orbit (the radius of the Earth + the apoapsis and periapsis of your orbit / 2) semiMajor = (bodyDia + ap + pe) / 2 #formula to calculate orbital period timeSeconds = (2 * math.pi) * math.sqrt(semiMajor**3 / gravPara) #making the result appear as minutes and seconds instead of just seconds timeMinutes = 0 while (timeSeconds &gt; 60): timeSeconds = timeSeconds - 60 timeMinutes = timeMinutes + 1 #round the variable to store seconds round(timeSeconds, 0) #print the result print timeMinutes print timeSeconds </code></pre> <p>So my question is: is it an error in my code, or is <code>math.pi</code> not very precise when used together in such a formula? Should I store it as a float and use the float instead or should I split up the calculation into multiple pieces?</p> <p>I would be very thankful if you could help me out on this one, as searching through the Python reference as well as other forums did not get me very far.</p> <p>PS: when using <code>print math.pi</code> it returns a precise value of Pi, so the <code>math.pi</code> function seems to be working correctly.</p>
-2
2016-10-18T17:03:39Z
40,114,664
<p><code>math.pi</code> is a float with 15 decimals: 3.141592653589793</p> <p>As per chepners comment to your original post, that equates to about the size of an atom when calculating spheres the size of the earth. </p> <p>So to answer your question: it's not <code>math.pi</code></p>
1
2016-10-18T17:38:09Z
[ "python", "python-2.7", "math" ]
Precise Python 2.7 calculation including Pi
40,114,115
<p>I am working on a small program that calculates different things related to orbital mechanics, such as the semi-major axis of an orbit, velocity etc. (No experience in this subject is required to answer this).</p> <p>Everything worked out well, until I tried to calculate the orbital period (a formula where I had to use Pi):</p> <p>T = 2π √ a<sup>3</sup> / µ <a href="https://i.stack.imgur.com/cyS2I.png" rel="nofollow">(Click for image)</a></p> <p>Where <em>T</em> is <em>time in seconds</em>, <em>a</em> is the <em>semi-major axis</em>, and <em>µ</em> is the <em>standard gravitational parameter</em>.</p> <p>Now, my problem is that my program does not calculate it very precise, as the result of the formula is a bit off; for example: a circular orbit at an altitude of 160km should take approx 88 minutes, but my program tells me an approx of 90 minutes and 37 seconds.</p> <p><strong>My code:</strong></p> <pre><code>#the standard gravitational parameter of the Earth gravPara = 3.986004418*10**14 #the semi-major axis of the orbit (the radius of the Earth + the apoapsis and periapsis of your orbit / 2) semiMajor = (bodyDia + ap + pe) / 2 #formula to calculate orbital period timeSeconds = (2 * math.pi) * math.sqrt(semiMajor**3 / gravPara) #making the result appear as minutes and seconds instead of just seconds timeMinutes = 0 while (timeSeconds &gt; 60): timeSeconds = timeSeconds - 60 timeMinutes = timeMinutes + 1 #round the variable to store seconds round(timeSeconds, 0) #print the result print timeMinutes print timeSeconds </code></pre> <p>So my question is: is it an error in my code, or is <code>math.pi</code> not very precise when used together in such a formula? Should I store it as a float and use the float instead or should I split up the calculation into multiple pieces?</p> <p>I would be very thankful if you could help me out on this one, as searching through the Python reference as well as other forums did not get me very far.</p> <p>PS: when using <code>print math.pi</code> it returns a precise value of Pi, so the <code>math.pi</code> function seems to be working correctly.</p>
-2
2016-10-18T17:03:39Z
40,114,815
<p>Okay - seems like I have found the solution to my problem; while editing my question to include my calculation for the variable <em>semiMajor</em>, I realized I forgot to include parentheses around <code>bodyDia + ap + pe</code>, which caused faulty prioritizing, leading to the not-very-precise calculation.</p> <p>So it was just a silly mistake in my code, and it was easily solved by adding two parentheses. Thank you for taking your time.</p>
0
2016-10-18T17:46:48Z
[ "python", "python-2.7", "math" ]
Extract a seris of tar files into self titled directories
40,114,156
<p>I have a series of tar files that I wish to extract their containing data into a new directory. I want this directory to be an edited version of the original tar file name. </p> <pre><code>import tarfile import glob import os for file in glob.glob("*.tar"): # Open file tar = tarfile.open(file, "r:") # Create new diretory with name of tar file (minus .tar) new_dir = file[0:-4] os.makedirs(new_dir) tar.extractall() os.chdir(new_dir) </code></pre> <p>This works fine up until the <code>tar.extractall()</code> part. Is there a way to directly extract the tar file into the target directory or am I forced to extract all and then move the files across?</p>
0
2016-10-18T17:05:14Z
40,115,347
<p>new_dir = "path"</p> <p><code>tar.extractall(path=new_dir)</code></p>
0
2016-10-18T18:20:32Z
[ "python", "tar" ]
Mapping csv file to nested json
40,114,225
<p>I have data in a csv in the form of </p> <pre><code>"category1", 2010, "deatil1" "category1", 2010, "deatil2" "category1", 2011, "deatil3" "category2", 2011, "deatil4" </code></pre> <p>I need to map it to json in form of </p> <pre><code> { "name": "Data", "children": [{ "name": "category1", "children": [{ "name": "2010", "children": [ {"name": "deatil1"}, {"name": "detail2"} ], "name": "2011", "children": [ {"name": "detail3"} ] }, { }] }, { "name": "category2", "children": [{ "name": "2011", "children": [{ "name": "detail4" }] } ] } ] } </code></pre> <p>Basically I need to collect up all the details for each unique category and year pair and put the list</p> <p>I have tried to use a nested dict structure but the output is not correct.</p> <p>I have created a custom dict class that handles the nesting of the nesting of the dictionaries. The following code collects the data in the right structure, but I am unsure how to proceed with outputting it in the right format. Any help would be greatly appreciated.</p> <pre><code>class Vividict(dict): def __missing__(self, key): value = self[key] = type(self)() return value dict = Vividict() for row in ws.iter_rows(row_offset=1): sector = row[0].value year = row[2].value detail = row[1].value dict[sector][year][detail] print json.dumps(dict).encode('utf8') </code></pre>
1
2016-10-18T17:10:32Z
40,116,288
<p>Starting from your <code>dict</code> structure, it's a matter of building up the new data structure. I am using here mostly list comprehensions where <code>dict</code> are created:</p> <pre><code>import json rows = [ ("category1", 2010, "deatil1"), ("category1", 2010, "deatil2"), ("category1", 2011, "deatil3"), ("category2", 2011, "deatil4")] class Vividict(dict): def __missing__(self, key): value = self[key] = type(self)() return value dict = Vividict() for row in rows: sector = row[0] year = row[1] detail = row[2] dict[sector][year][detail] # This is the new data structure, derived from the existing 'dict' d = {'name': 'Data', 'children': [ {'name': k1, # sector 'children': [ {'name': k2, # year 'children': [ { 'name': k3 # deatil } for k3 in v2.keys()] } for k2, v2 in v1.iteritems()] } for k1, v1 in dict.iteritems()] } print json.dumps(d).encode('utf8') </code></pre> <p>See it in action here: <a href="https://eval.in/662805" rel="nofollow">https://eval.in/662805</a></p>
2
2016-10-18T19:16:19Z
[ "python", "json", "csv", "dictionary" ]
Extract part of data from JSON file using python
40,114,248
<p>I have been trying to extract only certain data from a JSON file using python.I wanted to create an array from my json which has some entries as below</p> <pre><code>[{"Device Name":"abc", "Device Caps":["a1", "b1", "c1"]}, {"Device Name":"def", "Device Caps":["a2", "b2", "c2"]}, {"Device Name":"ghi", "Device Caps":["a3", "b3", "c3"]}, {"Device Name":"jkl", "Device Caps":["a4", "b4", "c4"]}] </code></pre> <p>I need my output as ["a1","a2","a3","a4"]</p>
-1
2016-10-18T17:11:44Z
40,114,291
<p>If that is literally your input file, then the following code will produce the output you want:</p> <pre><code>import json with open("input.json") as input_file: data = json.load(input_file) data = [d["Device Caps"][0] for d in data] print(data) </code></pre>
1
2016-10-18T17:14:56Z
[ "python", "json", "extract", "decode" ]
PyCharm template for python class __init__ function
40,114,251
<p>I have a python class with several init variables:</p> <pre><code>class Foo(object): def __init__(self, d1, d2): self.d1 = d1 self.d2 = d2 </code></pre> <p>Is there a way to create this code automatically in PyCharm, so I don't have to type explicitly:</p> <pre><code>self.dn = dn </code></pre> <p>This pattern happens very often in my code. Is there a better (Pythonic) way to initialize classes?</p> <p>I have already seen this post ( <a href="http://stackoverflow.com/questions/3652851/what-is-the-best-way-to-do-automatic-attribute-assignment-in-python-and-is-it-a">What is the best way to do automatic attribute assignment in Python, and is it a good idea?</a>), but I don't want to use a decorator as it makes the code less readable.</p>
1
2016-10-18T17:11:52Z
40,114,374
<p>You can start by making a custom <a href="https://www.jetbrains.com/help/pycharm/2016.2/live-templates.html" rel="nofollow">Live Template</a>. I'm not sure about whether you can auto-generate variable number of arguments this way, but, for two constructor arguments the live template may look like:</p> <pre><code>class $class_name$: def __init__(self, $arg1$, $arg2$): self.$arg1$ = $arg1$ self.$arg2$ = $arg2$ $END$ </code></pre> <p>This is how I've set it up in PyCharm:</p> <p><a href="https://i.stack.imgur.com/7aAma.png" rel="nofollow"><img src="https://i.stack.imgur.com/7aAma.png" alt="enter image description here"></a></p> <hr> <p>Or, you can change the way you set the instance attributes and generalize it for N arguments, see:</p> <ul> <li><a href="http://stackoverflow.com/questions/8187082/how-can-you-set-class-attributes-from-variable-arguments-kwargs-in-python">How can you set class attributes from variable arguments (kwargs) in python</a></li> </ul>
3
2016-10-18T17:20:28Z
[ "python", "class", "attributes", "pycharm" ]
How can I insert a Series into a DataFrame row?
40,114,327
<p>I have a DataFrame like this:</p> <pre><code>import pandas as pd import numpy as np df = pd.DataFrame(columns=['a','b','c','d'], index=['x','y','z']) df a b c d x NaN NaN NaN NaN y NaN NaN NaN NaN z NaN NaN NaN NaN </code></pre> <p>I also have a Series like this</p> <pre><code>s = pd.Series(np.random.randn(3), index=['b', 'c', 'd']) s b -0.738283 c -0.649760 d -0.777346 dtype: float64 </code></pre> <p>I want to insert the Series into a row of the DataFrame, for example the 1th row, resulting the final DataFrame:</p> <pre><code> a b c d x NaN NaN NaN NaN y NaN -0.738283 -0.649760 -0.777346 z NaN NaN NaN NaN </code></pre> <p>How can I do it? thanks in advance ;)</p>
2
2016-10-18T17:17:10Z
40,114,444
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iloc.html" rel="nofollow"><code>iloc</code></a> if need select <code>index</code> of <code>df</code> by position:</p> <pre><code>#select second row (python counts from 0) df.iloc[1] = s print (df) a b c d x NaN NaN NaN NaN y NaN 1.71523 0.269975 -1.3663 z NaN NaN NaN NaN </code></pre> <p>Or <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a>) if need select by label:</p> <pre><code>df.ix['y'] = s df.loc['z'] = s print (df) a b c d x NaN NaN NaN NaN y NaN 0.619316 0.917374 -0.559769 z NaN 0.619316 0.917374 -0.559769 </code></pre>
3
2016-10-18T17:25:29Z
[ "python", "pandas", "numpy", "dataframe" ]
Scrapy opening html in editor , not browser
40,114,350
<p><a href="https://i.stack.imgur.com/LWxmP.png" rel="nofollow"><img src="https://i.stack.imgur.com/LWxmP.png" alt="enter image description here"></a></p> <p>I am working on some code which returns an <code>HTML</code> string (<code>my_html</code>). I want to see how this looks in a browser using <a href="https://doc.scrapy.org/en/latest/topics/debug.html#open-in-browser" rel="nofollow">https://doc.scrapy.org/en/latest/topics/debug.html#open-in-browser</a>. I just asked a question on this (<a href="http://stackoverflow.com/questions/40109782/scrapy-how-to-load-html-string-into-open-in-browser-function">Scrapy - How to load html string into open_in_browser function</a>) and the answers have shown me how to load the string into the 'open_in_browser object'</p> <pre><code>headers = { 'accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", 'upgrade-insecure-requests': "1", 'user-agent': "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36", 'referer': "http://civilinquiry.jud.ct.gov/GetDocket.aspx", 'accept-encoding': "gzip, deflate, sdch", 'accept-language': "en-US,en;q=0.8", 'cache-control': "no-cache", } new_response = TextResponse('https://doc.scrapy.org/en/latest/topics/request-response.html#response-objects', headers=headers, body='&lt;html&gt;&lt;body&gt;Oh yeah!&lt;/body&gt;&lt;/html&gt;') open_in_browser(new_response) </code></pre> <p>However now I'm seeing the text open up in notepad rather than the browser (on my windows system) making me think that the system thinks this is a text string not html (even though it has an outer html tag):</p> <p>How can I get this working?</p> <p>edit:</p> <p>I changed the code to </p> <pre><code>new_response = Response('https://doc.scrapy.org/en/latest/topics/request-response.html#response-objects', headers=headers, body='&lt;html&gt;&lt;body&gt;Oh yeah!&lt;/body&gt;&lt;/html&gt;') </code></pre> <p>Now getting:</p> <pre><code>TypeError: Unsupported response type: Response </code></pre> <p>edit2:</p> <p>I realized that in my version of scrapy (1.1) the source is:</p> <pre><code>def open_in_browser(response, _openfunc=webbrowser.open): """Open the given response in a local web browser, populating the &lt;base&gt; tag for external links to work """ from scrapy.http import HtmlResponse, TextResponse # XXX: this implementation is a bit dirty and could be improved body = response.body if isinstance(response, HtmlResponse): if b'&lt;base' not in body: repl = '&lt;head&gt;&lt;base href="%s"&gt;' % response.url body = body.replace(b'&lt;head&gt;', to_bytes(repl)) ext = '.html' elif isinstance(response, TextResponse): ext = '.txt' else: raise TypeError("Unsupported response type: %s" % response.__class__.__name__) fd, fname = tempfile.mkstemp(ext) os.write(fd, body) os.close(fd) return _openfunc("file://%s" % fname) </code></pre> <p>I changed Response to HTMLresponse and it started working. Thank you</p>
1
2016-10-18T17:18:59Z
40,114,448
<p>Look at how the <a href="https://github.com/scrapy/scrapy/blob/129421c7e31b89b9b0f9c5f7d8ae59e47df36091/scrapy/utils/response.py#L63" rel="nofollow"><code>open_in_browser()</code></a> function is defined:</p> <pre><code>if isinstance(response, HtmlResponse): if b'&lt;base' not in body: repl = '&lt;head&gt;&lt;base href="%s"&gt;' % response.url body = body.replace(b'&lt;head&gt;', to_bytes(repl)) ext = '.html' elif isinstance(response, TextResponse): ext = '.txt' else: raise TypeError("Unsupported response type: %s" % response.__class__.__name__) </code></pre> <p>It would create a <code>.txt</code> file if it is getting a <code>TextResponse</code> - that's why you see the notepad opening the file with your HTML inside. </p> <p>Instead, you need to initialize the regular <a href="https://doc.scrapy.org/en/latest/topics/request-response.html#scrapy.http.Response" rel="nofollow"><code>scrapy.Response</code></a> object and pass it to <code>open_in_browser()</code>.</p> <p>Or, you can create the temp HTML file with the desired contents manually and then using the <code>file://</code> protocol open it in a default browser through the <a href="https://docs.python.org/2/library/webbrowser.html#webbrowser.open" rel="nofollow"><code>webbrowser.open()</code></a>. </p>
1
2016-10-18T17:25:47Z
[ "python", "scrapy" ]
finding different words in two lists
40,114,385
<p>i have two list and i want to delete the matching one and keep the different. here is the code:</p> <pre><code>def check_synonym(text): tokens=regexp_tokenize(text, r'[،؟!.؛\s+]\s*', gaps=True) based_text= ' '.join(cursor.execute('SELECT request FROM Male_Conversation_Engine WHERE request REGEXP?',[tokens[0]]).fetchone()) based_tokens=regexp_tokenize(str(based_text), r'[،؟!.؛\s+]\s*', gaps=True) for w1 in based_tokens: for w2 in tokens: if w1 == w2: based_tokens.remove(w1),tokens.remove(w2) return list </code></pre> <p>if the two list are "in Arabic":</p> <pre><code> tokens = ['هذا','الجهاز','الجميل'] based_tokens = ['هذا','الجهاز','جيد'] </code></pre> <p>the Output should be:</p> <pre><code> tokens = ['الجميل'] based_tokens = ['جيد'] </code></pre> <p>the actual Output:</p> <pre><code> tokens = ['الجهاز','جميل'] based_tokens = ['الجهاز','جيد'] </code></pre> <p>the side only delete the first element 'هذا' and return the rest of the list.</p> <p>(using python3)</p>
0
2016-10-18T17:21:09Z
40,114,442
<p>You can use a combination of sets and list comprehensions</p> <pre><code>s1 = set(tokens) s2 = set(based_tokens) tokens = [t for t in tokens if t not in s2] based_tokes = [t for t in based_tokens if t not in s1] </code></pre> <p>The only reason I am using sets is because for large lists it is much faster to check membership with sets.</p>
0
2016-10-18T17:25:22Z
[ "python" ]
finding different words in two lists
40,114,385
<p>i have two list and i want to delete the matching one and keep the different. here is the code:</p> <pre><code>def check_synonym(text): tokens=regexp_tokenize(text, r'[،؟!.؛\s+]\s*', gaps=True) based_text= ' '.join(cursor.execute('SELECT request FROM Male_Conversation_Engine WHERE request REGEXP?',[tokens[0]]).fetchone()) based_tokens=regexp_tokenize(str(based_text), r'[،؟!.؛\s+]\s*', gaps=True) for w1 in based_tokens: for w2 in tokens: if w1 == w2: based_tokens.remove(w1),tokens.remove(w2) return list </code></pre> <p>if the two list are "in Arabic":</p> <pre><code> tokens = ['هذا','الجهاز','الجميل'] based_tokens = ['هذا','الجهاز','جيد'] </code></pre> <p>the Output should be:</p> <pre><code> tokens = ['الجميل'] based_tokens = ['جيد'] </code></pre> <p>the actual Output:</p> <pre><code> tokens = ['الجهاز','جميل'] based_tokens = ['الجهاز','جيد'] </code></pre> <p>the side only delete the first element 'هذا' and return the rest of the list.</p> <p>(using python3)</p>
0
2016-10-18T17:21:09Z
40,114,739
<pre><code> set1=set(tokens) set2=set(based_tokens) tokens = set1-set2 based_tokens = set2-set1 </code></pre>
0
2016-10-18T17:42:19Z
[ "python" ]
regex to match several string in Python
40,114,423
<p>I have questions with regex in Python.</p> <p>Possible variations can be </p> <p>10 hours, 12 weeks or 7 business days.</p> <p>I want to have my regex something like </p> <pre><code>string = "I have an 7 business day trip and 12 weeks vacation." re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string) </code></pre> <p>so that I expect to find "7 business day" and "12 weeks" but it returns None</p>
0
2016-10-18T17:24:18Z
40,114,493
<p>You need to tweak your regex to this:</p> <pre><code>&gt;&gt;&gt; string = "I have an 7 business day trip and 12 weeks vacation." &gt;&gt;&gt; print re.findall(r'(\d+)\s*(?:business day|hour|week)s?', string) ['7', '12'] </code></pre> <p>This matches any number that is followed by <code>business day</code> or <code>hour</code> or <code>week</code> and an optional <code>s</code> in the end.</p>
1
2016-10-18T17:28:00Z
[ "python", "regex" ]
regex to match several string in Python
40,114,423
<p>I have questions with regex in Python.</p> <p>Possible variations can be </p> <p>10 hours, 12 weeks or 7 business days.</p> <p>I want to have my regex something like </p> <pre><code>string = "I have an 7 business day trip and 12 weeks vacation." re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string) </code></pre> <p>so that I expect to find "7 business day" and "12 weeks" but it returns None</p>
0
2016-10-18T17:24:18Z
40,114,543
<pre><code>string = "I have an 7 business day trip and 12 weeks vacation." print re.findall(r'\d+\s(?:business\s)?(?:hour|week|day)s?', string) ['7 business day', '12 weeks'] \d+\s(?:business\s)?(?:hour|week|day)s? </code></pre> <p><a href="https://www.debuggex.com/r/Ytu1HFfbmsd3BpFV" rel="nofollow">Debuggex Demo</a></p> <p>The demo should explain how this works. The reason yours wasn't is because it was looking for <code>7 businessdays</code> which doesn't match.</p> <p>Although if you don't want to accept <code>business week/hour</code>, you'll need to modify it further:</p> <pre><code>\d+\s(?:hour|week|(?:business )?day)s? </code></pre> <p><a href="https://www.debuggex.com/r/DeXvPszNWq8p7qVq" rel="nofollow">Debuggex Demo</a></p>
2
2016-10-18T17:30:57Z
[ "python", "regex" ]
regex to match several string in Python
40,114,423
<p>I have questions with regex in Python.</p> <p>Possible variations can be </p> <p>10 hours, 12 weeks or 7 business days.</p> <p>I want to have my regex something like </p> <pre><code>string = "I have an 7 business day trip and 12 weeks vacation." re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string) </code></pre> <p>so that I expect to find "7 business day" and "12 weeks" but it returns None</p>
0
2016-10-18T17:24:18Z
40,114,676
<p>Similar to @anubhava's answer but matches "7 business day" rather than just "7". Just move the closing parenthesis from after \d+ to the end:</p> <pre><code>re.findall(r'(\d+\s*(?:business day|hour|week)s?)', string) </code></pre>
0
2016-10-18T17:38:41Z
[ "python", "regex" ]
regex to match several string in Python
40,114,423
<p>I have questions with regex in Python.</p> <p>Possible variations can be </p> <p>10 hours, 12 weeks or 7 business days.</p> <p>I want to have my regex something like </p> <pre><code>string = "I have an 7 business day trip and 12 weeks vacation." re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string) </code></pre> <p>so that I expect to find "7 business day" and "12 weeks" but it returns None</p>
0
2016-10-18T17:24:18Z
40,114,778
<p>I've matched " trip and " between "7 business day" and "12 weeks"</p> <pre><code>import re string = "I have an 7 business days trip and 12 weeks vacation." print(re.findall(r'(\d+\sbusiness\sdays?)\strip\sand\s(\d+\s(?:hours?|weeks?|days?))\svacation', string)) </code></pre>
-1
2016-10-18T17:44:09Z
[ "python", "regex" ]
regex to match several string in Python
40,114,423
<p>I have questions with regex in Python.</p> <p>Possible variations can be </p> <p>10 hours, 12 weeks or 7 business days.</p> <p>I want to have my regex something like </p> <pre><code>string = "I have an 7 business day trip and 12 weeks vacation." re.findall(r'\d+\s(business)?\s(hours|weeks|days)', string) </code></pre> <p>so that I expect to find "7 business day" and "12 weeks" but it returns None</p>
0
2016-10-18T17:24:18Z
40,114,814
<p>\d+\s+(business\s)?(hour|week|day)s?</p>
-2
2016-10-18T17:46:43Z
[ "python", "regex" ]
Python method calls in constructor and variable naming conventions inside a class
40,114,431
<p>I try to process some data in Python and I defined a class for a sub-type of data. You can find a very simplified version of the class definition below. </p> <pre><code>class MyDataClass(object): def __init__(self, input1, input2, input3): """ input1 and input2 are a 1D-array input3 is a 2D-array """ self._x_value = None # int self._y_value = None # int self.data_array_1 = None # 2D array self.data_array_2 = None # 1D array self.set_data(input1, input2, input3) def set_data(self, input1, input2, input3): self._x_value, self._y_value = self.get_x_and_y_value(input1, input2) self.data_array_1 = self.get_data_array_1(input1) self.data_array_2 = self.get_data_array_2(input3) @staticmethod def get_x_and_y_value(input1, input2): # do some stuff return x_value, y_value def get_data_array_1(self, input1): # do some stuff return input1[self._x_value:self._y_value + 1] def get_data_array_2(self, input3): q = self.data_array_1 - input3[self._x_value:self._y_value + 1, :] return np.linalg.norm(q, axis=1) </code></pre> <p>I'm trying to follow the '<a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">Zen of Python</a>' and thereby to write beautiful code. I'm quite sceptic, whether the class definition above is a good pratice or not. While I was thinking about alternatives I came up with the following questions, to which I would like to kindly get your opinions and suggestions.</p> <ol> <li><p>Does it make sense to define ''get'' and ''set'' methods? </p> <p><em>IMHO, as the resulting data will be used several times (in several plots and computation routines), it is more convenient to create and store them once. Hence, I calculate the data arrays once in the constructor.</em></p> <p><em>I do not deal with huge amount of data and therefore processing takes not more than a second, however I cannot estimate its potential implications on RAM if someone would use the same procedure for huge data.</em></p></li> </ol> <hr> <ol start="2"> <li><p>Should I put the function <code>get_x_and_y_value()</code> out of the class scope and convert static method to a function?</p> <p><em>As the method is only called inside the class definition, it is better to use it as a static method. If I should define it as a function, should I put all the lines relevant to this class inside a script and create a module of it?</em></p></li> </ol> <hr> <ol start="3"> <li><p>The argument naming of the function <code>get_x_and_y_value()</code> are the same as <code>__init__</code> method. Should I change it?</p> <p><em>It would ease refactoring but could confuse others who read it.</em></p></li> </ol>
0
2016-10-18T17:24:44Z
40,114,971
<p>In Python, you do not need getter and setter functions. Use properties instead. This is why you can access attributes directly in Python, unlike other languages like Java where you absolutely need to use getters and setters and to protect your attributes.</p> <p>Consider the following example of a <code>Circle</code> class. Because we can use the <code>@property</code> decorator, we don't need getter and setter functions like other languages do. This is the Pythonic answer.</p> <p>This should address all of your questions.</p> <pre><code>class Circle(object): def __init__(self, radius): self.radius = radius self.x = 0 self.y = 0 @property def diameter(self): return self.radius * 2 @diameter.setter def diameter(self, value): self.radius = value / 2 @property def xy(self): return (self.x, self.y) @xy.setter def xy(self, xy_pair): self.x, self.y = xy_pair &gt;&gt;&gt; c = Circle(radius=10) &gt;&gt;&gt; c.radius 10 &gt;&gt;&gt; c.diameter 20 &gt;&gt;&gt; c.diameter = 10 &gt;&gt;&gt; c.radius 5.0 &gt;&gt;&gt; c.xy (0, 0) &gt;&gt;&gt; c.xy = (10, 20) &gt;&gt;&gt; c.x 10 &gt;&gt;&gt; c.y 20 </code></pre>
0
2016-10-18T17:56:13Z
[ "python" ]
Numpy 4d array slicing
40,114,534
<p>Why does slicing a 4d array give me a 3d array? I expected a 4d array with extent 1 in one of the dimensions.</p> <p>Example:</p> <pre><code>print X.shape (1783, 1, 96, 96) </code></pre> <p>Slice array:</p> <pre><code>print X[11,:,:,:].shape </code></pre> <p>or</p> <pre><code>print X[11,:].shape </code></pre> <p>gives me <code>(1, 96, 96)</code>, but I expected <code>(1, 1, 96, 96)</code></p> <p>I can do it by <code>print X[11:12,:].shape</code>, but I wonder why the first method doesn't work as I expect?</p>
0
2016-10-18T17:29:49Z
40,114,756
<p>Per <a href="https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">the docs</a>:</p> <blockquote> <p>An integer, <code>i</code>, returns the same values as <code>i:i+1</code> <strong>except</strong> the dimensionality of the returned object is reduced by <code>1</code>. In particular, a selection tuple with the <code>p</code>-th element an integer (and all other entries <code>:</code>) returns the corresponding sub-array with dimension <code>N - 1</code>. If <code>N = 1</code> then the returned object is an array scalar. </p> </blockquote> <hr> <p>Thus, when your index is an integer, the value(s) at that index is(are) returned and the corresponding axis is removed. In one dimension the behavior is as you would expect:</p> <pre><code>In [6]: a = np.arange(5); a Out[6]: array([0, 1, 2, 3, 4]) In [7]: a[2] Out[7]: 2 In [8]: a[2].shape Out[8]: () </code></pre> <p><code>a</code> is 1-dimensional, <code>a[2]</code> is 0-dimensional. </p> <p>In higher dimensions, if <code>X</code> is 4-dimensional and of shape <code>(1783,1,96,96)</code>, then <code>X[11,:,:,:]</code> returns all the values where the first axis index equals 11 and then that axis is removed. So <code>X[11,:,:,:].shape</code> is <code>(1,96,96)</code>.</p> <p>When the slice specifies a range, such as <code>a[2:3]</code> then all the values within that range are returned and the axis is not removed:</p> <pre><code>In [9]: a[2:3] Out[9]: array([2]) In [10]: a[2:3].shape Out[10]: (1,) </code></pre> <p>Similarly, <code>X[11:12, :, :, :]</code> has shape <code>(1,1,96,96)</code>.</p>
1
2016-10-18T17:43:21Z
[ "python", "numpy" ]
Why is this piece of code not working?
40,114,605
<p>I am currently doing a project for school in which I am supposed to make a dice game. Here is the code:</p> <pre><code>Roll = input("Do you want to Roll or Stick?") if Roll in ("Roll" , "roll"): print("Your new numbers are," , +number10 , +number20 , +number30 , +number40 , +number50) KeepDelete = input("Would you like to keep or delete a number?") if KeepDelete in("Keep", "keep"): print("Your numbers are," , +number10 , +number20 , +number30 , +number40 , +number50) print("Your final score is," , number10+number20+number30+number40+number50) if KeepDelete in("Delete", "delete"): Delete = int(input("What number would you like to delete?")) if Delete == (number10): del(number10) Score1 = int("Your numbers are" , number100 , number20 , number30 , number40 , number50) print("Your final score is" , +number100 + number20 + number30 +number40 + number50) if Delete == (number20): del(number20) Score2 = int("Your numbers are" , number10 , number200 , number30 , number40 , number50) print("Your final score is" , +number10 + number200 + number30 + number40 + number50) if Delete == (number30): del(number30) Score3 = int("Your numbers are" , number10 , number20 , number300 , number40 , number50) print("Your final score is" , +number10 + number20 +number300 + number40 + number50) if Delete == (number40): del(number40) Score4 = int("Your numbers are" , number10 , number20 , number30 , number400 , number50) print("Your final score is" +number10 + number20 + number30 + number400 + number50) if Delete == (number50): del(number50) Score5 = int("Your numbers are" , number10 , number20 , number30 , number40 , number500) print("Your final score is" +number10 + number20 + number30 + number40 + number500) </code></pre> <p>Here is the error code:</p> <pre><code>Score1 = int("Your numbers are" , number100 , number20 , number30 , number40 , number50) TypeError: int() takes at most 2 arguments (6 given) </code></pre> <p>Sorry for such a long piece but I have been confused on this for about six hours. Any help would be appreciated.</p>
-3
2016-10-18T17:34:57Z
40,115,023
<p>Just taking a section of your code: </p> <pre><code>print("Your final score is," , number10+number20+number30+number40+number50) if KeepDelete in("Delete", "delete"): Delete = int(input("What number would you like to delete?")) if Delete == (number10): del(number10) Score1 = int("Your numbers are" , number100 , number20 , number30 , number40 , number50) print("Your final score is" , +number100 + number20 + number30 +number40 + number50) </code></pre> <p>int() casts the arguments to integer format. The error message is telling you it takes two arguments: 1) the value to be converted and 2) the base.</p> <p>So in:</p> <pre><code>Delete = int(input("What number would you like to delete?")) </code></pre> <p>You're trying to cast the argument <code>input("What..."))</code> to an integer.</p> <p>In the specific error message you're getting, you're trying to cast <code>"your numbers are"</code> and all of the subsequent variables to <code>int</code>, and pass that to the variable Score 1. Python doesn't know where to start with that.</p> <p>You can find more information at <a href="https://docs.python.org/3/library/functions.html?highlight=int#int" rel="nofollow">Python Docs</a>.</p>
0
2016-10-18T17:59:29Z
[ "python", "python-3.x" ]
list_objects_v2() sometimes returns first key value incorrectly
40,114,736
<p>I am currently writing a Python script using boto3 that opens an S3 folder (the prefix) in a bucket and prints out the contents of that folder (XML pointer filenames). The code I have for that is this:</p> <pre><code>def getXMLFileName(self, bucketName, prefix): session = boto3.Session(profile_name=self.profileName) s3client = session.client('s3') try: for item in s3client.list_objects_v2(Bucket = bucketName, Prefix = prefix, MaxKeys = 5)['Contents']: print item['Key'] </code></pre> <p>The following code does work. It will print something similar to:</p> <pre><code> PrefixName/This.Is.The.XML.Filename1.xml PrefixName/This.Is.The.XML.Filename2.xml PrefixName/This.Is.The.XML.Filename3.xml PrefixName/This.Is.The.XML.Filename4.xml PrefixName/This.Is.The.XML.Filename5.xml </code></pre> <p>However, depending on which prefix I enter, some will print what I have above, which is correct, but other times it will only print out the prefix name for the first item (i.e. PrefixName/), and then it prints out correctly the rest of the files. So in this case, it prints:</p> <pre><code> PrefixName/ PrefixName/This.Is.The.XML.Filename1.xml PrefixName/This.Is.The.XML.Filename2.xml PrefixName/This.Is.The.XML.Filename3.xml PrefixName/This.Is.The.XML.Filename4.xml </code></pre> <p>I'm not really sure why it's doing that. I've spent at least 2 days trying to figure out why it's returning a 'null' filename for certain bucket folders, but others it works. Not sure if it's relevant, but the prefixes that DO work were all uploaded to S3 on the same day, and the ones that DON'T work were all uploaded a different day. Maybe it's a bucket permissions issue? I'm really not sure...</p> <p>I have figured out a way around this issue by adding an if statement to the for loop:</p> <pre><code>if item['Size'] == 0: pass else: print item['Key'] </code></pre> <p>However, I just want to know WHY it's outputting like that. </p> <p>Thanks in advance!</p>
0
2016-10-18T17:42:08Z
40,114,805
<p>Directories aren't real in S3, however, when you create your S3 dataset many tools will create a metadata construct that roughly maps to a directory on a regular file system. </p> <p>When you query using boto you will see those metadata constructs if they were created by the tool you used to upload.</p>
1
2016-10-18T17:46:14Z
[ "python", "amazon-s3", "boto3" ]
can't find ipython notebook in the app list of anaconda launcher
40,114,836
<p>I download anaconda launcher and successfully launched the Ipython notebook, then the next time I open the anaconda launcher I couldn't find the ipython notebook in the app list </p>
0
2016-10-18T17:47:55Z
40,135,824
<p>I reinstall the program again, the problem was that I accidentally have 2 version of the same program</p>
0
2016-10-19T15:32:23Z
[ "python", "anaconda", "launcher" ]
Python - Return Average of Word Length In Sentences
40,114,839
<p>I have a question very similar to this one: <a href="http://stackoverflow.com/questions/12761510/python-how-can-i-calculate-the-average-word-length-in-a-sentence-using-the-spl">Python: How can I calculate the average word length in a sentence using the .split command?</a></p> <p>I need the average word length for multiple sentences. Here's what I currently have. I'm getting the average of all the words when I want it by sentence. Also getting a 0 at the end of the first row that's produced.</p> <pre><code>words = "This is great. Just great." words = words.split('.') words = [sentence.split() for sentence in words] words2 = [len(sentence) for sentence in words] average = sum(len(word) for word in words)/len(words) print(words2) print(average) </code></pre>
-1
2016-10-18T17:48:04Z
40,114,919
<pre><code>sentences = words.split('.') sentences = [sentence.split() for sentence in sentences if len(sentence)] averages = [sum(len(word) for word in sentence)/len(sentence) for sentence in sentences] </code></pre>
-1
2016-10-18T17:52:49Z
[ "python", "string" ]
Python - Return Average of Word Length In Sentences
40,114,839
<p>I have a question very similar to this one: <a href="http://stackoverflow.com/questions/12761510/python-how-can-i-calculate-the-average-word-length-in-a-sentence-using-the-spl">Python: How can I calculate the average word length in a sentence using the .split command?</a></p> <p>I need the average word length for multiple sentences. Here's what I currently have. I'm getting the average of all the words when I want it by sentence. Also getting a 0 at the end of the first row that's produced.</p> <pre><code>words = "This is great. Just great." words = words.split('.') words = [sentence.split() for sentence in words] words2 = [len(sentence) for sentence in words] average = sum(len(word) for word in words)/len(words) print(words2) print(average) </code></pre>
-1
2016-10-18T17:48:04Z
40,115,275
<p>Try this:</p> <pre><code>data = "This is great. Just great." sentences = data.split('.')[:-1] #you need to account for the empty string as a result of the split num_words = [len(sentence.split(' ')) for sentence in sentences] average = sum(num for num in num_words)/(len(sentences)) print(num_words) print(len(sentences)) print(average) </code></pre>
-1
2016-10-18T18:16:52Z
[ "python", "string" ]
Python - Return Average of Word Length In Sentences
40,114,839
<p>I have a question very similar to this one: <a href="http://stackoverflow.com/questions/12761510/python-how-can-i-calculate-the-average-word-length-in-a-sentence-using-the-spl">Python: How can I calculate the average word length in a sentence using the .split command?</a></p> <p>I need the average word length for multiple sentences. Here's what I currently have. I'm getting the average of all the words when I want it by sentence. Also getting a 0 at the end of the first row that's produced.</p> <pre><code>words = "This is great. Just great." words = words.split('.') words = [sentence.split() for sentence in words] words2 = [len(sentence) for sentence in words] average = sum(len(word) for word in words)/len(words) print(words2) print(average) </code></pre>
-1
2016-10-18T17:48:04Z
40,115,959
<p>lets look at this line </p> <pre><code>average = sum(len(word) for word in words)/len(words) </code></pre> <p>here the len(words) = 2 this is not the len of words . it is the len of sentence</p> <pre><code>average = sum(len(word) for word in words)/(len(words[0])+len(words[1])) </code></pre> <p>hope you get the idea </p>
0
2016-10-18T18:55:16Z
[ "python", "string" ]
Python help (computer guess number)
40,114,859
<p>Im learning how to programme in python and i found 2 tasks that should be pretty simple but second one is very hard for me and dont know how to make it work.</p> <p>Basically i need to make program where computer guesses my number. So i enter number and than computer try's to guess it and everytime he picks number i need to enter lower or higher and this is the problem i dont how to. If anyone can advise me what can i do?</p> <p>For example (number is 5): computer asks 10? i write lower computer asks 4? i write higher after he guesses</p> <p>Program: I made a program already which automatically says higher or lower but i want to input lower or higher.</p> <pre><code>from random import randit number = int(input("Number? ")) attempts = 0 guess = 0 min = 0 max = 100 while guess != number: guess = randint(min,max) print(guess,"?") if guess &lt; number: print("Higher") min = guess elif guess &gt; number: print("Lower") max = guess attemps += 1 print("I needed", attempts, "attemps") </code></pre> <p>Thanks for anykind of help </p>
0
2016-10-18T17:49:04Z
40,115,218
<p>You may want to put in a case for if it doesn't match you input, also I think you need a case for when the guess finally equals the number, you may want to allow an input for "Found it!" or something like that.</p> <pre><code>from random import randint number = int(input("Number? ")) attempts = 0 guess = 0 min = 0 max = 100 while guess != number: guess = randint(min,max) print(guess,"?") answer = str(input("Higher/Lower? ")) if answer == 'Higher': min = guess elif answer == 'Lower': max = guess attempts += 1 print("I needed", attempts, "attempts") </code></pre>
0
2016-10-18T18:13:07Z
[ "python" ]
Python help (computer guess number)
40,114,859
<p>Im learning how to programme in python and i found 2 tasks that should be pretty simple but second one is very hard for me and dont know how to make it work.</p> <p>Basically i need to make program where computer guesses my number. So i enter number and than computer try's to guess it and everytime he picks number i need to enter lower or higher and this is the problem i dont how to. If anyone can advise me what can i do?</p> <p>For example (number is 5): computer asks 10? i write lower computer asks 4? i write higher after he guesses</p> <p>Program: I made a program already which automatically says higher or lower but i want to input lower or higher.</p> <pre><code>from random import randit number = int(input("Number? ")) attempts = 0 guess = 0 min = 0 max = 100 while guess != number: guess = randint(min,max) print(guess,"?") if guess &lt; number: print("Higher") min = guess elif guess &gt; number: print("Lower") max = guess attemps += 1 print("I needed", attempts, "attemps") </code></pre> <p>Thanks for anykind of help </p>
0
2016-10-18T17:49:04Z
40,115,555
<pre><code>from random import randit attempts = 0 guess = 0 min = 0 max = 100 while guess != number: number = int(input("Number? ")) guess = randint(min,max) print(guess,"?") if guess &lt; number: print("Higher") min = guess elif guess &gt; number: print("Lower") max = guess attemps += 1 print("I needed", attempts, "attemps") </code></pre> <p>problem is your using a loop but inputting value once at start of app . just bring input inside the while statement hope this help</p>
0
2016-10-18T18:32:06Z
[ "python" ]
Validating a Django model field based on another field's value?
40,114,876
<p>I have a Django app with models accessible by both Django REST Framework and a regular form interface. The form interface has some validation checks before saving changes to the model, but not using any special Django framework, just a simple local change in the view.</p> <p>I'd like to apply the same validation to forms and REST calls, so I want to move my validation into the model. I can see how to do that for simple cases using the validators field of the Field, but in one case I have a name/type/value model where the acceptable values for 'value' change depending on which type is selected. The validator doesn't get sent any information about the model that the field is in, so it doesn't have access to other fields.</p> <p>How can I perform this validation, without having essentially the same code in a serializer for DRF and my POST view for the form?</p>
1
2016-10-18T17:50:23Z
40,115,532
<p>The validation per-field doesn't get sent any information about other fields, when it is defined like this:</p> <pre><code>def validate_myfield(self, value): ... </code></pre> <p>However, if you have a method defined like this:</p> <pre><code>def validate(self, data): ... </code></pre> <p>Then you get all the data in a dict, and you can do cross-field validation. </p>
1
2016-10-18T18:30:47Z
[ "python", "django", "forms", "validation" ]
How do I arrange multiple arguments with string formatting in python
40,114,911
<p>I have this piece of code and I'm trying to figure out how to have multiple arguments in that second set of brackets. I want the number to be right aligned in 6 places and rounded to 2 decimal points. I get the error 'invalid format specifier' every time. </p> <pre><code>print("{0:&gt;5} {1:&gt;6, 6.2f}".format(pounds, euros)) </code></pre>
2
2016-10-18T17:52:29Z
40,115,065
<p>If you read the <a href="https://docs.python.org/3/library/string.html#format-specification-mini-language" rel="nofollow">Format Specification Mini-Language</a>, you'll notice that one can only specify the format width <em>once</em> and <em>precision</em> appears after the <code>'.'</code>:</p> <pre><code>&gt;&gt;&gt; "{0:&gt;5} {1:&gt;6,.2f}".format(10, 1500.657) ' 10 1,500.66' </code></pre>
0
2016-10-18T18:02:50Z
[ "python" ]
How to use python in a JS based app
40,114,977
<p>I have created an app using meteor.js framework. I need to run some python code for some important data crunching that will be used in the app. How can I do that? I am really new to Javascript and cant figure this out. I will be running python code on server. All I need is, as soon as I click a particular button, a piece of python code gets compiled.</p>
0
2016-10-18T17:56:49Z
40,115,033
<p>You'll need to expose your Python code over some sort of API. Since your Python is "running on the server" as you mentioned.</p> <p>The fastest way I can think of doing it is to setup an AWS Lambda function (<a href="https://aws.amazon.com/lambda/" rel="nofollow">https://aws.amazon.com/lambda/</a>), then expose it as an API route using AWS API Gateway(<a href="https://aws.amazon.com/api-gateway/" rel="nofollow">https://aws.amazon.com/api-gateway/</a>).</p> <p>Once your "number crunching" is completed, you'll need to return the relevant variables back to your client app. JSON is probably a good choice for this.</p>
0
2016-10-18T18:00:02Z
[ "javascript", "python" ]
Python dataset update - TypeError: update() takes at most 2 positional arguments (3 given)
40,115,187
<p>When trying to update database with data from a dict where uuident = uuident, i'm receiving this error</p> <h3>Error:</h3> <pre><code>TypeError: update() takes at most 2 positional arguments (3 given) </code></pre> <p>The error happens only in this update. If insert there is no errors at all.</p> <p>I'm a beginner, can you please help me out?</p> <h3>details</h3> <pre><code>Traceback (most recent call last): File "/home/ubuntu/workspace/ex50/bin/teste.py", line 59, in &lt;module&gt; main() File "/home/ubuntu/workspace/ex50/bin/teste.py", line 35, in main prec.precifica("7f559bb1-b6c6-44b7-ba4e-1e4592dcd009") File "/home/ubuntu/workspace/ex50/bin/precificator.py", line 81, in precifica produto_precificado.update(product,['uuident']) File "/usr/lib/python2.7/_abcoll.py", line 534, in update "arguments ({} given)".format(len(args))) TypeError: update() takes at most 2 positional arguments (3 given) </code></pre> <h2>teste.py</h2> <pre><code>from alcateia.alcateia import * from bling.bling import * from tray.tray import * import alcateia.alcateia import tray.tray import tray.trayservice from precificator import Precificator import logging def main(): logging.basicConfig(filename='myapp.log', level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') logging.info('Programa inicializado...') prec = Precificator() prec.precifica("7f559bb1-b6c6-44b7-ba4e-1e4592dcd009") logging.info('Processo finalizado!') logging.info('--------------------') if __name__ == '__main__': main() </code></pre> <h3>precificator.py</h3> <pre><code># coding: utf-8 import sys import uuid from sgcon import Produto from db import produtosalca, alca_uuid, cem, precificado import logging logger = logging.getLogger(__name__) class Precificator(object): """ modulo precificador """ def __init__(self): pass def precifica(self,uuident): print 'uuident value is %s' % uuident print 'uuident type is %s' % type(uuident) product = {} ## cria dict product product['uuident'] = uuident produto_cem = cem.find_one(uuident=uuident) ## gets produto_cem from database cem valorcem = produto_cem['valorcem'] margem = 0.04 ## definimos margem em 10% product['margem']=margem ## atribuimos margem valorMargem = valorcem * margem ## valor + margem product['valormargem']=valorMargem despadm = 15.00 ## desp adm 15 reais product['despadm'] = despadm outrasdesp = 5.00 ## outras desp 5 reais product['outrasdesp'] = outrasdesp somatudo = valorMargem + despadm + outrasdesp comissaovenda = 0.00 ##comissao mktplace 16% product['comissaovenda'] = comissaovenda comissaorecebiveis = 0.05 ##comissao / desp financeiras 0% product['comissaorecebiveis']=comissaorecebiveis cemcommargem = valorcem*(1+(margem)) ## cem com margem = cem*(1+margem) aliqICMS = produto_cem['aliqICMS'] product['aliqICMS'] = aliqICMS aliqPIS = produto_cem['aliqPIS'] aliqCofins = produto_cem['aliqCofins'] aliqTotalImposto = aliqICMS + aliqCofins + aliqPIS ## aliquota total (em %) dos impostos base = cemcommargem + despadm + outrasdesp ## Soma as despesas em reais ao valorcem e obtem a base para o calculo outrasAliq = comissaovenda + comissaorecebiveis ## outras aliquotas não tributárias indice = 1-(aliqTotalImposto + outrasAliq) ## índice para cálculo precovenda = base / indice ## aplica o índice product['precovenda']=precovenda ## atribui ao dict product ## ALL MATH DONE AND DICT PRODUCT IS READY TO GO TO DATABASE TABLE PRECIFICA produto_precificado = precificado.find_one(uuident=uuident) ## CHECKS IF ROW WITH THIS UUIDENT EXISTS IN TABLE PRECIFICA """ CHECKS AND ACT """ if produto_precificado: ## IF PRODUCT EXISTS IN DATABASE TABLE ## UPDATE print 'produto exists in db' print product print type(product) """ THIS DO NOT WORK """ produto_precificado.update(product,['uuident']) ## THIS DO NOT WORK!!!! ##produto_precificado.update(dict(precovenda=precovenda),['id']) else: ## IF product do not exists ## INSERT print 'produto nao existe no bd' """ THIS WORKS!!!! """ precificado.insert(product) ### THIS WORKS! </code></pre> <h2>UPDATE</h2> <p><code>produto_precificado</code> type is <code>&lt;class 'collections.OrderedDict'&gt;</code></p>
-1
2016-10-18T18:11:00Z
40,117,523
<p>The builtin dict update method accepts other keywords=values and updates the dict with that, or another dictionary and updates the dict with <strong>all</strong> keys from the second dict.</p> <p>What your probably want to do is:</p> <pre><code>produto_precificado[product['uuident']] = product </code></pre> <p>to make a hash of products according to uuident (or whatever key).</p>
0
2016-10-18T20:30:30Z
[ "python", "python-2.7", "dataset", "parameter-passing" ]
Python dataset update - TypeError: update() takes at most 2 positional arguments (3 given)
40,115,187
<p>When trying to update database with data from a dict where uuident = uuident, i'm receiving this error</p> <h3>Error:</h3> <pre><code>TypeError: update() takes at most 2 positional arguments (3 given) </code></pre> <p>The error happens only in this update. If insert there is no errors at all.</p> <p>I'm a beginner, can you please help me out?</p> <h3>details</h3> <pre><code>Traceback (most recent call last): File "/home/ubuntu/workspace/ex50/bin/teste.py", line 59, in &lt;module&gt; main() File "/home/ubuntu/workspace/ex50/bin/teste.py", line 35, in main prec.precifica("7f559bb1-b6c6-44b7-ba4e-1e4592dcd009") File "/home/ubuntu/workspace/ex50/bin/precificator.py", line 81, in precifica produto_precificado.update(product,['uuident']) File "/usr/lib/python2.7/_abcoll.py", line 534, in update "arguments ({} given)".format(len(args))) TypeError: update() takes at most 2 positional arguments (3 given) </code></pre> <h2>teste.py</h2> <pre><code>from alcateia.alcateia import * from bling.bling import * from tray.tray import * import alcateia.alcateia import tray.tray import tray.trayservice from precificator import Precificator import logging def main(): logging.basicConfig(filename='myapp.log', level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p') logging.info('Programa inicializado...') prec = Precificator() prec.precifica("7f559bb1-b6c6-44b7-ba4e-1e4592dcd009") logging.info('Processo finalizado!') logging.info('--------------------') if __name__ == '__main__': main() </code></pre> <h3>precificator.py</h3> <pre><code># coding: utf-8 import sys import uuid from sgcon import Produto from db import produtosalca, alca_uuid, cem, precificado import logging logger = logging.getLogger(__name__) class Precificator(object): """ modulo precificador """ def __init__(self): pass def precifica(self,uuident): print 'uuident value is %s' % uuident print 'uuident type is %s' % type(uuident) product = {} ## cria dict product product['uuident'] = uuident produto_cem = cem.find_one(uuident=uuident) ## gets produto_cem from database cem valorcem = produto_cem['valorcem'] margem = 0.04 ## definimos margem em 10% product['margem']=margem ## atribuimos margem valorMargem = valorcem * margem ## valor + margem product['valormargem']=valorMargem despadm = 15.00 ## desp adm 15 reais product['despadm'] = despadm outrasdesp = 5.00 ## outras desp 5 reais product['outrasdesp'] = outrasdesp somatudo = valorMargem + despadm + outrasdesp comissaovenda = 0.00 ##comissao mktplace 16% product['comissaovenda'] = comissaovenda comissaorecebiveis = 0.05 ##comissao / desp financeiras 0% product['comissaorecebiveis']=comissaorecebiveis cemcommargem = valorcem*(1+(margem)) ## cem com margem = cem*(1+margem) aliqICMS = produto_cem['aliqICMS'] product['aliqICMS'] = aliqICMS aliqPIS = produto_cem['aliqPIS'] aliqCofins = produto_cem['aliqCofins'] aliqTotalImposto = aliqICMS + aliqCofins + aliqPIS ## aliquota total (em %) dos impostos base = cemcommargem + despadm + outrasdesp ## Soma as despesas em reais ao valorcem e obtem a base para o calculo outrasAliq = comissaovenda + comissaorecebiveis ## outras aliquotas não tributárias indice = 1-(aliqTotalImposto + outrasAliq) ## índice para cálculo precovenda = base / indice ## aplica o índice product['precovenda']=precovenda ## atribui ao dict product ## ALL MATH DONE AND DICT PRODUCT IS READY TO GO TO DATABASE TABLE PRECIFICA produto_precificado = precificado.find_one(uuident=uuident) ## CHECKS IF ROW WITH THIS UUIDENT EXISTS IN TABLE PRECIFICA """ CHECKS AND ACT """ if produto_precificado: ## IF PRODUCT EXISTS IN DATABASE TABLE ## UPDATE print 'produto exists in db' print product print type(product) """ THIS DO NOT WORK """ produto_precificado.update(product,['uuident']) ## THIS DO NOT WORK!!!! ##produto_precificado.update(dict(precovenda=precovenda),['id']) else: ## IF product do not exists ## INSERT print 'produto nao existe no bd' """ THIS WORKS!!!! """ precificado.insert(product) ### THIS WORKS! </code></pre> <h2>UPDATE</h2> <p><code>produto_precificado</code> type is <code>&lt;class 'collections.OrderedDict'&gt;</code></p>
-1
2016-10-18T18:11:00Z
40,117,803
<p>I'm sorry for my terrible mistake here.</p> <p>Well, just in case somebody goes through the same:</p> <p>produto_precificado is a row from table precificado.</p> <p>So that was the error.</p> <p>I changed:</p> <pre><code>produto_precificado.update(product,['uuident']) </code></pre> <p>for</p> <pre><code>precificado.update(product,['uuident']) </code></pre> <p>Working like a charm. </p>
0
2016-10-18T20:47:55Z
[ "python", "python-2.7", "dataset", "parameter-passing" ]
Generate a lot of random strings
40,115,278
<p>I have a method that will generate 50,000 <em>random</em> strings, save them all to a file, and then run through the file, and delete all duplicates of the strings that occur. Out of those 50,000 random strings, after using <code>set()</code> to generate unique ones, on average 63 of them are left. </p> <p>Function to generate the strings:</p> <pre><code>def random_strings(size=8, chars=string.ascii_uppercase + string.digits + string.ascii_lowercase): return ''.join(random.choice(chars) for _ in xrange(size)) </code></pre> <p>Delete duplicates:</p> <pre><code> with open("dicts/temp_dict.txt", "a+") as data: created = 0 while created != 50000: string = random_strings() data.write(string + "\n") created += 1 sys.stdout.write("\rCreating password: {} out of 50000".format(created)) sys.stdout.flush() print "\nRemoving duplicates.." with open("dicts\\rainbow-dict.txt", "a+") as rewrite: rewrite.writelines(set(data)) </code></pre> <p>Example of before and after: <a href="https://gist.github.com/Ekultek/a760912b40cb32de5f5b3d2fc580b99f" rel="nofollow">https://gist.github.com/Ekultek/a760912b40cb32de5f5b3d2fc580b99f</a></p> <p>How can I generate completely random unique strings without duplicates?</p>
2
2016-10-18T18:17:01Z
40,115,439
<p>You can use <em>set</em> from the start</p> <pre><code>created = set() while len(created) &lt; 50000: created.add(random_strings()) </code></pre> <p>And save once outside the loop</p>
3
2016-10-18T18:25:41Z
[ "python", "string", "python-2.7", "random" ]
Generate a lot of random strings
40,115,278
<p>I have a method that will generate 50,000 <em>random</em> strings, save them all to a file, and then run through the file, and delete all duplicates of the strings that occur. Out of those 50,000 random strings, after using <code>set()</code> to generate unique ones, on average 63 of them are left. </p> <p>Function to generate the strings:</p> <pre><code>def random_strings(size=8, chars=string.ascii_uppercase + string.digits + string.ascii_lowercase): return ''.join(random.choice(chars) for _ in xrange(size)) </code></pre> <p>Delete duplicates:</p> <pre><code> with open("dicts/temp_dict.txt", "a+") as data: created = 0 while created != 50000: string = random_strings() data.write(string + "\n") created += 1 sys.stdout.write("\rCreating password: {} out of 50000".format(created)) sys.stdout.flush() print "\nRemoving duplicates.." with open("dicts\\rainbow-dict.txt", "a+") as rewrite: rewrite.writelines(set(data)) </code></pre> <p>Example of before and after: <a href="https://gist.github.com/Ekultek/a760912b40cb32de5f5b3d2fc580b99f" rel="nofollow">https://gist.github.com/Ekultek/a760912b40cb32de5f5b3d2fc580b99f</a></p> <p>How can I generate completely random unique strings without duplicates?</p>
2
2016-10-18T18:17:01Z
40,116,320
<p>You could guarantee unique strings by generating unique numbers, starting with a random number is a range that is 1/50000<sup>th</sup> of the total number of possibilities (62<sup>8</sup>). Then generate more random numbers, each time determining the window in which the next number can be selected. This is not <em>perfectly</em> random, but I believe it's practically close enough.</p> <p>Then these numbers can each be converted to strings by considering a representation of a 62-base number. Here is the code, and a test at the end to check that indeed all 50000 strings are unique:</p> <pre><code>import string import random def random_strings(count, size=8, chars=string.ascii_uppercase + string.digits + string.ascii_lowercase): max = len(chars) ** size - 1 start = 0 choices = [] for i in range(0,count): start = random.randint(start, start + (max-start) // (count-i)) digits = [] temp = start while len(digits) &lt; size: temp, i = divmod(temp, len(chars)) digits.append(chars[i]) choices.append(''.join(digits)) start += 1 return choices choices = random_strings(50000) # optional shuffle, since they are produced in order of `chars` random.shuffle(choices) # Test: output how many distinct values there are: print (len(set(choices))) </code></pre> <p>See it run on <a href="https://repl.it/Dz1g/2" rel="nofollow">repl.it</a></p> <p>This produces your strings in linear time. With the above parameters you'll have the answer within a second on the average PC.</p>
0
2016-10-18T19:18:44Z
[ "python", "string", "python-2.7", "random" ]
Calculate set difference using jinja2 (in ansible)
40,115,323
<p>I have two lists of strings in my ansible playbook, and I'm trying to find the elements in list A that aren't in list B - a set difference. However, I don't seem to be able to access the python <code>set</code> data structure. Here's what I was trying to do:</p> <pre><code>- set_fact: difference: "{{ (set(listA) - set(listB)).pop() }}" </code></pre> <p>But I get an error saying <code>'set' is undefined</code>. Makes sense to me since it's not a variable but I don't know what else to do. How can I calculate the set difference of these two lists? Is it impossible with the stock jinja functionality in ansible?</p>
2
2016-10-18T18:19:00Z
40,116,111
<p>Turns out there is a <a href="http://docs.ansible.com/ansible/playbooks_filters.html#set-theory-filters" rel="nofollow">built-in filter for this in ansible</a> (not in generic jinja) called <code>difference</code>.</p> <p>This accomplishes what I was trying to do in my question:</p> <pre><code>"{{ (listA | difference(listB)) | first }}" </code></pre>
0
2016-10-18T19:04:55Z
[ "python", "ansible", "jinja2" ]
Contains function in Pandas
40,115,346
<p>I am performing matching (kind of fuzzy matching) between the company names of two data frames. For doing so, first I am performing full merge between all the company names, where the starting alphabet matches. Which means all the companies starting with 'A' would be matched to all the companies starting with 'A' in other data frame. This is done as follows: </p> <pre><code>df1['df1_Start'] = df1['company1'].astype(str).str.slice(0,2) df2['df2_Start'] = df2['company2'].astype(str).str.slice(0,2) Merge = pd.merge(df1,df2, left_on='df1_Start',right_on='df2_Start') </code></pre> <p>Now I want to have all the rows from FullMerge where company in df1 contains the company in df2. This is because companies in df1 have elongated names. </p> <pre><code>Merge1=Merge[Merge['company1'].str.contains(Merge['company2'].str)] </code></pre> <p>This isn't working for me. How do I perform this task? Also, Please suggest what other ways can I use to match the company names. Because companies might be same in two data frames but are not written in the exactly same way. </p>
1
2016-10-18T18:20:32Z
40,115,373
<p>I think you need <code>|</code> with <code>join</code> for generating all values separated by <code>|</code> (or in <a href="http://stackoverflow.com/questions/8609597/python-regular-expressions-or">regex</a>) for <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.contains.html" rel="nofollow"><code>str.contains</code></a>:</p> <pre><code>Merge1=Merge[FullMerge['company1'].str.contains("|".join(Merge['company2'].tolist())] </code></pre>
0
2016-10-18T18:22:02Z
[ "python", "pandas", "fuzzywuzzy" ]
imgurpython.helpers.error.ImgurClientRateLimitError: Rate-limit exceeded
40,115,380
<p>I have the following error:</p> <pre><code>/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning Traceback (most recent call last): File "download.py", line 22, in &lt;module&gt; search = imgur_client.gallery_search('cat', window='all', sort='time', page=p) File "/usr/local/lib/python2.7/dist-packages/imgurpython/client.py", line 531, in gallery_search response = self.make_request('GET', 'gallery/search/%s/%s/%s' % (sort, window, page), data) File "/usr/local/lib/python2.7/dist-packages/imgurpython/client.py", line 153, in make_request raise ImgurClientRateLimitError() imgurpython.helpers.error.ImgurClientRateLimitError: Rate-limit exceeded! </code></pre> <p>for this code:</p> <pre><code> 1 from imgurpython import ImgurClient 2 import inspect 3 import random 4 import urllib2 5 import requests 6 from imgurpython.helpers.error import ImgurClientError 7 8 client_id = "ABC" 9 client_secret = "ABC" 10 access_token = "ABC" 11 refresh_token = "ABC" 12 13 14 15 image_type = ['jpg', 'jpeg'] 16 17 imgur_client = ImgurClient(client_id, client_secret, access_token, refresh_token) 18 19 item_count = 0 20 for p in range(1, 10000): 21 try: 22 search = imgur_client.gallery_search('cat', window='all', sort='time', page=p) 23 for i in range(0,https://gist.github.com/monajalal/e02792e9a5cbced301a8691b7a62836f len(search)): 24 item_count +=1 25 print(search[i].comment_count) 26 if search[i].comment_count &gt; 10 and not search[i].is_album: 27 print(search[i].type) 28 if search[i].type[6:] in image_type: 29 count = 0 30 try: 31 image_file = urllib2.urlopen(search[i].link, timeout = 5) 32 image_file_name = 'images/'+ search[i].id+'.'+search[i].type[6:] 33 output_image = open(image_file_name, 'wb') 34 output_image.write(image_file.read()) 35 for post in imgur_client.gallery_item_comments(search[i].id, sort='best'): 36 if count &lt;= 10: 37 count += 1 38 output_image.close() 39 except urllib2.URLError as e: 40 print(e) 41 continue 42 except socket.timeout as e: 43 print(e) 44 continue 45 except socket.error as e: 46 print(e) 47 continue 48 except ImgurClientError as e: 49 print(e) 50 continue 51 52 print item_count </code></pre> <p>Also I see this line almost very often:</p> <pre><code>/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning </code></pre> <p>How can I fix the error? Is there any workaround for rate limit error in Imgur? So I am creating this app for academic research use not for commercial and according to <a href="https://api.imgur.com/#limits" rel="nofollow">https://api.imgur.com/#limits</a> it should be free but I had to register my app to get client_id related stuff. How can I set my application as non-commercial so that I would not get this rate limit error or if all kind of applications get this error how should I handle it? How should I set my code so that it would make only 1250 requests per hour?</p> <p>Also here's my credit info:</p> <pre><code>User Limit: 500 User Remaining: 500 User Reset: 2016-10-18 14:32:41 User Client Limit: 12500 User Client Remaining: 9570 </code></pre> <p>UPDATE: With sleep(8) as suggested in the answer I end up with this going on continuously. For different search query this happens at different pages. How can I fix the code so that it would stop executing when this happens? Here's the related code to the update: <a href="https://gist.github.com/monajalal/e02792e9a5cbced301a8691b7a62836f" rel="nofollow">https://gist.github.com/monajalal/e02792e9a5cbced301a8691b7a62836f</a></p> <pre><code>page number is: 157 0 image/jpeg page number is: 157 0 page number is: 157 0 page number is: 157 /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning. InsecurePlatformWarning </code></pre>
0
2016-10-18T18:22:19Z
40,115,661
<p>The rate limit refers to how frequently you're hitting the API, not how many calls you're allowed. To prevent hammering, most APIs have a rate limit (eg: 30 requests per minute, 1 every 2 seconds). Your script is making requests as quickly possible, hundreds or even thousands of times faster than the limit.</p> <p>To prevent your script from hammering, the simplest solution is to introduce a <a href="https://docs.python.org/2/library/time.html#time.sleep" rel="nofollow"><code>sleep</code></a> to your for loop.</p> <pre><code>from time import sleep for i in range(10000): print i sleep(2) # seconds </code></pre> <p>Adjust the sleep time to be at least one second greater than what the API defines as its rate limit.</p> <p><a href="https://api.imgur.com/#limits" rel="nofollow">https://api.imgur.com/#limits</a></p> <blockquote> <p>The Imgur API uses a credit allocation system to ensure fair distribution of capacity. Each application can allow <strong>approximately 1,250 uploads per day or approximately 12,500 requests per day</strong>. If the daily limit is hit five times in a month, then the app will be blocked for the rest of the month. The remaining credit limit will be shown with each requests response in the <code>X-RateLimit-ClientRemaining</code> HTTP header.</p> </blockquote> <p>So 12500 requests / 24 hours is 520 requests per hour or ~8 per minute. That means your sleep should be about 8 seconds long.</p>
1
2016-10-18T18:38:42Z
[ "python", "api", "http", "imgur", "rate-limiting" ]
How can I store a file path in Mysql database using django?
40,115,404
<p>I need to store a file path in db using django via ajax form submission . </p> <p>Here is my view:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>def dashboard(request): container=[] DIR = os.path.realpath("/home/user/Desktop/Demo") WAY = os.listdir(DIR) for file in WAY: if file.endswith('.mp4'): file_name = file FDIR=os.path.join(DIR, file) container.append(FDIR) return render(request, 'dashboard.html', {'container': container})</code></pre> </div> </div> </p> <pre><code>def new_scheduler(request): if request.method =='POST': f_name = request.POST.get('file') dateAndTime = request.POST.get('dateAndTime') Scheduled_data = schedulesdb.objects.create( f_name = file, dateAndTime = dateAndTime, ) Scheduled_data.save() return HttpResponse ('done') </code></pre> <p>It save in database like <code>&lt;type 'file'&gt;</code> .</p> <p>Here is my model.py:</p> <pre><code>class schedulesdb(models.Model): f_name = models.CharField(max_length=100) dateAndTime = models.DateTimeField(['%Y-%m-%d %H:%M:%S'],null=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, default=2) def __unicode__(self): # on Python 2 return self.f_name </code></pre> <p>Thanks in advance :)</p>
1
2016-10-18T18:23:41Z
40,115,726
<p>From your code it's not 100% clear whether you're intending to handle file uploads from the client, or simply store strings that happen to be a file path (potentially for locating a file on some remote filesystem).</p> <p><strong>1. File uploads</strong></p> <p>Consider using the <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.FileField" rel="nofollow">FileField</a> model field type rather than the CharField.</p> <p>The Django documentation has a solid explanation and examples of how to do simple <a href="https://docs.djangoproject.com/en/1.10/topics/http/file-uploads/" rel="nofollow">file uploads</a>.</p> <p><strong>2. Obtaining the actual POST data value for the f_name field</strong></p> <p>Your code sample is storing "", because you're assigning 'file' (which is a builtin type) rather than the <code>f_name</code> variable that you previously declared. Like this:</p> <pre><code>def new_scheduler(request): if request.method =='POST': f_name = request.POST.get('file') dateAndTime = request.POST.get('dateAndTime') Scheduled_data = schedulesdb.objects.create( f_name = f_name, # Note the use of f_name instead of file dateAndTime = dateAndTime, ) Scheduled_data.save() return HttpResponse ('done') </code></pre>
0
2016-10-18T18:41:51Z
[ "python", "mysql", "ajax", "django" ]
Error in getting the running median
40,115,452
<p>I am trying to get a running median for a number of integers. For example: 6 elements will come one by one, let say 12,4,5,3,8,7 for which running median at each input is 12,8,5,4.5,6,5 respectively. I wrote a python code but it seems to give incorrect answer. Help is appreciated .</p> <pre><code>n = int(raw_input().strip()) s=[] for i in xrange(n): a=int(raw_input()) if len(s)==0: s.append(a) print "%.1f" % a else: for j in xrange(len(s)): if a&lt;s[j]: s.insert(j,a) if a&gt;=s[-1]: s.append(a) if len(s)%2==0: print "%.1f" % float((s[len(s)/2] + s[len(s)/2 -1])/2.0) else: print "%.1f" % s[len(s)/2] </code></pre>
0
2016-10-18T18:26:50Z
40,115,700
<pre><code>n = int(raw_input().strip()) s=[] for i in xrange(n): a=int(raw_input()) if len(s)==0: s.append(a) print "%.1f" % a else: for j in xrange(len(s)): if a&lt;s[j]: s.insert(j,a) break # inserted this break if a&gt;=s[-1]: s.append(a) if len(s)%2==0: print "%.1f" % float((s[len(s)/2] + s[len(s)/2 -1])/2.0) else: print "%.1f" % s[len(s)/2] </code></pre> <p>This was the output and input:</p> <pre><code> 6 12 12.0 4 8.0 5 5.0 3 4.5 8 5.0 7 6.0 </code></pre> <p>The issue was in your <code>for j in xrange(len(s))</code> you were inserting as long as a was less then the next value. You didn't just insert once, that added more values than you wanted into the list. Adding a <code>break</code> will only insert once, at the time it finds the first spot it belongs too. </p>
1
2016-10-18T18:40:46Z
[ "python", "python-2.7" ]
Error in getting the running median
40,115,452
<p>I am trying to get a running median for a number of integers. For example: 6 elements will come one by one, let say 12,4,5,3,8,7 for which running median at each input is 12,8,5,4.5,6,5 respectively. I wrote a python code but it seems to give incorrect answer. Help is appreciated .</p> <pre><code>n = int(raw_input().strip()) s=[] for i in xrange(n): a=int(raw_input()) if len(s)==0: s.append(a) print "%.1f" % a else: for j in xrange(len(s)): if a&lt;s[j]: s.insert(j,a) if a&gt;=s[-1]: s.append(a) if len(s)%2==0: print "%.1f" % float((s[len(s)/2] + s[len(s)/2 -1])/2.0) else: print "%.1f" % s[len(s)/2] </code></pre>
0
2016-10-18T18:26:50Z
40,115,786
<p>Read the comments embedded in the code below - </p> <pre><code>n = int(raw_input().strip()) s=[] for i in xrange(n): a=int(raw_input()) if len(s)==0: s.append(a) print "%.1f" % a else: for j in xrange(len(s)): if a&lt;s[j]: s.insert(j,a) break # break after insertion to avoid multiple insertions else: # Read https://docs.python.org/3/reference/compound_stmts.html#for s.append(a) if len(s)%2==0: print "%.1f" % float((s[len(s)/2] + s[len(s)/2 -1])/2.0) else: print "%.1f" % s[len(s)/2] </code></pre> <hr> <p>A more <em>Pythonic</em> (sic) way of doing the same - </p> <pre><code>import bisect n = int(raw_input().strip()) s=[] for i in xrange(n): a=int(raw_input()) bisect.insort_left(s, a) quotient, remainder = divmod(len(s), 2) if remainder: print "%.1f" % s[quotient] else: print "%.1f" % ((s[quotient - 1] + s[quotient])/2.0) </code></pre>
1
2016-10-18T18:44:24Z
[ "python", "python-2.7" ]
Concisely adding variables to Django context dictionary
40,115,565
<p>The Django documentation suggests adding variables to the context dictionary in class based views as follows:</p> <pre><code>def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(PublisherDetail, self).get_context_data(**kwargs) # Add in a QuerySet of all the books context['book_list'] = Book.objects.all() return context </code></pre> <p>I often have a lot of variables in my gather context function, so my code ends up looking like this:</p> <pre><code>def get_context_data(self, **kwargs): context = super(PublisherDetail, self).get_context_data(**kwargs) a = 2 b = 'hello' c = 75 # temp variable, not wanted in context dict d = a * c context['a'] = a context['b'] = b context['d'] = d return context </code></pre> <p>To avoid adding each variable to the context dictionary on its own line, I've begun doing the following:</p> <pre><code>def get_context_data(self, **kwargs): context = super(PublisherDetail, self).get_context_data(**kwargs) a = 2 b = 'hello' c = 75 # temp variable, not wanted in context dict d = a * c del c # delete any variables you don't want to add context.update({k:v for k,v in locals().copy().iteritems() if k[:2] != '__' and k != 'context'}) return context </code></pre> <p>It seems to be working, but I'm not very familiar with locals(). Is there any reason why I shouldn't be doing it this way?</p>
0
2016-10-18T18:32:36Z
40,115,625
<p>Use <code>locals</code> is such a bad idea. Just add to the context directly</p> <pre><code>def get_context_data(self, **kwargs): context = super(PublisherDetail, self).get_context_data(**kwargs) c = 75 # temp variable, not wanted in context dict context['a'] = 2 context['b'] = 'hello' context['d'] = context['a'] * c return context </code></pre>
0
2016-10-18T18:36:22Z
[ "python", "django", "dictionary" ]
Gathering the default landing page URL for a large ip hostlist on a single port
40,115,588
<h2>So here is the requirement breakdown:</h2> <ul> <li>Parse NMAP output to define a hostlist that is serving web services.</li> <li>Use a hostlist to define the default landing page URL for each listening protocol.</li> <li>Compile a master web services list to include IP:URL.</li> </ul> <h2>What I have done so far:</h2> <ul> <li>Generated a hostlist that includes all hosts listening for HTTP/S traffic. Each hostlist is separated by port/ssl usage.</li> </ul> <h2>What I am having trouble with:</h2> <ul> <li><p>It seems logical to be able to do the following: Use a list with the IP of every host listening for http over port 80 to run a query as if we are typing <em><a href="http://test.ip" rel="nofollow">http://test.ip</a></em> into a browser and capturing the default URL it lands on. <em><a href="http://test.url/index.html" rel="nofollow">http://test.url/index.html</a></em></p></li> <li><p>I have tried to use cURL and Wget and worked a bit with Scrapy but I am not able to capture just the default landing page URL in a scripted fashion. All I need is a means to take a single IP and resolve only the default landing page URL for a single port. I can then integrate this function into a broadened script to run against each port/prot. </p></li> </ul>
0
2016-10-18T18:33:43Z
40,121,997
<p>Why bother with all the extra parsing and tools if you're already scanning with Nmap? The <a href="https://nmap.org/book/nse.html" rel="nofollow">Nmap Scripting Engine</a> can do what you want easily for each HTTP port discovered. You can even use an existing script: <a href="https://nmap.org/nsedoc/scripts/http-title.html" rel="nofollow">http-title</a> will request the URL <code>/</code> and follow up to 5 redirects in order to retrieve the HTML title of the landing page. If a redirect is followed, it includes "Requested resource was <em>/path</em>" to show what the actual landing page URL was.</p>
0
2016-10-19T04:13:30Z
[ "python", "linux", "bash", "nmap", "penetration-testing" ]
Multiple Pandas DataFrame Bar charts on the same chart
40,115,598
<p>How to plot Multiple DataFrame Bar charts on the same chart? </p> <p>I want to plot top three scores (or top five). Since I know 1st >= 2nd >= 3rd, I want to plot the top three (or five) in the chart on the same bar, instead of spreading them out in three (or five) bars.</p> <p>The visual effect will be exactly like the stacked bar, but the bars are not stacking on top of each other, but measured from the bottom instead. </p> <p><a href="https://i.stack.imgur.com/dxjGj.png" rel="nofollow"><img src="https://i.stack.imgur.com/dxjGj.png" alt="stacked bar"></a></p> <p><strong>UPDATE:</strong> @DizietAsahi suggested to use stacked bar instead. I guess that's the simplest solution. Can someone provide dataframe manipulation code to get the difference of the scores below please? </p> <p>The source data is in the form of <code>TID</code>, and <code>Score</code>, just like the following data in CSV format, which has been already filtered out so as only top 3 are remaining. The raw data have much more scores for the same TID. The challenge of going this way is that, I also need to plot the MEAN score as well as the top three. I.e., I personally think it is impossible to manipulation the MEAN score as well as the top three at the same time to get the differences from below. So either ways have challenges (to me). </p> <p>Here is a sample data in CSV format:</p> <pre><code>TID,Score 06,510 06,472 06,441 07,630 07,619 07,574 08,617 08,589 08,560 09,610 09,595 09,553 10,593 10,550 10,542 11,442 11,404 11,381 </code></pre> <p>In DataFrame format (only for Multiple DataFrame Bar charts case. For using stacked bar, generating a bunch of random numbers as <code>Score</code> for each <code>TID</code> would be fine):</p> <pre><code>Scores = [ {"TID":07,"ScoreRank":1,"Score":834,"Average":690}, {"TID":07,"ScoreRank":2,"Score":820,"Average":690}, {"TID":07,"ScoreRank":3,"Score":788,"Average":690}, {"TID":08,"ScoreRank":1,"Score":617,"Average":571}, {"TID":08,"ScoreRank":2,"Score":610,"Average":571}, {"TID":08,"ScoreRank":3,"Score":600,"Average":571}, {"TID":09,"ScoreRank":1,"Score":650,"Average":584}, {"TID":09,"ScoreRank":2,"Score":644,"Average":584}, {"TID":09,"ScoreRank":3,"Score":618,"Average":584}, {"TID":10,"ScoreRank":1,"Score":632,"Average":547}, {"TID":10,"ScoreRank":2,"Score":593,"Average":547}, {"TID":10,"ScoreRank":3,"Score":577,"Average":547}, {"TID":11,"ScoreRank":1,"Score":479,"Average":409}, {"TID":11,"ScoreRank":2,"Score":445,"Average":409}, {"TID":11,"ScoreRank":3,"Score":442,"Average":409}, {"TID":12,"ScoreRank":1,"Score":370,"Average":299}, {"TID":12,"ScoreRank":2,"Score":349,"Average":299}, {"TID":12,"ScoreRank":3,"Score":341,"Average":299}, {"TID":13,"ScoreRank":1,"Score":342,"Average":252}, {"TID":13,"ScoreRank":2,"Score":318,"Average":252}, {"TID":13,"ScoreRank":3,"Score":286,"Average":252}, {"TID":14,"ScoreRank":1,"Score":303,"Average":257}, {"TID":14,"ScoreRank":2,"Score":292,"Average":257}, {"TID":14,"ScoreRank":3,"Score":288,"Average":257}, {"TID":15,"ScoreRank":1,"Score":312,"Average":242}, {"TID":15,"ScoreRank":2,"Score":276,"Average":242}, {"TID":15,"ScoreRank":3,"Score":264,"Average":242}, {"TID":16,"ScoreRank":1,"Score":421,"Average":369}, {"TID":16,"ScoreRank":2,"Score":403,"Average":369}, {"TID":16,"ScoreRank":3,"Score":398,"Average":369}, {"TID":17,"ScoreRank":1,"Score":479,"Average":418}, {"TID":17,"ScoreRank":2,"Score":466,"Average":418}, {"TID":17,"ScoreRank":3,"Score":455,"Average":418}, {"TID":18,"ScoreRank":1,"Score":554,"Average":463}, {"TID":18,"ScoreRank":2,"Score":521,"Average":463}, {"TID":18,"ScoreRank":3,"Score":520,"Average":463}] df = pandas.DataFrame(Scores) </code></pre> <p>Thanks</p>
0
2016-10-18T18:34:25Z
40,137,120
<p>Is this what you are looking for? </p> <pre><code>import pandas import matplotlib.pyplot as plt import numpy as np Scores = [ {"TID":7,"ScoreRank":1,"Score":834,"Average":690}, {"TID":7,"ScoreRank":2,"Score":820,"Average":690}, {"TID":7,"ScoreRank":3,"Score":788,"Average":690}, {"TID":8,"ScoreRank":1,"Score":617,"Average":571}, {"TID":8,"ScoreRank":2,"Score":610,"Average":571}, {"TID":8,"ScoreRank":3,"Score":600,"Average":571}, {"TID":9,"ScoreRank":1,"Score":650,"Average":584}, {"TID":9,"ScoreRank":2,"Score":644,"Average":584}, {"TID":9,"ScoreRank":3,"Score":618,"Average":584}, {"TID":10,"ScoreRank":1,"Score":632,"Average":547}, {"TID":10,"ScoreRank":2,"Score":593,"Average":547}, {"TID":10,"ScoreRank":3,"Score":577,"Average":547}, {"TID":11,"ScoreRank":1,"Score":479,"Average":409}, {"TID":11,"ScoreRank":2,"Score":445,"Average":409}, {"TID":11,"ScoreRank":3,"Score":442,"Average":409}, {"TID":12,"ScoreRank":1,"Score":370,"Average":299}, {"TID":12,"ScoreRank":2,"Score":349,"Average":299}, {"TID":12,"ScoreRank":3,"Score":341,"Average":299}, {"TID":13,"ScoreRank":1,"Score":342,"Average":252}, {"TID":13,"ScoreRank":2,"Score":318,"Average":252}, {"TID":13,"ScoreRank":3,"Score":286,"Average":252}, {"TID":14,"ScoreRank":1,"Score":303,"Average":257}, {"TID":14,"ScoreRank":2,"Score":292,"Average":257}, {"TID":14,"ScoreRank":3,"Score":288,"Average":257}, {"TID":15,"ScoreRank":1,"Score":312,"Average":242}, {"TID":15,"ScoreRank":2,"Score":276,"Average":242}, {"TID":15,"ScoreRank":3,"Score":264,"Average":242}, {"TID":16,"ScoreRank":1,"Score":421,"Average":369}, {"TID":16,"ScoreRank":2,"Score":403,"Average":369}, {"TID":16,"ScoreRank":3,"Score":398,"Average":369}, {"TID":17,"ScoreRank":1,"Score":479,"Average":418}, {"TID":17,"ScoreRank":2,"Score":466,"Average":418}, {"TID":17,"ScoreRank":3,"Score":455,"Average":418}, {"TID":18,"ScoreRank":1,"Score":554,"Average":463}, {"TID":18,"ScoreRank":2,"Score":521,"Average":463}, {"TID":18,"ScoreRank":3,"Score":520,"Average":463}] df = pandas.DataFrame(Scores) f, ax1 = plt.subplots(1, figsize=(10,5)) bar_width = 0.75 bar_l = [i+1 for i in range(len(np.unique(df['TID'])))] tick_pos = [i+(bar_width/2) for i in bar_l] ax1.bar(bar_l, df['Score'][df['ScoreRank'] == 1], width=bar_width, label='Rank1', alpha=0.5, color='#eaff0a') ax1.bar(bar_l, df['Score'][df['ScoreRank'] == 2], width=bar_width, label='Rank2', alpha=0.5, color='#939393') ax1.bar(bar_l, df['Score'][df['ScoreRank'] == 3], width=bar_width, label='Rank3', alpha=0.5, color='#e29024') ax1.bar(bar_l, df['Average'][df['ScoreRank'] == 3], width=bar_width, label='Average', alpha=0.5, color='#FF0000') plt.xticks(tick_pos, np.unique(df['TID'])) ax1.set_ylabel("Score") ax1.set_xlabel("TID") plt.legend(loc='upper right') plt.xlim([min(tick_pos)-bar_width, max(tick_pos)+bar_width]) plt.show() </code></pre> <p>result: </p> <p><a href="https://i.stack.imgur.com/wh4bi.png" rel="nofollow"><img src="https://i.stack.imgur.com/wh4bi.png" alt="enter image description here"></a></p>
1
2016-10-19T16:40:26Z
[ "python", "matplotlib", "dataframe", "charts", "bar-chart" ]
How to turn a 1D radial profile into a 2D array in python
40,115,608
<p>I have a list that models a phenomenon that is a function of radius. I want to convert this to a 2D array. I wrote some code that does exactly what I want, but since it uses nested for loops, it is quite slow.</p> <pre><code>l = len(profile1D)/2 critDim = int((l**2 /2.)**(1/2.)) profile2D = np.empty([critDim, critDim]) for x in xrange(0, critDim): for y in xrange(0,critDim): r = ((x**2 + y**2)**(1/2.)) profile2D[x,y] = profile1D[int(l+r)] </code></pre> <p>Is there a more efficient way to do the same thing by avoiding these loops?</p>
1
2016-10-18T18:34:59Z
40,115,736
<p>Here's a vectorized approach using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p> <pre><code>a = np.arange(critDim)**2 r2D = np.sqrt(a[:,None] + a) out = profile1D[(l+r2D).astype(int)] </code></pre> <p>If there are many repeated indices generated by <code>l+r2D</code>, we can use <a href="https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.take.html" rel="nofollow"><code>np.take</code></a> for some further performance boost, like so -</p> <pre><code>out = np.take(profile1D,(l+r2D).astype(int)) </code></pre> <p><strong>Runtime test</strong></p> <p>Function definitions -</p> <pre><code>def org_app(profile1D,l,critDim): profile2D = np.empty([critDim, critDim]) for x in xrange(0, critDim): for y in xrange(0,critDim): r = ((x**2 + y**2)**(1/2.)) profile2D[x,y] = profile1D[int(l+r)] return profile2D def vect_app1(profile1D,l,critDim): a = np.arange(critDim)**2 r2D = np.sqrt(a[:,None] + a) out = profile1D[(l+r2D).astype(int)] return out def vect_app2(profile1D,l,critDim): a = np.arange(critDim)**2 r2D = np.sqrt(a[:,None] + a) out = np.take(profile1D,(l+r2D).astype(int)) return out </code></pre> <p>Timings and verification -</p> <pre><code>In [25]: # Setup input array and params ...: profile1D = np.random.randint(0,9,(1000)) ...: l = len(profile1D)/2 ...: critDim = int((l**2 /2.)**(1/2.)) ...: In [26]: np.allclose(org_app(profile1D,l,critDim),vect_app1(profile1D,l,critDim)) Out[26]: True In [27]: np.allclose(org_app(profile1D,l,critDim),vect_app2(profile1D,l,critDim)) Out[27]: True In [28]: %timeit org_app(profile1D,l,critDim) 10 loops, best of 3: 154 ms per loop In [29]: %timeit vect_app1(profile1D,l,critDim) 1000 loops, best of 3: 1.69 ms per loop In [30]: %timeit vect_app2(profile1D,l,critDim) 1000 loops, best of 3: 1.68 ms per loop In [31]: # Setup input array and params ...: profile1D = np.random.randint(0,9,(5000)) ...: l = len(profile1D)/2 ...: critDim = int((l**2 /2.)**(1/2.)) ...: In [32]: %timeit org_app(profile1D,l,critDim) 1 loops, best of 3: 3.76 s per loop In [33]: %timeit vect_app1(profile1D,l,critDim) 10 loops, best of 3: 59.8 ms per loop In [34]: %timeit vect_app2(profile1D,l,critDim) 10 loops, best of 3: 59.5 ms per loop </code></pre>
0
2016-10-18T18:42:12Z
[ "python", "performance", "numpy", "multidimensional-array", "vectorization" ]
vectorize and parallelize if it's add compute?
40,115,612
<p>What's the most efficient technique and Why?</p> <pre><code>min_dist = 999999999999999999999999999999999999999999 for i in range(len(self.data)): data = self.data[i] dist = MySuperLongFunction(data) if dist &lt; min_dist: min_dist = dist return min_dist </code></pre> <p>or</p> <pre><code>vdist = [0]*len(self.data) for i in range(len(self.data)): data = self.data[i] dist = MySuperLongFunction(data) vdist[i] = dist return min(vdist) </code></pre> <p>I know that the min(vdist) add compute to do but the second one can be parallelize verry easily because the for don't depend of previous itération so I can compute 8 time at one the MySuperLongFunction(data). So what's the most effective? </p>
0
2016-10-18T18:35:45Z
40,115,722
<p>You need to generate the function value for each input data in self.data, hence, <code>DARRAY = [MySuperLongFunction(x) for x in self.data]</code> has to be computed no matter what. As you already pointed out, computing <code>DARRAY</code> could be parallelized, hence, we are left with returning the <code>min</code> value in this case,</p> <p>So, i would say it's <code>min([MySuperLongFunction(x) for x in self.data])</code></p>
1
2016-10-18T18:41:45Z
[ "python", "multithreading", "vectorization" ]
How to add additional tick labels, formatted differently, in matplotlib
40,115,650
<p>I'm having real problems plotting a 2nd line of tick labels on x-axis directly underneath the original ones. I'm using seaborn so I need to add these extra labels after the plot is rendered.</p> <p>Below is <a href="http://content.screencast.com/users/cmardiros/folders/Jing/media/51a8b412-e3db-4030-81c9-cd389336f626/00000034.png" rel="nofollow">what I'm trying</a> to achieve but I'd like the gap between the 2 rows of tick labels to be a bit bigger and make the 2nd row bold and a different colour.</p> <p><a href="https://i.stack.imgur.com/V1pGKm.png" rel="nofollow"><img src="https://i.stack.imgur.com/V1pGKm.png" alt="enter image description here"></a></p> <p>My attempts involve hacking the existing tick labels and appending the new strings underneath separated by newline:</p> <pre><code> # n_labels is list that has the new labels I wish to plot directly # underneath the 1st row locs = ax.get_xticks().tolist() labels = [x.get_text() for x in ax.get_xticklabels()] nl = ['\n'.join([l, n_labels[i]]) for i, l in enumerate(labels)] ax.set_xticks(locs) ax.set_xticklabels(nl) </code></pre> <p>Any ideas? Thank you!</p>
0
2016-10-18T18:37:44Z
40,117,351
<p>One possibility would be to create a second x-axis on top of the first, and adjust the position and xtickslabels of the second x-axis. Check <a href="http://matplotlib.org/examples/axes_grid/demo_parasite_axes2.html" rel="nofollow">this example</a> in the documentation as a starting point.</p>
0
2016-10-18T20:18:44Z
[ "python", "matplotlib" ]
Sort a list of lists based on an if/else condition in Python 3.5
40,115,654
<p>I need to sort a list containing nested lists based on a condition. The condition is: if first index is 0, sort on index nr 7. Then if second index is 0, sort on index nr 8. So the below list (unsorted):</p> <pre><code>[[11, 37620, 'mat', 'xxx', 1, 28.5, 0, 11, 37620, 'Arp', 'xxx', 1, 28], [10, 24210, 'Skatt', 'xxx', 2, 40, 0, 0, 0, 0, 0, 0, 0], [10, 37010, 'test, a', 'xxx', 5, 36.75, 0, 10, 37010, '', 'xxx', 7, 50.75], [0, 0, 'mottagare', 'xxx', 3, 20.25, 0, 10, 21511, 0, 0, 0, 0], [10, 40000, 'eld', 'xxx', 5, 30.5, 0, 10, 40000, 'Oly', 'xxx', 5, 30], [10, 17060, 'bok', 'xxx', 1, 28.5, 0, 0, 0, 0, 0, 0, 0]] </code></pre> <p>Should look like this:</p> <pre><code>[[10, 17060, 'bok', 'xxx', 1, 28.5, 0, 0, 0, 0, 0, 0, 0], [0, 0, 'mottagare', 'xxx', 3, 20.25, 0, 10, 21511, 0, 0, 0, 0], [10, 24210, 'Skatt', 'xxx', 2, 40, 0, 0, 0, 0, 0, 0, 0], [10, 40000, 'eld', 'xxx', 5, 30.5, 0, 10, 40000, 'Oly', 'xxx', 5, 30], [10, 37010, 'test, a', 'xxx', 5, 36.75, 0, 10, 37010, '', 'xxx', 7, 50.75], [11, 37620, 'mat', 'xxx', 1, 28.5, 0, 11, 37620, 'Arp', 'xxx', 1, 28]] </code></pre> <p>I have tried with a_list.sort(key = itemgetter(0)) and lambda, but the zero's always end up first. I have solved this by bubble sort, but it is awfully slow already with 6000 elements in the lists. I paste the bubblesort below for reference. The list zero values are originally <code>None</code>, but for sorting in Python 3 I have converted them to int 0.</p> <pre><code>the_list_pos = 0 for key, value in kund_dict2.items(): # Start sorting from the whole list, since the_list_pos is zero for passnum in range(len(komplett_lista)-1,the_list_pos,-1): # Loop the list, one by one for i in range(passnum): # If these helper variables are None at the end, nothing happens comp1 = None comp2 = None # Check that the variables to compare are not None, and set them to appropiate values if komplett_lista[i][0] is not None and komplett_lista[i][0] == key: comp1 = komplett_lista[i][1] elif komplett_lista[i][7] is not None and komplett_lista[i][7] == key: comp1 = komplett_lista[i][8] if komplett_lista[i+1][0] is not None and komplett_lista[i+1][0] == key: comp2 = komplett_lista[i+1][1] elif komplett_lista[i+1][7] is not None and komplett_lista[i+1][7] == key: comp2 = komplett_lista[i+1][8] # Do the actual sorting if comp1 is not None and comp2 is not None: if comp1 &gt; comp2: temp = komplett_lista[i] komplett_lista[i] = komplett_lista[i+1] komplett_lista[i+1] = temp # update the position so that we do not sort over the already sorted data the_list_pos += (value) </code></pre> <p>Any advices to solve this is greatly appreciated!</p>
0
2016-10-18T18:38:22Z
40,115,739
<p>Write a function to contain your logic for finding which column to sort on:</p> <pre><code>def sort_col_value(row): # if first index is 0, sort on index nr 7. if row[0] == 0: return row[7] # Then if second index is 0, sort on index nr 8 if row[1] == 0: return row[8] return row[0] </code></pre> <p>then use this function as the <code>key</code> parameter:</p> <pre><code>mylist.sort(key=sort_col_value) </code></pre>
2
2016-10-18T18:42:24Z
[ "python", "list", "sorting", "python-3.5" ]