title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Conditional Iteration over a dataframe
38,984,043
<p>I have a dataframe <code>df</code> which looks like:</p> <pre><code> id location grain 0 BBG.XETR.AD.S XETR 16.545 1 BBG.XLON.VB.S XLON 6.2154 2 BBG.XLON.HF.S XLON NaN 3 BBG.XLON.RE.S XLON NaN 4 BBG.XLON.LL.S XLON NaN 5 BBG.XLON.AN.S XLON 3.215 6 BBG.XLON.TR.S XLON NaN 7 BBG.XLON.VO.S XLON NaN </code></pre> <p>In reality this dataframe will be much larger. I would like to iterate over this dataframe returning the <code>'grain'</code> value but I am only interested in the rows that have a value (not NaN) in the 'grain' column. So only returning as I iterate over the dataframe the following values:</p> <pre><code>16.545 6.2154 3.215 </code></pre> <p>I can iterate over the dataframe using:</p> <pre><code>for staticidx, row in df.iterrows(): value= row['grain'] </code></pre> <p>But this returns a value for all rows including those with a NaN value. Is there a way to either remove the NaN rows from the dataframe or skip the rows in the dataframe where grain equals NaN?</p> <p>Many thanks</p>
1
2016-08-16T20:37:52Z
38,984,252
<p>This:</p> <pre><code>df[pd.notnull(df['grain'])] </code></pre> <p>Or this:</p> <pre><code>df['grain].dropna() </code></pre>
0
2016-08-16T20:51:16Z
[ "python", "pandas" ]
Conditional Iteration over a dataframe
38,984,043
<p>I have a dataframe <code>df</code> which looks like:</p> <pre><code> id location grain 0 BBG.XETR.AD.S XETR 16.545 1 BBG.XLON.VB.S XLON 6.2154 2 BBG.XLON.HF.S XLON NaN 3 BBG.XLON.RE.S XLON NaN 4 BBG.XLON.LL.S XLON NaN 5 BBG.XLON.AN.S XLON 3.215 6 BBG.XLON.TR.S XLON NaN 7 BBG.XLON.VO.S XLON NaN </code></pre> <p>In reality this dataframe will be much larger. I would like to iterate over this dataframe returning the <code>'grain'</code> value but I am only interested in the rows that have a value (not NaN) in the 'grain' column. So only returning as I iterate over the dataframe the following values:</p> <pre><code>16.545 6.2154 3.215 </code></pre> <p>I can iterate over the dataframe using:</p> <pre><code>for staticidx, row in df.iterrows(): value= row['grain'] </code></pre> <p>But this returns a value for all rows including those with a NaN value. Is there a way to either remove the NaN rows from the dataframe or skip the rows in the dataframe where grain equals NaN?</p> <p>Many thanks</p>
1
2016-08-16T20:37:52Z
38,984,333
<p>Let's compare different methods (for 800K rows DF):</p> <pre><code>In [21]: df = pd.concat([df] * 10**5, ignore_index=True) In [22]: df.shape Out[22]: (800000, 3) In [23]: %timeit df.grain[~pd.isnull(df.grain)] The slowest run took 5.33 times longer than the fastest. This could mean that an intermediate result is being cached. 100 loops, best of 3: 17.1 ms per loop In [24]: %timeit df.ix[df.grain.notnull(), 'grain'] 10 loops, best of 3: 23.9 ms per loop In [25]: %timeit df[pd.notnull(df['grain'])] 10 loops, best of 3: 35.9 ms per loop In [26]: %timeit df.grain.ix[df.grain.notnull()] 100 loops, best of 3: 17.4 ms per loop In [27]: %timeit df.dropna(subset=['grain']) 10 loops, best of 3: 56.6 ms per loop In [28]: %timeit df.grain[df.grain.notnull()] 100 loops, best of 3: 17 ms per loop In [30]: %timeit df['grain'].dropna() 100 loops, best of 3: 16.3 ms per loop </code></pre>
0
2016-08-16T20:55:49Z
[ "python", "pandas" ]
MultiValueDictKeyError at /registroEstudianteMayor/ "'Acudiente'"
38,984,044
<p>I have this error </p> <blockquote> <p>MultiValueDictKeyError at /registroEstudianteMayor/"'Acudiente'" ",</p> </blockquote> <p>I searched a lot for an answer to this error but I couldn't find any.</p> <p>I have this controller:</p> <pre><code>def post(self, request, *args, **kwargs): generos = parametros['generos'] tiposDocumento = parametros['tiposDocumento'] zonas = parametros['zonas'] #Toma de datos numeroDocumento = request.POST['numeroDocumento'] tipoDocumento = request.POST['tipoDocumento'] contrasena = request.POST['contrasena'] contrasena2 = request.POST['contrasena2'] correoElectronico = request.POST['correoElectronico'] nombres = request.POST['nombres'] apellidos = request.POST['apellidos'] fechaNacimiento = request.POST['fechaNacimiento'] genero = request.POST['genero'] direccion = request.POST['direccion'] barrio = request.POST['barrio'] telefonoFijo = request.POST['telefonoFijo'] telefonoCelular = request.POST['telefonoCelular'] seguridadSocial = request.POST['seguridadSocial'] #Toma de datos particulares nombreAcudiente = request.POST['Acudiente'] telefonoAcudiente = request.POST['telefonoAcudiente'] foto = request.FILES['foto'] cedula = request.FILES['cedula'] #Inicializo datos opcionales zona = "" comuna = "" grupoEtnico = "" condicion = "" enviarInfoAlCorreo = False #Inicializo Datos Opcionales particulares desempeno = "" lugar = "" #Tomo los datos opcionales if request.POST['zona']: zona = request.POST['zona'] if request.POST['comuna']: comuna = request.POST['comuna'] if request.POST['grupoEtnico']: grupoEtnico = request.POST['grupoEtnico'] if request.POST['condicion']: condicion = request.POST['condicion'] if "enviarInfoAlCorreo" in request.POST.keys(): enviarInfoAlCorreo = True #tomo datos opcionales particulares if request.POST['Labor']: desempeno = request.POST['Labor'] if request.POST['Lugar']: lugar = request.POST['Lugar'] #Validaciones errorNumeroDocumento = (User.objects.filter(username=numeroDocumento) or not re.match("^([0-9]{8,20})$",numeroDocumento)) errorTipoDocumento = (tipoDocumento not in (parametros["tiposDocumento"])) errorContrasena = (request.POST["contrasena"]!=request.POST["contrasena2"]) errorCorreoElectronico = (User.objects.filter(email=correoElectronico) or not re.match(r"^[A-Za-z0-9\._-]+@[A-Za-z0-9]+\.[a-zA-Z]+$", correoElectronico)) errorFechaNacimiento = not fechaCorrecta(fechaNacimiento) errorGenero = (genero not in (parametros["generos"])) errorTelefonos = (not re.match("^([0-9]{7,12})$",telefonoFijo) or not re.match("^([0-9]{7,12})$",telefonoCelular) or not re.match("^([0-9]{7,12})$",telefonoAcudiente)) if (errorContrasena or errorNumeroDocumento or errorTipoDocumento or errorCorreoElectronico or errorFechaNacimiento or errorGenero or errorTelefonos): return render_to_response('Generales/registroEstudianteMayor.html', locals(), context_instance = RequestContext(request)) #Guardar usuario usuario = User.objects.create_user(id=User.objects.all().count() + 1, username=numeroDocumento, email=correoElectronico, password=contrasena) usuario.first_name = nombres usuario.last_name = apellidos usuario.save() #Guardo estudiante estudiante = Estudiante(user = usuario, tipoDocumento = tipoDocumento, fechaNacimiento = fechaNacimiento, genero = genero, direccion = direccion, barrio = barrio, zona = zona, comuna = comuna, telefonoFijo = telefonoFijo, telefonoCelular = telefonoCelular, grupoEtnico = grupoEtnico, condicion = condicion, seguridadSocial = seguridadSocial, enviarInfoAlCorreo = enviarInfoAlCorreo) estudiante.save() #Guardo datos particulares del Mayor datosMayor = DatosFamiliaMayor(idEstudiante= user, nombreContacto= nombreAcudiente, telefonoContacto= telefonoAcudiente, desempeno= desempeno, lugar= lugar, cedula= cedula, foto= foto) datosMayor.save() return inicioControl(request, registerSuccess=True) </code></pre> <p>and the part of the view being affected is:</p> <pre><code>&lt;label class="control-label col-md-4" for="acud"&gt;Nombre Acudiente:&lt;/label&gt; &lt;div class= "col-md-8"&gt; &lt;input type="text" name="Nomacud" requiered="true" value="{{Acudiente}}" class="form-control" id="nomacud"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group" id="TelAcudiente"&gt; &lt;label class="control-label col-md-4" for="Acudtel"&gt;Telefono Acudiente:&lt;/label&gt; &lt;div class="col-md-8"&gt; &lt;input type="text" name="Telacud" requiered="true" value="{{telefonoAcudiente}}" class="form-control" id="telacud"&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>In <code>TelefonoAcudiente</code> the error is the same.</p>
0
2016-08-16T20:37:59Z
38,984,317
<p>You don't have a field called Acudiente in your view; you have one called Nomacud instead.</p> <p>Really though you should be using Django forms for all this.</p>
0
2016-08-16T20:54:44Z
[ "python", "django", "multivalue" ]
add training data to existing LinearSVC
38,984,069
<p>I am scraping approximately 200,000 websites, looking for certain types of media posted on the websites of small businesses. I have a pickled linearSVC, which I've trained to predict the probability that a link found on a web page contains media of the type that I'm looking for, and it performs rather well (overall accuracy around 95%). However, I would like the scraper to periodically update the classifier with new data as it scrapes.</p> <p>So my question is, if I have loaded a pickled sklearn LinearSVC, is there a way to add in new training data without re-training the whole model? Or do I have to load all of the previous training data, add the new data, and train an entirely new model?</p>
1
2016-08-16T20:39:15Z
38,984,364
<p>You cannot add data to SVM and achieve the same result as if you would add it to the original training set. You can either retrain with extended training set starting with the previous solution (should be faster) or train on new data only and completely diverge from the previous solution.</p> <p>There are only few models that can do what you would like to achieve here - like for example Ridge Regression or Linear Discriminant Analysis (and their Kernelized - Kernel Ridge Regression or Kernel Fischer Discriminant, or "extreme"-counterparts - ELM or EEM), which have a property of being able to add new training data "on the fly".</p>
2
2016-08-16T20:58:20Z
[ "python", "machine-learning", "scikit-learn" ]
Using Python Exscript need to create regular expression for set_prompt() for cisco switch
38,984,101
<p>Having a hard time figuring out how to write a regular expression in python/exscript so that the prompt matches the output when i run "copy run tftp"...</p> <p>For example the prompt changes to...</p> <p>"Address or name of remote host []?"</p> <p>then to...</p> <p>"Destination filename [lab-3560.confg]?"</p> <p>I know I need to set the "set_prompt()" prior to executing the command conn.execute('copy run tftp') just no clue on the proper syntax(s)</p>
0
2016-08-16T20:41:09Z
39,045,058
<p>There are so many ways to do this, here is an example:</p> <p>So all you need to do is parse the returned prompt/text, here is a small example from this <a href="http://www.electricmonk.nl/log/2014/07/26/scripting-a-cisco-switch-with-python-and-expect/" rel="nofollow">link</a>:</p> <pre><code>import pexpect switch_ip = "10.0.0.1" switch_un = "user" switch_pw = "s3cr3t" switch_port = "Gi2/0/2" switch_vlan = 300 config = "lab-3560.confg" child = pexpect.spawn('ssh %s@%s' % (switch_un, switch_ip)) child.logfile = sys.stdout child.timeout = 4 child.expect('Address or name of remote host []?') child.sendline(switch_ip) child.expect('Destination filename [lab-3560.confg]?') child.sendline(config) </code></pre>
0
2016-08-19T17:50:44Z
[ "python", "cisco", "exscript" ]
pexpect multithread program hangs when spawning a shell
38,984,177
<p>I have a multi-threaded program. When the program is running, some of the threads hang sometimes during the call to pexpect.spawn(). </p> <p>This program creates a Session object in each thread, and a Session object spawns a pexpect session when it is created. In the program, each Session object is binding to one specific thread.</p> <pre><code>class CustomizedThread(threading.Thread): __init__(self, thread_name): super().__init__(name=thread_name) def run(self): session = Session() ... class Session: __init__(self, session_name): self.name = session_name print('Thread {} is spawning a shell in session {}.'.format( threading.currentThread(), session.name)) self.pexpect_session = pexpect.spawn('/bin/sh') print('Thread {} finished spawning a shell in session {}.'.format( threading.currentThread(), session.name)) self.pexpect_session.sendline('ssh MACHINE_NAME') ... __del__(self): print('Thread {} is cleaning up session {}.'.format( threading.currentThread(), session.name)) self.pexepect_session.close(force=True) </code></pre> <p>The following is an example output when thread 2 is hanging, the destructor of Session object 1 is triggered during the call to pexpect.spawn() on thread 2.</p> <pre><code>... Thread 1 is spawning a shell in session 1. Thread 1 finished spawning a shell in session 1. Thread 2 is spawning a shell in session 2. Thread 2 is cleaning up session 1. </code></pre> <p>Attaching the hanging process to gdb, and I got the following stack trace. It shows the thread is hanging when attempting to write the exception message to a file descriptor: </p> <pre><code>(gdb) where #0 0x00007fff9628391a in write () from /usr/lib/system/libsystem_kernel.dylib #1 0x000000010ed7aa22 in _Py_write_impl (fd=2, buf=0x10f3f1010, count=76, gil_held=1) at ../Python/fileutils.c:1269 #2 0x000000010ed7a9a1 in _Py_write (fd=2, buf=0x10f3f1010, count=76) at ../Python/fileutils.c:1327 #3 0x000000010ede8795 in _io_FileIO_write_impl (self=0x10f3875f8, b=0x7000013dd168) at ../Modules/_io/fileio.c:840 #4 0x000000010ede7957 in _io_FileIO_write (self=0x10f3875f8, arg=0x11312c148) at ../Modules/_io/clinic/fileio.c.h:245 #5 0x000000010ebbfd72 in PyCFunction_Call (func=0x112ed7b98, args=0x112fc6330, kwds=0x0) at ../Objects/methodobject.c:134 #6 0x000000010eb2803d in PyObject_Call (func=0x112ed7b98, arg=0x112fc6330, kw=0x0) at ../Objects/abstract.c:2165 #7 0x000000010eb290de in PyObject_CallMethodObjArgs (callable=0x112ed7b98, name=0x10f234d40) at ../Objects/abstract.c:2394 #8 0x000000010edf0456 in _bufferedwriter_raw_write (self=0x10f25de58, start=0x10f3f1010 "\nThread 2 is cleaning up session 1. \"terminated\" is 0, but there was no child process. Did someone else call waitpid() on our process?\n"..., len=76) at ../Modules/_io/bufferedio.c:1847 </code></pre> <p>The exception message '"terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?' is from the line where the pexpect session is closed</p> <pre><code>self.pexepect_session.close(force=True) </code></pre> <p>Also, in the spawn() method of pexpect, the process is forked (the process that I attached to in gdb) to execute '/bin/sh' and a pipe is created to write any exception message to the parent process.</p> <p>It looks like the forked process garbage collected the Session object of another thread but caught a exception when trying to close a session on another thread. The process is hanging writing the exception message to the pipe because the exception message should've been read from the other side.</p>
1
2016-08-16T20:46:01Z
38,984,282
<p>Rather than using threads to spawn shells and pexpect to run ssh, just use <a href="http://www.paramiko.org/" rel="nofollow">Paramiko</a>. It's a very good, mature library which implements ssh without having to shell out. And you can run multiple sessions in a single thread which will probably be more efficient in Python anyway--see here: <a href="http://stackoverflow.com/questions/760978/long-running-ssh-commands-in-python-paramiko-module-and-how-to-end-them">Long-running ssh commands in python paramiko module (and how to end them)</a></p>
0
2016-08-16T20:52:44Z
[ "python", "multithreading", "fork", "pexpect" ]
pexpect multithread program hangs when spawning a shell
38,984,177
<p>I have a multi-threaded program. When the program is running, some of the threads hang sometimes during the call to pexpect.spawn(). </p> <p>This program creates a Session object in each thread, and a Session object spawns a pexpect session when it is created. In the program, each Session object is binding to one specific thread.</p> <pre><code>class CustomizedThread(threading.Thread): __init__(self, thread_name): super().__init__(name=thread_name) def run(self): session = Session() ... class Session: __init__(self, session_name): self.name = session_name print('Thread {} is spawning a shell in session {}.'.format( threading.currentThread(), session.name)) self.pexpect_session = pexpect.spawn('/bin/sh') print('Thread {} finished spawning a shell in session {}.'.format( threading.currentThread(), session.name)) self.pexpect_session.sendline('ssh MACHINE_NAME') ... __del__(self): print('Thread {} is cleaning up session {}.'.format( threading.currentThread(), session.name)) self.pexepect_session.close(force=True) </code></pre> <p>The following is an example output when thread 2 is hanging, the destructor of Session object 1 is triggered during the call to pexpect.spawn() on thread 2.</p> <pre><code>... Thread 1 is spawning a shell in session 1. Thread 1 finished spawning a shell in session 1. Thread 2 is spawning a shell in session 2. Thread 2 is cleaning up session 1. </code></pre> <p>Attaching the hanging process to gdb, and I got the following stack trace. It shows the thread is hanging when attempting to write the exception message to a file descriptor: </p> <pre><code>(gdb) where #0 0x00007fff9628391a in write () from /usr/lib/system/libsystem_kernel.dylib #1 0x000000010ed7aa22 in _Py_write_impl (fd=2, buf=0x10f3f1010, count=76, gil_held=1) at ../Python/fileutils.c:1269 #2 0x000000010ed7a9a1 in _Py_write (fd=2, buf=0x10f3f1010, count=76) at ../Python/fileutils.c:1327 #3 0x000000010ede8795 in _io_FileIO_write_impl (self=0x10f3875f8, b=0x7000013dd168) at ../Modules/_io/fileio.c:840 #4 0x000000010ede7957 in _io_FileIO_write (self=0x10f3875f8, arg=0x11312c148) at ../Modules/_io/clinic/fileio.c.h:245 #5 0x000000010ebbfd72 in PyCFunction_Call (func=0x112ed7b98, args=0x112fc6330, kwds=0x0) at ../Objects/methodobject.c:134 #6 0x000000010eb2803d in PyObject_Call (func=0x112ed7b98, arg=0x112fc6330, kw=0x0) at ../Objects/abstract.c:2165 #7 0x000000010eb290de in PyObject_CallMethodObjArgs (callable=0x112ed7b98, name=0x10f234d40) at ../Objects/abstract.c:2394 #8 0x000000010edf0456 in _bufferedwriter_raw_write (self=0x10f25de58, start=0x10f3f1010 "\nThread 2 is cleaning up session 1. \"terminated\" is 0, but there was no child process. Did someone else call waitpid() on our process?\n"..., len=76) at ../Modules/_io/bufferedio.c:1847 </code></pre> <p>The exception message '"terminated" is 0, but there was no child process. Did someone else call waitpid() on our process?' is from the line where the pexpect session is closed</p> <pre><code>self.pexepect_session.close(force=True) </code></pre> <p>Also, in the spawn() method of pexpect, the process is forked (the process that I attached to in gdb) to execute '/bin/sh' and a pipe is created to write any exception message to the parent process.</p> <p>It looks like the forked process garbage collected the Session object of another thread but caught a exception when trying to close a session on another thread. The process is hanging writing the exception message to the pipe because the exception message should've been read from the other side.</p>
1
2016-08-16T20:46:01Z
39,090,310
<p>The issue can be worked around by switching to multiprocessing. Mixing multithreading and fork is problematic.</p>
0
2016-08-22T23:43:27Z
[ "python", "multithreading", "fork", "pexpect" ]
Unpickle class instances by interating over a list
38,984,207
<p>I am trying to unpickle various class instances which are saved in separate .pkl files by iterating over a list containing all the class instances (each class instance appends itself to the appropriate list when instantiated).</p> <p>This <strong>works</strong>:</p> <pre><code># LOAD IN INGREDIENT INSTANCES for each in il: with open('Ingredients/{}.pkl'.format(each), 'rb') as f: globals()[each] = pickle.load(f) </code></pre> <p>For example, one ingredient is <code>Aubergine</code>:</p> <pre><code>print(Aubergine) </code></pre> <p>output:</p> <pre><code>Name: Aubergine Price: £1.00 Portion Size: 1 </code></pre> <p>However, this <strong>doesn't work</strong>:</p> <pre><code># LOAD IN RECIPE INSTANCES for each in rl: with open('Recipes/{}.pkl'.format(each.name), 'rb') as f: globals()[each] = pickle.load(f) </code></pre> <p>I can only assume that the issue stems from <code>each.name</code> being used for the file names of the recipes, whereas <code>each</code> is used for the ingredient file names. This is intentional, however, as the <code>name</code> attribute of the recipes is formatted for the end-user (i.e. contains white space etc.) I think this may be the issue, but I am not sure.</p> <p>Both the ingredient and recipe classes use:</p> <pre><code>def __repr__(self): return self.name </code></pre> <p>For example:</p> <p>I have a recipe class instance <code>SausageAubergineRagu</code>, for which <code>self.name</code> is <code>'Sausage &amp; Aubergine Ragu'</code>, and this is inside the list <code>rl</code>. I have tried testing this individually:</p> <p>input:</p> <pre><code>rl </code></pre> <p>output:</p> <pre><code>[Sausage &amp; Aubergine Ragu] </code></pre> <p>So I believe that this code:</p> <pre><code># LOAD IN RECIPE INSTANCES for each in rl: with open('Recipes/{}.pkl'.format(each.name), 'rb') as f: globals()[each] = pickle.load(f) </code></pre> <p>...should result in this:</p> <pre><code>with open('Recipes/Sausage &amp; Aubergine Ragu.pkl', 'rb') as f: globals()[SausageAubergineRagu] = pickle.load(f) </code></pre> <p>But attempting to access the recipe class instances results in a NameError.</p> <p><strong>One final note</strong> - please <strong>don't</strong> ask why I am doing things this way. Instead help me to address and solve the problem, so I can make it work, and understand what is going on. Appreciated :)</p>
-2
2016-08-16T20:48:29Z
38,984,345
<p>The <code>NameError</code> you are getting is Python telling you that you are trying to use a variable that hasn't been defined yet.</p> <p>You aren't defining <code>SausageAubergineRagu</code> before you use it in this line:</p> <pre><code>globals()[SausageAubergineRagu] = pickle.load(f) </code></pre> <p>In your first example, you are adding keys and values to <code>globals</code>. You are using instances of recipes (<code>each</code>) as keys, and the pickled data as values.</p> <p>In your second example, you are attempting to do the same thing, but instead of using instances of recipes (<code>each</code>) as keys, you are using <code>SausageAubergineRagu</code>, which is undefined.</p> <p>How is Python supposed to know what <code>SausageAubergineRagu</code> is? If you want that line to work, you will need to define it first, or use something that is already defined, like <code>each</code>, which is what you do in your other snippet.</p> <p>Honestly, using instances of custom classes as keys in <code>globals</code> seems bizarre to me anyway (usually people use strings), but since you apparently want to make it work, the answer is simple:</p> <p>Define <code>SausageAubergineRagu</code> before attempting to use it as a key in a dictionary.</p>
0
2016-08-16T20:56:41Z
[ "python", "class", "filenames", "pickle" ]
How to use gather in python 3.5.2
38,984,257
<p>I tried to learn how asnychron programming in python works and wrote a small tornado app which executues two asnyc loops with sleep commands. If I wait for both coroutines with two await commands, it behaves as expected (first loop, than the second loop is executed.) If I combine both coroutines with gather, nothing happens. (No errors, no print output, the webrequest is never finished.)</p> <p>I don't understand what is happening with *await gather(<em>coros, return_exceptions=True)</em>,</p> <pre><code>from asyncio import gather import os.path import tornado.ioloop from tornado.options import define, options, parse_command_line import tornado.web import tornado.platform.asyncio from tornado.gen import sleep import datetime; define("port", default=8888, help="run on the given port", type=int) define("debug", default=False, help="run in debug mode") class AsyncTestHandler(tornado.web.RequestHandler): async def get(self): operation = self.get_query_argument('operation') if operation == 'with_two_waits': await self._with_two_waits() elif operation == 'with_gather': await self._with_gather() else: self.finish('use operation=with_two_waits or operation=with_gather') return self.finish('finished ' + operation); async def _with_two_waits(self): print('_with_two_waits: start' + str(datetime.datetime.now()) ) w1 = self._wait_loop("First loop", 8) w2 = self._wait_loop("Second loop", 6) await w1 await w2 print('_with_two_waits: finished' + str(datetime.datetime.now())) async def _with_gather(self): print('_with_gather: start' + str(datetime.datetime.now())) coros = [] coros.append(self._wait_loop("First loop", 8)) coros.append(self._wait_loop("Second loop", 6)) await gather(*coros, return_exceptions=True) print ('_with_gather: finished' + str(datetime.datetime.now())) async def _wait_loop(self, loop_name, count): for i in range(1, count + 1): print(loop_name + ' ' + str(i) + '/' + str(count) + ' ' + str(datetime.datetime.now())) await sleep(0.1) print(loop_name + ' complete') def start_web_app(): parse_command_line() app = tornado.web.Application( [ (r"/asnycTest", AsyncTestHandler), ], debug=options.debug, ) app.listen(options.port) tornado.ioloop.IOLoop.current().start() if __name__ == "__main__": start_web_app() </code></pre>
1
2016-08-16T20:51:26Z
39,048,127
<p><code>gather</code> uses the asyncio event loop. If you wish to mix asyncio with tornado, you need to install tornado's asyncio event loop:</p> <p>Add this to your imports:</p> <pre><code>from tornado.platform.asyncio import AsyncIOMainLoop </code></pre> <p>Remove this:</p> <pre><code>import tornado.platform.asyncio </code></pre> <p>And add this line right after the imports:</p> <pre><code>AsyncIOMainLoop().install() </code></pre>
0
2016-08-19T21:48:15Z
[ "python", "async-await" ]
Write xml from list of path/values
38,984,272
<p>This is a follow-up to the previous question: <a href="http://stackoverflow.com/questions/38983126/write-xml-with-a-path-and-value">Write xml with a path and value</a>. I want to now add in two additional things: 1) Attributes and 2) Multiple items with a parent node. Here is the list of paths I have:</p> <pre><code>[ {'Path': 'Item/Info/Name', 'Value': 'Body HD'}, {'Path': 'Item/Info/Synopsis', 'Value': 'A great movie'}, {'Path': 'Item/Locales/Locale[@Country="US"][@Language="ES"]/Name', 'Value': 'El Grecco'}, {'Path': 'Item/Genres/Genre', 'Value': 'Action'}, {'Path': 'Item/Genres/Genre', 'Value': 'Drama'}, {'Path': 'Item/Purchases/Purchase[@Country="US"]/HDPrice', 'Value': '10.99'}, {'Path': 'Item/Purchases/Purchase[@Country="US"]/SDPrice', 'Value': '9.99'}, {'Path': 'Item/Purchases/Purchase[@Country="CA"]/SDPrice', 'Value': '4.99'}, ] </code></pre> <p>The xml it should generate is:</p> <pre><code>&lt;Item&gt; &lt;Info&gt; &lt;Name&gt;Body HD&lt;/Name&gt; &lt;Synopsis&gt;A great movie&lt;/Synopsis&gt; &lt;/Info&gt; &lt;Locales&gt; &lt;Locale Country="US" Language="ES"&gt; &lt;Name&gt;El Grecco&lt;/Name&gt; &lt;/Locale&gt; &lt;/Locales&gt; &lt;Genres&gt; &lt;Genre&gt;Action&lt;/Genre&gt; &lt;Genre&gt;Drama&lt;/Genre&gt; &lt;/Genres&gt; &lt;Purchases&gt; &lt;Purchase Country="US"&gt; &lt;HDPrice&gt;10.99&lt;/HDPrice&gt; &lt;SDPrice&gt;9.99&lt;/SDPrice&gt; &lt;/Purchase&gt; &lt;Purchase Country="CA"&gt; &lt;SDPrice&gt;4.99&lt;/SDPrice&gt; &lt;/Purchase&gt; &lt;/Purchases&gt; &lt;/Item&gt; </code></pre> <p>How would I build this out?</p>
0
2016-08-16T20:52:25Z
38,984,918
<p>To build a XML tree from xpaths and values, I use RegEx and <code>lxml</code>:</p> <pre><code>import re from lxml import etree </code></pre> <p>The entries are:</p> <pre><code>entries = [ {'Path': 'Item/Info/Name', 'Value': 'Body HD'}, {'Path': 'Item/Info/Synopsis', 'Value': 'A great movie'}, {'Path': 'Item/Locales/Locale[@Country="US"][@Language="ES"]/Name', 'Value': 'El Grecco'}, {'Path': 'Item/Genres/Genre', 'Value': 'Action'}, {'Path': 'Item/Genres/Genre', 'Value': 'Drama'}, {'Path': 'Item/Purchases/Purchase[@Country="US"]/HDPrice', 'Value': '10.99'}, {'Path': 'Item/Purchases/Purchase[@Country="US"]/SDPrice', 'Value': '9.99'}, {'Path': 'Item/Purchases/Purchase[@Country="CA"]/SDPrice', 'Value': '4.99'}, ] </code></pre> <p>To parse each xpath step, I use the following RegEx (very simple one):</p> <pre><code>TAG_REGEX = r"(?P&lt;tag&gt;\w+)" CONDITION_REGEX = r"(?P&lt;condition&gt;(?:\[.*?\])*)" STEP_REGEX = TAG_REGEX + CONDITION_REGEX ATTR_REGEX = r"@(?P&lt;key&gt;\w+)=\"(?P&lt;value&gt;.*?)\"" search_step = re.compile(STEP_REGEX, flags=re.DOTALL).search findall_attr = re.compile(ATTR_REGEX, flags=re.DOTALL).findall def parse_step(step): mo = search_step(step) if mo: tag = mo.group("tag") condition = mo.group("condition") return tag, dict(findall_attr(condition)) raise ValueError(xpath) </code></pre> <p>The <code>parse_step</code> return a <em>tag name</em> and a <em>attributes dictionary</em>.</p> <p>Then, I process the same way to build the XML tree:</p> <pre><code>root = None for entry in entries: path = entry["Path"] parts = path.split("/") xpath_list = ["/" + parts[0]] + parts[1:] curr = root for xpath in xpath_list: tag_name, attrs = parse_step(xpath) if curr is None: root = curr = etree.Element(tag_name, **attrs) else: nodes = curr.xpath(xpath) if nodes: curr = nodes[0] else: curr = etree.SubElement(curr, tag_name, **attrs) if curr.text: curr = etree.SubElement(curr.getparent(), curr.tag, **curr.attrib) curr.text = entry["Value"] print(etree.tostring(root, pretty_print=True)) </code></pre> <p>The result is:</p> <pre><code>&lt;Item&gt; &lt;Info&gt; &lt;Name&gt;Body HD&lt;/Name&gt; &lt;Synopsis&gt;A great movie&lt;/Synopsis&gt; &lt;/Info&gt; &lt;Locales&gt; &lt;Locale Country="US" Language="ES"&gt; &lt;Name&gt;El Grecco&lt;/Name&gt; &lt;/Locale&gt; &lt;/Locales&gt; &lt;Genres&gt; &lt;Genre&gt;Action&lt;/Genre&gt; &lt;Genre&gt;Drama&lt;/Genre&gt; &lt;/Genres&gt; &lt;Purchases&gt; &lt;Purchase Country="US"&gt; &lt;HDPrice&gt;10.99&lt;/HDPrice&gt; &lt;SDPrice&gt;9.99&lt;/SDPrice&gt; &lt;/Purchase&gt; &lt;Purchase Country="CA"&gt; &lt;SDPrice&gt;4.99&lt;/SDPrice&gt; &lt;/Purchase&gt; &lt;/Purchases&gt; &lt;/Item&gt; </code></pre>
1
2016-08-16T21:40:43Z
[ "python", "xml", "xpath", "lxml" ]
Avoid altering user arguments by deepcopy in the __init__ method?
38,984,311
<p>I want to avoid that user arguments get changed after creating a new instance of an object and working with the object. Is it good practice here to immediately copy the critical arguments in the <strong>init</strong>() method or is there a better solution?</p> <p>Here is a specific example:</p> <pre><code>import copy class Myclass: def __init__(self, x): self.x = copy.deepcopy(x) def change(self): self.x[0] += 1 &gt;&gt;&gt; x = [0] &gt;&gt;&gt; C = Myclass(x) &gt;&gt;&gt; C.change() &gt;&gt;&gt; print(x) 0 </code></pre>
0
2016-08-16T20:54:38Z
38,985,108
<p>The author of Fluent Python - Luciano Ramalho - has examples in his book of coping in the <code>__init__.py</code> and I'd be incline to aggree with him.</p> <p>He doesn't use deep copy however, he just takes advantage that you can initialise a list with another. Saves you an <code>import</code>.</p> <pre><code>class MyClass: def __init__(self, options: list): self.options = list(options) </code></pre> <p>Great book; Highly recommended.</p>
1
2016-08-16T21:55:42Z
[ "python" ]
Selenium Clicks but Doesn't Select
38,984,340
<p>I'm working on making an automated web scraper run on Khan Academy to make offline backups of questions using selenium and a python scraper (to come later). I'm currently working on getting it to answer questions (right or wrong doesn't matter) to proceed through exercises. Unfortunately, selenium's .click() function doesn't actually select an answer. I think it has something to do with being pointed at the wrong object but I can't tell. It currently highlights the option, but doesn't select it.</p> <p><a href="http://pastebin.com/RXwDUAAw" rel="nofollow">HTML for a single option (out of 4)</a></p> <p>I made some code to reproduce the error, and hooked it up to a test account for all your debugging needs. Thanks.</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() # gets us to the SAT Math Exercise page driver.get('https://www.khanacademy.org/mission/sat/tasks/5505307403747328') # these next lines just automate logging in. Nothing special. login = driver.find_element_by_name('identifier') login.send_keys('stackflowtest') # look, I made a new account just for you guys passw = driver.find_element_by_name('password') passw.send_keys('stackoverflow') button = driver.find_elements_by_xpath("//*[contains(text(), 'Sign in')]") button[1].click() driver.implicitly_wait(5) # wait for things to become visible radio = driver.find_element_by_class_name('perseus-radio-option') radio.click() check = driver.find_element_by_xpath("//*[contains(text(), 'Check answer')]") check.click() </code></pre>
1
2016-08-16T20:56:16Z
39,023,055
<p>After a trial and error process, I found that the actual click selection can be accomplished by pointing to the element with class "description"</p> <pre><code>from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() # gets us to the SAT Math Exercise page driver.get('https://www.khanacademy.org/mission/sat/tasks/5505307403747328') # these next lines just automate logging in. Nothing special. login = driver.find_element_by_name('identifier') login.send_keys('stackflowtest') # look, I made a new account just for you guys passw = driver.find_element_by_name('password') passw.send_keys('stackoverflow') button = driver.find_elements_by_xpath("//*[contains(text(), 'Sign in')]") button[1].click() driver.implicitly_wait(5) # wait for things to become visible radio = driver.find_element_by_class_name('description') radio.click() check = driver.find_element_by_xpath("//*[contains(text(), 'Check answer')]") check.click() </code></pre> <p>For people dealing with similar issues, I would recommend clicking on the very edge of the space that allows you to select and inspecting the element there. This prevents you from accidentally using one of the innermost tags.</p>
0
2016-08-18T16:16:41Z
[ "python", "selenium" ]
Python fluent filter, map, etc
38,984,369
<p>I love python. However, one thing that bugs me a bit is that I don't know how to format functional activities in a fluid manner like a can in javascript.</p> <p>example (randomly created on the spot): Can you help me convert this to python in a fluent looking manner?</p> <pre><code>var even_set = [1,2,3,4,5] .filter(function(x){return x%2 === 0;}) .map(function(x){ console.log(x); // prints it for fun return x; }) .reduce(function(num_set, val) { num_set[val] = true; }, {}); </code></pre> <p>I'd like to know if there are fluid options? Maybe a library.</p> <p>In general, I've been using list comprehensions for most things but it's a real problem if I want to print</p> <p>e.g., How can I print every even number between 1 - 5 in python 2.x using list comprehension (Python 3 print() as a function but Python 2 it doesn't). It's also a bit annoying that a list is constructed and returned. I'd rather just for loop.</p>
1
2016-08-16T20:58:35Z
38,984,512
<p>The biggest dealbreaker to the code you wrote is that Python doesn't support multiline anonymous functions. The return value of <code>filter</code> or <code>map</code> is a list, so you can continue to chain them if you so desire. However, you'll either have to define the functions ahead of time, or use a lambda.</p>
1
2016-08-16T21:07:08Z
[ "python", "functional-programming", "fluent" ]
Python fluent filter, map, etc
38,984,369
<p>I love python. However, one thing that bugs me a bit is that I don't know how to format functional activities in a fluid manner like a can in javascript.</p> <p>example (randomly created on the spot): Can you help me convert this to python in a fluent looking manner?</p> <pre><code>var even_set = [1,2,3,4,5] .filter(function(x){return x%2 === 0;}) .map(function(x){ console.log(x); // prints it for fun return x; }) .reduce(function(num_set, val) { num_set[val] = true; }, {}); </code></pre> <p>I'd like to know if there are fluid options? Maybe a library.</p> <p>In general, I've been using list comprehensions for most things but it's a real problem if I want to print</p> <p>e.g., How can I print every even number between 1 - 5 in python 2.x using list comprehension (Python 3 print() as a function but Python 2 it doesn't). It's also a bit annoying that a list is constructed and returned. I'd rather just for loop.</p>
1
2016-08-16T20:58:35Z
38,984,604
<p>Arguments against doing this notwithstanding, here is a translation into Python of your JS code.</p> <pre class="lang-py prettyprint-override"><code>from __future__ import print_function from functools import reduce def print_and_return(x): print(x) return x def isodd(x): return x % 2 == 0 def add_to_dict(d, x): d[x] = True return d even_set = list(reduce(add_to_dict, map(print_and_return, filter(isodd, [1, 2, 3, 4, 5])), {})) </code></pre> <p>It should work on both Python 2 and Python 3.</p>
2
2016-08-16T21:15:04Z
[ "python", "functional-programming", "fluent" ]
Python fluent filter, map, etc
38,984,369
<p>I love python. However, one thing that bugs me a bit is that I don't know how to format functional activities in a fluid manner like a can in javascript.</p> <p>example (randomly created on the spot): Can you help me convert this to python in a fluent looking manner?</p> <pre><code>var even_set = [1,2,3,4,5] .filter(function(x){return x%2 === 0;}) .map(function(x){ console.log(x); // prints it for fun return x; }) .reduce(function(num_set, val) { num_set[val] = true; }, {}); </code></pre> <p>I'd like to know if there are fluid options? Maybe a library.</p> <p>In general, I've been using list comprehensions for most things but it's a real problem if I want to print</p> <p>e.g., How can I print every even number between 1 - 5 in python 2.x using list comprehension (Python 3 print() as a function but Python 2 it doesn't). It's also a bit annoying that a list is constructed and returned. I'd rather just for loop.</p>
1
2016-08-16T20:58:35Z
38,984,608
<p>Comprehensions are the fluent python way of handling filter/map operations.</p> <p>Your code would be something like:</p> <pre><code>def evenize(input_list): return [x for x in input_list if x % 2 == 0] </code></pre> <p>Comprehensions don't work well with side effects like console logging, so do that in a separate loop. Chaining function calls isn't really that common an idiom in python. Don't expect that to be your bread and butter here. Python libraries tend to follow the "alter state or return a value, but not both" pattern. Some exceptions exist.</p> <p><strong>Edit:</strong> On the plus side, python provides several flavors of comprehensions, which are awesome:</p> <p>List comprehension: <code>[x for x in range(3)] == [0, 1, 2]</code></p> <p>Set comprehension: <code>{x for x in range(3)} == {0, 1, 2}</code></p> <p>Dict comprehension: ` {x: x**2 for x in range(3)} == {0: 0, 1: 1, 2: 4}</p> <p>Generator comprehension (or generator expression): <code>(x for x in range(3)) == &lt;generator object &lt;genexpr&gt; at 0x10fc7dfa0&gt;</code> </p> <p>With the generator comprehension, nothing has been evaluated yet, so it is a great way to prevent blowing up memory usage when pipelining operations on large collections.</p> <p>For instance, if you try to do the following, even with python3 semantics for <code>range</code>:</p> <pre><code>for number in [x**2 for x in range(10000000000000000)]: print(number) </code></pre> <p>you will get a memory error trying to build the initial list. On the other hand, change the list comprehension into a generator comprehension:</p> <pre><code>for number in (x**2 for x in range(1e20)): print(number) </code></pre> <p>and there is no memory issue (it just takes forever to run). What happens is the range object gets built (which only stores the start, stop and step values (0, 1e20, and 1)) the object gets built, and then the for-loop begins iterating over the genexp object. Effectively, the for-loop calls </p> <pre><code>GENEXP_ITERATOR = `iter(genexp)` number = next(GENEXP_ITERATOR) # run the loop one time number = next(GENEXP_ITERATOR) # run the loop one time # etc. </code></pre> <p>(Note the GENEXP_ITERATOR object is not visible at the code level)</p> <p><code>next(GENEXP_ITERATOR)</code> tries to pull the first value out of genexp, which then starts iterating on the range object, pulls out one value, squares it, and yields out the value as the first <code>number</code>. The next time the for-loop calls <code>next(GENEXP_ITERATOR)</code>, the generator expression pulls out the second value from the range object, squares it and yields it out for the second pass on the for-loop. The first set of numbers are no longer held in memory. </p> <p>This means that no matter how many items in the generator comprehension, the memory usage remains constant. You can pass the generator expression to other generator expressions, and create long pipelines that never consume large amounts of memory.</p> <pre><code>def pipeline(filenames): basepath = path.path('/usr/share/stories') fullpaths = (basepath / fn for fn in filenames) realfiles = (fn for fn in fullpaths if os.path.exists(fn)) openfiles = (open(fn) for fn in realfiles) def read_and_close(file): output = file.read(100) file.close() return output prefixes = (read_and_close(file) for file in openfiles) noncliches = (prefix for prefix in prefixes if not prefix.startswith('It was a dark and stormy night') return {prefix[:32]: prefix for prefix in prefixes} </code></pre> <p>At any time, if you need a data structure for something, you can pass the generator comprehension to another comprehension type (as in the last line of this example), at which point, it will force the generators to evaluate all the data they have left, but unless you do that, the memory consumption will be limited to what happens in a single pass over the generators.</p>
0
2016-08-16T21:15:22Z
[ "python", "functional-programming", "fluent" ]
Python fluent filter, map, etc
38,984,369
<p>I love python. However, one thing that bugs me a bit is that I don't know how to format functional activities in a fluid manner like a can in javascript.</p> <p>example (randomly created on the spot): Can you help me convert this to python in a fluent looking manner?</p> <pre><code>var even_set = [1,2,3,4,5] .filter(function(x){return x%2 === 0;}) .map(function(x){ console.log(x); // prints it for fun return x; }) .reduce(function(num_set, val) { num_set[val] = true; }, {}); </code></pre> <p>I'd like to know if there are fluid options? Maybe a library.</p> <p>In general, I've been using list comprehensions for most things but it's a real problem if I want to print</p> <p>e.g., How can I print every even number between 1 - 5 in python 2.x using list comprehension (Python 3 print() as a function but Python 2 it doesn't). It's also a bit annoying that a list is constructed and returned. I'd rather just for loop.</p>
1
2016-08-16T20:58:35Z
38,985,641
<p>Generators, iterators, and <code>itertools</code> give added powers to chaining and filtering actions. But rather than remember (or look up) rarely used things, I gravitate toward helper functions and comprehensions. </p> <p>For example in this case, take care of the logging with a helper function:</p> <pre><code>def echo(x): print(x) return x </code></pre> <p>Selecting even values is easy with the <code>if</code> clause of a comprehension. And since the final output is a dictionary, use that kind of comprehension:</p> <pre><code>In [118]: d={echo(x):True for x in s if x%2==0} 2 4 In [119]: d Out[119]: {2: True, 4: True} </code></pre> <p>or to add these values to an existing dictionary, use <code>update</code>.</p> <pre><code>new_set.update({echo(x):True for x in s if x%2==0}) </code></pre> <p>another way to write this is with an intermediate generator:</p> <pre><code>{y:True for y in (echo(x) for x in s if x%2==0)} </code></pre> <p>Or combine the echo and filter in one generator</p> <pre><code>def even(s): for x in s: if x%2==0: print(x) yield(x) </code></pre> <p>followed by a dict comp using it:</p> <pre><code>{y:True for y in even(s)} </code></pre>
1
2016-08-16T22:49:46Z
[ "python", "functional-programming", "fluent" ]
Filter list of tuples for tuples that contain certain items python
38,984,419
<p>I have a list of tuples like so:</p> <pre><code>a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w'), ('1', '5', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p>I want to be able to filter out the tuples that contain certain items. For example, I want to find all the tuples that contain <code>'5', '5', 'w', 'w', 'w', 'w'</code> specifically and place them in a list. </p> <pre><code>filter_for = ['5', '5', 'w', 'w', 'w', 'w'] </code></pre> <p>Expected result would be:</p> <pre><code>result = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p><code>filter_for</code> will have a varying length of 1 to 7 so I using <code>and</code> is not going to be ideal. </p> <p>I've tried using</p> <pre><code>[i for i in a if all(j in filtered_for for j in a)] </code></pre> <p>but that doesn't work.</p> <p>EDIT: If <code>('1', '5', '5', '5', 'w', 'w', 'w', 'w')</code> was also in the list I wouldn't want that tuple to be found. I guess I didn't specify this as all working solutions below would return this tuple as well.</p>
0
2016-08-16T21:01:52Z
38,984,624
<p>Did you mean this</p> <pre><code>[i for i in a if all([j in i for j in filter_for])] </code></pre> <p>instead of your line?</p> <pre><code>[i for i in a if all(j in filter_for for j in a)] </code></pre>
0
2016-08-16T21:16:53Z
[ "python", "list", "tuples" ]
Filter list of tuples for tuples that contain certain items python
38,984,419
<p>I have a list of tuples like so:</p> <pre><code>a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w'), ('1', '5', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p>I want to be able to filter out the tuples that contain certain items. For example, I want to find all the tuples that contain <code>'5', '5', 'w', 'w', 'w', 'w'</code> specifically and place them in a list. </p> <pre><code>filter_for = ['5', '5', 'w', 'w', 'w', 'w'] </code></pre> <p>Expected result would be:</p> <pre><code>result = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p><code>filter_for</code> will have a varying length of 1 to 7 so I using <code>and</code> is not going to be ideal. </p> <p>I've tried using</p> <pre><code>[i for i in a if all(j in filtered_for for j in a)] </code></pre> <p>but that doesn't work.</p> <p>EDIT: If <code>('1', '5', '5', '5', 'w', 'w', 'w', 'w')</code> was also in the list I wouldn't want that tuple to be found. I guess I didn't specify this as all working solutions below would return this tuple as well.</p>
0
2016-08-16T21:01:52Z
38,984,702
<p>This code seems to work, it tests every list by dividing them in several lists of the same length as <code>filter_for</code></p> <p><strong>Edit</strong>: I tried to add some excluded patterns after your edit</p> <pre><code>a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w'), ('1', '5', '5', '5', 'w', 'w', 'w', 'w')] filter_for = ['5', '5', 'w', 'w', 'w', 'w'] excluded = [('1', '5', '5', '5', 'w', 'w', 'w', 'w')] # add a padding key to excluded patterns for x in range(len(excluded)): value = excluded[x] excl = {'value': value} for i in range(len(value) - len(filter_for) + 1): if list(value[i:i+len(filter_for)]) == list(filter_for): excl['padding'] = (i, len(value) - i - len(filter_for)) excluded[x] = excl def isexcluded(lst, i): # check if the lst is excluded by one of the `excluded` lists for excl in excluded: start_padding, end_padding = excl['padding'] # get start and end indexes start = max(i-start_padding, 0) end = min(i + len(excl['value']) + end_padding, len(lst)) if list(lst[start:end]) == list(excl['value']): return True return False def get_lists(lists, length, excluded): for lst in lists: # get all the 'sublist', parts of the list that are of the same # length as filter_for for i in range(len(lst)-length+1): tests = [list(lst[i:i+length]) == list(filter_for), not isexcluded(lst, i)] if all(tests): yield lst result = list(get_lists(a, len(filter_for), excluded)) print(result) # python 2: print result </code></pre>
-1
2016-08-16T21:22:24Z
[ "python", "list", "tuples" ]
Filter list of tuples for tuples that contain certain items python
38,984,419
<p>I have a list of tuples like so:</p> <pre><code>a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w'), ('1', '5', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p>I want to be able to filter out the tuples that contain certain items. For example, I want to find all the tuples that contain <code>'5', '5', 'w', 'w', 'w', 'w'</code> specifically and place them in a list. </p> <pre><code>filter_for = ['5', '5', 'w', 'w', 'w', 'w'] </code></pre> <p>Expected result would be:</p> <pre><code>result = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p><code>filter_for</code> will have a varying length of 1 to 7 so I using <code>and</code> is not going to be ideal. </p> <p>I've tried using</p> <pre><code>[i for i in a if all(j in filtered_for for j in a)] </code></pre> <p>but that doesn't work.</p> <p>EDIT: If <code>('1', '5', '5', '5', 'w', 'w', 'w', 'w')</code> was also in the list I wouldn't want that tuple to be found. I guess I didn't specify this as all working solutions below would return this tuple as well.</p>
0
2016-08-16T21:01:52Z
38,984,739
<p>If I understand your requirements correctly, this should return the expected results. Here we convert the lists to strings, and use <a href="https://docs.python.org/3/reference/expressions.html#membership-test-details" rel="nofollow"><code>in</code></a> to check for membership.</p> <pre><code>&gt;&gt;&gt; a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w')] &gt;&gt;&gt; filter_for = ''.join(['5', '5', 'w', 'w', 'w', 'w']) &gt;&gt;&gt; print [tup for tup in a if filter_for in ''.join(tup)] [('1','2','5','5','w','w','w','w'), ('1','3','5','5','w','w','w','w')] </code></pre> <hr> <p>The below code has been updated to match <strong>exact</strong> sub-lists in the list of tuples. Instead of <em>pattern matching</em> like in the example above, we take a far different approach here. </p> <p>We start off by finding the <code>head</code> and <code>tail</code> of the filter list. We then find the the indices of where the <code>head</code> and <code>tail</code> occur in <code>tup</code> (<em>we must reverse</em> <code>tup</code> <em>to find the</em> <code>tail_index</code><em>, as</em> <code>index</code> <em>returns only the <strong>first</strong> element matched</em>). Using our indices pair, we can then slice that sublist spanning the distance between <code>head</code> and <code>tail</code>. If this sublist <strong>matches</strong> the filter, then we know that <em>only</em> that range exists in the search tuple.</p> <pre><code>def match_list(filter_list, l): results = [] filter_for = tuple(filter_list) head = filter_for[0] tail = filter_for[-1] for tup in l: reverse_tup = tup[::-1] if head and tail in tup: try: head_index = tup.index(head) index_key = reverse_tup.index(tail) tail_index = -index_key if index_key else None if tup[head_index:tail_index] == filter_for: results.append(tup) # Prints out condition-satisfied tuples. except ValueError: continue return results </code></pre> <p><strong>Sample output</strong></p> <pre><code> &gt;&gt;&gt; a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w'), ('1', '5', '5', '5', 'w', 'w', 'w', 'w')] # &lt;- Does not match! &gt;&gt;&gt; filter_for = ['5', '5', 'w', 'w', 'w', 'w'] &gt;&gt;&gt; print match_list(filter_for, a) [('1','2','5','5','w','w','w','w'), ('1','3','5','5','w','w','w','w')] </code></pre>
2
2016-08-16T21:26:09Z
[ "python", "list", "tuples" ]
Filter list of tuples for tuples that contain certain items python
38,984,419
<p>I have a list of tuples like so:</p> <pre><code>a = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '4', '5', 'w', 'w', 'w', 'w'), ('1', '4', '4', '4', 'w', 'w', 'w', 'w'), ('1', '5', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p>I want to be able to filter out the tuples that contain certain items. For example, I want to find all the tuples that contain <code>'5', '5', 'w', 'w', 'w', 'w'</code> specifically and place them in a list. </p> <pre><code>filter_for = ['5', '5', 'w', 'w', 'w', 'w'] </code></pre> <p>Expected result would be:</p> <pre><code>result = [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w')] </code></pre> <p><code>filter_for</code> will have a varying length of 1 to 7 so I using <code>and</code> is not going to be ideal. </p> <p>I've tried using</p> <pre><code>[i for i in a if all(j in filtered_for for j in a)] </code></pre> <p>but that doesn't work.</p> <p>EDIT: If <code>('1', '5', '5', '5', 'w', 'w', 'w', 'w')</code> was also in the list I wouldn't want that tuple to be found. I guess I didn't specify this as all working solutions below would return this tuple as well.</p>
0
2016-08-16T21:01:52Z
38,984,803
<p>I'm not sure If I get the point what you're trying. But I would do it as following:</p> <pre><code>&gt;&gt;&gt;[i for i in a if "".join(filter_for) in "".join(i)] [('1', '2', '5', '5', 'w', 'w', 'w', 'w'), ('1', '3', '5', '5', 'w', 'w', 'w', 'w')] </code></pre>
2
2016-08-16T21:30:32Z
[ "python", "list", "tuples" ]
How to verify that at least one of several fields in a model are not blank
38,984,465
<p>I have a model:</p> <pre><code>class Artwork(models.Model): title = models.CharField(max_length=50) description = models.TextField(null=True, blank=True) image_file = models.ImageField(upload_to='portfolios/image/%Y/%m', null=True, blank=True) video_file = models.FileField(upload_to='portfolios/video/%Y/%m', null=True, blank=True) video_url = models.URLField(blank=True, null=True) </code></pre> <p>When a user edits one of these objects, how can I verify the at least one of these three fields is provided with data: <code>image_file</code>, <code>video_file</code>, or <code>video_url</code> so that the verification message appears in the form by the field, similar to what happens automatically if you set <code>blank=False</code> and leave it blank?</p>
1
2016-08-16T21:04:27Z
38,984,646
<p>You need to overwrite the form's <code>clean</code> method and assign an error message to a field. Here's an example where all three fields get an error message if they are all blank, adapted from the <a href="https://docs.djangoproject.com/en/1.10/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other" rel="nofollow">Django docs</a>:</p> <pre><code>from django import forms class ArtworkForm(forms.Form): def clean(self): cleaned_data = super(ArtWorkForm, self).clean() image_file = cleaned_data.get("image_file") video_file = cleaned_data.get("video_file") video_url = cleaned_data.get("video_url") if not (image_file or video_file or video_url): msg = "your error message." self.add_error('image_file', msg) self.add_error('video_file', msg) self.add_error('video_url', msg) </code></pre>
2
2016-08-16T21:18:21Z
[ "python", "django", "forms" ]
How to specify postgres table columns as variables in python?
38,984,495
<p>So I have a table that is being updated with new columns every time a new instance of a class is being instantiated. Here's my code doing that.</p> <pre><code>query = "alter table test add column %s integer" rows = (str(Driver.count), str(Driver.count+1)) for c in rows: cur.execute(query, (AsIs(c),)) conn.commit() </code></pre> <p>Driver.count is the counter that is being incremented every new instance of the class. Now when I want to update the table, I use a command similar to this:</p> <pre><code>cur.execute("INSERT INTO test (str(Driver.count), str(Driver.count+1)) \ VALUES (%d, %d)" % (currentRow,currentCol)); </code></pre> <p>Where the two columns I am specifying are variables. I know the above command won't work, since the column variables somehow need to be outside of the quotations, like when I specify the values to be inserted. How can I do this?</p>
2
2016-08-16T21:06:19Z
38,984,537
<pre><code>cur.execute('INSERT INTO test ("%d", "%d") VALUES (%d, %d)' % (Driver.count, Driver.count+1, currentRow, currentCol)) </code></pre> <p>Or using newer syntax:</p> <pre><code>cur.execute('INSERT INTO test ("{}", "{}") VALUES ({}, {})'.format( Driver.count, Driver.count+1, currentRow, currentCol)) </code></pre>
2
2016-08-16T21:08:58Z
[ "python", "postgresql", "class" ]
Create property with no implemented setter
38,984,508
<pre><code>class Human: def __init__(self) -&gt; None: self.name = None # type: str def introduce(self): print("I'm " + self.name) class Alice(Human): def __init__(self) -&gt; None: super().__init__() self.name = "Alice" class Bob(Human): def __init__(self, rude: bool) -&gt; None: super().__init__() self.rude = rude @property def name(self) -&gt; str: return "BOB!" if self.rude else "Bob" if __name__ == '__main__': alice = Alice() alice.introduce() bob = Bob(rude=True) bob.introduce() </code></pre> <p>In the code above, there is an abstract <code>Human</code> class (in reality it is not a human and has more complex methods, not related to the problem). Most of its implementations would set their names by simply assigning a string to the <code>name</code> attribute (just as <code>Alice</code>). But there are few exceptions, like <code>Bob</code>, when there is more complex logic assigned (the value depends on the object state in the moment of resolving).</p> <p>Therefore in <code>Bob</code> class I created a custom getter for the <code>name</code> property. But as an effect, it is impossible to create a class instance, because invoking the superconstructor results in the following error.</p> <pre><code>AttributeError: can't set attribute </code></pre> <p>And it is impossible to add a naive setter as well.</p> <pre><code>@name.setter def name(self, name: str): self.name = name </code></pre> <p>Why? Because it would result in an infinite loop. How to solve that issue?</p>
0
2016-08-16T21:06:59Z
38,984,574
<p>If you're certain that your subclasses will assign <code>name</code>, then you can leave out the assignment in the parent constructor. Right now, <code>Human</code> is attempting to set to <code>name</code>, when there is no setter. If you removed it from the <code>Human</code> constructor, then <code>Human</code> can look like this:</p> <pre><code>class Human: def introduce(self): print("I'm " + self.name) </code></pre>
1
2016-08-16T21:11:53Z
[ "python", "python-3.x" ]
Create property with no implemented setter
38,984,508
<pre><code>class Human: def __init__(self) -&gt; None: self.name = None # type: str def introduce(self): print("I'm " + self.name) class Alice(Human): def __init__(self) -&gt; None: super().__init__() self.name = "Alice" class Bob(Human): def __init__(self, rude: bool) -&gt; None: super().__init__() self.rude = rude @property def name(self) -&gt; str: return "BOB!" if self.rude else "Bob" if __name__ == '__main__': alice = Alice() alice.introduce() bob = Bob(rude=True) bob.introduce() </code></pre> <p>In the code above, there is an abstract <code>Human</code> class (in reality it is not a human and has more complex methods, not related to the problem). Most of its implementations would set their names by simply assigning a string to the <code>name</code> attribute (just as <code>Alice</code>). But there are few exceptions, like <code>Bob</code>, when there is more complex logic assigned (the value depends on the object state in the moment of resolving).</p> <p>Therefore in <code>Bob</code> class I created a custom getter for the <code>name</code> property. But as an effect, it is impossible to create a class instance, because invoking the superconstructor results in the following error.</p> <pre><code>AttributeError: can't set attribute </code></pre> <p>And it is impossible to add a naive setter as well.</p> <pre><code>@name.setter def name(self, name: str): self.name = name </code></pre> <p>Why? Because it would result in an infinite loop. How to solve that issue?</p>
0
2016-08-16T21:06:59Z
38,984,808
<p>For class <code>Bob</code>I would have used something like this in this case:</p> <pre><code>@name.setter def name(self, name: str): self._name = name </code></pre> <p>Afterwards you can do whatever you want in the more complex getter with the internal value. Or did I get the question wrong?</p> <p>Executing the code would give:</p> <p><code>I'm Alice</code> <code>I'm BOB!</code></p>
1
2016-08-16T21:30:51Z
[ "python", "python-3.x" ]
Create property with no implemented setter
38,984,508
<pre><code>class Human: def __init__(self) -&gt; None: self.name = None # type: str def introduce(self): print("I'm " + self.name) class Alice(Human): def __init__(self) -&gt; None: super().__init__() self.name = "Alice" class Bob(Human): def __init__(self, rude: bool) -&gt; None: super().__init__() self.rude = rude @property def name(self) -&gt; str: return "BOB!" if self.rude else "Bob" if __name__ == '__main__': alice = Alice() alice.introduce() bob = Bob(rude=True) bob.introduce() </code></pre> <p>In the code above, there is an abstract <code>Human</code> class (in reality it is not a human and has more complex methods, not related to the problem). Most of its implementations would set their names by simply assigning a string to the <code>name</code> attribute (just as <code>Alice</code>). But there are few exceptions, like <code>Bob</code>, when there is more complex logic assigned (the value depends on the object state in the moment of resolving).</p> <p>Therefore in <code>Bob</code> class I created a custom getter for the <code>name</code> property. But as an effect, it is impossible to create a class instance, because invoking the superconstructor results in the following error.</p> <pre><code>AttributeError: can't set attribute </code></pre> <p>And it is impossible to add a naive setter as well.</p> <pre><code>@name.setter def name(self, name: str): self.name = name </code></pre> <p>Why? Because it would result in an infinite loop. How to solve that issue?</p>
0
2016-08-16T21:06:59Z
38,984,848
<p>why not make a dummy setter</p> <pre><code>@name.setter def name(self, value): pass </code></pre> <p>When <code>self.name = None</code> is executed it will call this setter and actually do nothing</p>
2
2016-08-16T21:35:12Z
[ "python", "python-3.x" ]
Tkinter unintentional recursion with menu bar command...cause?
38,984,544
<p>I'm trying to make a Python GUI using <code>tkinter</code>, and I need a menu item that opens another copy of the main window. I tried to do the following code, and when I ran the program, it froze for a bit, then opened a large number of windows. The last error message printed is below.</p> <p>I have two questions.</p> <ol> <li>How can I accomplish the task of making the "New" button open a new window and instance of the <code>TheThing</code> class? (In IDLE, <code>File &gt; New File</code> has the behavior I'm seeking.)</li> <li><p>Why is this error happening?</p> <pre class="lang-none prettyprint-override"><code>RecursionError: maximum recursion depth exceeded while calling a Python object </code></pre></li> </ol> <p>My code:</p> <pre><code>import tkinter as tk class TheThing: def __init__(self, root): root.option_add('*tearOff', False) menubar = tk.Menu(root) root.config(menu = menubar) file = tk.Menu(menubar) menubar.add_cascade(menu = file, label = "File") file.add_command(label = 'New', command = doathing()) def doathing(): thing1 = tk.Tk() thing2 = TheThing(thing1) def main(): win = tk.Tk() do = TheThing(win) win.mainloop() if __name__ == '__main__': main() </code></pre> <p>Places I've already looked for answers:</p> <ul> <li><p><a href="http://stackoverflow.com/questions/10039485/tkinter-runtimeerror-maximum-recursion-depth-exceeded">This question</a> seemed like it was having a very similar problem. I may be able to study that and find a solution, but I still won't understand the problem.</p></li> <li><p><a href="http://stackoverflow.com/questions/22955575/maximum-recursion-depth-exceeded-while-calling-a-python-object">This question</a> was about recursion, python, and tkinter, but seemed to be about more the <code>after</code> thing.</p></li> </ul>
2
2016-08-16T21:09:27Z
38,984,706
<p>The problem is in this line:</p> <pre><code> file.add_command(label = 'New', command = doathing()) </code></pre> <p>Here, you <em>execute</em> the <code>doathing</code> callback and then try to bind its result (which is <code>None</code>) to the command. In this specific case, this also leads to an infinite recursion, as the callback will create a new instance of the frame, which will again execute the callback, which will create another frame, and so on. Instead of calling the function, you have to bind the function <em>itself</em> to the command.</p> <pre><code> file.add_command(label = 'New', command = doathing) # no () </code></pre> <p>In case you need to pass parameters to that function (not the case here) you can use a <code>lambda</code>:</p> <pre><code> file.add_command(label = 'New', command = lambda: doathing(params)) </code></pre> <hr> <p>Also, instead of creating another <code>Tk</code> instance you should probably just create a <a href="http://effbot.org/tkinterbook/toplevel.htm" rel="nofollow"><code>Toplevel</code></a> instance in the callback, i.e.</p> <pre><code>def doathing(): thing1 = tk.Toplevel() thing2 = TheThing(thing1) </code></pre>
2
2016-08-16T21:22:38Z
[ "python", "recursion", "tkinter" ]
How to run createsuperuser from PyDev Django shell
38,984,559
<p>I can't figure out how to do <code>python manage.py createsuperuser</code> in my PyDev Django shell.</p> <p>I was hoping something below would work, but nothing did. I've never really used these shells before, and hope there's a way to create this superuser with a shell.</p> <pre><code>import manage python manage.py createsuperuser File "&lt;ipython-input-15-fcfe38f02d6e&gt;", line 1 python manage.py createsuperuser ^ SyntaxError: invalid syntax </code></pre> <p>I tried doing it with the Windows cmd, which led to this error:</p> <pre><code>C:\Users\Rasmus\workspace\Crowd\src&gt;python manage.py createsuperuser Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 25, in &lt;module&gt; import MySQLdb as Database ImportError: No module named 'MySQLdb' </code></pre> <p>During handling of the above exception, another exception occurred:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 327, in execute django.setup() File "C:\Anaconda3\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Anaconda3\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Anaconda3\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 662, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "C:\Users\Rasmus\workspace\Crowd\src\Cr\models.py", line 3, in &lt;module&gt; class User(models.Model): File "C:\Anaconda3\lib\site-packages\django\db\models\base.py", line 108, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Anaconda3\lib\site-packages\django\db\models\base.py", line 307, in add_to_class value.contribute_to_class(cls, name) File "C:\Anaconda3\lib\site-packages\django\db\models\options.py", line 263, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Anaconda3\lib\site-packages\django\db\__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Anaconda3\lib\site-packages\django\db\utils.py", line 212, in __getitem__ backend = load_backend(db['ENGINE']) File "C:\Anaconda3\lib\site-packages\django\db\utils.py", line 116, in load_backend return import_module('%s.base' % backend_name) File "C:\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 662, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "C:\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 28, in &lt;module&gt; raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' </code></pre> <p>Which I find weird seeing as my Django is connected to my database and that I can store and retrieve objects from the database within PyDev.</p> <p>Are there other ways to <code>createsuperuser</code> than using shell or cmd? Like doing it with a method?</p>
0
2016-08-16T21:10:43Z
38,984,728
<pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") from django.core.management import execute_from_command_line execute_from_command_line(["manage.py","createsuperuser"]) </code></pre>
1
2016-08-16T21:24:58Z
[ "python", "django" ]
How to run createsuperuser from PyDev Django shell
38,984,559
<p>I can't figure out how to do <code>python manage.py createsuperuser</code> in my PyDev Django shell.</p> <p>I was hoping something below would work, but nothing did. I've never really used these shells before, and hope there's a way to create this superuser with a shell.</p> <pre><code>import manage python manage.py createsuperuser File "&lt;ipython-input-15-fcfe38f02d6e&gt;", line 1 python manage.py createsuperuser ^ SyntaxError: invalid syntax </code></pre> <p>I tried doing it with the Windows cmd, which led to this error:</p> <pre><code>C:\Users\Rasmus\workspace\Crowd\src&gt;python manage.py createsuperuser Traceback (most recent call last): File "C:\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 25, in &lt;module&gt; import MySQLdb as Database ImportError: No module named 'MySQLdb' </code></pre> <p>During handling of the above exception, another exception occurred:</p> <pre><code>Traceback (most recent call last): File "manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 327, in execute django.setup() File "C:\Anaconda3\lib\site-packages\django\__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Anaconda3\lib\site-packages\django\apps\registry.py", line 108, in populate app_config.import_models(all_models) File "C:\Anaconda3\lib\site-packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "C:\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 662, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "C:\Users\Rasmus\workspace\Crowd\src\Cr\models.py", line 3, in &lt;module&gt; class User(models.Model): File "C:\Anaconda3\lib\site-packages\django\db\models\base.py", line 108, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "C:\Anaconda3\lib\site-packages\django\db\models\base.py", line 307, in add_to_class value.contribute_to_class(cls, name) File "C:\Anaconda3\lib\site-packages\django\db\models\options.py", line 263, in contribute_to_class self.db_table = truncate_name(self.db_table, connection.ops.max_name_length()) File "C:\Anaconda3\lib\site-packages\django\db\__init__.py", line 36, in __getattr__ return getattr(connections[DEFAULT_DB_ALIAS], item) File "C:\Anaconda3\lib\site-packages\django\db\utils.py", line 212, in __getitem__ backend = load_backend(db['ENGINE']) File "C:\Anaconda3\lib\site-packages\django\db\utils.py", line 116, in load_backend return import_module('%s.base' % backend_name) File "C:\Anaconda3\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 662, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "C:\Anaconda3\lib\site-packages\django\db\backends\mysql\base.py", line 28, in &lt;module&gt; raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb' </code></pre> <p>Which I find weird seeing as my Django is connected to my database and that I can store and retrieve objects from the database within PyDev.</p> <p>Are there other ways to <code>createsuperuser</code> than using shell or cmd? Like doing it with a method?</p>
0
2016-08-16T21:10:43Z
38,984,761
<p>Based on the error information "loading MySQLdb module: No module named 'MySQLdb'", you need to install <a href="https://pypi.python.org/pypi/MySQL-python/1.2.5" rel="nofollow">MySQL-python</a></p>
1
2016-08-16T21:27:38Z
[ "python", "django" ]
Concatenating Strings: str + str or "{:s}{:s}".format()?
38,984,644
<p>Is there any difference between </p> <pre><code>str_ = "foo" + "bar" </code></pre> <p>and </p> <pre><code>str_ = "{:s}{:s}".format("foo","bar") </code></pre> <p>or is it simply preference?</p>
-1
2016-08-16T21:18:20Z
38,984,805
<p><em>Semantically?</em> No, both end up joining <code>"foo"</code> and <code>"bar"</code> and assigning them to <code>str</code>.</p> <p><em>Computationally?</em> Surely, Python will create the literal for <code>"foobar"</code> during compilation, the <code>str = "foo" + "bar"</code> assignment will be faster.</p> <p><em>From a readability aspect?</em> Again, <code>str = "foo" + "bar"</code> is surely more clear and concise.</p> <hr> <p>The common errata in both your examples is that you're assigning to <code>str</code> which is a built-in name, so don't, you mask it.</p>
2
2016-08-16T21:30:39Z
[ "python", "string", "python-3.x" ]
Concatenating Strings: str + str or "{:s}{:s}".format()?
38,984,644
<p>Is there any difference between </p> <pre><code>str_ = "foo" + "bar" </code></pre> <p>and </p> <pre><code>str_ = "{:s}{:s}".format("foo","bar") </code></pre> <p>or is it simply preference?</p>
-1
2016-08-16T21:18:20Z
38,984,943
<p>To complete @Jim explanation, here's a little benchmark showing a comparison between both methods:</p> <pre><code># measure execution time import timeit def f1(num_iterations): for i in range(num_iterations): value = "foo" + "bar" def f2(num_iterations): for i in range(num_iterations): value = "{:s}{:s}".format("foo", "bar") N = 100000000 print timeit.timeit('f1(N)', setup='from __main__ import f1, N', number=1) print timeit.timeit('f2(N)', setup='from __main__ import f2, N', number=1) </code></pre> <p>The results in my laptop gives: f1=4.49492255239s and f2=47.5562411453s</p> <p>So the conclusion is using format when N is big will be much slower than using the simpler str concatenation version.</p>
1
2016-08-16T21:42:57Z
[ "python", "string", "python-3.x" ]
Concatenating Strings: str + str or "{:s}{:s}".format()?
38,984,644
<p>Is there any difference between </p> <pre><code>str_ = "foo" + "bar" </code></pre> <p>and </p> <pre><code>str_ = "{:s}{:s}".format("foo","bar") </code></pre> <p>or is it simply preference?</p>
-1
2016-08-16T21:18:20Z
38,985,024
<p>Regards Jim answer, using <code>+</code> operator with many strings, can be slow. </p> <p>Avoid doing something like this:</p> <pre><code>s = ' ' for p in parts: s += p </code></pre> <p>each <code>+=</code> operation create a new string. To avoid that, use <code>join()</code>.</p> <pre><code>' '.join(parts) </code></pre> <p>In your example, you don't need to use <code>+</code>. Simply place them adjacent to each other with no +. </p> <pre><code>string = 'foo' 'bar' print(string) &gt;"foobar" </code></pre>
0
2016-08-16T21:49:52Z
[ "python", "string", "python-3.x" ]
Concatenating Strings: str + str or "{:s}{:s}".format()?
38,984,644
<p>Is there any difference between </p> <pre><code>str_ = "foo" + "bar" </code></pre> <p>and </p> <pre><code>str_ = "{:s}{:s}".format("foo","bar") </code></pre> <p>or is it simply preference?</p>
-1
2016-08-16T21:18:20Z
38,985,144
<p>If you want to see the actual difference:</p> <pre><code>import dis def concat(): return 'foo' + 'bar' def format(): return '{}{}'.format('foo', 'bar') dis.dis(concat) print('*'*80) dis.dis(format) </code></pre>
2
2016-08-16T21:58:57Z
[ "python", "string", "python-3.x" ]
Lookahead to get values within quotes
38,984,648
<p>Without doing a python <code>split</code>, what would be the regex to get the following:</p> <pre><code>s = '[@Country="US"][@Language="ES"]' ["US", "ES"] </code></pre> <p>The current one I am using doesn't stop before the second quotation and bracket, <code>"]</code>:</p> <pre><code>re.findall(r'=\"(.+)?\"\]', s) </code></pre> <p>What would be the correct regex here?</p>
0
2016-08-16T21:18:30Z
38,984,668
<p>You just need a negated character class:</p> <pre><code>="([^"]+)" </code></pre> <p>See the <a href="https://regex101.com/r/rA3jC4/2" rel="nofollow">regex demo</a></p> <p><strong>Details</strong>:</p> <ul> <li><code>="</code> - a literal <code>="</code> text</li> <li><code>([^"]+)</code> - Group 1 (this will be returned by <code>re.findall</code>) 1 or more characters other than <code>"</code></li> <li><code>"</code> - a double quote.</li> </ul> <p><strong>NOTE</strong>: if there are only uppercase ASCII letters inside, you may make the pattern more precise with <code>="([A-Z]+)"</code>.</p> <p><a href="http://ideone.com/vqlM3E" rel="nofollow">Python demo</a>:</p> <pre><code>import re p = re.compile(r'="([^"]+)"') s = '[@Country="US"][@Language="ES"]' print(p.findall(s)) # =&gt; ['US', 'ES'] </code></pre>
2
2016-08-16T21:19:58Z
[ "python", "regex" ]
Lookahead to get values within quotes
38,984,648
<p>Without doing a python <code>split</code>, what would be the regex to get the following:</p> <pre><code>s = '[@Country="US"][@Language="ES"]' ["US", "ES"] </code></pre> <p>The current one I am using doesn't stop before the second quotation and bracket, <code>"]</code>:</p> <pre><code>re.findall(r'=\"(.+)?\"\]', s) </code></pre> <p>What would be the correct regex here?</p>
0
2016-08-16T21:18:30Z
38,984,671
<p>Regular expressions are greedy: means that the regex matches the biggest string possible matching your regex since you accept any character before the closing bracket. If you accept any character BUT the closing bracket it works as you wanted.</p> <pre><code>re.findall(r'=\"([^\]]+)?\"\]', s) </code></pre> <p>or activate the non-greedy mode or regex with <code>+?</code>. Matches as soon as closing bracket is found.</p> <pre><code>re.findall(r'=\"(.+?)?\"\]', s) </code></pre>
1
2016-08-16T21:20:04Z
[ "python", "regex" ]
Lookahead to get values within quotes
38,984,648
<p>Without doing a python <code>split</code>, what would be the regex to get the following:</p> <pre><code>s = '[@Country="US"][@Language="ES"]' ["US", "ES"] </code></pre> <p>The current one I am using doesn't stop before the second quotation and bracket, <code>"]</code>:</p> <pre><code>re.findall(r'=\"(.+)?\"\]', s) </code></pre> <p>What would be the correct regex here?</p>
0
2016-08-16T21:18:30Z
38,984,696
<p>Your regex was almost right, try this one:</p> <pre><code>re.findall(r'=\"(.+?)\"\]', s) </code></pre> <p>? Should be inside the parenthesis</p>
1
2016-08-16T21:22:12Z
[ "python", "regex" ]
Lookahead to get values within quotes
38,984,648
<p>Without doing a python <code>split</code>, what would be the regex to get the following:</p> <pre><code>s = '[@Country="US"][@Language="ES"]' ["US", "ES"] </code></pre> <p>The current one I am using doesn't stop before the second quotation and bracket, <code>"]</code>:</p> <pre><code>re.findall(r'=\"(.+)?\"\]', s) </code></pre> <p>What would be the correct regex here?</p>
0
2016-08-16T21:18:30Z
38,984,810
<p>I would go with Wiktor's solution too. If you have a consistent pattern where the groups will always be enclosed in " " then something like this should do well.</p> <pre><code>import re output = [] s = '[@Country="US"][@Language="ES"]' regex = r'"([^"]+)"' value = re.findall(regex, s) output.append(value) print(output) </code></pre>
0
2016-08-16T21:31:04Z
[ "python", "regex" ]
Car class program not displaying updated speed
38,984,679
<p>I do not understand what is wrong. Here is my code:</p> <pre><code>class CarClass(object): def __init__(self,year_model,make): self.__year_model=year_model self.__make=make self.__speed=0 def accelerate(self): self.__speed+=5 def brake(self): self.__speed-=5 def get_speed(self): return self.__speed #create car1 object car1=CarClass(2013,'TATA') #updates speed of car car1.accelerate() print('The current speeed is:') car1.get_speed() car1.accelerate() car1.accelerate() print('The current speeed is:') car1.get_speed() car1.accelerate() car1.accelerate() print('The current speeed is:') car1.get_speed() car1.accelerate() car1.accelerate() print('The current speeed is:') car1.get_speed() car1.accelerate() </code></pre> <p>And here is the output of my code:</p> <pre class="lang-none prettyprint-override"><code>The current speeed is: The current speeed is: The current speeed is: The current speeed is: The current speeed is: The current speeed is: </code></pre> <p>It should be displaying the speed every time it is incremented 5 times, but it isn't displaying any speed. I have been working on this code for a while now, and yet no progress has been made.</p>
0
2016-08-16T21:20:30Z
38,984,770
<p>when you type <code>car1.get_speed()</code> in a python interpreter, you get the returned value all right, but when you are running a program, you need to print it explicitly like this for instance:</p> <pre><code>print('The current speeed is:'+str(car1.get_sp‌​eed())) </code></pre> <p>(otherwise all methods returning something other than <code>None</code> will print a lot of nonsense in the console all the time if return code were ignored)</p>
1
2016-08-16T21:28:13Z
[ "python", "class" ]
Car class program not displaying updated speed
38,984,679
<p>I do not understand what is wrong. Here is my code:</p> <pre><code>class CarClass(object): def __init__(self,year_model,make): self.__year_model=year_model self.__make=make self.__speed=0 def accelerate(self): self.__speed+=5 def brake(self): self.__speed-=5 def get_speed(self): return self.__speed #create car1 object car1=CarClass(2013,'TATA') #updates speed of car car1.accelerate() print('The current speeed is:') car1.get_speed() car1.accelerate() car1.accelerate() print('The current speeed is:') car1.get_speed() car1.accelerate() car1.accelerate() print('The current speeed is:') car1.get_speed() car1.accelerate() car1.accelerate() print('The current speeed is:') car1.get_speed() car1.accelerate() </code></pre> <p>And here is the output of my code:</p> <pre class="lang-none prettyprint-override"><code>The current speeed is: The current speeed is: The current speeed is: The current speeed is: The current speeed is: The current speeed is: </code></pre> <p>It should be displaying the speed every time it is incremented 5 times, but it isn't displaying any speed. I have been working on this code for a while now, and yet no progress has been made.</p>
0
2016-08-16T21:20:30Z
38,984,823
<p>Here's a working example of your code:</p> <pre><code>class CarClass(object): def __init__(self, year_model, make): self.__year_model = year_model self.__make = make self.__speed = 0 def accelerate(self): self.__speed += 5 def brake(self): self.__speed -= 5 def get_speed(self): return self.__speed # create car1 object car1 = CarClass(2013, 'TATA') # updates speed of car for i in range(4): car1.accelerate() print('The current speeed is: {0}'.format(car1.get_speed())) car1.accelerate() </code></pre> <p>As you can see, now it's printing the car's speed after the acceleration, you forgot to print it. Also, try to avoid <a href="https://en.wikipedia.org/wiki/Copy_and_paste_programming" rel="nofollow">copy &amp; paste</a> of code blocks, that's an antipattern.</p>
1
2016-08-16T21:32:15Z
[ "python", "class" ]
Not writing to log file when using pywinauto
38,984,783
<p>I am trying to automate some Windows action using <a href="https://pywinauto.github.io/" rel="nofollow">pywinauto</a>, but when I <code>import pywinauto</code>, logging to the log file stops working.</p> <p>Before importing - the code is writing the log the file, as in the following example:</p> <pre><code>import logging logging.basicConfig(filename='log.txt', filemode='a', level=logging.DEBUG, format="%(message)s",) logging.info("Test") ..... </code></pre> <p>After importing - the code is <strong>NOT</strong> writing the log the file, as in the following example:</p> <pre><code>import logging from pywinauto import application logging.basicConfig(filename='log.txt', filemode='a', level=logging.DEBUG, format="%(message)s",) logging.info("Test") ..... </code></pre>
1
2016-08-16T21:29:16Z
38,984,784
<p>Turns out that <code>pywinauto</code> has its own usage of <code>logging</code> module.</p> <p>In <a href="https://github.com/pywinauto/pywinauto/blob/master/pywinauto/actionlogger.py#L88" rel="nofollow"><code>pywinauto/actionlogger.py</code></a>, the codes sets the logging level to <code>WARNING</code>, which disables writing of log messages under <code>WARNING</code> level (<code>INFO</code>, <code>DEBUG</code> and <code>NOTSET</code> levels) to the log file.</p> <p>I have found a workaround to continue working with both <code>pywinauto</code> and <code>logging</code> - just importing <code>pywinauto</code> <strong>after</strong> the basic configuration of <code>logging</code>, instead of in the beginning:</p> <pre><code>import logging logging.basicConfig(filename='log.txt', filemode='a', level=logging.DEBUG, format="%(message)s",) from pywinauto import application logging.info("Test") ..... </code></pre> <p>This example works well - writes "Test" to the log file.</p>
2
2016-08-16T21:29:16Z
[ "python", "logging", "pywinauto", "pywin" ]
NetMQ Extended Request-Reply using c# and python
38,984,895
<p>I am able to have c# (client) and python (server) talk to each other by using a simple request-reply. However, I want my web application built on c# asp.net to be stable and need more clients and servers, so I tried connecting c# and python using the Extended REQ-REP connection.</p> <p>But when I run the code below, it does not do its job as a broker and outputs nothing. What am I doing wrong here?</p> <p>5600 = c# client</p> <p>5601 = python server</p> <pre><code>using (var frontend = new RouterSocket("@tcp://127.0.0.1:5600")) using (var backend = new DealerSocket("@tcp://127.0.0.1:5601")) { // Handler for messages coming in to the frontend frontend.ReceiveReady += (s, p) =&gt; { var msg = p.Socket.ReceiveFrameString(); backend.SendFrame(msg); // Relay this message to the backend }; // Handler for messages coming in to the backend backend.ReceiveReady += (s, p) =&gt; { var msg = p.Socket.ReceiveFrameString(); frontend.SendFrame(msg); // Relay this message to the frontend }; using (var poller = new NetMQPoller { backend, frontend }) { // Listen out for events on both sockets and raise events when messages come in poller.Run(); } } </code></pre>
0
2016-08-16T21:39:06Z
38,993,188
<p>You are not sending the all message frames with the correct flags.</p> <p>You can try and user Proxy of netmq that does exactly that. If you still want to write it by hand take a look how the proxy do it with the correct frames flags here:</p> <p><a href="https://github.com/zeromq/netmq/blob/master/src/NetMQ/Proxy.cs" rel="nofollow">https://github.com/zeromq/netmq/blob/master/src/NetMQ/Proxy.cs</a></p> <p>Update:</p> <p>Following is an example on how to use the proxy in your case:</p> <pre><code>using (var frontend = new RouterSocket("@tcp://127.0.0.1:5600")) using (var backend = new DealerSocket("@tcp://127.0.0.1:5601")) { using (var poller = new NetMQPoller { backend, frontend }) { var proxy = new Proxy(frontend, backend, null, poller); proxy.Start(); proxy.Run(); } } </code></pre> <p>You can also use it without a poller:</p> <pre><code>using (var frontend = new RouterSocket("@tcp://127.0.0.1:5600")) using (var backend = new DealerSocket("@tcp://127.0.0.1:5601")) { var proxy = new Proxy(frontend, backend); proxy.Start(); } </code></pre>
0
2016-08-17T09:46:28Z
[ "c#", "python", "asp.net", "message-queue", "netmq" ]
skipping consecutive alerts
38,984,936
<p>I'm trying to formulate a logic for the following table</p> <pre><code>Hour|Alert_Flag --------------- 6 |0 7 |1 8 |1 9 |1 10 |0 11 |1 where Alert_Flag=1 means raise an alert and Alert_Flag=0 means no alert raised </code></pre> <p>What i want to accomplish here is to raise an alert at 7 since the Alert_flag is set to 1, but then not raise an alert for the subsequent hours uptil 10, since the alert was already raised for 7</p> <p>The next alert should be raised at 11, since there was a break in between.</p> <p>How can I pythonically represent this?</p> <p>I'm new to programming, would be great if anyone could help </p>
0
2016-08-16T21:42:22Z
38,985,048
<p>Here's some clues to solve it yourself:</p> <pre><code>alerts = [(6, 0), (7, 1), (8, 1), (9, 1), (10, 0), (11, 1)] clock_state = 1 for item in alerts: hour, alert_flag = item if alert_flag != clock_state: print "Clock not ringing at {0}".format(hour) else: print "Clock ringing at {0}".format(hour) clock_state = not clock_state </code></pre> <p>One little advice though, next time try to show some code you've attempted, even if it's not working, people here don't like questions with shows any effort to solve the problems.</p> <p><strong>EDIT</strong></p> <p>If you want to show only changes from 0->1, here you go:</p> <pre><code>alerts = [(6, 0), (7, 1), (8, 1), (9, 1), (10, 0), (11, 1)] len_alerts = len(alerts) for index in range(len_alerts - 1): hour1, alert_flag1 = alerts[index] hour2, alert_flag2 = alerts[index + 1] if alert_flag1 == 0 and alert_flag2 == 1: print "Clock ringing at {0}".format(hour2) </code></pre>
2
2016-08-16T21:51:09Z
[ "python", "skip" ]
skipping consecutive alerts
38,984,936
<p>I'm trying to formulate a logic for the following table</p> <pre><code>Hour|Alert_Flag --------------- 6 |0 7 |1 8 |1 9 |1 10 |0 11 |1 where Alert_Flag=1 means raise an alert and Alert_Flag=0 means no alert raised </code></pre> <p>What i want to accomplish here is to raise an alert at 7 since the Alert_flag is set to 1, but then not raise an alert for the subsequent hours uptil 10, since the alert was already raised for 7</p> <p>The next alert should be raised at 11, since there was a break in between.</p> <p>How can I pythonically represent this?</p> <p>I'm new to programming, would be great if anyone could help </p>
0
2016-08-16T21:42:22Z
38,985,052
<p>Assuming your alert flags are in a list:</p> <pre><code>for i in range(len(alert_flags)-1): if alert_flags[i] == 0 and alert_flags[i+1] == 1: # code to raise an alert </code></pre>
2
2016-08-16T21:51:46Z
[ "python", "skip" ]
skipping consecutive alerts
38,984,936
<p>I'm trying to formulate a logic for the following table</p> <pre><code>Hour|Alert_Flag --------------- 6 |0 7 |1 8 |1 9 |1 10 |0 11 |1 where Alert_Flag=1 means raise an alert and Alert_Flag=0 means no alert raised </code></pre> <p>What i want to accomplish here is to raise an alert at 7 since the Alert_flag is set to 1, but then not raise an alert for the subsequent hours uptil 10, since the alert was already raised for 7</p> <p>The next alert should be raised at 11, since there was a break in between.</p> <p>How can I pythonically represent this?</p> <p>I'm new to programming, would be great if anyone could help </p>
0
2016-08-16T21:42:22Z
38,985,178
<pre><code>from collections import OrderedDict hour_alerts = OrderedDict([ ("6", 0), ("7", 1), ("8", 1), ("9", 1), ("10", 0), ("11", 1) ]) raiseAlert = 0 for each in hour_alerts.keys(): if hour_alerts[each]== 0: raiseAlert = 1 elif (hour_alerts[each] and raiseAlert): print "alerting after break" raiseAlert = 0 </code></pre> <p>There are many ways to do this. This is just one way. Also echo @BPL comments about showing your efforts</p>
0
2016-08-16T22:01:12Z
[ "python", "skip" ]
skipping consecutive alerts
38,984,936
<p>I'm trying to formulate a logic for the following table</p> <pre><code>Hour|Alert_Flag --------------- 6 |0 7 |1 8 |1 9 |1 10 |0 11 |1 where Alert_Flag=1 means raise an alert and Alert_Flag=0 means no alert raised </code></pre> <p>What i want to accomplish here is to raise an alert at 7 since the Alert_flag is set to 1, but then not raise an alert for the subsequent hours uptil 10, since the alert was already raised for 7</p> <p>The next alert should be raised at 11, since there was a break in between.</p> <p>How can I pythonically represent this?</p> <p>I'm new to programming, would be great if anyone could help </p>
0
2016-08-16T21:42:22Z
38,985,471
<p>All you need to do is store a state of the previous alert, below is a quick example to show that, alerts only when the alert flag is set and previous seen alert flag was not set.</p> <pre><code>for i,n in enumerate(alerts): if n == 1 and (i==0 or alerts[i-1] == 0): print "Alert on",i </code></pre>
1
2016-08-16T22:28:05Z
[ "python", "skip" ]
Parsing a string and converting a date using Python
38,984,996
<p>I am trying to parse this "For The Year Ending December 31, 2015" and convert it to 2015-12-31 using the datetime lib. How would I go about partitioning and then converting the date? My program is looking through an excel file with multiple sheets and combining them into one; however, there is need now to add a date column, but I can only get it write the full value to the cell. So my data column currently has "For The Year Ending December 31, 2015" in all the rows.</p> <p>Thanks in advance!</p> <p>Here is the code block that is working now. Thanks all! edited to account for text that could vary.</p> <pre><code> if rx &gt; (options.startrow-1): ws.write(rowcount, 0, sheet.name) date_value = sheet.cell_value(4,0) s = date_value.split(" ") del s[-1] del s[-1] del s[-1] string = ' '.join(s) d = datetime.strptime(date_value, string + " %B %d, %Y") result = datetime.strftime(d, '%Y-%m-%d') ws.write(rowcount, 9, result) for cx in range(sheet.ncols): </code></pre>
-1
2016-08-16T21:47:08Z
38,985,098
<pre><code>from datetime import datetime date_string = 'For The Year Ending December 31, 2015' date_string_format = 'For The Year Ending %B %d, %Y' date_print_class = datetime.strptime(date_string, date_string_format) wanted_date = datetime.strftime(date_print_class, '%Y-%m-%d') print(wanted_date) </code></pre>
2
2016-08-16T21:55:07Z
[ "python", "parsing", "datetime" ]
Parsing a string and converting a date using Python
38,984,996
<p>I am trying to parse this "For The Year Ending December 31, 2015" and convert it to 2015-12-31 using the datetime lib. How would I go about partitioning and then converting the date? My program is looking through an excel file with multiple sheets and combining them into one; however, there is need now to add a date column, but I can only get it write the full value to the cell. So my data column currently has "For The Year Ending December 31, 2015" in all the rows.</p> <p>Thanks in advance!</p> <p>Here is the code block that is working now. Thanks all! edited to account for text that could vary.</p> <pre><code> if rx &gt; (options.startrow-1): ws.write(rowcount, 0, sheet.name) date_value = sheet.cell_value(4,0) s = date_value.split(" ") del s[-1] del s[-1] del s[-1] string = ' '.join(s) d = datetime.strptime(date_value, string + " %B %d, %Y") result = datetime.strftime(d, '%Y-%m-%d') ws.write(rowcount, 9, result) for cx in range(sheet.ncols): </code></pre>
-1
2016-08-16T21:47:08Z
38,985,120
<p>Simply include the hard-coded portion and then use the proper identifiers:</p> <pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; s = "For The Year Ending December 31, 2015" &gt;&gt;&gt; d = datetime.datetime.strptime(s, 'For The Year Ending %B %d, %Y') &gt;&gt;&gt; result = datetime.datetime.strftime(d, '%Y-%m-%d') &gt;&gt;&gt; print(result) 2015-12-31 </code></pre>
3
2016-08-16T21:56:59Z
[ "python", "parsing", "datetime" ]
How to append a tuple to a numpy array without it being preformed element-wise?
38,985,011
<p>If I try </p> <p><code>x = np.append(x, (2,3))</code></p> <p>the tuple <code>(2,3)</code> does not get appended to the end of the array, rather <code>2</code> and <code>3</code> get appended individually, even if I originally declared <code>x</code> as </p> <p><code>x = np.array([], dtype = tuple)</code> </p> <p>or </p> <p><code>x = np.array([], dtype = (int,2))</code></p> <p>What is the proper way to do this?</p>
1
2016-08-16T21:48:05Z
38,985,058
<p>If I understand what you mean, you can use <code>vstack</code>:</p> <pre><code>&gt;&gt;&gt; a = np.array([(1,2),(3,4)]) &gt;&gt;&gt; a = np.vstack((a, (4,5))) &gt;&gt;&gt; a array([[1, 2], [3, 4], [4, 5]]) </code></pre>
0
2016-08-16T21:52:05Z
[ "python", "arrays", "numpy" ]
How to append a tuple to a numpy array without it being preformed element-wise?
38,985,011
<p>If I try </p> <p><code>x = np.append(x, (2,3))</code></p> <p>the tuple <code>(2,3)</code> does not get appended to the end of the array, rather <code>2</code> and <code>3</code> get appended individually, even if I originally declared <code>x</code> as </p> <p><code>x = np.array([], dtype = tuple)</code> </p> <p>or </p> <p><code>x = np.array([], dtype = (int,2))</code></p> <p>What is the proper way to do this?</p>
1
2016-08-16T21:48:05Z
38,985,136
<p>You need to supply the shape to numpy dtype, like so:</p> <pre><code>x = np.dtype((np.int32, (1,2))) x = np.append(x,(2,3)) </code></pre> <p>Outputs</p> <pre><code>array([dtype(('&lt;i4', (2, 3))), 1, 2], dtype=object) </code></pre> <p>[Reference][1]<a href="http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.dtypes.html</a></p>
1
2016-08-16T21:58:19Z
[ "python", "arrays", "numpy" ]
How to append a tuple to a numpy array without it being preformed element-wise?
38,985,011
<p>If I try </p> <p><code>x = np.append(x, (2,3))</code></p> <p>the tuple <code>(2,3)</code> does not get appended to the end of the array, rather <code>2</code> and <code>3</code> get appended individually, even if I originally declared <code>x</code> as </p> <p><code>x = np.array([], dtype = tuple)</code> </p> <p>or </p> <p><code>x = np.array([], dtype = (int,2))</code></p> <p>What is the proper way to do this?</p>
1
2016-08-16T21:48:05Z
38,985,245
<p>I agree with @user2357112 comment:</p> <blockquote> <p>appending to NumPy arrays is catastrophically slower than appending to ordinary lists. It's an operation that they are not at all designed for</p> </blockquote> <p>Here's a little benchmark:</p> <pre><code># measure execution time import timeit import numpy as np def f1(num_iterations): x = np.dtype((np.int32, (2, 1))) for i in range(num_iterations): x = np.append(x, (i, i)) def f2(num_iterations): x = np.array([(0, 0)]) for i in range(num_iterations): x = np.vstack((x, (i, i))) def f3(num_iterations): x = [] for i in range(num_iterations): x.append((i, i)) x = np.array(x) N = 50000 print timeit.timeit('f1(N)', setup='from __main__ import f1, N', number=1) print timeit.timeit('f2(N)', setup='from __main__ import f2, N', number=1) print timeit.timeit('f3(N)', setup='from __main__ import f3, N', number=1) </code></pre> <p>I wouldn't use neither np.append nor vstack, I'd just create my python array properly and then use it to construct the np.array</p> <p><strong>EDIT</strong></p> <p>Here's the benchmark output on my laptop:</p> <ul> <li>append: 12.4983000173</li> <li>vstack: 1.60663705793</li> <li>list: 0.0252208517006</li> </ul> <p>[Finished in 14.3s]</p>
2
2016-08-16T22:07:10Z
[ "python", "arrays", "numpy" ]
How to append a tuple to a numpy array without it being preformed element-wise?
38,985,011
<p>If I try </p> <p><code>x = np.append(x, (2,3))</code></p> <p>the tuple <code>(2,3)</code> does not get appended to the end of the array, rather <code>2</code> and <code>3</code> get appended individually, even if I originally declared <code>x</code> as </p> <p><code>x = np.array([], dtype = tuple)</code> </p> <p>or </p> <p><code>x = np.array([], dtype = (int,2))</code></p> <p>What is the proper way to do this?</p>
1
2016-08-16T21:48:05Z
38,986,554
<p><code>np.append</code> is easy to use with a case like:</p> <pre><code>In [94]: np.append([1,2,3],4) Out[94]: array([1, 2, 3, 4]) </code></pre> <p>but its first example is harder to understand. It shows the same sort of flat concatenate that bothers you:</p> <pre><code>&gt;&gt;&gt; np.append([1, 2, 3], [[4, 5, 6], [7, 8, 9]]) array([1, 2, 3, 4, 5, 6, 7, 8, 9]) </code></pre> <p>Stripped of dimensional tests, <code>np.append</code> does</p> <pre><code>In [166]: np.append(np.array([1,2],int),(2,3)) Out[166]: array([1, 2, 2, 3]) In [167]: np.concatenate([np.array([1,2],int),np.array((2,3))]) Out[167]: array([1, 2, 2, 3]) </code></pre> <p>So except for the simplest cases you need to understand what <code>np.array((2,3))</code> does, and how <code>concatenate</code> handles dimensions.</p> <p>So apart from the speed issues, <code>np.append</code> can be trickier to use that the interface suggests. The parallels to list <code>append</code> are only superficial.</p> <p>As for <code>append</code> (or <code>concatenate</code>) with <code>dtype=object</code> (not <code>dtype=tuple</code>) or a compound <code>dtype</code> ('i,i'), I couldn't tell you what happens without testing. At a minimum the inputs should already be arrays, and should have a matching <code>dtype</code>. Otherwise the results can unpredicatable.</p>
0
2016-08-17T00:49:55Z
[ "python", "arrays", "numpy" ]
mpi4py only works under mpiexec
38,985,018
<p>I have set up <code>mpi4py</code> on a new server, and it isn't quite working. When I import <code>mpi4py.MPI</code>, it crashes. However, if I do the same thing under <code>mpiexec</code>, it works. On my other server and on my workstation, both techniques work fine. What am I missing on the new server?</p> <p>Here's what happens on the new server:</p> <pre><code>$ python -c 'from mpi4py import MPI; print("OK")' -------------------------------------------------------------------------- It looks like orte_init failed for some reason; your parallel process is likely to abort. There are many reasons that a parallel process can fail during orte_init; some of which are due to configuration or environment problems. This failure appears to be an internal failure; here's some additional information (which may only be relevant to an Open MPI developer): PMI2_Job_GetId failed failed --&gt; Returned value (null) (14) instead of ORTE_SUCCESS -------------------------------------------------------------------------- -------------------------------------------------------------------------- It looks like orte_init failed for some reason; your parallel process is likely to abort. There are many reasons that a parallel process can fail during orte_init; some of which are due to configuration or environment problems. This failure appears to be an internal failure; here's some additional information (which may only be relevant to an Open MPI developer): orte_ess_init failed --&gt; Returned value (null) (14) instead of ORTE_SUCCESS -------------------------------------------------------------------------- -------------------------------------------------------------------------- It looks like MPI_INIT failed for some reason; your parallel process is likely to abort. There are many reasons that a parallel process can fail during MPI_INIT; some of which are due to configuration or environment problems. This failure appears to be an internal failure; here's some additional information (which may only be relevant to an Open MPI developer): ompi_mpi_init: ompi_rte_init failed --&gt; Returned "(null)" (14) instead of "Success" (0) -------------------------------------------------------------------------- *** An error occurred in MPI_Init_thread *** on a NULL communicator *** MPI_ERRORS_ARE_FATAL (processes in this communicator will now abort, *** and potentially your MPI job) [Octomore:45430] Local abort before MPI_INIT completed successfully; not able to aggregate error messages, and not able to guarantee that all other processes were killed! </code></pre> <p>If I run it with <code>mpiexec</code>, it's fine.</p> <pre><code>$ mpiexec -np 1 python -c 'from mpi4py import MPI; print("OK")' OK </code></pre> <p>I'm running on CentOS 6.7. I've installed Python 2.7 as a software collection, and I've loaded the <code>openmpi/gnu/1.10.2</code> module. MPICH and MPICH2 are also installed, so they may be conflicting with OpenMPI. I haven't loaded the MPICH modules, though. I'm running Python in a virtualenv:</p> <pre><code>$ pip list mpi4py (2.0.0) pip (8.1.2) setuptools (18.0.1) wheel (0.24.0) </code></pre>
0
2016-08-16T21:48:57Z
39,024,769
<p>It turned out that <code>mpi4py</code> is not compatible with version 1.10.2 of OpenMPI. It works fine with version 1.6.5.</p> <pre><code>$ module load openmpi/gnu/1.6.5 $ python -c 'from mpi4py import MPI; print("OK")' OK </code></pre>
0
2016-08-18T18:03:25Z
[ "python", "mpi", "mpi4py" ]
Using class from another file in python package and conflicts in __init__()
38,985,042
<p>I'm writing a python package (python 3.6) and have the following directory structure:</p> <pre><code>package/ | __init__.py | fileA.py | fileB.py | tests/ | | __init__.py | | test_classA.py | | test_classB.py </code></pre> <h2>Setup</h2> <p>My files have the following contents:</p> <pre><code># package/fileA.py from package import ClassB def ClassA: def __init__(self): self.my_ClassB = ClassB() </code></pre> <p>-</p> <pre><code># package/fileB.py def ClassB: def __init__(self): self.foo = "bar" </code></pre> <p>-</p> <pre><code># package/tests/test_classB.py from package import ClassB # &lt;performs some unit tests here&gt; </code></pre> <p>-</p> <pre><code># package/tests/test_classA.py from package import ClassA # &lt;performs some unit tests here&gt; </code></pre> <p>-</p> <pre><code># package/__init__.py from .fileA import ClassA from .fileB import ClassB </code></pre> <h2>Circular importing</h2> <p>When I ran <code>python test_classB.py</code>, I get the following traceback error showing that I have circular import statements, which are not allowed by python. Note - the package is not literally called <code>package</code> and I have edited the Traceback to match the toy example above.</p> <pre><code>Traceback (most recent call last): File "package/tests/test_classB.py", line 2, in &lt;module&gt; from package import ClassB File "/anaconda/lib/python3.5/site-packages/package/__init__.py", line 2, in &lt;module&gt; from .fileA import ClassA File "/anaconda/lib/python3.5/site-packages/package/merparse.py", line 2, in &lt;module&gt; from package import ClassB ImportError: cannot import name 'ClassB' </code></pre> <h2>Correcting the error</h2> <p>However, when I remove those two lines in my <code>package/__init__.py</code> file:</p> <pre><code># package/__init__.py from .fileA import ClassA from .fileB import ClassB </code></pre> <p>...and I change the import method for <code>package/fileA.py</code>:</p> <pre><code># package/fileA.py from package.fileB import ClassB def ClassA: def __init__(self): self.my_ClassB = ClassB() </code></pre> <p>... <code>package/tests/test_classB.py</code> runs correctly.</p> <h2>My Question</h2> <p>My question is: How can I keep the one file: one class structure in my files and import with <code>from package import ClassA</code> instead of having to import with <code>from package.fileA import ClassA</code>?</p> <p>In my package I would like to import classes from other files, but don't know how to get around circular importing.</p> <h2>Edit: Solution</h2> <p>Thanks to @mirandak and @martin-kalcok below for their help.</p> <p>The only file that I had to edit was <code>fileA.py</code> to not refer to the package name in the import statement.</p> <pre><code># package/fileA.py from .fileB import ClassB def ClassA: def __init__(self): self.my_ClassB = ClassB() </code></pre> <p>The <code>package/__init__.py</code> file still contains import statements in case I want to import the package from other scripts in the future that I don't couple with the package.</p> <pre><code># package/__init__.py from .fileA import ClassA from .fileB import ClassB </code></pre>
1
2016-08-16T21:50:52Z
38,985,422
<p>The problem is with <code>package/fileA.py</code>. It's both a part of <code>package</code> and calling the <code>__init__.py</code> file of <code>package</code> as it's imported - creating a circular dependency.</p> <p>Can you change <code>fileA.py</code> to look like this?</p> <pre><code># package/fileA.py from .fileB import ClassB def ClassA: def __init__(self): self.my_ClassB = ClassB() </code></pre>
2
2016-08-16T22:23:25Z
[ "python", "python-3.x", "import", "package" ]
Using class from another file in python package and conflicts in __init__()
38,985,042
<p>I'm writing a python package (python 3.6) and have the following directory structure:</p> <pre><code>package/ | __init__.py | fileA.py | fileB.py | tests/ | | __init__.py | | test_classA.py | | test_classB.py </code></pre> <h2>Setup</h2> <p>My files have the following contents:</p> <pre><code># package/fileA.py from package import ClassB def ClassA: def __init__(self): self.my_ClassB = ClassB() </code></pre> <p>-</p> <pre><code># package/fileB.py def ClassB: def __init__(self): self.foo = "bar" </code></pre> <p>-</p> <pre><code># package/tests/test_classB.py from package import ClassB # &lt;performs some unit tests here&gt; </code></pre> <p>-</p> <pre><code># package/tests/test_classA.py from package import ClassA # &lt;performs some unit tests here&gt; </code></pre> <p>-</p> <pre><code># package/__init__.py from .fileA import ClassA from .fileB import ClassB </code></pre> <h2>Circular importing</h2> <p>When I ran <code>python test_classB.py</code>, I get the following traceback error showing that I have circular import statements, which are not allowed by python. Note - the package is not literally called <code>package</code> and I have edited the Traceback to match the toy example above.</p> <pre><code>Traceback (most recent call last): File "package/tests/test_classB.py", line 2, in &lt;module&gt; from package import ClassB File "/anaconda/lib/python3.5/site-packages/package/__init__.py", line 2, in &lt;module&gt; from .fileA import ClassA File "/anaconda/lib/python3.5/site-packages/package/merparse.py", line 2, in &lt;module&gt; from package import ClassB ImportError: cannot import name 'ClassB' </code></pre> <h2>Correcting the error</h2> <p>However, when I remove those two lines in my <code>package/__init__.py</code> file:</p> <pre><code># package/__init__.py from .fileA import ClassA from .fileB import ClassB </code></pre> <p>...and I change the import method for <code>package/fileA.py</code>:</p> <pre><code># package/fileA.py from package.fileB import ClassB def ClassA: def __init__(self): self.my_ClassB = ClassB() </code></pre> <p>... <code>package/tests/test_classB.py</code> runs correctly.</p> <h2>My Question</h2> <p>My question is: How can I keep the one file: one class structure in my files and import with <code>from package import ClassA</code> instead of having to import with <code>from package.fileA import ClassA</code>?</p> <p>In my package I would like to import classes from other files, but don't know how to get around circular importing.</p> <h2>Edit: Solution</h2> <p>Thanks to @mirandak and @martin-kalcok below for their help.</p> <p>The only file that I had to edit was <code>fileA.py</code> to not refer to the package name in the import statement.</p> <pre><code># package/fileA.py from .fileB import ClassB def ClassA: def __init__(self): self.my_ClassB = ClassB() </code></pre> <p>The <code>package/__init__.py</code> file still contains import statements in case I want to import the package from other scripts in the future that I don't couple with the package.</p> <pre><code># package/__init__.py from .fileA import ClassA from .fileB import ClassB </code></pre>
1
2016-08-16T21:50:52Z
38,985,526
<p>First of all, renaming your package to literary "package" really confuses this whole situation, but here's my take on it :D.<br> I don't think you are dealing with circular dependency, python just states that it cannot import <code>classB</code> from <code>package</code> and that is because there is no file named <code>classB</code> in <code>package</code> directory. Changing import statement to<br> </p> <pre><code>from package.fileB import ClassB </code></pre> <p>works because there is directory <code>package</code> which contains file <code>fileB</code> which contains object <code>ClassB</code>.<br> To answer your question whether you can import classes with statement </p> <pre class="lang-py prettyprint-override"><code>from package import ClassB </code></pre> <p>you can't, unless your <code>package</code> is file and <code>classB</code> is object inside this file. However i don't see how this different import statement would be a dealbraker<br> <strong>Side Note</strong>: Your objects <code>ClassB</code> and <code>ClassA</code> are not classes, they are functions. Python uses keyword <code>class</code> to create classes and <code>def</code> to define functions.<br> <strong>Side note 2</strong>: Are you sure your <code>__init__.py</code> file needs to hold any code at all?<br> <strong>Personal Note</strong>: I know that keeping 1 File / 1 Class structure is matter of personal preferences, it is not required in python and I myself find it much more comfortable to group multiple related classes and functions into one file</p>
2
2016-08-16T22:34:25Z
[ "python", "python-3.x", "import", "package" ]
Pandas Groupby and Sum Only One Column
38,985,053
<p>So I have a dataframe, df1, that looks like the following:</p> <pre><code> A B C 1 foo 12 California 2 foo 22 California 3 bar 8 Rhode Island 4 bar 32 Rhode Island 5 baz 15 Ohio 6 baz 26 Ohio </code></pre> <p>I want to group by column A and then sum column B while keeping the value in column C. Something like this:</p> <pre><code> A B C 1 foo 34 California 2 bar 40 Rhode Island 3 baz 41 Ohio </code></pre> <p>The issue is, when I say df.groupby('A').sum() column C gets removed returning</p> <pre><code> B A bar 40 baz 41 foo 34 </code></pre> <p>How can I get around this and keep column C when I group and sum?</p>
1
2016-08-16T21:51:54Z
38,985,129
<p>The only way to do this would be to include C in your groupby (the groupby function can accept a list).</p> <p>Give this a try:</p> <pre><code>df.groupby(['A','C'])['B'].sum() </code></pre> <p>One other thing to note, if you need to work with df after the aggregation you can also use the as_index=False option to return a dataframe object. This one gave me problems when I was first working with Pandas. Example:</p> <pre><code>df.groupby(['A','C'], as_index=False)['B'].sum() </code></pre>
1
2016-08-16T21:58:06Z
[ "python", "pandas" ]
Pandas Groupby and Sum Only One Column
38,985,053
<p>So I have a dataframe, df1, that looks like the following:</p> <pre><code> A B C 1 foo 12 California 2 foo 22 California 3 bar 8 Rhode Island 4 bar 32 Rhode Island 5 baz 15 Ohio 6 baz 26 Ohio </code></pre> <p>I want to group by column A and then sum column B while keeping the value in column C. Something like this:</p> <pre><code> A B C 1 foo 34 California 2 bar 40 Rhode Island 3 baz 41 Ohio </code></pre> <p>The issue is, when I say df.groupby('A').sum() column C gets removed returning</p> <pre><code> B A bar 40 baz 41 foo 34 </code></pre> <p>How can I get around this and keep column C when I group and sum?</p>
1
2016-08-16T21:51:54Z
38,985,197
<p>If you don't care what's in your column C and just want the <code>nth</code> value, you could just do this:</p> <pre><code>df.groupby('A').agg({'B' : 'sum', 'C' : lambda x: x.iloc[n]}) </code></pre>
0
2016-08-16T22:02:53Z
[ "python", "pandas" ]
Issue with base64 to binary conversion
38,985,112
<p>I have a base64 string and would like to write it to a file as a JPEG, using Python 3.</p> <pre><code>file = request.json['file'] prefix = 'data:' + file['filetype'] + ';base64,' full_base64 = prefix + file['base64'] # full_base64 = data:image/jpeg;base64,/9j/4AAQSkZJ.... # base 64 verified with http://codebeautify.org/base64-to-image-converter file_data = b64decode(full_base64) with open('uploads/' + str(uuid.uuid4()) + '.jpeg', 'wb') as file: file.write(file_data) </code></pre> <p>But if I try to open the file using an image viewer, I get this error:</p> <pre><code>Error interpreting JPEG image file (Not a JPEG file: starts with 0x75 0xab) </code></pre> <p>The base64 string seems to be correct (I verified it using <a href="http://codebeautify.org/base64-to-image-converter" rel="nofollow">http://codebeautify.org/base64-to-image-converter</a>), so the issue must be with <code>b64encode</code> or with writing the file.</p> <p>Thank you</p>
0
2016-08-16T21:56:19Z
38,985,584
<p>If you want to create a valid JPEG file that can be read by image viewers then you should not be prepending the data URI to the file. You still need to decode the base64 encoded image data though.</p> <pre><code>with open('uploads/' + str(uuid.uuid4()) + '.jpeg', 'wb') as f: f.write(b64decode(file['base64'])) </code></pre> <p>This will produce JPEG file that can be opened by standard image viewers.</p> <p>Also, be careful of you use as <code>file</code> as a variable name - it shadows the builtin <code>file</code>.</p> <p>If for some reason you want to create files that contain the data URI, for example to be easily inserted into HTML or CSS files, then you do not need to decode the incoming JPEG data - it's already base64 encoded:</p> <pre><code>image = request.json['file'] prefix = 'data:' + image['filetype'] + ';base64,' data_URI = prefix + image['base64'] # data_URI = data:image/jpeg;base64,/9j/4AAQSkZJ.... with open('uploads/' + str(uuid.uuid4()) + '.jpeg', 'wb') as f: f.write(data_URI) </code></pre> <p>This simply prepends the data URI prefix to the already base64 encoded data, and writes that to a file.</p>
0
2016-08-16T22:40:59Z
[ "python", "image", "python-3.x", "base64" ]
tkinter Label updating but not correctly
38,985,226
<p>Using Python 3.5. I have a <code>tkinter</code> form. The user clicks a button to import many files into a <code>Listbox</code>. Another button loops thru the files and reads and extracts data from them.</p> <p>I have a <code>Label</code> on the form that indicates the status of the loop. The status, for the most part, works as expected except that extra characters are added on the end. I'm not sure where the characters come from. I also <code>print()</code> the same content as the <code>Label</code> back to the screen and the <code>print()</code> displays exactly what it should.</p> <p>My question is why is my <code>Label</code> not displaying the correct string?</p> <p>My code, greatly shortened:</p> <pre><code>class tk_new_db: def __init__(self, master): self.master = master # sets 'root' to the instance variable 'master' self.var_text_2 = StringVar() self.var_text_2.set('STATUS: Active') self.label_6 = Label(master, textvariable=self.var_text_2, font=self.font_10) self.label_6.grid(row=15, sticky=W, padx=15) def execute_main(self): # extract data from files file_num = 0 nf = len(self.listbox_1.get(0, END)) for fr in li: file_num += 1 print('STATUS: Extracting Loads from File ' '{} in {}'.format(file_num, nf)) self.var_text_2.set('STATUS: Extracting Loads from File ' '{} in {}'.format(file_num, nf)) self.master.update_idletasks() </code></pre> <p>The <code>print()</code> is writing the following: <code>STATUS: Extracting Loads from File 1 in 5</code></p> <p>The <code>Label</code> is writing the following: <code>STATUS: Extracting Loads from File 1 in 5 nce...</code></p> <p>It always adds <code>' nce...'</code> on the Form.</p> <p>EDIT:</p> <p>I do use <code>self.var_text_2</code> earlier in the program. The <code>' nce...'</code> looks like it is a fragment of the previous string. I've since tried resetting the variable in two different ways, but I'm still getting the same result. </p> <pre><code> self.var_text_2.set('STATUS: Checking .F06 Files for Convergence...') self.master.update_idletasks() self.var_text_2.__del__() self.var_text_2.set('STATUS: Checking .F06 Files for Convergence...') self.master.update_idletasks() self.var_text_2.set('') </code></pre> <p>How do you properly delete the <code>StringVar()</code> for reuse?</p>
0
2016-08-16T22:05:28Z
38,998,662
<p>The only explanation I can think of is that you're stacking labels on top of each other in the same row and column, so when you add a long string that ends in "nce..." and later update the screen by adding a shorter label in the same grid cell, the trailing text of the longer label underneath is showing through.</p> <p>The reasons I draw this conclusion are:</p> <ol> <li>this is a common mistake I've seen several times</li> <li>there are no bugs in tkinter that would cause this</li> <li>there is nothing in the code that you've shown that could possibly add "nce..." to the end of the string</li> <li>the fact that you use <code>sticky="w"</code> rather than <code>sticky="ew"</code>, which will cause a shorter label to not completely overlay a longer label if placed in the same row and column</li> </ol>
0
2016-08-17T13:52:59Z
[ "python", "tkinter", "label" ]
tkinter Label updating but not correctly
38,985,226
<p>Using Python 3.5. I have a <code>tkinter</code> form. The user clicks a button to import many files into a <code>Listbox</code>. Another button loops thru the files and reads and extracts data from them.</p> <p>I have a <code>Label</code> on the form that indicates the status of the loop. The status, for the most part, works as expected except that extra characters are added on the end. I'm not sure where the characters come from. I also <code>print()</code> the same content as the <code>Label</code> back to the screen and the <code>print()</code> displays exactly what it should.</p> <p>My question is why is my <code>Label</code> not displaying the correct string?</p> <p>My code, greatly shortened:</p> <pre><code>class tk_new_db: def __init__(self, master): self.master = master # sets 'root' to the instance variable 'master' self.var_text_2 = StringVar() self.var_text_2.set('STATUS: Active') self.label_6 = Label(master, textvariable=self.var_text_2, font=self.font_10) self.label_6.grid(row=15, sticky=W, padx=15) def execute_main(self): # extract data from files file_num = 0 nf = len(self.listbox_1.get(0, END)) for fr in li: file_num += 1 print('STATUS: Extracting Loads from File ' '{} in {}'.format(file_num, nf)) self.var_text_2.set('STATUS: Extracting Loads from File ' '{} in {}'.format(file_num, nf)) self.master.update_idletasks() </code></pre> <p>The <code>print()</code> is writing the following: <code>STATUS: Extracting Loads from File 1 in 5</code></p> <p>The <code>Label</code> is writing the following: <code>STATUS: Extracting Loads from File 1 in 5 nce...</code></p> <p>It always adds <code>' nce...'</code> on the Form.</p> <p>EDIT:</p> <p>I do use <code>self.var_text_2</code> earlier in the program. The <code>' nce...'</code> looks like it is a fragment of the previous string. I've since tried resetting the variable in two different ways, but I'm still getting the same result. </p> <pre><code> self.var_text_2.set('STATUS: Checking .F06 Files for Convergence...') self.master.update_idletasks() self.var_text_2.__del__() self.var_text_2.set('STATUS: Checking .F06 Files for Convergence...') self.master.update_idletasks() self.var_text_2.set('') </code></pre> <p>How do you properly delete the <code>StringVar()</code> for reuse?</p>
0
2016-08-16T22:05:28Z
39,007,684
<p>I think I can explain. Root.mainloop repeatedly calls root.update. Root.update executes tasks on the 'main' event queue. In brief, it only executes idletasks when the event queue is empty <em>after</em> checking for file events (on non-Windows), window-gui events, and timer events. Idletasks, which are not well documented but seem to primarily be screen update tasks, are never added to the main event queue. It is therefore possible that idletasks will remain undone indefinitely. Root.update_idletasks exists to force execution of idletasks anyway.</p> <p>When mainloop is running, calling update within a task run by update is usually unnecessary and possibly worse. It is something only for adventurous experts. Hence the warnings you have read (which assume that you are running mainloop).</p> <p>When mainloop is not running and update is not being called repeatedly, either because you never called mainloop or because you block it with a long running loop, then you likely must call update yourself. What you seem to have discovered is that part of completely handling a StringVar update is a main event and not just an idletask.</p> <p>I sympathize with your desire to do repeated tasks with a for loop, but doing so currently means taking responsibility for event handling yourself. I hope in the future that it will be possible to have 'async for' (new in 3.5) interoperate with Tk.mainloop, but it is not as easy as I hoped.</p> <p>In the meanwhile, you could put the body of the for loop into a callback and loop with root.after. </p>
0
2016-08-17T23:22:03Z
[ "python", "tkinter", "label" ]
How to load table from SQLLite db file from PySpark?
38,985,350
<p>I am trying to load table from a SQLLite .db file stored at local disk. Is there any clean way to do this in PySpark?</p> <p>Currently, I am using a solution that works but not as elegant. First I read the table using pandas though sqlite3. One concern is that during the process schema information is not passed (may or may not be a problem). I am wondering whether there is a direct way to load the table without using Pandas. </p> <pre><code>import sqlite3 import pandas as pd db_path = 'alocalfile.db' query = 'SELECT * from ATableToLoad' conn = sqlite3.connect(db_path) a_pandas_df = pd.read_sql_query(query, conn) a_spark_df = SQLContext.createDataFrame(a_pandas_df) </code></pre> <p>There seems a way using jdbc to do this, but I have not figure out how to use it in PySpark.</p>
2
2016-08-16T22:16:54Z
39,002,270
<p>So first thing, you would need is to startup pyspark with JDBC driver jar in path Download the sqllite jdbc driver and provide the jar path in below . <a href="https://bitbucket.org/xerial/sqlite-jdbc/downloads/sqlite-jdbc-3.8.6.jar" rel="nofollow">https://bitbucket.org/xerial/sqlite-jdbc/downloads/sqlite-jdbc-3.8.6.jar</a></p> <pre><code>pyspark --conf spark.executor.extraClassPath=&lt;jdbc.jar&gt; --driver-class-path &lt;jdbc.jar&gt; --jars &lt;jdbc.jar&gt; --master &lt;master-URL&gt; </code></pre> <p>For explaination of above pyspark command, see below post</p> <p><a href="http://stackoverflow.com/questions/29821518/apache-spark-jdbc-connection-not-working">Apache Spark : JDBC connection not working</a></p> <p>Now here is how you would do it:-</p> <p>Now to read the sqlite database file, simply read it into spark dataframe</p> <pre><code>df = sqlContext.read.format('jdbc').\ options(url='jdbc:sqlite:Chinook_Sqlite.sqlite',\ dbtable='employee',driver='org.sqlite.JDBC').load() </code></pre> <p><code>df.printSchema()</code> to see your schema.</p> <p>Full Code:- <a href="https://github.com/charles2588/bluemixsparknotebooks/blob/master/Python/sqllite_jdbc_bluemix.ipynb" rel="nofollow">https://github.com/charles2588/bluemixsparknotebooks/blob/master/Python/sqllite_jdbc_bluemix.ipynb</a></p> <p>Thanks, Charles.</p>
0
2016-08-17T16:51:20Z
[ "python", "sqlite", "apache-spark", "pyspark", "data-science" ]
How to convert MySQL query result to JSON object?
38,985,363
<p>Goal is to migrate some crucial data from MySQL db to a NoSQL document based db. To make the process simpler, I assume it's best to first convert mysql query result to JSON object. Is this possible?</p>
0
2016-08-16T22:18:01Z
38,985,784
<p>Suppose your SQL query's result set <code>row</code>s contain 4 values each, you just need to give these fields names and create a dict to insert into your NoSQL databse.</p> <pre><code>fieldnames = ['field1', 'field2', 'field3', 'field4'] dict_row = dict(zip(fieldnames, row)) </code></pre>
0
2016-08-16T23:06:48Z
[ "python", "mysql", "json" ]
Why does gensim Doc2Vec give me different vectors for the same sentence?
38,985,470
<p>I am training on two identical sentences (documents) using from <code>gensim.models.doc2vec import Doc2Vec</code> and when checking out the vectors for each sentence they are completely different. Does the Neural Network have a different random initialisation per sentence?</p> <pre><code># imports from gensim.models.doc2vec import LabeledSentence from gensim.models.doc2vec import Doc2Vec from gensim import utils # Document iteration class (turns many documents in to sentences # each document being once sentence) class LabeledDocs(object): def __init__(self, sources): self.sources = sources flipped = {} # make sure that keys are unique for key, value in sources.items(): if value not in flipped: flipped[value] = [key] else: raise Exception('Non-unique prefix encountered') def __iter__(self): for source, prefix in self.sources.items(): with utils.smart_open(source) as fin: # print fin.read().strip(r"\n") yield LabeledSentence(utils.to_unicode(fin.read()).split(), [prefix]) def to_array(self): self.sentences = [] for source, prefix in self.sources.items(): with utils.smart_open(source) as fin: #print fin, fin.read() self.sentences.append( LabeledSentence(utils.to_unicode(fin.read()).split(), [prefix])) return self.sentences # play and play3 are names of identical documents (diff gives nothing) inp = LabeledDocs({"play":"play", "play3":"play3"}) model = Doc2Vec(size=20, window=8, min_count=2, workers=1, alpha=0.025, min_alpha=0.025, batch_words=1) model.build_vocab(inp.to_array()) for epoch in range(10): model.train(inp) # post to this model.docvecs["play"] is very different from # model.docvecs["play3"] </code></pre> <p>Why is this ? Both <code>play</code> and <code>play3</code> contain :</p> <pre class="lang-none prettyprint-override"><code>foot ball is a sport played with a ball where teams of 11 each try to score on different goals and play with the ball </code></pre>
1
2016-08-16T22:27:47Z
39,370,190
<p><strong>Yes</strong>, each sentence vector is initialized differently.</p> <p>In particular in the <a href="https://github.com/RaRe-Technologies/gensim/blob/develop/gensim/models/doc2vec.py#L366" rel="nofollow"><code>reset_weights</code></a> method. The code initializing the sentence vectors randomly is this:</p> <pre><code>for i in xrange(length): # construct deterministic seed from index AND model seed seed = "%d %s" % (model.seed, self.index_to_doctag(i)) self.doctag_syn0[i] = model.seeded_vector(seed) </code></pre> <p>Here you can see that each sentence vector is initialized using the random seed of the model and the tag of the sentence. Therefore it makes sense that in your example <code>play</code> and <code>play3</code> result in different vectors.</p> <p>However if you train the model properly I would expect both vectors to end up very close to each other.</p>
1
2016-09-07T12:38:05Z
[ "python", "neural-network", "gensim" ]
How to count the minimum number of possible connected components given only negative information
38,985,598
<p><strong>Preface and setup:</strong> </p> <p>Consider the following iterative clustering procedure. A user is given a set of nodes. In each iteration of the clustering process, a user marks two nodes as either matching or not matching by placing either a positive or negative edge between the two nodes. A positive edge indicates that the pair of nodes must belong to the same cluster, likewise a negative edge indicates the nodes must belong to different clusters. The current number of clusters is defined by the connected components of the graph using only the positive edges. A user is not allowed to make invalid moves (eg. place a negative edge within a positive connected component). </p> <p>At each iteration of the clustering process I want to know the maximum and minimum number of clusters that could result from the processes. The maximum number is simple: it is just the current number of positive connected components. However, the minimum was not immediately obvious. </p> <hr> <p><strong>The main problem:</strong></p> <p>My question is about computing the minimum number of clusters. Given a set of nodes, and a set of edges denoting that two nodes must belong to different clusters, what is the minimum number of clusters possible?</p> <hr> <p><strong>A possibly inelegant solution:</strong></p> <p>I believe I have an algorithm that will compute this number, but I think it can be improved (if it is correct). In my current algorithm I first condense all positive edges, such that each positive component is represented by just a single node. This allows us to just ignore positive information. </p> <p>Given only a set of nodes and negative information: 1) choose a random node. 2) find all other nodes that this node could be connected to without causing an inconsistency. 3) remove these nodes from the graph and increment the count by one. 4) iterate on the remaining nodes. 5) when no nodes remain in the graph, return the current count. </p> <p>The following python code formalizes this a bit more:</p> <pre><code> import networkx as nx def minimum_number_compoments_possible(nodes, negative_edges): """ Find minimum number of connected compoments possible Each edge represents that two nodes must be separated &gt;&gt;&gt; nodes = [1, 2, 3, 4, 5, 6, 7] &gt;&gt;&gt; negative_edges = [(1, 2), (2, 3), (4, 5)] &gt;&gt;&gt; minimum_number_compoments_possible(nodes, negative_edges) 2 """ num = 0 # Create the negative graph g_neg = nx.Graph() g_neg.add_nodes_from(nodes) g_neg.add_edges_from(negative_edges) # Initialize unused nodes to be everything unused = list(g_neg.nodes()) # complement of the graph contains all possible positive edges g_pos = nx.complement(g_neg) # Iterate until we have used all nodes while len(unused) &gt; 0: # Seed a new "minimum compoment" num += 1 # Grab a random unused node n1 n1 = unused[0] unused.remove(n1) neigbs = list(g_pos.neighbors(n1)) while len(neigbs) &gt; 0: # Find node n2, that n1 could be connected to n2 = neigbs[0] unused.remove(n2) # Collapse negative information of n1 and n2 g_neg = nx.contracted_nodes(g_neg, n1, n2) # Compute new possible positive edges g_pos = nx.complement(g_neg) # Iterate until n1 has no more possible connections neigbs = list(g_pos.neighbors(n1)) return num </code></pre> <p>The running time of this algorithm should be O(n^3) where n is the total number of edges and vertices in the graph (unless I made a mistake or the fact that nodes are condensing plays into the calculation; I'm assuming it doesn't). If this algorithm is correct, it seems like it could be improved in both runtime and simplicity, but maybe not. This is the part where I need help. </p> <hr> <p><strong>The part where I need help:</strong></p> <p>I'm wondering if there is a more elegant solution, or if this problem is a known problem and has a proper name. I initially thought that this property might have something to do with the degree of the negative graph, but I'm not seeing anything obvious. </p> <p><strong>EDIT</strong>: Some comments have brought up that this problem might be reducible to a problem in NP, in which case my algorithm is likely not correct. I'm looking into this more, but I haven't thought of a counter example yet. </p> <p><strong>EDIT2</strong>: I'm convinced that this is NP-complete and I do see the reduction to minimum clique cover. I found a counter example using the graph with edges: [(1, 8), (1, 9), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 8), (4, 9), (5, 7), (5, 8), (5, 9), (6, 7), (6, 8), (6, 9)] and randomizing the indices chosen instead of using just the first. My incorrect algorithm returns either 3 or 4. </p> <p>I guess the task now is to determine if there is a good approximation algorithm for this task. In my setting a user is much more likely to mark a pair of nodes with a positive edge, so maybe this algorithm will still usually produce the correct solution in most scenarios. </p>
0
2016-08-16T22:43:21Z
38,985,860
<blockquote> <p>I'm wondering if there is a more elegant solution</p> </blockquote> <p>Collapse positively-connected components. If there is a negative self-loop, then it's unsatisfiable. Otherwise, find a minimal coloration of the resulting graph (which only has negative edges), and you got a solution.</p> <p>The complexity is terrible (coloration…), but it seems easier to explain.</p> <p>EDIT: Actually, I'm surprised you have a O(n^3) algorithm. I think the coloration problem can be reduced to yours, symmetrically to what I have done above.</p> <hr> <blockquote> <p>if this problem is a known problem and has a proper name</p> </blockquote> <p>If you see it as an integer problem instead of a graph problem, you could call this 1-SAT modulo equality.</p> <p>“1-SAT” because it's a conjunction of atoms, and “<a href="https://en.wikipedia.org/wiki/Satisfiability_modulo_theories" rel="nofollow">modulo equality</a>” because you want to assign a number to each node according to equal/not-equal constraints.</p>
1
2016-08-16T23:13:52Z
[ "python", "algorithm", "graph", "networkx" ]
How to count the minimum number of possible connected components given only negative information
38,985,598
<p><strong>Preface and setup:</strong> </p> <p>Consider the following iterative clustering procedure. A user is given a set of nodes. In each iteration of the clustering process, a user marks two nodes as either matching or not matching by placing either a positive or negative edge between the two nodes. A positive edge indicates that the pair of nodes must belong to the same cluster, likewise a negative edge indicates the nodes must belong to different clusters. The current number of clusters is defined by the connected components of the graph using only the positive edges. A user is not allowed to make invalid moves (eg. place a negative edge within a positive connected component). </p> <p>At each iteration of the clustering process I want to know the maximum and minimum number of clusters that could result from the processes. The maximum number is simple: it is just the current number of positive connected components. However, the minimum was not immediately obvious. </p> <hr> <p><strong>The main problem:</strong></p> <p>My question is about computing the minimum number of clusters. Given a set of nodes, and a set of edges denoting that two nodes must belong to different clusters, what is the minimum number of clusters possible?</p> <hr> <p><strong>A possibly inelegant solution:</strong></p> <p>I believe I have an algorithm that will compute this number, but I think it can be improved (if it is correct). In my current algorithm I first condense all positive edges, such that each positive component is represented by just a single node. This allows us to just ignore positive information. </p> <p>Given only a set of nodes and negative information: 1) choose a random node. 2) find all other nodes that this node could be connected to without causing an inconsistency. 3) remove these nodes from the graph and increment the count by one. 4) iterate on the remaining nodes. 5) when no nodes remain in the graph, return the current count. </p> <p>The following python code formalizes this a bit more:</p> <pre><code> import networkx as nx def minimum_number_compoments_possible(nodes, negative_edges): """ Find minimum number of connected compoments possible Each edge represents that two nodes must be separated &gt;&gt;&gt; nodes = [1, 2, 3, 4, 5, 6, 7] &gt;&gt;&gt; negative_edges = [(1, 2), (2, 3), (4, 5)] &gt;&gt;&gt; minimum_number_compoments_possible(nodes, negative_edges) 2 """ num = 0 # Create the negative graph g_neg = nx.Graph() g_neg.add_nodes_from(nodes) g_neg.add_edges_from(negative_edges) # Initialize unused nodes to be everything unused = list(g_neg.nodes()) # complement of the graph contains all possible positive edges g_pos = nx.complement(g_neg) # Iterate until we have used all nodes while len(unused) &gt; 0: # Seed a new "minimum compoment" num += 1 # Grab a random unused node n1 n1 = unused[0] unused.remove(n1) neigbs = list(g_pos.neighbors(n1)) while len(neigbs) &gt; 0: # Find node n2, that n1 could be connected to n2 = neigbs[0] unused.remove(n2) # Collapse negative information of n1 and n2 g_neg = nx.contracted_nodes(g_neg, n1, n2) # Compute new possible positive edges g_pos = nx.complement(g_neg) # Iterate until n1 has no more possible connections neigbs = list(g_pos.neighbors(n1)) return num </code></pre> <p>The running time of this algorithm should be O(n^3) where n is the total number of edges and vertices in the graph (unless I made a mistake or the fact that nodes are condensing plays into the calculation; I'm assuming it doesn't). If this algorithm is correct, it seems like it could be improved in both runtime and simplicity, but maybe not. This is the part where I need help. </p> <hr> <p><strong>The part where I need help:</strong></p> <p>I'm wondering if there is a more elegant solution, or if this problem is a known problem and has a proper name. I initially thought that this property might have something to do with the degree of the negative graph, but I'm not seeing anything obvious. </p> <p><strong>EDIT</strong>: Some comments have brought up that this problem might be reducible to a problem in NP, in which case my algorithm is likely not correct. I'm looking into this more, but I haven't thought of a counter example yet. </p> <p><strong>EDIT2</strong>: I'm convinced that this is NP-complete and I do see the reduction to minimum clique cover. I found a counter example using the graph with edges: [(1, 8), (1, 9), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9), (3, 4), (3, 5), (3, 6), (3, 7), (3, 8), (3, 9), (4, 8), (4, 9), (5, 7), (5, 8), (5, 9), (6, 7), (6, 8), (6, 9)] and randomizing the indices chosen instead of using just the first. My incorrect algorithm returns either 3 or 4. </p> <p>I guess the task now is to determine if there is a good approximation algorithm for this task. In my setting a user is much more likely to mark a pair of nodes with a positive edge, so maybe this algorithm will still usually produce the correct solution in most scenarios. </p>
0
2016-08-16T22:43:21Z
38,985,996
<p>Computing the minimum number of clusters in your problem is NP complete.</p> <p>One can reduce the <a href="https://en.wikipedia.org/wiki/Clique_cover" rel="nofollow">clique cover problem</a> to it: given a graph, let the nodes be vertices of the graph, and let there be a negative edge between two nodes if and only if there is no edge between the corresponding vertices in the graph. Then finding a minimal set of clusters is equivalent to finding a minimal clique covering in the original graph.</p> <p>The reduction the other way is similar: coalesce nodes with positive edges, and construct a graph with edges between two nodes if and only if there is no negative edge in the original problem. Then finding a minimal clique covering of this graph is equivalent to finding a minimal set of clusters in the original set of nodes.</p> <p>Finding a minimal covering of a graph by cliques is one of <a href="https://en.wikipedia.org/wiki/Karp%27s_21_NP-complete_problems" rel="nofollow">Karp's 21 NP complete problems.</a></p>
1
2016-08-16T23:30:07Z
[ "python", "algorithm", "graph", "networkx" ]
CM to INCH Converting Program Python
38,985,615
<p>Hello i am trying to make a converting program but i can't get it to work, I am going to convert multiply different things but i start with CM to INCH. I get error TypeError: unsupported operand type(s) for /: 'str' and 'float'. Here is some of the code:</p> <pre><code> print('Press the number of the one you want to convert: ') number = input() inch = float(2.54) if number == '1': print('How many inch? ') print('There are %s'.format(number / inch)) Here is the whole code: print('Welcome to the converting program') print('What of these do you want to convert?') print( "\nHow many centimeters in inches? 1" "\nHow many milliliters in a pint? 2" "\nHow many acres in a square-mile? 3" "\nHow many pounds in a metric ton? 4" "\nHow many calories in a BTU? 5") print('Press the number of the one you want to convert: ') number = float(input()) inch = float(2.54) if number == '1': print('How many inch? ') print('There are {0}'.format(number / inch)) elif number == '2': print('millimeters') elif number == '3': print('acres') elif number == '4': print('pounds') elif number == '5': print('calories') </code></pre>
1
2016-08-16T22:45:41Z
38,985,699
<p>%s is the notation for formatting a string, %f should be used for floats. In newer versions of python however you should use {0}</p> <pre><code>print('There are {0}'.format(number / inch)) </code></pre> <p>Read <a href="https://www.python.org/dev/peps/pep-3101/" rel="nofollow" title="pep">PEP 3101</a> for more information on this.</p> <p>Further to this, as Sebastian Hietsch mentioned in his answer, your input variable is a string that will need to be converted to a float first. Do this before your formatting expression.</p> <pre><code>number = float(input()) inch = float(2.54) </code></pre> <p>You may want to add some error handling:</p> <pre><code>try: number = float(input()) except TypeError as e: print('input must be a float') inch = float(2.54) </code></pre> <p>Of course, you will need to remove the quotes from the '1' in the if statement.</p>
1
2016-08-16T22:55:53Z
[ "python" ]
CM to INCH Converting Program Python
38,985,615
<p>Hello i am trying to make a converting program but i can't get it to work, I am going to convert multiply different things but i start with CM to INCH. I get error TypeError: unsupported operand type(s) for /: 'str' and 'float'. Here is some of the code:</p> <pre><code> print('Press the number of the one you want to convert: ') number = input() inch = float(2.54) if number == '1': print('How many inch? ') print('There are %s'.format(number / inch)) Here is the whole code: print('Welcome to the converting program') print('What of these do you want to convert?') print( "\nHow many centimeters in inches? 1" "\nHow many milliliters in a pint? 2" "\nHow many acres in a square-mile? 3" "\nHow many pounds in a metric ton? 4" "\nHow many calories in a BTU? 5") print('Press the number of the one you want to convert: ') number = float(input()) inch = float(2.54) if number == '1': print('How many inch? ') print('There are {0}'.format(number / inch)) elif number == '2': print('millimeters') elif number == '3': print('acres') elif number == '4': print('pounds') elif number == '5': print('calories') </code></pre>
1
2016-08-16T22:45:41Z
38,985,719
<p>The problem is that <code>number</code> is a string and you can't perform mathematical operations on it. What you'll need to do is convert it to an integer or a float using <code>int(number)</code> or <code>float(number)</code>. So you could do: <code>print("There are ℅f".format(float(number)/inch))</code></p>
0
2016-08-16T22:58:37Z
[ "python" ]
How to ignore timezone when using bson.json_util.loads in python?
38,985,657
<p>I'm dumping and loading bson to text files and my datetimes are having time zone info added to them. I do not want the time zone info added.</p> <pre><code>import bson, datetime d1 = datetime.datetime.now() d2 = bson.json_util.loads(bson.json_util.dumps(d1)) </code></pre> <p>Results in d1:</p> <pre><code>datetime.datetime(2016, 8, 16, 14, 38, 41, 984544) </code></pre> <p>and d2 :</p> <pre><code>datetime.datetime(2016, 8, 16, 14, 56, 10, 155000, tzinfo=&lt;bson.tz_util.FixedOffset object at 0x1042ca050&gt;) </code></pre> <p>In this particular case I can do</p> <pre><code>d3 = d2.replace(tzinfo=None) </code></pre> <p>to remove the timezone. However, I'm doing this for a larger object with times all over the place among other types. Is there a way to instruct <code>bson.json_util.loads</code> to always set <code>tzinfo=None</code> when it tries to parse a datetime?</p>
0
2016-08-16T22:51:11Z
38,986,104
<p>Interesting. The <code>bson</code> source directly overwrites <code>object_hook</code> so you can't pass in a custom one.</p> <p>From the <a href="https://github.com/mongodb/mongo-python-driver/blob/master/bson/json_util.py" rel="nofollow">source here</a>: </p> <pre><code>def loads(s, *args, **kwargs): """Helper function that wraps :class:`json.loads`. Automatically passes the object_hook for BSON type conversion. """ kwargs['object_hook'] = lambda dct: object_hook(dct) return json.loads(s, *args, **kwargs) </code></pre> <p>Their source (inside <code>object_hook</code>) is also explicitly setting the timezone, which is causing the behavior that you're seeing:</p> <pre><code>aware = datetime.datetime.strptime( dt, "%Y-%m-%dT%H:%M:%S.%f").replace(tzinfo=utc) if not offset or offset == 'Z': # UTC return aware </code></pre> <p>I think you're going to have to do another pass over your resulting data set to remove the time zones, if you absolutely can't have a time zone set.</p> <p><strong>EDIT</strong>: It looks like there is a <a href="https://github.com/mongodb/mongo-python-driver/blob/57d1ccde2fdb7c7861b1ff0ae8f3bf325f793b42/bson/json_util.py" rel="nofollow">pending change</a> to add a <code>JsonOptions</code> class that would allow you to pass <code>tz_aware=False</code>. So if you can wait until the python driver updates to 3.4, you should be able to get your desired behavior.</p>
0
2016-08-16T23:43:15Z
[ "python", "datetime", "timezone", "pymongo", "bson" ]
XPath expression not working in scrapy spider but it is scrapy shell
38,985,665
<p>I'm working on a small project to get my head around scrapy and I've come across a problem with my xpath.</p> <p>The xpath works in the scrapy shell and the equivalent in javascript but when I put it in the spider.py file it doesn't work. Do I need to change some of the xpath in the spider.py file?</p> <p>I run the following the the scrapy shell.</p> <pre><code>scrapy shell -s USER_AGENT='Safari/537.36' 'https://www.gumtree.com/search?q=iphone+6' response.xpath('//div[@class="listing-content"]//meta[@itemprop="price"]/@content').extract() </code></pre> <p>Which correctly returns the prices. But when I put it in the spider.py file it returns nothing. The spider.py is the following:</p> <pre><code>import scrapy from phone_scraper.items import PhoneScraperItem class PhoneSpider(scrapy.Spider): """Docstring for PhoneSpider. """ name = "phone" allowed_domains = ["gumtree.com"] start_urls = [ "https://www.gumtree.com/search?q=iphone+6" ] def parse(self, response): item = PhoneScraperItem() item['price'] = response.xpath('//div[@class="listing-content"]//meta[@itemprop="price"]/@content').extract() </code></pre> <p>I then run it with the following in the terminal:</p> <pre><code>scrapy crawl phone -o items.json </code></pre> <p>To get this output in the console:</p> <pre><code>2016-08-16 23:44:35 [scrapy] INFO: Scrapy 1.1.1 started (bot: phone_scraper) 2016-08-16 23:44:35 [scrapy] INFO: Overridden settings: {'NEWSPIDER_MODULE': 'phone_scraper.spiders', 'FEED_URI': 'items.json', 'SPIDER_MODULES': ['phone_scraper.spiders'], 'BOT_NAME': 'phone_scraper', 'USER_AGENT': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36', 'FEED_FORMAT': 'json'} 2016-08-16 23:44:35 [scrapy] INFO: Enabled extensions: ['scrapy.extensions.feedexport.FeedExporter', 'scrapy.extensions.logstats.LogStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.corestats.CoreStats'] 2016-08-16 23:44:35 [scrapy] INFO: Enabled downloader middlewares: ['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware', 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware', 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware', 'scrapy.downloadermiddlewares.retry.RetryMiddleware', 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware', 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware', 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware', 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware', 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware', 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware', 'scrapy.downloadermiddlewares.stats.DownloaderStats'] 2016-08-16 23:44:35 [scrapy] INFO: Enabled spider middlewares: ['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware', 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware', 'scrapy.spidermiddlewares.referer.RefererMiddleware', 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware', 'scrapy.spidermiddlewares.depth.DepthMiddleware'] 2016-08-16 23:44:35 [scrapy] INFO: Enabled item pipelines: [] 2016-08-16 23:44:35 [scrapy] INFO: Spider opened 2016-08-16 23:44:35 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min) 2016-08-16 23:44:35 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6024 2016-08-16 23:44:35 [scrapy] DEBUG: Crawled (200) &lt;GET https://www.gumtree.com/search?q=iphone+6&gt; (referer: None) 2016-08-16 23:44:35 [scrapy] INFO: Closing spider (finished) 2016-08-16 23:44:35 [scrapy] INFO: Dumping Scrapy stats: {'downloader/request_bytes': 305, 'downloader/request_count': 1, 'downloader/request_method_count/GET': 1, 'downloader/response_bytes': 51936, 'downloader/response_count': 1, 'downloader/response_status_count/200': 1, 'finish_reason': 'finished', 'finish_time': datetime.datetime(2016, 8, 16, 22, 44, 35, 887734), 'log_count/DEBUG': 2, 'log_count/INFO': 7, 'response_received_count': 1, 'scheduler/dequeued': 1, 'scheduler/dequeued/memory': 1, 'scheduler/enqueued': 1, 'scheduler/enqueued/memory': 1, 'start_time': datetime.datetime(2016, 8, 16, 22, 44, 35, 407480)} 2016-08-16 23:44:35 [scrapy] INFO: Spider closed (finished) </code></pre> <hr> <p><strong>EDIT: Follow-up-question</strong></p> <p>I have a follow up question using a do loop to get the above information. I hope this is the right way to ask it. </p> <p>I have changed the parse function from above to the following and now it is not returning anything again.</p> <pre><code>def parse(self, response): for sel in response.xpath('//div[@class="listing-content"]'): item = PhoneScraperItem() item['price'] = sel.xpath('meta[@item-prop="price"]/@content').extract() yield item </code></pre> <p>Am I concatenating the XPath incorrectly?</p>
0
2016-08-16T22:52:41Z
38,985,675
<p>You forgot to <em>return the item</em> from the <code>parse()</code> callback:</p> <pre><code>def parse(self, response): item = PhoneScraperItem() item['price'] = response.xpath('//div[@class="listing-content"]//meta[@itemprop="price"]/@content').extract() return item </code></pre>
0
2016-08-16T22:53:28Z
[ "python", "xpath", "web-scraping", "scrapy" ]
django override admin works locally not on production
38,985,674
<p>I have the following directory structure in my django 10 project:</p> <pre><code>/my-project/ # project dir +app1 +templates +admin base.html 404.html 500.html </code></pre> <p>My templates attribute looks like this in settings:</p> <pre><code>TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ 'templates/', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'common.context_processors.site_info', ], }, }, ] </code></pre> <p>My custom base.html displays on my local machine. When I upload this to my production server it no longer overrides and uses the base.html file in project folder.</p> <p>I have changed around the order of apps suggested <a href="http://stackoverflow.com/questions/14823790/django-admin-template-overrides-not-working-in-production-environment">here</a> and tried printing the dirs element of the templates attribute which prints "templates/" like <a href="http://stackoverflow.com/questions/11793890/custom-django-admin-templates-not-working">here</a>.</p> <p>Does anyone know how I can get this to work on my production environment?</p>
0
2016-08-16T22:53:15Z
38,988,239
<p>You must use absolute path in your settings to avoid issues. For example:</p> <pre><code>import os PROJECT_ROOT = os.path.join(os.path.dirname(__file__), '..', '..') # depending where your settings.py live ... 'DIRS': [ os.path.join(PROJECT_ROOT, 'templates'), ], </code></pre>
1
2016-08-17T04:42:12Z
[ "python", "django", "django-templates", "django-admin", "django-settings" ]
Rewriting datetime in mysql
38,985,691
<p>I'm having some trouble modifying a sql table that contains a date.</p> <p>This is the code I'm running:</p> <pre><code>import pymysql cnx=pymysql.connect(dbstuff) cursor=cnx.cursor() cursor.execute("SELECT * FROM devices ORDER BY ip_addr,Port ASC") results=cursor.fetchall() lst = [(i,)+line[1:] for i, line in enumerate(results, 1)] values = ', '.join(map(str,lst)) query="DELETE FROM devices; INSERT INTO devices VALUES {}".format(values) query = query.replace("None","NULL") cursor.execute(query) cnx.commit() cnx.close() </code></pre> <p>If the date column in sql is NULL, this runs without a problem. If there is a date inserted into the field, I get the following error:</p> <blockquote> <p>"FUNCTION datetime.datetime does not exist."</p> </blockquote> <p>When I look at the results of the sql select query, the date column value is converted to the following:</p> <blockquote> <p>datetime.datetime(2016, 8, 16, 11, 24, 4)</p> </blockquote> <p>I assume this is a python thing and not a sql thing. I haven't been to find anyway to convert this to a format sql would understand.</p>
0
2016-08-16T22:55:06Z
38,985,779
<p>Calling the <strong>str</strong> function of the datetime.datetime object will convert it to the string format required by SQL. It is currently trying to insert a python object. Simply wrap your object like this:</p> <pre><code>dt = str(my_datetime_object) </code></pre>
0
2016-08-16T23:05:49Z
[ "python", "mysql" ]
Error while deploying django app to heroku
38,985,695
<p>I am trying to deploy a django app to heroku through github. </p> <p>I am getting the following error ImportError: No module named settings.staging</p> <p>But I have the "staging.py" file under "settings" folder.</p> <p>My github code is on :<a href="https://github.com/PramathaMadhavankutty/we_are_social" rel="nofollow">https://github.com/PramathaMadhavankutty/we_are_social</a></p> <p>folder structure:</p> <pre><code>root folder/ manage.py Procfile settings/ staging.py ... project-folder/ wsgi.py </code></pre> <hr> <p>wsgi.py</p> <pre><code>import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "we_are_social.settings") application = get_wsgi_application() </code></pre> <p>Procfile</p> <pre><code> web: gunicorn we_are_social.wsgi:application </code></pre> <p>log file</p> <pre><code>2016-08-16T21:43:22.513176+00:00 app[web.1]: self.callable = self.load() 2016-08-16T21:43:22.513176+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load 2016-08-16T21:43:22.513177+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp 2016-08-16T21:43:22.513177+00:00 app[web.1]: return util.import_app(self.app_uri) 2016-08-16T21:43:22.513178+00:00 app[web.1]: application = get_wsgi_application() 2016-08-16T21:43:22.513178+00:00 app[web.1]: File "/app/we_are_social/wsgi.py", line 17, in &lt;module&gt; 2016-08-16T21:43:22.513178+00:00 app[web.1]: __import__(module) 2016-08-16T21:43:22.513179+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application 2016-08-16T21:43:22.513179+00:00 app[web.1]: django.setup() 2016-08-16T21:43:22.513180+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2016-08-16T21:43:22.513180+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 55, in __getattr__ 2016-08-16T21:43:22.513179+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/__init__.py", line 17, in setup 2016-08-16T21:43:22.513177+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/util.py", line 357, in import_app 2016-08-16T21:43:22.513182+00:00 app[web.1]: __import__(name) 2016-08-16T21:43:22.513180+00:00 app[web.1]: self._setup(name) 2016-08-16T21:43:22.513181+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 43, in _setup 2016-08-16T21:43:22.513181+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2016-08-16T21:43:22.513181+00:00 app[web.1]: mod = importlib.import_module(self.SETTINGS_MODULE) 2016-08-16T21:43:22.513182+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/importlib/__init__.py", line 37, in import_module 2016-08-16T21:43:22.513181+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/django/conf/__init__.py", line 99, in __init__ 2016-08-16T21:43:22.536787+00:00 app[web.1]: [2016-08-16 21:43:22 +0000] [3] [INFO] Reason: Worker failed to boot. 2016-08-16T21:43:22.513356+00:00 app[web.1]: [2016-08-16 21:43:22 +0000] [10] [INFO] Worker exiting (pid: 10) 2016-08-16T21:43:22.536539+00:00 app[web.1]: [2016-08-16 21:43:22 +0000] [3] [INFO] Shutting down: Master 2016-08-16T21:43:22.513183+00:00 app[web.1]: ImportError: No module named settings.staging 2016-08-16T21:45:48.063161+00:00 heroku[run.3662]: Process exited with status 0 2016-08-16T21:45:48.038116+00:00 heroku[run.3662]: State changed from up to complete </code></pre> <p>Can someone please help me to sort this out? Thanks in advance.</p>
0
2016-08-16T22:55:33Z
38,985,742
<p>Just create an empty <code>__init__.py</code> file in your settings folder (you are missing it now). It will indicate that folder is a package and thus files from it can be imoprted</p>
2
2016-08-16T23:01:08Z
[ "python", "django", "heroku" ]
Imitating the "magic wand" photoshop tool in OpenCV
38,985,755
<p>I'm trying to isolate the sky region from a series of grayscale images in OpenCV. All of the images are fairly similar: the top of the image is always a sky region, and is always a bright, gray-white colour. I've attempted contour-based approaches, and written my own algorithm to extract the line of the horizon and divide the image into two masks accordingly. However, I've noticed that the reliability of the magic wand tool in Photoshop on this image set is MUCH more accurate.</p> <p>Here's the image that I'm processing:</p> <p><a href="http://i.stack.imgur.com/uF8SM.png" rel="nofollow"><img src="http://i.stack.imgur.com/uF8SM.png" alt="enter image description here"></a></p> <p>and the result that I hope to achieve:</p> <p><a href="http://i.stack.imgur.com/irOlf.png" rel="nofollow"><img src="http://i.stack.imgur.com/irOlf.png" alt="enter image description here"></a></p> <p>How can this be imitated in OpenCV?</p>
-2
2016-08-16T23:03:06Z
38,985,872
<p>I think what you're looking for is the <a href="http://docs.opencv.org/3.1.0/d8/d83/tutorial_py_grabcut.html#gsc.tab=0" rel="nofollow">grabcut algorithm</a></p>
2
2016-08-16T23:15:17Z
[ "python", "c++", "opencv", "image-processing", "photoshop" ]
How to register class instance count in two separate files?
38,985,796
<p>So I have a python class <code>Driver</code> which has a method <code>drive</code> which essentially runs a loop forever. I have it set up so that with every new instance of the class, a counter goes up. So if I make two separate instances of the class in 2 different files and run them one after the other, will the one that runs second register that it's a 2nd instance of the class, and the counter go up to 2? Or does this only work for instance calls in the same file?</p>
0
2016-08-16T23:08:01Z
38,985,920
<p>If you are running the files on after another with the interpreter, then the counter will reset once you run the second file, since everything from the first file being run will have exited memory. If you need data to persist between running two different files, your best bet is to write it to an external file in the first file and then read it in the second.</p>
0
2016-08-16T23:21:35Z
[ "python", "class", "instance" ]
SQL iterate over distinct values of a column and build a data frame for each value
38,985,893
<p>I have a table that looks like the following:</p> <pre><code>|A|B|C|D| |---|---|---|---| |1|b1|c1|d1| |1|b2|c2|d2| |2|b3|c3|d3| |2|b4|c4|d4| </code></pre> <p>I would like to iterate over distinct values of A and build a pandas data frame out of the remaining columns and then use that table to do calculations. I tried the following:</p> <pre><code>import sqlite3 import pandas as pd conn = sqlite3.connection('my_db.db') c = conn.cursor() for entry in c.execute("SELECT DISTINCT A in table): df = pd.DataFrame(c.execute("SELECT * FROM table WHERE A = ?", (entry[0],)).fetchall()) </code></pre> <p>This doesn't work because the second cursor object that builds the dataframe overwrites the cursor object that i was iterating over. I also discovered that you can not have two cursor objects. How should I work around this? </p>
0
2016-08-16T23:17:23Z
38,986,164
<p>Is there a particular reason you don't want to do this whole operation in pandas itself? You could simply do it like so:</p> <pre><code>parent_df = pd.read_sql(c, "SELECT * from table") for name, group in parent_df.groupby('A'): print(name, group.head()) </code></pre> <p>Or</p> <pre><code>parent_df.set_index('A', inplace=True) parent_df.head(20) </code></pre>
1
2016-08-16T23:52:50Z
[ "python", "sql", "sqlite", "python-3.x", "pandas" ]
SQL iterate over distinct values of a column and build a data frame for each value
38,985,893
<p>I have a table that looks like the following:</p> <pre><code>|A|B|C|D| |---|---|---|---| |1|b1|c1|d1| |1|b2|c2|d2| |2|b3|c3|d3| |2|b4|c4|d4| </code></pre> <p>I would like to iterate over distinct values of A and build a pandas data frame out of the remaining columns and then use that table to do calculations. I tried the following:</p> <pre><code>import sqlite3 import pandas as pd conn = sqlite3.connection('my_db.db') c = conn.cursor() for entry in c.execute("SELECT DISTINCT A in table): df = pd.DataFrame(c.execute("SELECT * FROM table WHERE A = ?", (entry[0],)).fetchall()) </code></pre> <p>This doesn't work because the second cursor object that builds the dataframe overwrites the cursor object that i was iterating over. I also discovered that you can not have two cursor objects. How should I work around this? </p>
0
2016-08-16T23:17:23Z
38,986,224
<p>Put all the data you're interested in into a DataFrame (if it's not a huge dataset) then filter the dataset. </p> <pre><code>df = pd.DataFrame(c.execute("SELECT * FROM table").fetchall()) distict_a = df['A'].unique() for a in distinct_a: df_for_this_a = df.query[df.A == a] </code></pre>
1
2016-08-17T00:01:07Z
[ "python", "sql", "sqlite", "python-3.x", "pandas" ]
SQL iterate over distinct values of a column and build a data frame for each value
38,985,893
<p>I have a table that looks like the following:</p> <pre><code>|A|B|C|D| |---|---|---|---| |1|b1|c1|d1| |1|b2|c2|d2| |2|b3|c3|d3| |2|b4|c4|d4| </code></pre> <p>I would like to iterate over distinct values of A and build a pandas data frame out of the remaining columns and then use that table to do calculations. I tried the following:</p> <pre><code>import sqlite3 import pandas as pd conn = sqlite3.connection('my_db.db') c = conn.cursor() for entry in c.execute("SELECT DISTINCT A in table): df = pd.DataFrame(c.execute("SELECT * FROM table WHERE A = ?", (entry[0],)).fetchall()) </code></pre> <p>This doesn't work because the second cursor object that builds the dataframe overwrites the cursor object that i was iterating over. I also discovered that you can not have two cursor objects. How should I work around this? </p>
0
2016-08-16T23:17:23Z
38,987,371
<p>Consider using pandas's <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql.html" rel="nofollow">read_sql</a> (with parameterization in passing the cursor value) and iteratively save each dataframe to a dictionary where the reference key is the corresponding distinct value (dict route avoids multiple dfs in your global environment):</p> <pre><code>import sqlite3 import pandas as pd conn = sqlite3.connect('my_db.db') c = conn.cursor() dfDict = {} for entry in c.execute("SELECT DISTINCT A FROM table"): strSQL = "SELECT * FROM table WHERE A = :nameofparam" dfDict[entry[0]] = pd.read_sql(strSQL, conn, params={'nameofparam': entry[0]}) c.close() conn.close() for k, v in dfDict.items(): print(k, '\n', v.head()) </code></pre>
1
2016-08-17T02:55:02Z
[ "python", "sql", "sqlite", "python-3.x", "pandas" ]
SQL iterate over distinct values of a column and build a data frame for each value
38,985,893
<p>I have a table that looks like the following:</p> <pre><code>|A|B|C|D| |---|---|---|---| |1|b1|c1|d1| |1|b2|c2|d2| |2|b3|c3|d3| |2|b4|c4|d4| </code></pre> <p>I would like to iterate over distinct values of A and build a pandas data frame out of the remaining columns and then use that table to do calculations. I tried the following:</p> <pre><code>import sqlite3 import pandas as pd conn = sqlite3.connection('my_db.db') c = conn.cursor() for entry in c.execute("SELECT DISTINCT A in table): df = pd.DataFrame(c.execute("SELECT * FROM table WHERE A = ?", (entry[0],)).fetchall()) </code></pre> <p>This doesn't work because the second cursor object that builds the dataframe overwrites the cursor object that i was iterating over. I also discovered that you can not have two cursor objects. How should I work around this? </p>
0
2016-08-16T23:17:23Z
39,028,112
<p>The end solution was to use <code>pandas.read_sql</code> with <code>chunksize</code></p> <p>I found <a href="http://stackoverflow.com/questions/18107953/how-to-create-a-large-pandas-dataframe-from-an-sql-query-without-running-out-of">this post</a> useful as well.</p> <pre><code>import sqlite3 import pandas as pd conn = sqlite3.connection('my_db.db') for df in pd.read_sql("SELECT * from table ORDER BY A ASC", conn, chunksize = 100000): group = df.groupby('A') last = group.first().tail(1).index.values[0] last_a = 0 for a, g_df in group: if (a == last_a): g_df = l_df.append(g_df) ....calculations.... if (a == last): l_df = g_df l_a = a </code></pre> <p>It is really important to have logic that ties together the groupby data frames that are split into two different chunks.</p>
0
2016-08-18T21:55:50Z
[ "python", "sql", "sqlite", "python-3.x", "pandas" ]
calculate different statistics for multi-dimensional numpy array
38,985,980
<p>There exists an <code>nd.array</code> referred to as <code>label1</code>, when printing it out, it has</p> <pre><code>[[0 0 0 ..., 0 0 0] [0 0 0 ..., 0 88 0] [0 0 0 ..., 0 0 0] ..., [0 0 1 ..., 0 0 0] [0 0 0 ..., 0 2 0] [0 0 0 ..., 0 0 0]] </code></pre> <p>Its shape is <code>(729,816)</code>. Are there any ways to know how many unique values are in this array? When running <code>print(np.where(label1==label1.max()))</code>, the result looks like this <code>(array([ 0, 0, 0, ..., 234, 234, 234]), array([450, 451, 452, ..., 433, 434, 435]))</code>, does that mean it has two arrays (or two lines) have those maximum values?</p>
1
2016-08-16T23:28:11Z
38,986,060
<ol> <li>To get the sorted unique values in your array, do <code>numpy.unique(label1)</code>.</li> <li>When called on a two-dimensional array, <code>numpy.where</code> returns two arrays which are the row and column coordinates of all matching entries. So, if <code>numpy.where</code> returns <code>(array([0]), array([1]))</code> it means that one match was found at row 0, column 1.</li> </ol> <p><strong>EDIT:</strong> If you want to extract and print the row and column coordinates from <code>numpy.where</code>, you can do it like this:</p> <pre><code>rows, cols = np.where(label1==label1.max()) for row, col in zip(rows, cols): print row, col </code></pre>
0
2016-08-16T23:37:39Z
[ "python", "numpy" ]
Creating a matrix of a certain size from a dictionary
38,986,074
<p>I am wanting to solve a systems of equations through linalg.solve(A, b) Solve a linear matrix equation, or system of linear scalar equations from scipy.org. Specifically, I have two dictionaries, dict1 and dict1, and I need to convert them to matrices in order to use the above script. </p> <pre><code> food = ['fruits', 'vegetables', 'bread', 'meat'] frequency = ['daily', 'rarely'] consumptions = {'fruits': {'daily': 6, 'rarely': 4}, 'vegetables': {'daily': 8, 'rarely': 6}, 'bread': {'daily': 2, 'rarely': 1}, 'meat': {'daily': 2, 'rarely': 1}} dict1 = {} for f in food: #type of food for j in food: dict2 = {} total = 0. for q in frequency: dict2.update({q:(consumptions.get(j).get(q)*consumptions.get(f).get(q))}) key = f+'v'+j #comparing the different foods dict1.update({key:dict2}) </code></pre> <p>This gives me:</p> <pre><code>{'breadvbread': {'daily': 4, 'rarely': 1}, 'breadvfruits': {'daily': 12, 'rarely': 4}, 'breadvmeat': {'daily': 4, 'rarely': 1}, 'breadvvegetables': {'daily': 16, 'rarely': 6}, 'fruitsvbread': {'daily': 12, 'rarely': 4}, 'fruitsvfruits': {'daily': 36, 'rarely': 16}, 'fruitsvmeat': {'daily': 12, 'rarely': 4}, 'fruitsvvegetables': {'daily': 48, 'rarely': 24}, 'meatvbread': {'daily': 4, 'rarely': 1}, 'meatvfruits': {'daily': 12, 'rarely': 4}, 'meatvmeat': {'daily': 4, 'rarely': 1}, 'meatvvegetables': {'daily': 16, 'rarely': 6}, 'vegetablesvbread': {'daily': 16, 'rarely': 6}, 'vegetablesvfruits': {'daily': 48, 'rarely': 24}, 'vegetablesvmeat': {'daily': 16, 'rarely': 6}, 'vegetablesvvegetables': {'daily': 64, 'rarely': 36}} </code></pre> <p>I would like to convert this into a 4 x 4 matrix since I am using 4 types of foods. I did not put dict2 as once I figure out how to convert to a matrix with one dictionary, I can do the other but if you need it, I can update. </p> <p>I am new to Python and wanted to play around with dictionaries and the matrix solver :) . It was easy to do it with arrays, but now I want to see how to go about if I have dictionaries.</p>
0
2016-08-16T23:39:13Z
38,986,463
<p>You can create a numpy array from the dictionary using list comprehensions:</p> <pre><code>import numpy as np A = np.array([[(consumptions[x]["daily"]*consumptions[y]["daily"], consumptions[x]["rarely"]*consumptions[y]["rarely"]) for y in food] for x in food]) </code></pre> <p>This will give you:</p> <pre><code>array([[[36, 16], [48, 24], [12, 4], [12, 4]], [[48, 24], [64, 36], [16, 6], [16, 6]], [[12, 4], [16, 6], [ 4, 1], [ 4, 1]], [[12, 4], [16, 6], [ 4, 1], [ 4, 1]]]) </code></pre> <p>This is a 4x4x2 array:</p> <pre><code>&gt; A.shape (4, 4, 2) </code></pre> <p>Then, to get a 4x4 matrix of the <code>daily</code> values and the <code>rarely</code> values separately, use numpy's advanced slicing. Unlike Python lists, numpy arrays can be sliced over multiple dimensions at once. This is done by placing a slice object (ex: 3:, 0, :) within the brackets for each dimension of the array, separated by commas. Our array, <code>A</code>, has three dimensions:</p> <pre><code>&gt; A.ndim 3 </code></pre> <p>The third dimension indicates whether a value is "daily" (0) or "rarely" (1). So to get all of the daily values, we want all of the rows (:), all of the columns (:), and only the first entry in the third dimension (0). With numpy's advanced slicing, we just separte the slice we want for each dimension with commas:</p> <pre><code>&gt; daily = A[:, :, 0] &gt; daily array([[36, 48, 12, 12], [48, 64, 16, 16], [12, 16, 4, 4], [12, 16, 4, 4]]) &gt; rarely = A[:, :, 1] &gt; rarely array([[16, 24, 4, 4], [24, 36, 6, 6], [ 4, 6, 1, 1], [ 4, 6, 1, 1]]) </code></pre> <p>If you want to make the meaning of these values more explicit, you can convert the numpy arrays to a pandas DataFrame:</p> <pre><code>&gt; import pandas as pd &gt; df = pd.DataFrame(daily, columns=food, index=food) &gt; df fruits vegetables bread meat fruits 36 48 12 12 vegetables 48 64 16 16 bread 12 16 4 4 meat 12 16 4 4 </code></pre> <p>See <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing</a> for more info on advanced slicing.</p>
2
2016-08-17T00:36:30Z
[ "python", "python-2.7", "numpy", "dictionary", "matrix" ]
pip Error: bad interpreter: No such file or directory
38,986,075
<p>Here's a sample from my console:</p> <pre><code>Ryans-MacBook-Pro:~ Ryan$ pip -bash: /Library/Frameworks/Python.framework/Versions/3.5/bin/pip: /Library/Frameworks/Python.framework/Versions/3.5/bin/python: bad interpreter: No such file or directory </code></pre> <p>What does this error mean and how do I fix it? It has prevented me from downloading new things via pip install!</p>
0
2016-08-16T23:39:27Z
38,999,458
<p>You could try to execute pip via a python version you know works on your system.</p> <p>Something like:</p> <pre><code>/path/to/python /path/to/pip </code></pre> <p>You could use:</p> <pre><code>which python which pip </code></pre> <p>to find out the relevant paths.</p>
0
2016-08-17T14:28:43Z
[ "python", "bash", "install", "pip" ]
Why are the code colours different for every line in my Jupyter (Ubuntu)?
38,986,117
<p>I was using Jupyter in Windows and just switched to Ubuntu. I found the colour of the code is very weird in the firefox browser. E.g. it highlights the variables in every other line.</p> <p>I tried to solve this problem by <a href="http://github.com/dunovank/jupyter-themes/blob/master/README.md" rel="nofollow">installing a custom theme</a> and the effect should be like</p> <p><img src="http://i.stack.imgur.com/MipMb.png" alt="enter image description here"></p> <p>Instead, it still highlights every other variable on my side, like</p> <p><img src="http://i.stack.imgur.com/2SWtE.png" alt="enter image description here"></p> <p>This just makes my eyes very tired when try to debug the code.</p> <p>I also tried disabling all the add-ons in Firefox which didn't help. Is there any setting that I can change to restore to the default colour display? </p>
1
2016-08-16T23:45:35Z
39,112,179
<p>I sometimes get this if I'm copying/pasting from a source that has a different indentation size than that of the jupyter notebook. In your screenshot it looks like a small indent size so this seems like the likely culprit. Try highlighting the full block of indented code and hitting <code>ctrl+[</code> then <code>ctrl+]</code> (this unindents the selected lines of code, then reindents them using the jupyter indent size). </p> <p>If this doesn't work, you might try checking to see if there are any custom indentation settings specified in either ".jupyter/nbconfig/notebook.json" or ".jupyter/custom/custom.js" (... or whatever the Windows equivalents are).</p> <p>In ".jupyter/nbconfig/notebook.json", I have the indentUnit set to 4 spaces (and have also enabled linewrapping).</p> <pre><code>{ "CodeCell": { "cm_config": { "indentUnit": 4, "lineWrapping":true } } } </code></pre> <p>Most editors allow you to set your indent size (Atom, sublime text, etc.) so you can avoid this issue in the future by making sure you have the same indent size everywhere you're swapping code to/from (assuming this is what's causing the red highlighting). Python's default is 4 so def recommend sticking with that. </p>
0
2016-08-23T23:24:51Z
[ "python", "ubuntu", "ipython", "jupyter" ]
Rearrange text file based on matches in columns
38,986,202
<p>I am working with a data set:</p> <pre><code>ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0.6 IML Pg 18:00:52.264 -0.6 </code></pre> <p>Using AWK and I need lines that match, to be printed onto the same line.</p> <p>i.e. </p> <pre><code>ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 </code></pre> <p>I've been trying all sorts of different ideas but cannot locate code to do this. I have been trying to use AWK, as instructed by my superior. Would be interested to see if it would be easier in Python?</p> <p>(note white space between lines to preserve structure)</p>
0
2016-08-16T23:58:02Z
38,986,284
<p>As I understand it, you are matching on the first field and the file is sorted. In that case, try:</p> <pre><code>$ awk 'NR&gt;1{printf "%s%s",($1==last?" ":"\n"),$0}; NR==1{printf "%s",$0} {last=$1} END{print""}' file ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0.6 IML Pg 18:00:52.264 -0.6 </code></pre> <h3>How it works</h3> <ul> <li><p><code>NR==1{printf "%s",$0}</code></p> <p>For the first line, we print it with no trailing newline.</p></li> <li><p><code>NR&gt;1{printf "%s%s",($1==last?" ":"\n"),$0}</code></p> <p>For lines after the first, we print a space if the first fields match or a newline if they don't, followed by the line.</p> <p>The tricky-looking part here is the ternary statement <code>$1==last?" ":"\n"</code>. This just tests to see if the first field is equal to the last first field. If it is, it returns the string after the <code>?</code>. If it isn't, it returns the string after the <code>:</code>.</p></li> <li><p><code>last=$1</code></p> <p>We update the variable <code>last</code> to the most recent first field.</p></li> <li><p><code>END{print""}</code></p> <p>After we have finished reading the file and to make sure that we have a complete final line, we print a newline.</p></li> </ul>
2
2016-08-17T00:08:45Z
[ "python", "unix", "awk" ]
Rearrange text file based on matches in columns
38,986,202
<p>I am working with a data set:</p> <pre><code>ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0.6 IML Pg 18:00:52.264 -0.6 </code></pre> <p>Using AWK and I need lines that match, to be printed onto the same line.</p> <p>i.e. </p> <pre><code>ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 </code></pre> <p>I've been trying all sorts of different ideas but cannot locate code to do this. I have been trying to use AWK, as instructed by my superior. Would be interested to see if it would be easier in Python?</p> <p>(note white space between lines to preserve structure)</p>
0
2016-08-16T23:58:02Z
38,986,768
<p>another <code>awk</code></p> <pre><code>$ awk '{a[$1]=a[$1]?a[$1] FS $0:$0} END{for(k in a) print a[k] | "sort" }' file | column -t ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0.6 IML Pg 18:00:52.264 -0.6 </code></pre> <p>accumulate records with the same key, print at the end and sort (by the key), <code>column</code> for prettying. Doesn't require the keys to be contiguous or sorted.</p>
1
2016-08-17T01:21:20Z
[ "python", "unix", "awk" ]
Rearrange text file based on matches in columns
38,986,202
<p>I am working with a data set:</p> <pre><code>ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0.6 IML Pg 18:00:52.264 -0.6 </code></pre> <p>Using AWK and I need lines that match, to be printed onto the same line.</p> <p>i.e. </p> <pre><code>ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 </code></pre> <p>I've been trying all sorts of different ideas but cannot locate code to do this. I have been trying to use AWK, as instructed by my superior. Would be interested to see if it would be easier in Python?</p> <p>(note white space between lines to preserve structure)</p>
0
2016-08-16T23:58:02Z
38,993,617
<p>This could be approached in Python as follows:</p> <pre><code>from itertools import groupby data = """ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0.6 IML Pg 18:00:52.264 -0.6""" print '\n'.join(' '.join(g) for k,g in groupby(data.splitlines(), key=lambda x: x.split()[0])) </code></pre> <p>This would display:</p> <pre><code>ALI P 18:00:40.583 0.0 ALI S 18:00:58.188 1.4 BRD Pg 18:00:48.918 0.4 BRD Sg 18:01:09.437 -1.8 GAN Pn 18:00:58.207 -0.0 GAN Sn 18:01:27.791 0.1 GLB P 18:00:27.265 -0.4 GLB S 18:00:34.187 0.1 GOB S 18:01:13.638 -0.6 IML Pg 18:00:52.264 -0.6 </code></pre>
1
2016-08-17T10:06:31Z
[ "python", "unix", "awk" ]
How to extract time from string in python using pattern matching?
38,986,205
<p>An example of the python string is <code>'8:30 AM- 10:00 PM Subject: Math'</code>. In general, the string contains a start time, end time, and the subject I want to separate this string into 3 components: the start time, end time, and subject. For example <code>8:30 AM</code>, <code>10:00 PM</code>, and <code>Subject: Math</code>.</p> <p>How can I do this using regex in python?</p>
0
2016-08-16T23:58:26Z
38,986,230
<p>You can use <a href="https://docs.python.org/3/library/re.html#re.split" rel="nofollow"><code>re.split()</code></a> using a <em>positive lookbehind</em> to <code>AM</code> or <code>PM</code> having an optional <code>-</code> and a space character as a delimiter:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; &gt;&gt;&gt; s = "8:30 AM- 10:00 PM Subject: Math" &gt;&gt;&gt; re.split(r"(?&lt;=AM|PM)-?\s", s) ['8:30 AM', '10:00 PM', 'Subject: Math'] </code></pre>
2
2016-08-17T00:01:55Z
[ "python", "regex" ]
Python 2.7 easy_install - the process cannot access the file because it is being used by another process error
38,986,217
<p>Using Python I am trying to install a library called <a href="https://code.google.com/archive/p/yappi/" rel="nofollow">yappi</a> through easy_install. However I am getting this error below on Windows 7 Command Shell:</p> <p><a href="http://i.stack.imgur.com/4oCpl.png" rel="nofollow"><img src="http://i.stack.imgur.com/4oCpl.png" alt="enter image description here"></a></p> <p>I explored alternative installations. I tried previously 'pip install yappi' but this didn't work due to a separate error (can't build wheel) which is a separate question. </p>
0
2016-08-17T00:00:03Z
39,050,639
<p>Try downloading the appropriate wheel from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/#yappi" rel="nofollow">here</a>.</p> <p>Then use <code>pip install [package]</code>.</p>
1
2016-08-20T04:59:49Z
[ "python", "python-2.7", "easy-install", "yappi" ]
Django form DateTimeField initial value is blank
38,986,225
<p>I have a create form in which I'm submitting the field ['created_at'] as a hidden datetimefield. I'm importing from django.utils import timezone and have this working on another model. Does anyone have any insight into why the value is blank? Thanks for any help!</p> <p>form:</p> <pre><code>class CreateForm(ModelForm): class Meta: model = Animal fields = ('name', 'course', 'core', 'animal_group', 'image_on', 'image_off', 'created_at',) labels = { "image_on": "Animal Image", "image_off": "Incompleted Animal Image", } widgets = { 'name': forms.Textarea(attrs={'cols': 80, 'rows': 1}), } def __init__(self, *args, **kwargs): super(CreateForm, self).__init__(*args, **kwargs) self.fields['created_at'] = forms.DateTimeField(initial = timezone.now()) self.fields['created_at'].widget = forms.HiddenInput() def clean(self): cleaned_data = self.cleaned_data return cleaned_data </code></pre> <p>However when the templates renders the hidden input is there, but it doesn't have a value. <a href="http://i.stack.imgur.com/Ulnab.png" rel="nofollow"><img src="http://i.stack.imgur.com/Ulnab.png" alt="enter image description here"></a></p> <p>Here is the template code snippet:</p> <pre><code>&lt;form action="/support/add_animal/" enctype="multipart/form-data" method="POST"&gt; {% csrf_token %} {{ create_form | crispy }} &lt;br&gt; &lt;input type="submit" class="btn btn-success" value="Save"&gt; &lt;/form&gt; </code></pre>
0
2016-08-17T00:01:09Z
39,009,987
<p>Rather than continue banging my head on the wall with this, I opted to set the created_at time in the model rather than worry about it elsewhere. </p> <p>Set the attribute to have <code>(default=timezone.now)</code> and that cured my woes.</p>
0
2016-08-18T04:24:24Z
[ "python", "django-forms", "timezone", "hidden-field" ]
Spacy Pipeline?
38,986,235
<p>So lately I've been playing around with a WikiDump. I preprocessed it and trained it on Word2Vec + Gensim</p> <p>Does anyone know if there is only one script within Spacy that would generate tokenization, sentence recognition, part of speech tagging, lemmatization, dependency parsing, and named entity recognition all at once</p> <p>I have not been able to find clear documentation Thank you </p>
0
2016-08-17T00:02:35Z
39,058,506
<p>Spacy gives you all of that with just using <code>en_nlp = spacy.load('en'); doc=en_nlp(sentence)</code>. The <a href="https://spacy.io/docs/#getting-started" rel="nofollow">documentation</a> gives you details about how to access each of the elements.</p> <p>An example is given below:</p> <pre><code>In [1]: import spacy ...: en_nlp = spacy.load('en') In [2]: en_doc = en_nlp(u'Hello, world. Here are two sentences.') </code></pre> <p>Sentences can be obtained by using <code>doc.sents</code>:</p> <pre><code>In [4]: list(en_doc.sents) Out[4]: [Hello, world., Here are two sentences.] </code></pre> <p>Noun chunks are given by <code>doc.noun_chunks</code>:</p> <pre><code>In [6]: list(en_doc.noun_chunks) Out[6]: [two sentences] </code></pre> <p><a href="https://spacy.io/docs/#examples-entities" rel="nofollow">Named entity</a> is given by <code>doc.ents</code>:</p> <pre><code>In [11]: [(ent, ent.label_) for ent in en_doc.ents] Out[11]: [(two, u'CARDINAL')] </code></pre> <p>Tokenization: You can iterate over the doc to get tokens. <code>token.orth_</code> gives str of the token.</p> <pre><code>In [12]: [tok.orth_ for tok in en_doc] Out[12]: [u'Hello', u',', u'world', u'.', u'Here', u'are', u'two', u'sentences', u'.'] </code></pre> <p>POS is given by <code>token.tag_</code>:</p> <pre><code>In [13]: [tok.tag_ for tok in en_doc] Out[13]: [u'UH', u',', u'NN', u'.', u'RB', u'VBP', u'CD', u'NNS', u'.'] </code></pre> <p>Lemmatization:</p> <pre><code>In [15]: [tok.lemma_ for tok in en_doc] Out[15]: [u'hello', u',', u'world', u'.', u'here', u'be', u'two', u'sentence', u'.'] </code></pre> <p>Dependency parsing. You can traverse the parse tree by using <code>token.dep_</code> <code>token.rights</code> or <code>token.lefts</code>. You can write a function to print dependencies:</p> <pre><code>In [19]: for token in en_doc: ...: print(token.orth_, token.dep_, token.head.orth_, [t.orth_ for t in token.lefts], [t.orth_ for t in token.rights]) ...: (u'Hello', u'ROOT', u'Hello', [], [u',', u'world', u'.']) (u',', u'punct', u'Hello', [], []) (u'world', u'npadvmod', u'Hello', [], []) ... </code></pre> <p>For more details please consult the spacy documentation.</p>
3
2016-08-20T20:38:37Z
[ "python", "nlp", "spacy" ]
Running time for converting list to set in Python
38,986,244
<p>In Python, what are the running time and space complexities if a list is converted to a set?</p> <pre><code>Example: data = [1,2,3,4,5,5,5,5,6] # this turns list to set and overwrites the list data = set(data) print data # output will be (1,2,3,4,5,6) </code></pre>
0
2016-08-17T00:03:36Z
38,986,278
<p>You have to iterate through the entire list, which is O(n) time, and then insert each into a set, which is O(1) time. So the overall time complexity is O(n), where n is the length of the list.</p> <p>No other space other than the set being created or the list being used is needed.</p>
1
2016-08-17T00:08:03Z
[ "python", "list", "set", "runtime", "space" ]
Running time for converting list to set in Python
38,986,244
<p>In Python, what are the running time and space complexities if a list is converted to a set?</p> <pre><code>Example: data = [1,2,3,4,5,5,5,5,6] # this turns list to set and overwrites the list data = set(data) print data # output will be (1,2,3,4,5,6) </code></pre>
0
2016-08-17T00:03:36Z
38,986,289
<p>Converting a list to a set requires that every item in the list be visited once, O(n). Inserting an element into a set is O(1), so the overall time complexity would be O(n).</p> <p>Space required for the new set is less than or equal to the length of the list, so that is also O(n).</p> <p>Here's a good <a href="https://wiki.python.org/moin/TimeComplexity" rel="nofollow">reference</a> for Python data structures.</p>
1
2016-08-17T00:09:32Z
[ "python", "list", "set", "runtime", "space" ]
How to access Pymongo nested document with variable
38,986,261
<p>I understand that in order to find a nested document that I am to use the dot notation, but I need what follows the dot be in variable form. I am doing the following:</p> <pre><code>collection.update_one( {'_id': md5_hash}, {'$addToSet' : { 'src_id': src_id, 'offset.src_id' : offset}} ) </code></pre> <p>and getting </p> <pre><code>{ "_id" : "de03fe65a6765caa8c91343acc62cffc", "total_count" : 1, "src_id" : [ "a3c1b98d5606be7c5f0c5d14ffb0b741" ], "offset" : { "a3c1b98d5606be7c5f0c5d14ffb0b741" : [ 512 ], "src_id" : [ 512, 1024, 1536, 2048, 2560, 3072, 3584, 4096, 4608 ] }, "per_source_count" : { "a3c1b98d5606be7c5f0c5d14ffb0b741" : 1 } } </code></pre> <p>I don't want "src_id" in the offset document I want to add to the a3c1b98d5606be7c5f0c5d14ffb0b741 key. I am using python3.5 and pymongo version 3.2.2. Thanks!</p>
1
2016-08-17T00:05:58Z
38,986,305
<p>You can just have a nested dictionary:</p> <pre><code>collection.update_one({'_id': md5_hash}, {'$addToSet': {'offset': {src_id: offset}}}) </code></pre> <p>Or, you can dynamically make the field via string formatting or concatenation:</p> <pre><code>collection.update_one({'_id': md5_hash}, {'$addToSet': {'offset.%s' % src_id: offset}}) </code></pre>
1
2016-08-17T00:11:19Z
[ "python", "mongodb", "nested", "pymongo" ]
Python NameError: name is not defined (related to having default input argument types)
38,986,341
<p>I have a problem with the fact that I am calling <code>len(myByteArray)</code> in the input arguments to a function I am declaring. I'd like that to be a default argument, but Python doesn't seem to like it. <code>myByteArray</code> is of type <code>bytearray</code>. See <a href="https://docs.python.org/3.1/library/functions.html#bytearray" rel="nofollow">documentation on bytearray here</a>. I am accessing its built-in <code>find</code> function, <a href="https://docs.python.org/3.5/library/stdtypes.html#sequence-types-list-tuple-range" rel="nofollow">documented here</a> (see "bytes.find").</p> <p>My function:</p> <pre><code>def circularFind(myByteArray, searchVal, start=0, end=len(myByteArray)): """ Return the first-encountered index in bytearray where searchVal is found, searching to the right, in incrementing-index order, and wrapping over the top and back to the beginning if index end &lt; index start """ if (end &gt;= start): return myByteArray.find(searchVal, start, end) else: #end &lt; start, so search to highest index in bytearray, and then wrap around and search to "end" if nothing was found index = myByteArray.find(searchVal, start, len(myByteArray)) if (index == -1): #if searchVal not found yet, wrap around and keep searching index = myByteArray.find(searchVal, 0, end) return index </code></pre> <p>Examples to attempt to use the function above:</p> <pre><code>#------------------------------------------------------------------- #EXAMPLES: #------------------------------------------------------------------- #Only executute this block of code if running this module directly, #*not* if importing it #-see here: http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm if __name__ == "__main__": #if running this module as a stand-alone program import random random.seed(0) bytes = bytearray(100) for i in range(len(bytes)): bytes[i] = int(random.random()*256) print(list(bytes)); print(); print('built-in method:') print(bytes.find(255)) print(bytes.find(2,10,97)) print(bytes.find(5,97,4)) print('\ncircularFind:') print(circularFind(bytes,255)) print(circularFind(bytes,2,10,97)) print(circularFind(bytes,5,97,4)) </code></pre> <p>Error: </p> <blockquote> <p>NameError: name 'myByteArray' is not defined</p> </blockquote> <p>If I just remove my default arguments (<code>=0</code> and <code>=len(myByteArray)</code>), however, it works fine. But...I really want those default arguments there so that the <code>start</code> and <code>end</code> arguments are optional. What do I do? </p> <p>In C++ this would be easy, as argument types are specified when you write functions.</p>
1
2016-08-17T00:17:26Z
38,986,421
<p>At the time of passing the parameters, the parameters are not initialised</p> <pre><code>&gt;&gt;&gt; def a(b=1,c=b): ... print(c,b) ... Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'b' is not defined </code></pre> <p>so you need to send len of myByteArray as another variable.</p> <p>So what you could do is,</p> <pre><code>def circularFind(myByteArray, searchVal, start=0, end=-1): if end == -1: end = len(myByteArray) #reset of code here. </code></pre>
1
2016-08-17T00:29:56Z
[ "python", "python-3.x", "arguments", "nameerror" ]
Python NameError: name is not defined (related to having default input argument types)
38,986,341
<p>I have a problem with the fact that I am calling <code>len(myByteArray)</code> in the input arguments to a function I am declaring. I'd like that to be a default argument, but Python doesn't seem to like it. <code>myByteArray</code> is of type <code>bytearray</code>. See <a href="https://docs.python.org/3.1/library/functions.html#bytearray" rel="nofollow">documentation on bytearray here</a>. I am accessing its built-in <code>find</code> function, <a href="https://docs.python.org/3.5/library/stdtypes.html#sequence-types-list-tuple-range" rel="nofollow">documented here</a> (see "bytes.find").</p> <p>My function:</p> <pre><code>def circularFind(myByteArray, searchVal, start=0, end=len(myByteArray)): """ Return the first-encountered index in bytearray where searchVal is found, searching to the right, in incrementing-index order, and wrapping over the top and back to the beginning if index end &lt; index start """ if (end &gt;= start): return myByteArray.find(searchVal, start, end) else: #end &lt; start, so search to highest index in bytearray, and then wrap around and search to "end" if nothing was found index = myByteArray.find(searchVal, start, len(myByteArray)) if (index == -1): #if searchVal not found yet, wrap around and keep searching index = myByteArray.find(searchVal, 0, end) return index </code></pre> <p>Examples to attempt to use the function above:</p> <pre><code>#------------------------------------------------------------------- #EXAMPLES: #------------------------------------------------------------------- #Only executute this block of code if running this module directly, #*not* if importing it #-see here: http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm if __name__ == "__main__": #if running this module as a stand-alone program import random random.seed(0) bytes = bytearray(100) for i in range(len(bytes)): bytes[i] = int(random.random()*256) print(list(bytes)); print(); print('built-in method:') print(bytes.find(255)) print(bytes.find(2,10,97)) print(bytes.find(5,97,4)) print('\ncircularFind:') print(circularFind(bytes,255)) print(circularFind(bytes,2,10,97)) print(circularFind(bytes,5,97,4)) </code></pre> <p>Error: </p> <blockquote> <p>NameError: name 'myByteArray' is not defined</p> </blockquote> <p>If I just remove my default arguments (<code>=0</code> and <code>=len(myByteArray)</code>), however, it works fine. But...I really want those default arguments there so that the <code>start</code> and <code>end</code> arguments are optional. What do I do? </p> <p>In C++ this would be easy, as argument types are specified when you write functions.</p>
1
2016-08-17T00:17:26Z
38,986,430
<p>Python default arguments are evaluated when the function is defined. Rather, you want something like this:</p> <pre><code>def circularFind(myByteArray, searchVal, start=0, end=None): """ Return the first-encountered index in bytearray where searchVal is found, searching to the right, in incrementing-index order, and wrapping over the top and back to the beginning if index end &lt; index start """ if end is None: end = len(myByteArray) # continue doing what you were doing </code></pre>
1
2016-08-17T00:31:38Z
[ "python", "python-3.x", "arguments", "nameerror" ]
How would you use the ord function to get ord("a") as 0?
38,986,342
<p>For example, in python, when I type in <code>ord("a")</code> it returns <code>97</code> because it refers to the ascii list. I want <code>ord("a")</code> to return zero from a string that I created such as </p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" </code></pre> <p>so <code>ord("b")</code> would be <code>1</code> and <code>ord("c")</code> would be <code>2</code> ect. How would I go about doing this?</p>
-1
2016-08-17T00:17:28Z
38,986,374
<p>Something like this should do the trick:</p> <pre><code>def my_ord(c): alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" return alphabet.index(c) </code></pre>
0
2016-08-17T00:22:35Z
[ "python" ]
How would you use the ord function to get ord("a") as 0?
38,986,342
<p>For example, in python, when I type in <code>ord("a")</code> it returns <code>97</code> because it refers to the ascii list. I want <code>ord("a")</code> to return zero from a string that I created such as </p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" </code></pre> <p>so <code>ord("b")</code> would be <code>1</code> and <code>ord("c")</code> would be <code>2</code> ect. How would I go about doing this?</p>
-1
2016-08-17T00:17:28Z
38,986,375
<p>You can create a <code>dict</code> to map from characters to indices and then do lookups into that. This will avoid repeatedly searching the string as other answers are suggesting (which is <code>O(n)</code>) and instead give <code>O(1)</code> lookup time with respect to the alphabet:</p> <pre><code>my_ord_dict = {c : i for i, c in enumerate(alphabet)} my_ord_dict['0'] # 26 </code></pre> <p>At that point you can easily wrap it in a function:</p> <pre><code>def my_ord(c): return my_ord_dict['0'] </code></pre> <p>Or use the bound method directly</p> <pre><code>my_ord = my_ord_dict.__getitem__ </code></pre> <p>But you don't want to change the name that refers to a builtin function, that'll confuse everyone else trying to use it that can see your change. If you are really trying to hurt yourself you can replace <code>my_ord</code> with <code>ord</code> in the above.</p>
0
2016-08-17T00:22:36Z
[ "python" ]
How would you use the ord function to get ord("a") as 0?
38,986,342
<p>For example, in python, when I type in <code>ord("a")</code> it returns <code>97</code> because it refers to the ascii list. I want <code>ord("a")</code> to return zero from a string that I created such as </p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" </code></pre> <p>so <code>ord("b")</code> would be <code>1</code> and <code>ord("c")</code> would be <code>2</code> ect. How would I go about doing this?</p>
-1
2016-08-17T00:17:28Z
38,986,376
<p>You don't.</p> <p>You're going about this the wrong way: you're making the mistake</p> <blockquote> <p>This existing thing doesn't meet my needs. I want to make it meet my needs!</p> </blockquote> <p>instead, the way to go about the problem is</p> <blockquote> <p>This existing thing doesn't meet my needs. I need a thing that does meet my needs!</p> </blockquote> <p>Once you realize that, the problem is now pretty straightforward. e.g.</p> <pre><code>DEFAULT_ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" def myord(x, alphabet=DEFAULT_ALPHABET): return alphabet.find(x) </code></pre>
2
2016-08-17T00:22:41Z
[ "python" ]
How would you use the ord function to get ord("a") as 0?
38,986,342
<p>For example, in python, when I type in <code>ord("a")</code> it returns <code>97</code> because it refers to the ascii list. I want <code>ord("a")</code> to return zero from a string that I created such as </p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" </code></pre> <p>so <code>ord("b")</code> would be <code>1</code> and <code>ord("c")</code> would be <code>2</code> ect. How would I go about doing this?</p>
-1
2016-08-17T00:17:28Z
38,986,388
<p>If i've understood correctly, this is what you want:</p> <pre><code>alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 .,?!" def crypt(c, key=97): return ord(c)-key def decrypt(c, key=97): return chr(c+key) dst = [crypt(c) for c in alphabet] src = [decrypt(c) for c in dst] print dst print ''.join(src) </code></pre>
0
2016-08-17T00:25:14Z
[ "python" ]
Creating a hyperlink in Python
38,986,343
<p>I'm trying to create a hyper link in python that includes string and variables but i keep getting a syntax error, I think its probably because of quotations but I cant seen to figure it out. Thanks for the help.</p> <pre><code>'&lt;a href="http://maps.google.com/maps?z=12&amp;t=m&amp;q=loc:'str(p['latitude']+'+'+str(p['longitude']))'"&gt;Click Here&lt;/a&gt;'}) </code></pre>
-2
2016-08-17T00:17:58Z
38,986,385
<p>Assuming both Latitude and Longitude are Integers:</p> <pre><code>'&lt;a href="http://maps.google.com/maps?z=12&amp;t=m&amp;q=loc:'+str(p['latitude'])+'+'+str(p['longitude'])+'"&gt;Click Here&lt;/a&gt;' </code></pre> <p>Try This.</p> <p>Your mistake is that you are not concatenating the strings properly.</p>
0
2016-08-17T00:24:28Z
[ "python", "python-2.7" ]
Kind of pyramid numbers pattern exercise
38,986,344
<p>Can you help to simplify this code and make it more efficient? Mine seems like it's not the best version; what can I improve?</p> <pre><code> 1 232 34543 4567654 567898765 678901109876 </code></pre> <p>This is the code I made:</p> <pre><code>c = -1 for y in range(1, 7): print() print((6-y) * " ", end="") c += 1 for x in range(1, y+1): print(y%10, end="") y += 1 while y - c &gt; 2: print(y-2, end="") y -= 1 </code></pre>
0
2016-08-17T00:18:26Z
38,986,563
<p>First of all, I'm guessing that you didn't really want to print that <strong>y</strong> value of 10; that you really wanted the base-10 reduction to 0. Note that you have an extra character in the pyramid base.</p> <p>Do <em>not</em> change the value of a loop parameter while you're inside the loop. Specifically, don't change y within the <strong>for y</strong> loop.</p> <p>Get rid of <strong>c</strong>; you can derive it from the other values.</p> <p>For flexibility, make your upper limit a parameter: you have two constants (6 and 7) that depend on one concept (row limit).</p> <p>Here's my version:</p> <pre><code>row_limit = 7 for y in range(1, row_limit): print() print((row_limit-y-1) * " ", end="") for x in range(y, 2*y): print(x%10, end="") for x in range(2*(y-1), y-1, -1): print(x%10, end="") print() </code></pre> <p>Output:</p> <pre><code> 1 232 34543 4567654 567898765 67890109876 </code></pre> <hr> <p>If you really want to push things, you can shorten the loops with string concatenation and comprehension, but it's likely harder to read for you.</p> <pre><code>for y in range(1, row_limit): print() print((row_limit-y-1) * " " + ''.join([str(x%10) for x in range(y, 2*y)]) + \ ''.join([str(x%10) for x in range(2*(y-1), y-1, -1)]), end="") print() </code></pre> <p>Each of the loops is turned into a list comprehension, such as:</p> <pre><code>[str(x%10) for x in range(y, 2*y)] </code></pre> <p>Then, this list of characters is joined with no interstitial character; this forms half of the row. The second half of the row is the other loop (counting down). In front of all this, I concatenate the proper number of spaces.</p> <p>Frankly, I prefer my first form.</p>
0
2016-08-17T00:50:47Z
[ "python", "design-patterns", "numbers" ]
Kind of pyramid numbers pattern exercise
38,986,344
<p>Can you help to simplify this code and make it more efficient? Mine seems like it's not the best version; what can I improve?</p> <pre><code> 1 232 34543 4567654 567898765 678901109876 </code></pre> <p>This is the code I made:</p> <pre><code>c = -1 for y in range(1, 7): print() print((6-y) * " ", end="") c += 1 for x in range(1, y+1): print(y%10, end="") y += 1 while y - c &gt; 2: print(y-2, end="") y -= 1 </code></pre>
0
2016-08-17T00:18:26Z
38,986,584
<p>Here's my implementation.</p> <p><strong>Python 2</strong>:</p> <pre><code>def print_triangle(n): for row_num in xrange(1, n + 1): numbers = [str(num % 10) for num in xrange(row_num, 2 * row_num)] num_string = ''.join(numbers + list(reversed(numbers))[1:]) print '{}{}'.format(' ' * (n - row_num), num_string) </code></pre> <p><strong>Python 3</strong>:</p> <pre><code>def print_triangle(n): for row_num in range(1, n + 1): numbers = [str(num % 10) for num in range(row_num, 2 * row_num)] num_string = ''.join(numbers + list(reversed(numbers))[1:]) print('{}{}'.format(' ' * (n - row_num), num_string)) </code></pre> <p><strong>Input</strong>:</p> <pre><code>print_triangle(5) print_triangle(6) print_triangle(7) </code></pre> <p><strong>Output</strong>:</p> <pre><code> 1 232 34543 4567654 567898765 1 232 34543 4567654 567898765 67890109876 1 232 34543 4567654 567898765 67890109876 7890123210987 </code></pre>
0
2016-08-17T00:53:55Z
[ "python", "design-patterns", "numbers" ]
Building a server and client with xmlrpc in python
38,986,369
<p>I'm trying to build a client and a server using xmlrpc in python, I HAVE to use a class named FunctionWrapper which has a method and the client use it, the method's name is sendMessage_wrapper(self, message), and the server is declared in another class, I'm trying to register the method in the server but when i call the method from de client I raise and error, can you help me, please?</p> <p>Cliente:</p> <pre><code>#! /usr/bin/env python # -*- coding: utf-8 -*- import sys import xmlrpclib from SimpleXMLRPCServer import SimpleXMLRPCServer from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from Constants.Constants import * class MyApiClient: def __init__(self, contact_port = DEFAULT_PORT,contact_ip=LOCALHOST_CLIENT): self.contact_port = contact_port self.contact_ip = contact_ip self.proxy = xmlrpclib.ServerProxy(contact_ip+str(self.contact_port)+"/") def sendMessage(self,message): self.proxy.sendMessage_wrapper(message) a = MyApiClient() a.sendMessage("Hi") a.sendMessage("WORKING") </code></pre> <p>Server:</p> <pre><code>#! /usr/bin/env python # -*- coding: utf-8 -*- import sys import xmlrpclib from SimpleXMLRPCServer import SimpleXMLRPCServer from os import path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) from Constants.Constants import * class MyApiServer: def __init__(self,wrapper, my_port = DEFAULT_PORT): self.port = my_port self.server = SimpleXMLRPCServer((LOCALHOST,self.port)) self.wrapper = wrapper self.server.register_instance(self.wrapper) print("Running") self.server.serve_forever() class FunctionWrapper: def __init__(self): self.message = None """ Procedimiento que ofrece nuestro servidor, este metodo sera llamado por el cliente con el que estamos hablando, debe de hacer lo necesario para mostrar el texto en nuestra pantalla. """ def sendMessage_wrapper(self, message): self.message = message self.showMessage() def showMessage(self): print ("Mensaje "+self.message) #raise NotImplementedError( "Should have implemented this" ) a = FunctionWrapper() b = MyApiServer(a) </code></pre>
0
2016-08-17T00:21:48Z
38,986,383
<p>Here are the constants in case you need it </p> <pre><code>#! /usr/bin/env python # -*- coding: utf-8 -*- #Nombres para etiquetas login local y remoto MY_PORT_NUMBER_TITLE = "Cual es mi puerto?" OTHER_PORT_NUMBER_TITLE = "Cual es el puerto de contacto?" OTHER_IP_NUMBER_TITLE = "Cual es la direccion ip de contacto?" LOGIN_TITLE = "Acceder" #Nombres para las etiquetas del chat CONVERSATION_TITLE = "Conversacion" SEND_TITLE = "Responder" #Titulo de las ventans GUI LOGIN_WINDOW = "Login" CHAT_WINDOW = "Chat" #Modos de acceso al chat, local o remoto LOCAL = "Local" REMOTE = "Remote" #Mensajes de error WARNING = "¡Alerta!" MISSING_MESSAGE = "No hay ningun mensaje para enviar" #Localhost LOCALHOST = "localhost" DEFAULT_PORT = 5000 LOCALHOST_CLIENT = "http://localhost:" </code></pre>
0
2016-08-17T00:23:38Z
[ "python", "xmlrpclib" ]