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
In sympy, how do I get the coefficients of a rational expression?
39,348,937
<p>I have a rational (here: bilinear) expression and want I sympy to collect the coefficients. But how?</p> <pre><code>from sympy import symbols, Wild, pretty_print a, b, c, d, x, s = symbols("a b c d x s") def coeffs(expr): n0 = Wild("n0", exclude=[x]) n1 = Wild("n1", exclude=[x]) d0 = Wild("d0", exclude=[x]) d1 = Wild("d1", exclude=[x]) match = expr.match((n0 + n1*x) / (d0 + d1*x)) n0 = n0.xreplace(match) n1 = n1.xreplace(match) d0 = d0.xreplace(match) d1 = d1.xreplace(match) return [n0, n1, d0, d1] if __name__ == '__main__': pretty_print(coeffs((a + b*x) / (c + d*x))) pretty_print(coeffs(2 * (a + b*x) / (c + d*x))) pretty_print(coeffs(s * (a + b*x) / (c + d*x))) </code></pre> <p>I tried this using <code>match</code>, but it fails almost always, for example in the last line (the one with a symbolic prefactor of "s") I get</p> <pre><code>Traceback (most recent call last): File "...", line 20, in &lt;module&gt; pretty_print(coeffs(s * (a + b*x) / (c + d*x))) File "...", line 11, in coeffs n0 = n0.xreplace(match) File "/usr/lib/python3/dist-packages/sympy/core/basic.py", line 1626, in xreplace return rule.get(self, self) AttributeError: 'NoneType' object has no attribute 'get' </code></pre> <p>so the match did not work.</p>
3
2016-09-06T12:21:09Z
39,352,751
<p>If you know that the expressions you will consider are rational, you could extract their numerator and denominator and find their coefficients independently.</p> <p>Here's one approach to do so:</p> <pre><code>import sympy as sp def get_rational_coeffs(expr): num, denom = expr.as_numer_denom() return [sp.Poly(num, x).all_coeffs(), sp.Poly(denom, x).all_coeffs()] a, b, c, d, x, s = sp.symbols("a b c d x s") expr = (a + b*x) / (c + d*x) # note the order of returned coefficients ((n1, n0), (d1, d0)) = get_rational_coeffs(s*expr) print(((n0, n1), (d0, d1))) </code></pre> <blockquote> <p><code>((a*s, b*s), (c, d))</code></p> </blockquote> <p>The above approach is also faster than <code>coeffs</code>. I get the following timings (based on Jupyter's <code>%timeit</code> magic) for the case where the coefficients of <code>expr</code> are required (case where <code>coeffs</code> succeeds):</p> <pre><code>%timeit get_rational_coeffs(expr) %timeit coeffs(expr) </code></pre> <blockquote> <p><code>1000 loops, best of 3: 1.33 ms per loop</code></p> <p><code>1000 loops, best of 3: 1.99 ms per loop</code></p> </blockquote>
3
2016-09-06T15:28:43Z
[ "python", "numpy", "sympy" ]
I'm not sure what a certain code line does
39,348,980
<p>I was trying to have a program using Python to create a "pyramid" based on a number, n, out of o's and came up with this: ( I would print nn, that would be the lines.)</p> <pre><code>import time n = 0 while True: n += 2 #just another way to show n=n+2 nn = n, "o" #nn would be an amount of o's, based on what #n was time.sleep(1) print (nn, str.center(40, " ")) </code></pre> <p>Not sure how to make nn the o's and not sure what line 6 does either. Does anyone know the answer to either question? ( I'm not in a class just programming for fun.)</p>
0
2016-09-06T12:23:51Z
39,349,087
<pre><code>import time n = 0 while True: n += 2 #just another way to show n=n+2 nn = "o" * n #nn would be an amount of o's, based on what #n was time.sleep(1) print (nn.center(40," ")) </code></pre> <p>As someone has mentioned in the comments "o" * n will give a a string containing n "o"s. I've fixed the print line to use the correct method a calling the center method.</p>
1
2016-09-06T12:30:18Z
[ "python" ]
I'm not sure what a certain code line does
39,348,980
<p>I was trying to have a program using Python to create a "pyramid" based on a number, n, out of o's and came up with this: ( I would print nn, that would be the lines.)</p> <pre><code>import time n = 0 while True: n += 2 #just another way to show n=n+2 nn = n, "o" #nn would be an amount of o's, based on what #n was time.sleep(1) print (nn, str.center(40, " ")) </code></pre> <p>Not sure how to make nn the o's and not sure what line 6 does either. Does anyone know the answer to either question? ( I'm not in a class just programming for fun.)</p>
0
2016-09-06T12:23:51Z
39,349,116
<p>You can try this:</p> <pre><code>from __future__ import print_function import time for n in range(0, 40, 2): nn = n * "o" #nn would be an amount of o's, based on what #n was time.sleep(1) print(nn.center(40, " ")) </code></pre>
1
2016-09-06T12:32:28Z
[ "python" ]
I'm not sure what a certain code line does
39,348,980
<p>I was trying to have a program using Python to create a "pyramid" based on a number, n, out of o's and came up with this: ( I would print nn, that would be the lines.)</p> <pre><code>import time n = 0 while True: n += 2 #just another way to show n=n+2 nn = n, "o" #nn would be an amount of o's, based on what #n was time.sleep(1) print (nn, str.center(40, " ")) </code></pre> <p>Not sure how to make nn the o's and not sure what line 6 does either. Does anyone know the answer to either question? ( I'm not in a class just programming for fun.)</p>
0
2016-09-06T12:23:51Z
39,349,150
<p>This will be the answer to your question</p> <pre><code>import time n = 0 while True: n += 2 nn = n * "o" time.sleep(1) print (nn.center(40, " ")) if n &gt; 30: break </code></pre> <p>The reason why they have put <code>time.sleep(1)</code> is to make it look like an animation. <code>print (nn, str.center(40, " "))</code> this must be changed to <code>nn.center(40, " ")</code> as <code>.center</code> is a method of string. </p>
1
2016-09-06T12:34:05Z
[ "python" ]
I'm not sure what a certain code line does
39,348,980
<p>I was trying to have a program using Python to create a "pyramid" based on a number, n, out of o's and came up with this: ( I would print nn, that would be the lines.)</p> <pre><code>import time n = 0 while True: n += 2 #just another way to show n=n+2 nn = n, "o" #nn would be an amount of o's, based on what #n was time.sleep(1) print (nn, str.center(40, " ")) </code></pre> <p>Not sure how to make nn the o's and not sure what line 6 does either. Does anyone know the answer to either question? ( I'm not in a class just programming for fun.)</p>
0
2016-09-06T12:23:51Z
39,349,187
<p>You can also use the <a href="https://docs.python.org/3/library/string.html#format-string-syntax" rel="nofollow">built-in formatting options</a> offered by python. Take a look at this:</p> <pre><code>def pyramid_builder(height, symbol='o', padding=' '): for n in range(0, height, 2): # wonkiness-correction by @mhawke print('{0:{1}^{2}}'.format(symbol*n, padding, height * 2)) pyramid_builder(20, 'o') </code></pre> <p>The <code>^</code> symbol says that you want your print <strong>centered</strong>. Before it (<code>{1}</code>) comes the padding symbol and after it (<code>{2}</code>) the total width.</p> <p>This is fully customisable and fun to play with.</p>
1
2016-09-06T12:36:26Z
[ "python" ]
Getting signature from Outlook using python with Redemption RDO
39,349,096
<p>I wrote a program that creates a mail in outlook and saves it as .msg format. I want to add the signature of the user that is sending the mail (so the current account user) at the end of the HTMLBody. So far I haven't been able to find anything.</p> <p>Any help would be appreacited. Here is an easy example of my code:</p> <pre><code>win32com.client.gencache.EnsureDispatch("Outlook.Application") session = win32com.client.Dispatch("Redemption.RDOSession") session.Logon("Outlook") signatures = session.Signatures msg = session.GetMessageFromMsgFile(r"test.msg") msg.Subject = "test subject" msg.HTMLBody ="&lt;html&gt;&lt;body&gt; &lt;b&gt; this is a body&lt;/b&gt;&lt;/body&gt;&lt;/html&gt;" signatures.Item(1).ApplyTo(msg, False) msg.SaveAs("file.msg") </code></pre> <p>It works now thanks for all the answers! :)</p>
0
2016-09-06T12:31:10Z
39,351,360
<p>By defualt, you can find user's signatures stored in the following folder on the disk:</p> <pre><code> C:\Users\%username%\AppData\Roaming\Microsoft\Signatures </code></pre> <p>It may contain the following files:</p> <ul> <li>.htm - This file is used when creating HTML messages.</li> <li>.rtf - This file is used when creating Rich Text messages.</li> <li><p>.txt - This file is used when creating Plain Text message.</p></li> <li><p>_files - This folder is used in Outlook 2007, 2010 and 2013 to store supporting files for your signature such as formatting, images and/or business cards (vcf-files).</p></li> </ul> <p>Basically you need to read an appropriate file on the disk and then instert the content to the mail item.</p>
0
2016-09-06T14:20:06Z
[ "python", "email", "outlook", "outlook-redemption", "rdo" ]
Getting signature from Outlook using python with Redemption RDO
39,349,096
<p>I wrote a program that creates a mail in outlook and saves it as .msg format. I want to add the signature of the user that is sending the mail (so the current account user) at the end of the HTMLBody. So far I haven't been able to find anything.</p> <p>Any help would be appreacited. Here is an easy example of my code:</p> <pre><code>win32com.client.gencache.EnsureDispatch("Outlook.Application") session = win32com.client.Dispatch("Redemption.RDOSession") session.Logon("Outlook") signatures = session.Signatures msg = session.GetMessageFromMsgFile(r"test.msg") msg.Subject = "test subject" msg.HTMLBody ="&lt;html&gt;&lt;body&gt; &lt;b&gt; this is a body&lt;/b&gt;&lt;/body&gt;&lt;/html&gt;" signatures.Item(1).ApplyTo(msg, False) msg.SaveAs("file.msg") </code></pre> <p>It works now thanks for all the answers! :)</p>
0
2016-09-06T12:31:10Z
39,352,373
<p>You can use RDOSignature.ApplyTo - please see <a href="http://www.dimastr.com/redemption/rdosignature.htm" rel="nofollow">http://www.dimastr.com/redemption/rdosignature.htm</a> </p>
0
2016-09-06T15:09:24Z
[ "python", "email", "outlook", "outlook-redemption", "rdo" ]
Conditional in Django Tables
39,349,152
<p>I am trying to include a conditional in my Django table, but I am having some issues finding the correct syntax to do so.</p> <p>I have a boolean field in one of my models, and based on that value - I would like to render a different <code>label_link</code> and callback url for that specific db record.</p> <p>Here is the code I am using:</p> <pre><code>class Feature(BaseTable): orderable = False title_english = tables.Column() featured_item = tables.Column() if (featured_item == False): actions = tables.TemplateColumn(""" {% url 'add_feature' pk=record.pk as url_ %} {% label_link url_ 'Add to Features' %} """, attrs=dict(cell={'class': 'span1'})) else: actions = tables.TemplateColumn(""" {% url 'remove_feature' pk=record.pk as url_ %} {% label_link url_ 'Remove From Features' %} """, attrs=dict(cell={'class': 'span1'})) </code></pre> <p>Now I am aware currently that this is just checking to see if the value exists - therefore always rendering the code under the <code>else</code> statement.</p> <p>I have been unable to find any documentation that covers this particular nuance of Django tables.</p> <p>Note: I'm using Django 1.5 and Python 2.7</p>
0
2016-09-06T12:34:27Z
39,349,293
<p>You can't put the if statement in the <code>Feature</code> class - it is processed when the class is loaded, so you don't have access to the table data yet.</p> <p>Inside the <code>TemplateColumn</code>, you can access the current row of the table with <code>record</code>, so you could move the logic there.</p> <pre><code>class Feature(BaseTable): ... actions = tables.TemplateColumn(""" {% if not record.featured_item %} {% url 'add_feature' pk=record.pk as url_ %} {% label_link url_ 'Add to Features' %} {% else %} {% url 'remove_feature' pk=record.pk as url_ %} {% label_link url_ 'Remove From Features' %} {% endif %} """, attrs=dict(cell={'class': 'span1'})) </code></pre>
2
2016-09-06T12:42:45Z
[ "python", "django", "postgresql", "django-tables2" ]
How to generate a 2d grid from a set of randomly generated coordinates?
39,349,158
<p>The plan for the use of this is in a text based Space RPG game. I want to generate random points (x,y coordinates) - which I have already done - followed by plotting them with connections shown on a 2d grid. As a side, how would I label these coordinates?</p> <p><strong>The code for the random generation is included below:</strong></p> <pre><code>import time import random import math radius = 200 rangeX = (0, 2500) rangeY = (0, 2500) qty = 40 deltas = set() for x in range(-radius, radius+1): for y in range(-radius, radius+1): if x*x + y*y &lt;= radius*radius: deltas.add((x,y)) randPoints = [] excluded = set() i = 0 while i&lt;qty: x = random.randrange(*rangeX) y = random.randrange(*rangeY) if (x,y) in excluded: continue randPoints.append((x,y)) i += 1 excluded.update((x+dx, y+dy) for (dx,dy) in deltas) time.sleep(0.001) stars = {} keyName = 1 for item in randPoints: stars[str(keyName)] = [item, 0,] keyName += 1 </code></pre>
0
2016-09-06T12:34:55Z
39,350,839
<p>Instead of providing you with a direct answer I will point you in a general direction as the scope of this question seems rather big.</p> <p>Consider using pygame; it provides you with drawing functions, has an event system that you can use to detect user input and has many other helpful features for creating games as the name suggests.</p> <p>Strongly consider using classes; your code will become more readable and more flexible. Adding features to your stars such as a label, surface temperature, color of emitted (pulsing?) light, available raw materials.. etc. becomes much easier to handle.</p> <p>To generate names you could put existing star names in a text file, load it and pick one at random. For added bonus points use a markov chain to generate seemingly random names.</p> <p><a href="https://www.pygame.org" rel="nofollow">https://www.pygame.org</a></p> <p><a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">https://docs.python.org/3/tutorial/classes.html</a></p> <p><a href="https://en.wikipedia.org/wiki/Markov_chain" rel="nofollow">https://en.wikipedia.org/wiki/Markov_chain</a></p>
0
2016-09-06T13:55:07Z
[ "python", "random", "grid", "2d" ]
Merging CSV Using pandas dataframe
39,349,216
<p>I am using the below code. All my CSV files have uniform structure. When a dataframe is formed, it contains two columns for date in my CSV.</p> <p>In the resulting dataframe, for few rows date value is in first date column, while for rest of the data, it goes to second date column.</p> <p>Any idea, why two columns (Date columns), are getting generated for one column in the source CSV files.</p> <pre><code>all_data = pd.DataFrame() for f in glob.glob("/Users/tcssig/Desktop/Files/*.csv"): df = pd.read_csv(f) all_data = all_data.append(df,ignore_index=True) In [76]: all_data.columns Out[76]: Index(['0', '0.1', 'Channel_ID', 'Date', 'Date ', 'Duration (HH:MM)','Episode #', 'Image', 'Language', 'Master House ID', 'Parental Rating','Program Category', 'Program Title', 'StartTime_ET', 'StartTime_ET2','Synopsis'], dtype='object') </code></pre>
1
2016-09-06T12:38:02Z
39,349,237
<p>because you have a space in the second column:</p> <pre><code>'Date', 'Date ' ^ </code></pre> <p>so you need to normalise the columns prior to appending</p> <pre><code>all_data = pd.DataFrame() for f in glob.glob("/Users/tcssig/Desktop/Files/*.csv"): df = pd.read_csv(f) df.columns = df.columns.str.strip() all_data = all_data.append(df,ignore_index=True) </code></pre> <p>here I use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html#pandas.Series.str.rstrip"><code>str.strip</code></a> to remove any leading and trailing whitespace</p>
5
2016-09-06T12:39:34Z
[ "python", "csv", "pandas" ]
how I fix unicode error in Python Dexterity Type?
39,349,257
<p>I created one Dexterity Type using python, and the code is:</p> <pre><code># -*- coding: utf-8 -*- from plone.app.textfield import RichText from plone.autoform import directives from plone.namedfile import field as namedfile from plone.supermodel.directives import fieldset from plone.supermodel import model from z3c.form.browser.radio import RadioFieldWidget from zope import schema from zope.schema.vocabulary import SimpleVocabulary from zope.schema.vocabulary import SimpleTerm from DateTime import DateTime from projetime.ged import MessageFactory as _ TipoDeDocumentoVocabulary = SimpleVocabulary( [SimpleTerm(value=u'processo', title=_(u'Processos')), SimpleTerm(value=u'contratos', title=_(u'Contratos')), SimpleTerm(value=u'outros', title=_(u'Outros'))] ) TipoDeUploadVocabulary = SimpleVocabulary( [SimpleTerm(value=u'sim', title=_(u'Sim')), SimpleTerm(value=u'nao', title=_(u'Não'))] ) agora = DateTime() class IDigitalFile(model.Schema): """Dexterity-Schema """ directives.widget(TipoDeDocumento=RadioFieldWidget) TipoDeDocumento = schema.Choice( title=_(u"Tipo de Documento"), vocabulary=TipoDeDocumentoVocabulary, required=True ) titulo = schema.TextLine( title=_(u"Título"), required=True ) codDoDocumento = schema.TextLine( title=_(u"Cód. do Documento"), required=False ) CpfCnpj = schema.TextLine( title=_(u"CPF/CNPJ"), required=False ) Assunto = schema.TextLine( title=_(u"Assunto"), required=True ) Tipo = schema.TextLine( title=_(u"Tipo"), required=False ) Descricao = schema.Text( title=_(u"Descrição"), required=True ) fieldset('File', fields['Arquivo'] ) Arquivo = namedfile.NamedBlobFile( title=_(u"Arquivo Digitalizado"), required=True ) directives.omitted(['Automatico', 'uploded_at']) directives.read_permission(Automatico="cmf.ManagePortal") directives.write_permission(Automatico="cmf.ManagePortal") directives.widget(Automatico=RadioFieldWidget) Automatico = schema.Bool( Title=_(u"Upload via Script?"), vocabulary=TipoDeUploadVocabulary, required=True, default=u"Não" ) directives.read_permission(uploded_at="cmf.ManagePortal") directives.write_permission(uploded_at="cmf.ManagePortal") uploded_at = schema.Datetime( title=_(u"Data de Upload"), required=True, default=agora ) </code></pre> <p>And the error is:</p> <p><code>WrongType: (&lt;zope.i18nmessageid.message.MessageFactory object at 0x7f118f168890&gt;, &lt;type 'unicode'&gt;, 'title')</code></p> <p>I Set up in fist line:</p> <p><code># -*- coding: utf-8 -*-</code></p> <p>But the error persists.</p>
0
2016-09-06T12:40:56Z
39,350,812
<p>The solutions is change the line 13:</p> <p><code>from projetime.ged import MessageFactory as _</code></p> <p>to:</p> <p><code>from projetime.ged import _</code></p> <p>Like see here <a href="https://github.com/plone/Products.CMFPlone/issues/386" rel="nofollow">https://github.com/plone/Products.CMFPlone/issues/386</a></p>
0
2016-09-06T13:53:57Z
[ "python", "zope", "dexterity", "plone-4.x" ]
How to remove outer list?
39,349,281
<p>I have a simple example, Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p> <p>And i am solving it like this:</p> <pre><code>n = 4 list_range = list(range(1,n+1)) divisor_list = [] divisor_list.append([i for i in list_range if n%i==0]) print divisor_list #output: #[[1, 2, 4]] </code></pre> <p>I want the output to be <code>[1, 2, 4]</code></p> <p>I can achieve this by:</p> <pre><code>n = 4 list_range = list(range(1,n+1)) divisor_list = [] for i in list_range: if n % i == 0: divisor_list.append(i) print divisor_list #output: #[1, 2, 4] </code></pre> <p>But is there a better way of achieving this ?</p>
-1
2016-09-06T12:42:10Z
39,349,353
<p>Use <code>extend</code>: <code>divisor_list.extend([i for i in list_range if n%i==0])</code></p>
1
2016-09-06T12:45:24Z
[ "python", "list", "python-2.7" ]
How to remove outer list?
39,349,281
<p>I have a simple example, Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p> <p>And i am solving it like this:</p> <pre><code>n = 4 list_range = list(range(1,n+1)) divisor_list = [] divisor_list.append([i for i in list_range if n%i==0]) print divisor_list #output: #[[1, 2, 4]] </code></pre> <p>I want the output to be <code>[1, 2, 4]</code></p> <p>I can achieve this by:</p> <pre><code>n = 4 list_range = list(range(1,n+1)) divisor_list = [] for i in list_range: if n % i == 0: divisor_list.append(i) print divisor_list #output: #[1, 2, 4] </code></pre> <p>But is there a better way of achieving this ?</p>
-1
2016-09-06T12:42:10Z
39,349,370
<p>You don't need append, just use:</p> <pre><code>divisor_list = [i for i in list_range if n% i == 0] </code></pre> <p>This way you just assign the result of list comprehension, giving you one clean list. No need to append a list, that will nest a list in a list, and no need to initialize as an empty list. That's redundant because you add to the list just the next line. Just assign to list comprehension. As @joel goldstick mentioned, you can just loop over <em>half</em> of <code>list_range</code> because nothing will be a division if it's more than 1/2 the number:</p> <pre><code>list_range = list(range(1, (n / 2) + 1)) </code></pre>
1
2016-09-06T12:46:22Z
[ "python", "list", "python-2.7" ]
How to remove outer list?
39,349,281
<p>I have a simple example, Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p> <p>And i am solving it like this:</p> <pre><code>n = 4 list_range = list(range(1,n+1)) divisor_list = [] divisor_list.append([i for i in list_range if n%i==0]) print divisor_list #output: #[[1, 2, 4]] </code></pre> <p>I want the output to be <code>[1, 2, 4]</code></p> <p>I can achieve this by:</p> <pre><code>n = 4 list_range = list(range(1,n+1)) divisor_list = [] for i in list_range: if n % i == 0: divisor_list.append(i) print divisor_list #output: #[1, 2, 4] </code></pre> <p>But is there a better way of achieving this ?</p>
-1
2016-09-06T12:42:10Z
39,349,372
<p>You can use assign the result of the list comprehension to the variable.</p>
1
2016-09-06T12:46:26Z
[ "python", "list", "python-2.7" ]
How to remove outer list?
39,349,281
<p>I have a simple example, Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p> <p>And i am solving it like this:</p> <pre><code>n = 4 list_range = list(range(1,n+1)) divisor_list = [] divisor_list.append([i for i in list_range if n%i==0]) print divisor_list #output: #[[1, 2, 4]] </code></pre> <p>I want the output to be <code>[1, 2, 4]</code></p> <p>I can achieve this by:</p> <pre><code>n = 4 list_range = list(range(1,n+1)) divisor_list = [] for i in list_range: if n % i == 0: divisor_list.append(i) print divisor_list #output: #[1, 2, 4] </code></pre> <p>But is there a better way of achieving this ?</p>
-1
2016-09-06T12:42:10Z
39,349,390
<p>You don't need to initialize <code>divisor_list</code> as an empty sequence at all. The comprehension you're appending is the actual answer you're looking for.</p> <pre><code>divisor_list = [i for i in list_range if n%i==0] </code></pre>
1
2016-09-06T12:47:08Z
[ "python", "list", "python-2.7" ]
How to remove outer list?
39,349,281
<p>I have a simple example, Create a program that asks the user for a number and then prints out a list of all the divisors of that number.</p> <p>And i am solving it like this:</p> <pre><code>n = 4 list_range = list(range(1,n+1)) divisor_list = [] divisor_list.append([i for i in list_range if n%i==0]) print divisor_list #output: #[[1, 2, 4]] </code></pre> <p>I want the output to be <code>[1, 2, 4]</code></p> <p>I can achieve this by:</p> <pre><code>n = 4 list_range = list(range(1,n+1)) divisor_list = [] for i in list_range: if n % i == 0: divisor_list.append(i) print divisor_list #output: #[1, 2, 4] </code></pre> <p>But is there a better way of achieving this ?</p>
-1
2016-09-06T12:42:10Z
39,349,758
<p>It makes no sense to loop through all range of numbers, it's a waste! Just try to prove there are no more divisors after n/2, here's another benchmarked version comparing an alternative method <code>f2</code>:</p> <pre><code>import math import timeit def f1(num): return [i for i in range(1, num + 1) if num % i == 0] def f2(num): square_root = int(math.sqrt(num)) + 1 output = [] for i in range(1, square_root): if (num % i == 0 and i * i != num): output.append(i) output.append(num / i) if (num % i == 0 and i * i == num): output.append(i) return output def bench(f, N): for n in range(1, N): f(N) N = 10000 print timeit.timeit('bench(f1, N)', setup='from __main__ import bench, f1, N', number=1) print timeit.timeit('bench(f2, N)', setup='from __main__ import bench, f2, N', number=1) </code></pre> <p>Results on my cpu are:</p> <pre><code>4.39642974016 0.124005777533 </code></pre> <p>f2 won't give a sorted list, but that's irrelevant, you didn't mention that in your question</p>
1
2016-09-06T13:05:20Z
[ "python", "list", "python-2.7" ]
How to remove square brackets in result pos_tag
39,349,400
<p>I want to extract nouns from dataframe. I do as below</p> <pre><code>import pandas as pd import nltk from nltk.tag import pos_tag df = pd.DataFrame({'pos': ['noun', 'Alice', 'good', 'well', 'city']}) noun=[] for index, row in df.iterrows(): noun.append([word for word,pos in pos_tag(row) if pos == 'NN']) df['noun'] = noun </code></pre> <p>and i get df['noun']</p> <pre><code>0 [noun] 1 [Alice] 2 [] 3 [] 4 [city] </code></pre> <p>I use regex </p> <pre><code>df['noun'].replace('[^a-zA-Z0-9]', '', regex = True) </code></pre> <p>and again</p> <pre><code>0 [noun] 1 [Alice] 2 [] 3 [] 4 [city] Name: noun, dtype: object </code></pre> <p>what's wrong?</p>
0
2016-09-06T12:47:36Z
39,349,493
<p>The bracket means you have lists in each cell of the data frame. If you are sure there is only one element at most in each list, you can use <code>str</code> on the noun column and extract the first element:</p> <pre><code>df['noun'] = df.noun.str[0] df # pos noun #0 noun noun #1 Alice Alice #2 good NaN #3 well NaN #4 city city </code></pre>
2
2016-09-06T12:52:30Z
[ "python", "nltk", "pos-tagger" ]
install qgis on debian jessie
39,349,492
<p>I need to install qgis, qgis server, and lizmap on Debian jessie, and I can not install them. Currently my sources.list is as follows</p> <p><a href="http://i.stack.imgur.com/48W3h.jpg" rel="nofollow">enter image description here</a></p> <p>debian version installed:</p> <pre><code>root@SIG:~# cat /etc/debian_version stretch/sid </code></pre> <p>Firstly, the system was wheezy (7.3) According to our needs, I must make the upgrade the server to jessie.</p> <p>here is my screen snapshot when I type on putty:</p> <pre><code>root@SIG:~# apt-get install qgis python-qgis qgis-plugin-grass </code></pre> <p>I receive the following error messages</p> <p><a href="http://i.stack.imgur.com/moDGm.jpg" rel="nofollow">enter image description here</a></p> <p>And I followed to apt-get -f install but the problem still resists.</p> <p>I do not know; is it possible of the internet connection a bit slow? Because our internet connection is not famous</p> <p>Desolated, we used the French language in our system</p>
-1
2016-09-06T12:52:28Z
39,349,847
<p>It seems that you're missing some dependencies. Try the following using root mode, or sudo if you wish. </p> <pre><code>apt-get install -f </code></pre> <p>then,</p> <pre><code>apt-get install qgis python-qgis qgis-plugin-grass </code></pre>
1
2016-09-06T13:09:33Z
[ "python", "qgis" ]
App Engine throws 404 Not Found for any path but root
39,349,590
<p>I want to split my App Engine implementation into several files. So I wrote in my app.yaml file:</p> <pre><code>runtime: python27 api_version: 1 threadsafe: true handlers: - url: /imageuploader script: imageuploader.app - url: /search script: main.app - url: / static_files: index.html upload: index.html libraries: - name: MySQLdb version: "latest" </code></pre> <p>Basically I search and image upload to be on different paths and root path to have index file.</p> <p>Here are my handlers:</p> <p>main.py:</p> <pre><code>class MainPage(webapp2.RequestHandler): def get(self): #Implementation app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) </code></pre> <p>imageuploader.py:</p> <pre><code>class UserPhoto(ndb.Model): blob_key = ndb.BlobKeyProperty() class PhotoUploadFormHandler(webapp2.RequestHandler): def get(self): # [START upload_url] upload_url = blobstore.create_upload_url('/upload_photo') # [END upload_url] # [START upload_form] # To upload files to the blobstore, the request method must be "POST" # and enctype must be set to "multipart/form-data". self.response.out.write(""" &lt;html&gt;&lt;body&gt; &lt;form action="{0}" method="POST" enctype="multipart/form-data"&gt; Upload File: &lt;input type="file" name="file"&gt;&lt;br&gt; &lt;input type="submit" name="submit" value="Submit"&gt; &lt;/form&gt; &lt;/body&gt;&lt;/html&gt;""".format(upload_url)) # [END upload_form] # [START upload_handler] class PhotoUploadHandler(blobstore_handlers.BlobstoreUploadHandler): def post(self): try: upload = self.get_uploads()[0] user_photo = UserPhoto( user=users.get_current_user().user_id(), blob_key=upload.key()) user_photo.put() self.redirect('/view_photo/%s' % upload.key()) except: self.error(500) # [END upload_handler] # [START download_handler] class ViewPhotoHandler(blobstore_handlers.BlobstoreDownloadHandler): def get(self, photo_key): if not blobstore.get(photo_key): self.error(404) else: self.send_blob(photo_key) # [END download_handler] app = webapp2.WSGIApplication([ ('/', PhotoUploadFormHandler), ('/upload_photo', PhotoUploadHandler), ('/view_photo/([^/]+)?', ViewPhotoHandler), ], debug=True) # [END all] </code></pre> <p>Now, the weird thing is that if I set </p> <pre><code>-url: /.* script: main.app </code></pre> <p>It all works. I also tried <code>/search/.+</code> and <code>/imageuploader/.+</code>. I must have forgotten something completely obvious but I cant figure out what is it.</p>
0
2016-09-06T12:56:55Z
39,352,009
<p>Each <code>app.yaml</code> route script config (like <code>script: imageuploader.app</code>) requires a python file with a matching name (<code>imageuploader.py</code> in this case) which is defining an app called <code>app</code> (just like the <code>main.py</code> does) with app routes being, of course, a subset of (or equal to) the corresponding path from the <code>app.yaml</code> file (<code>/imageuploader</code> in this case).</p> <p>So, problems with your implementation:</p> <ul> <li>the <code>main.py</code> app path is <code>/</code> - doesn't match the corresponding <code>/search</code> path in <code>app.yaml</code></li> <li>none of the 3 app path patterns in <code>imageuploader.py</code> matches the corresponding <code>/imageuploader</code> path in <code>app.yaml</code></li> <li>the <code>/</code> path in <code>app.yaml</code> is actually mapped to the static resource <code>index.html</code>, so it'll be served by GAE directly - no point adding a handler for it as that handler should never be invoked (you may want to revisit the static resources mapping).</li> </ul> <p>Your attempt using <code>/.*</code> mapped to <code>main.app</code> could only have worked <strong>before</strong> you removed the handler code now in <code>imageuploader.py</code>, but should not be working with the <code>main.py</code> content from your question.</p> <p>Assuming your patterns in the <code>app.yaml</code> are the ones you desire, these would be the app configs you'd need (to continue with your approach):</p> <p>main.py:</p> <pre><code>app = webapp2.WSGIApplication([ ('/search', MainPage), ], debug=True) </code></pre> <p>imageuploader.py:</p> <pre><code>app = webapp2.WSGIApplication([ ('/imageuploader', ...), # TODO: revisit mappings ], debug=True) </code></pre> <p>But I'd suggest a simpler to manage approach, using <a href="http://webapp2.readthedocs.io/en/latest/guide/routing.html#guide-routing-lazy-handlers" rel="nofollow">webapp2's lazy loading</a> of the handler code.</p> <p>You keep a single, generic mapping in the <code>app.yaml</code>, which would match <strong>any url pattern</strong> in the <code>main.py</code> file:</p> <pre><code>- url: /.* script: main.app </code></pre> <p>You have a single app route mapping definition in <code>main.py</code>, but which can lazy-load handlers from both <code>main.py</code> as well as other modules/files. For example something like this:</p> <pre><code>app = webapp2.WSGIApplication([ ('/upload', 'imageuploader.PhotoUploadFormHandler'), ('/upload_photo', 'imageuploader.PhotoUploadHandler'), ('/view_photo/([^/]+)?', 'imageuploader.ViewPhotoHandler'), ('/main_page', MainPage), ], debug=True) </code></pre> <p>A middle-ground approach is also possible, allowing you to completely de-couple <code>imageuploader.py</code> from <code>main.py</code> but with a slightly more careful url pattern choice.</p> <p>You could have in <code>app.yaml</code>:</p> <pre><code>- url: /photo.* script: imageuploader.app </code></pre> <p>And in <code>imageuploader.py</code> have url patterns matching that <code>/photo.*</code> one:</p> <pre><code>app = webapp2.WSGIApplication([ ('/photo_upload_form', PhotoUploadFormHandler), ('/photo_upload', PhotoUploadHandler), ('/photo_view/([^/]+)?', ViewPhotoHandler), ], debug=True) </code></pre>
2
2016-09-06T14:51:19Z
[ "python", "google-app-engine", "app.yaml" ]
Arg parse: parse file name as string (python)
39,349,653
<p>I would like to parse the name of a file into my script as a string, rather than directly converting the file into an object.</p> <p>Here is a sample code, <code>test.py</code>:</p> <pre><code>import argparse import os.path def is_valid_file(parser, arg): if not os.path.exists(arg): parser.error("The file %s does not exist! Use the --help flag for input options." % arg) else: return open(arg, 'r') parser = argparse.ArgumentParser(description='test') parser.add_argument("-test", dest="testfile", required=True, help="test", type=lambda x: is_valid_file(parser, x)) args = parser.parse_args() print args.testfile </code></pre> <p><code>testfile</code> is a <code>.txt</code> file containing: <code>1,2,3,4</code></p> <p>In principal would like <code>print args.testfile</code> to return the invoked name of <code>testfile</code> as a string:</p> <pre><code>$ python test.py -test test.txt &gt;&gt; "test.txt" </code></pre> <p>To achieve this I need to prevent argparser from converting test.txt into an object. How can I do this?</p> <p>Many thanks!</p>
-1
2016-09-06T13:00:21Z
39,352,415
<p>you can modify your function as follows to return the string after having checked it exists:</p> <pre><code>def is_valid_file(parser, arg): if not os.path.exists(arg): parser.error("The file %s does not exist! Use the --help flag for input options." % arg) else: return arg </code></pre> <p>There's also a more direct method:</p> <pre><code>parser.add_argument("-test", dest="testfile", required=True, help="test", type=file) # file exists in python 2.x only parser.add_argument("-test", dest="testfile", required=True, help="test", type=lambda f: open(f)) # python 3.x args = parser.parse_args() print(args.testfile.name) # name of the file from the file handle </code></pre> <p>actually <code>args.testfile</code> is the file handle, opened by argparser (exception if not found). You can read from it directly.</p>
0
2016-09-06T15:10:53Z
[ "python", "string", "filenames", "argparse" ]
Arg parse: parse file name as string (python)
39,349,653
<p>I would like to parse the name of a file into my script as a string, rather than directly converting the file into an object.</p> <p>Here is a sample code, <code>test.py</code>:</p> <pre><code>import argparse import os.path def is_valid_file(parser, arg): if not os.path.exists(arg): parser.error("The file %s does not exist! Use the --help flag for input options." % arg) else: return open(arg, 'r') parser = argparse.ArgumentParser(description='test') parser.add_argument("-test", dest="testfile", required=True, help="test", type=lambda x: is_valid_file(parser, x)) args = parser.parse_args() print args.testfile </code></pre> <p><code>testfile</code> is a <code>.txt</code> file containing: <code>1,2,3,4</code></p> <p>In principal would like <code>print args.testfile</code> to return the invoked name of <code>testfile</code> as a string:</p> <pre><code>$ python test.py -test test.txt &gt;&gt; "test.txt" </code></pre> <p>To achieve this I need to prevent argparser from converting test.txt into an object. How can I do this?</p> <p>Many thanks!</p>
-1
2016-09-06T13:00:21Z
39,354,560
<p>The <code>FileType</code> type factory does most of what your code does, with a slightly different message mechanism:</p> <pre><code>In [16]: parser=argparse.ArgumentParser() In [17]: parser.add_argument('-f',type=argparse.FileType('r')) In [18]: args=parser.parse_args(['-f','test.txt']) In [19]: args Out[19]: Namespace(f=&lt;_io.TextIOWrapper name='test.txt' mode='r' encoding='UTF-8'&gt;) In [20]: args.f.read() Out[20]: ' 0.000000, 3.333333, 6.666667, 10.000000, 13.333333, 16.666667, 20.000000, 23.333333, 26.666667, 30.000000\n' In [21]: args.f.close() </code></pre> <p>For a valid name it opens the file, which you can use and close. But you can't use it in a <code>with</code> context.</p> <p>If the file doesn't exist it exits with usage and a <code>cant open</code> message.</p> <pre><code>In [22]: args=parser.parse_args(['-f','test11.txt']) usage: ipython3 [-h] [-f F] ipython3: error: argument -f: can't open 'test11.txt': [Errno 2] No such file or directory: 'test11.txt' </code></pre> <p><code>FileType</code> <code>__call__</code> handles the error with an <code>argparse.ArgumentTypeError</code></p> <pre><code> except OSError as e: message = _("can't open '%s': %s") raise ArgumentTypeError(message % (string, e)) </code></pre> <p>Using this error mechanism, and omitting your <code>open</code> I'd suggest:</p> <pre><code>def valid_file(astring): if not os.path.exists(astring): msg = "The file %s does not exist! Use the --help flag for input options." % astring raise argparse.ArgumentTypeError(msg) else: return astring </code></pre> <p>Which could be used as:</p> <pre><code>In [32]: parser=argparse.ArgumentParser() In [33]: parser.add_argument('-f',type=valid_file) In [34]: args=parser.parse_args(['-f','test11.txt']) usage: ipython3 [-h] [-f F] ipython3: error: argument -f: The file test11.txt does not exist! Use the --help flag for input options. An exception has occurred, use %tb to see the full traceback. SystemExit: 2 In [35]: args=parser.parse_args(['-f','test.txt']) In [36]: args Out[36]: Namespace(f='test.txt') In [37]: with open(args.f) as f:print(f.read()) 0.000000, 3.333333, 6.666667, 10.000000, 13.333333, 16.666667, 20.000000, 23.333333, 26.666667, 30.000000 </code></pre> <p><a href="http://bugs.python.org/issue13824" rel="nofollow">http://bugs.python.org/issue13824</a> worries about <code>FileType</code> opening a file but not closing it. I proposed a <code>FileContext</code>, modeled on <code>FileType</code>, but instead of opening the file, returns an object that can be use as:</p> <pre><code>with arg.file() as f: f.read() </code></pre> <p>It would do the file existence or creatablity testing, without actually opening or creating the file. It's a more complicated solution.</p>
0
2016-09-06T17:19:24Z
[ "python", "string", "filenames", "argparse" ]
'import sitecustomize' fails when opening spyder with non-empty file
39,349,701
<p>I get the error message <code>'import sitecustomize' failed; use -v for traceback</code> in the internal python console in Spyder. </p> <p>The interesting thing is, this only happens inside Spyder, running python in a shell doesn't show the same behaviour.</p> <p>Furthermore, when I do </p> <pre><code>spyder --reset </code></pre> <p>It all works until I close Spyder during having any python file open in Spyder. After restart, the error message is shown again.</p> <p>I saw the answer to <a href="http://stackoverflow.com/questions/17258634/import-sitecustomize-failed-upon-starting-spyder">&#39;import sitecustomize&#39; failed upon starting spyder</a>. I am on Ubuntu 16.04 with Python 2.7.12 (64bit) and Spyder version 2.3.8 and not running a firewall, so this answer most probably doesn't fit to my case. Furthermore, setting the <code>DEBUG_SPYDER</code> variable to <code>True</code>, shows no errors related to this failed import.</p>
0
2016-09-06T13:02:37Z
39,350,377
<p>I found the problem to be special characters in the path name of the current working-directory. Changing working-directories to a path without special characters before exiting spyder resolved the problem.</p>
0
2016-09-06T13:34:51Z
[ "python", "spyder" ]
multiple columns from a file into a single column of lists in pandas
39,349,711
<p>I'm new to pandas , and need to prepare a table using pandas , imitating exact function performed by following code snippet:</p> <pre><code>with open(r'D:/DataScience/ml-100k/u.item') as f: temp='' for line in f: fields = line.rstrip('\n').split('|') movieId = int(fields[0]) name = fields[1] geners = fields[5:25] geners = map(int, geners) </code></pre> <p>My question is how to add a geners column in pandas having same : <code>geners = fields[5:25]</code></p>
0
2016-09-06T13:03:00Z
40,125,850
<p>It's not clear to me what you intend to accomplish -- a single genres column containing fields 5-25 concatenated? Or separate genre columns for fields 5-25?</p> <p>For the latter, you can use <code>[pandas.read_csv](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html)</code>:</p> <pre class="lang-py prettyprint-override"><code>import pandas as pd cols = ['movieId', 'name'] + ['genre_' + str(i) for i in range(5, 25)] df = pd.read_csv(r'D:/DataScience/ml-100k/u.item', delimiter='|', names=cols) </code></pre> <p>For the former, you could concatenate the genres into say, a space-separated list, using:</p> <pre class="lang-py prettyprint-override"><code>df['genres'] = df[cols[2:]].apply(lambda x: ' '.join(x), axis=1) df.drop(cols[2:], axis=1, inplace=True) # drop the separate genre_N columns </code></pre>
0
2016-10-19T08:21:12Z
[ "python", "pandas", "data-science" ]
Bash script equivalent in windows to run pip and python commands?
39,349,884
<p>I have a python code which I need to send it to a client who will run it windows. The python code works on a few imported modules mentioned in <code>requirements.txt</code>:</p> <pre><code>requests==2.11.1 xlwt==1.1.2 beautifulsoup4==4.5.1 </code></pre> <p>If I have to execute the code in windows, I’ll have manually ask the client to download these above modules before running the script. I have created a bash script ( for linux), which is such:</p> <pre><code>sudo pip install -r requirements.txt echo "Requirements met" python ./isb.py </code></pre> <p>What is the bash script equivalent in windows? I want to client to only execute 1 file which executes other remaining files. </p> <p>Can an executable be made for a task like this? The code and other files are <a href="https://drive.google.com/drive/folders/0B0byAC8kZZPhYklnRVEzN245WFk?usp=sharing" rel="nofollow">here</a> if need be. </p>
0
2016-09-06T13:11:23Z
39,350,054
<p>I has similar task in the past. So I just used a tool py2exe which builds a standalone executable and it resolves dependencies at build time. A valid python interpreter will be included to the build. So your client can just execute this standalone exe file by double-click or from cmd shell.</p>
0
2016-09-06T13:19:33Z
[ "python", "windows", "cmd", "exe" ]
Simple but require bit manipulation Python Hex and INT
39,349,977
<p>I have an integer - say for example </p> <pre><code>a = 12345 b = hex(a) </code></pre> <p>I have to send this to an MCU in a specific format. First I have to convert it into hex. which I did and it gives me --- 0x3039; </p> <p>I need an array something like this - [0x39, 0x30]</p> <p>Currently I am converting the whole number into a string then to a list and then doing some element of list manipulation. </p> <p>I am hoping there is something easier. Which can be done in a line or two? It should work even with the following numbers - 1234, 123, 12, 1- Implying it should work from single digit to five digit numbers. </p>
0
2016-09-06T13:15:46Z
39,350,047
<p>If you need a list of hex strings with number as little endian bytes:</p> <pre><code>a=12345 l = [hex(a&amp;0xff),hex(a&gt;&gt;8)] # little endian format, as hex string print(l) </code></pre> <p>gives:</p> <pre><code>['0x39', '0x30'] </code></pre> <p>note the quotes, it is not possible to print <code>[0x39, 0x30]</code>. If you want the integer values, just do</p> <pre><code>l = [a&amp;0xff,a&gt;&gt;8] # little endian, format as bytes </code></pre> <p>which gives:</p> <pre><code>[57, 48] </code></pre> <p>and BTW:</p> <pre><code>[0x39, 0x30]==[57, 48] =&gt; True </code></pre> <p>it's just that representation/print of integers in a list is in decimal :)</p>
2
2016-09-06T13:19:06Z
[ "python", "arrays", "string", "int" ]
When should token be generated using oAuth
39,350,002
<p>I am striving to understand oAuth2 to implement in my REST API. I am using DRF in my backend and react native for building mobile app. I can create user registration and login in DRF but when and where should i actually create a token. Do i have to create token when user registers or when user logins ? I might get negative voting but i know some expert will enlighten me. </p> <p>The usecase is i have a mobile app called foodie where user can create their account and login. User can login and create account from web too.</p> <p>Where should i actually implement oAuth token in my code? </p> <p><strong>serializers.py</strong></p> <pre><code>class UserCreateSerializer(ModelSerializer): class Meta: model = User fields = [ 'username', 'email', 'first_name', 'last_name', 'password', 'confirm_password' ] extra_kwargs = {"password": {"write_only": True}} def create(self, validated_data): username = validated_data['username'] first_name = validated_data['first_name'] last_name = validated_data['last_name'] email = validated_data['email'] password = validated_data['password'] confirm_password = validated_data['password'] user_obj = User( username = username, first_name = first_name, last_name = last_name, email = email ) user_obj.set_password(password) user_obj.save() return validated_data class UserLoginSerializer(ModelSerializer): # token = CharField(allow_blank=True, read_only=True) username = CharField() class Meta: model = User fields = [ 'username', 'password', # 'token', ] extra_kwargs = {"password":{"write_only": True}} def validate(self, data): return data </code></pre> <p><strong>views.py</strong></p> <pre><code>class UserCreateAPI(CreateAPIView): serializer_class = UserCreateSerializer queryset = User.objects.all() permission_classes = [AllowAny] class UserLoginAPI(APIView): permission_classes = [AllowAny] serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): # access_token = AccessToken.objects.get(token=request.data.get('token'), expires__gt=timezone.now()) data = request.data serializer = UserLoginSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) </code></pre>
0
2016-09-06T13:16:45Z
39,350,548
<p>Probably, The question you should be asking is will a simple encrypted cookie not suffice which you pass to the server when you try to access the protected URLs/Resources. Now, If you want to still produce the token then after login hook the code to respond back with token in either header or in response payload. Once token is there, you pass the token in http header as Authorization: Bearer to the resource server which processes the token and gives the access.</p>
0
2016-09-06T13:42:44Z
[ "python", "django", "python-3.x", "oauth", "django-rest-framework" ]
How to write better way to python inheritance?
39,350,017
<p>I have written this,</p> <pre><code>class Sp(): def __init__(self): self.price = 1 class A(Sp): def __init__(self): super(A, self).__init__() self.test = True class B(A): pass class C(A): pass class D(A): """In this class I don't want to inherit Sp class, but need A class""" def __init__(self): super(D, self).__init__() self.me = 'ok' self.list_ = [Sp()] </code></pre> <p><strong>Sp</strong> is the Parent class for <strong>A</strong>. And I'm using <strong>A</strong> class in <strong>B</strong>,<strong>C</strong> and <strong>D</strong>, But <strong>D</strong> don't need Sp inheritance instead it needs <strong>Sp</strong> instance object inside <strong>D</strong>(Please look into <strong>D</strong> class). I want to stop <strong>Sp</strong> inheritance in <strong>D</strong>, is there any good way to write this ?</p>
-2
2016-09-06T13:17:20Z
39,350,347
<p>You can't inherit from <code>A</code> without inheriting from <code>Sp</code> if <code>A</code> itself inherits from <code>Sp</code>. You could try to work around it though, by making <code>A</code> inherit from two classes, one of which implements the non-<code>Sp</code> behaviors (say, call it <code>Abits</code>), and <code>Sp</code> (<code>class A(Abits, Sp):</code>). Then have <code>B</code> and <code>C</code> inherit <code>A</code>, while <code>D</code> inherits solely from <code>Abits</code>.</p> <p>If <code>A</code> doesn't need to be created independently, you could just make <code>A</code> not inherit from <code>Sp</code> at all, and have <code>B</code> and <code>C</code> inherit from both <code>A</code> and <code>Sp</code> (<code>class B(A, Sp):</code>), while <code>D</code> only inherits from <code>A</code>, which saves the need for a separate <code>Abits</code>.</p> <p>Lastly, you might consider composition. Have <code>D</code> not inherit from anything, just contain an instance of <code>A</code>. Then use <a href="https://docs.python.org/3/reference/datamodel.html#object.__getattr__" rel="nofollow">the <code>__getattr__</code> special method</a> to get attributes from <code>A</code> when they're not defined on <code>D</code>:</p> <pre><code>class D(object): # Explicitly inheriting from object not needed on Py3 def __init__(self, ...): self.a = A(...) def __getattr__(self, name): # Only called when attribute "name" doesn't exist on instance of D return getattr(self.a, name) </code></pre> <p>You might also need to use <code>__setattr__</code> if you need to mutate the <code>A</code> instance. This is trickier (because <code>__setattr__</code> is called unconditionally, not just when an attribute doesn't exist), but there are plenty of examples of using it available if you search.</p>
0
2016-09-06T13:33:08Z
[ "python", "inheritance" ]
Selenium Webdriver Python: I can't seem to locate all the text in a label tag
39,350,070
<pre><code>&lt;label class="control-label"&gt; Rental Charge: &lt;span class="required" ng-show="vm.rentalInfo.reason"&gt;* (Min of $30.00)&lt;/span&gt; &lt;/label&gt; </code></pre> <p>I used </p> <pre><code>driver.find_element_by_xpath("//label[@ class = 'control-label']/span[@class = 'required']").text </code></pre> <p>and the only <code>text</code> I get back is the <code>asterisk *</code>, <code>(Min of $30.00)</code> is not displayed. Does anyone know why this is?</p>
0
2016-09-06T13:20:15Z
39,351,429
<p>I am guessing this is a timing issue. <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="nofollow">Wait</a> for "$" to be present in element explicitly with <code>text_to_be_present_in_element</code> expected condition:</p> <pre><code>from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) elm = wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, 'span[ng-show*="rentalIn‌​fo.reason"]'), "$")) print(elm.text) </code></pre>
0
2016-09-06T14:23:02Z
[ "python", "angularjs", "selenium", "selenium-webdriver", "automated-tests" ]
Selenium Webdriver Python: I can't seem to locate all the text in a label tag
39,350,070
<pre><code>&lt;label class="control-label"&gt; Rental Charge: &lt;span class="required" ng-show="vm.rentalInfo.reason"&gt;* (Min of $30.00)&lt;/span&gt; &lt;/label&gt; </code></pre> <p>I used </p> <pre><code>driver.find_element_by_xpath("//label[@ class = 'control-label']/span[@class = 'required']").text </code></pre> <p>and the only <code>text</code> I get back is the <code>asterisk *</code>, <code>(Min of $30.00)</code> is not displayed. Does anyone know why this is?</p>
0
2016-09-06T13:20:15Z
39,352,336
<p>It's hard to say what is the issue in your case, it it is not timing issue. You should try using <code>get_att‌​ribute()</code> as below may be it helps :-</p> <pre><code> driver.find_element_by_css_selector("span.required[ng-show*='rentalIn‌​fo.reason']").get_att‌​ribute("textContent"‌​) </code></pre> <p>or </p> <pre><code>driver.find_element_by_css_selector("span.required[ng-show*='rentalIn‌​fo.reason']").get_att‌​ribute("innerHTML") </code></pre>
0
2016-09-06T15:07:09Z
[ "python", "angularjs", "selenium", "selenium-webdriver", "automated-tests" ]
Selenium Webdriver Python: I can't seem to locate all the text in a label tag
39,350,070
<pre><code>&lt;label class="control-label"&gt; Rental Charge: &lt;span class="required" ng-show="vm.rentalInfo.reason"&gt;* (Min of $30.00)&lt;/span&gt; &lt;/label&gt; </code></pre> <p>I used </p> <pre><code>driver.find_element_by_xpath("//label[@ class = 'control-label']/span[@class = 'required']").text </code></pre> <p>and the only <code>text</code> I get back is the <code>asterisk *</code>, <code>(Min of $30.00)</code> is not displayed. Does anyone know why this is?</p>
0
2016-09-06T13:20:15Z
39,353,378
<p>I tried to be a little specific like @alecxe suggested. So i used xpath <em>driver.find_element_by_xpath("//span[@ng-show = 'vm.rentalInfo.reason']").text</em> and it gave me the whole text "* (Min of $30.00)". Thanks to Saurabh Gaur and alecxe for your responses.</p>
0
2016-09-06T16:06:08Z
[ "python", "angularjs", "selenium", "selenium-webdriver", "automated-tests" ]
Doubts about a Python Webserver
39,350,075
<p>I've a project which I developed a code to capture a temperature in some sensors and displaying a temperature to people, in fact I've a database (txt archive) whose was readed in a webserver to people in same network, now I've to improve this webpage (with some graphics, analitycs and etc) . Someone has a tip to improve that? or begin a new project with a better solution ?</p>
-1
2016-09-06T13:20:23Z
39,350,197
<p>For sure, if you are beginner in python then you should try do it as simple as it can be for example using Flask, all information you can find here: <a href="http://flask.pocoo.org/" rel="nofollow">http://flask.pocoo.org/</a><br><br> Also if you want to write serious web page which contain advanced backend then you probably need Django: <a href="https://www.djangoproject.com/" rel="nofollow">https://www.djangoproject.com/</a> <br> <strong>EDIT:</strong><br> I see that you already have some application that probably contain data from sensors, then it is good idea to re use it as a module for your web-service .</p>
0
2016-09-06T13:25:56Z
[ "python", "webserver" ]
Having error null value in column "publicatithon_date" violates not-null constraint in django
39,350,113
<p>Hello I'm new to django and I'm learning django with this book: djangobook.com and I stuck in chapter 5 &amp; 6 because when I try to check my work(in <a href="http://127.0.0.1:8000/admin/books/book/add/" rel="nofollow">http://127.0.0.1:8000/admin/books/book/add/</a>) I get some errors and I was trying to fix those errors and after that they gone but I got a new error and I tried to figure out how to solve it but I still don't know how. This is my error:</p> <blockquote> <p>IntegrityError at /admin/books/book/add/</p> <p>null value in column "publicatithon_date" violates not-null constraint</p> </blockquote> <p>And you can see all of my codes here: <a href="https://github.com/Anahitahf/mysite2" rel="nofollow">https://github.com/Anahitahf/mysite2</a></p> <p>How can I solve this error? Thanks in advance for any feedbacks.</p>
0
2016-09-06T13:22:00Z
39,350,406
<p>As the error states, the publication_date is a not-null field and you're trying to add a Book with publication_date not set.<br> One option to fix that is to make publication_date accept null values in your models.py thus: </p> <pre><code>publication_date = models.DateField(null=true,) </code></pre> <p>However, I think that the issue is being caused as you're trying to reload the page?? Anyhow, try to go back to the admin page and then try to create a new Book again. The error should not happen then. If it does, then you can set the null property of publication_date as true.</p> <p><strong>edit:</strong><br> Going through your models you don't have a "publicatithon_date" field in them. Maybe you created that field by mistake and removed it from your model after making a migrations?? You should do the following in your terminal:</p> <pre><code>$ python manage.py dbshell $ mysql&gt; | psql&gt; ALTER TABLE table_name DROP column publicatithon_date; $ python manage.py syncdb </code></pre> <p>And it will drop the wrong field from the table.</p>
0
2016-09-06T13:36:12Z
[ "python", "django" ]
How to return a comparison operator based on provided two values?
39,350,132
<p>I would like to create a python function that once provided with two <code>int</code> values will return a comparison string. There are the obvious ways, of using <code>if</code> blocks or <code>for</code> and <code>while</code> loops. I am just curious to find out the best possible solution.</p> <pre><code>def get_comparison_operator(a, b): if a == b: op = '==' elif a &gt; b: op = '&gt;' # ... etc return op </code></pre> <p>A simple <code>if-else</code> block will run into the problem of distinguishing between <code>==</code> and <code>&lt;=</code> or <code>&gt;=</code> so probably I would go with a <code>for</code> loop with a <code>break</code>. However, as I said before, I am keen to learn the efficient way of doing this, if any.</p>
0
2016-09-06T13:22:35Z
39,350,287
<p>You may use <code>operator</code> module to reduce line count, but in the end of the day you need to keep list of operations to check.</p> <pre><code>import operator operators = [operator.eq, operator.lt, operator.gt, operator.ne] labels = ["==", "&lt;", "&gt;", "!="] def get_comparison_operator(a, b): for op, label in zip(operators, labels): if op(a, b): return label return None </code></pre> <p>Obviously check order is crucial here, if greater equal is checked before greater, second one will not have a change to be returned.</p> <p>Alternative form with list of tuples, I must say table-like form looks really nice.</p> <pre><code>import operator operators = [ (operator.eq, "=="), (operator.lt, "&lt;"), (operator.gt, "&gt;"), (operator.ne, "!=") ] def get_comparison_operator(a, b): for op, label in operators: if op(a, b): return label return None </code></pre> <p>Obviously, eq/lt/gt is fairly trivial, since 3 possibilities covers 100% of cases and they are mutually exclusive. Maybe for some weirder operators this approach makes more sense.</p>
4
2016-09-06T13:30:06Z
[ "python" ]
Tensorflow: parallel for loop results in out-of-memory
39,350,164
<p>My tensorflow code is like these:</p> <pre><code>for i in range(100): Zk = Zk + function_call(...) </code></pre> <p>It seems that tensorflow runs these 100 iterations in parallel, and keeps many temp vectors which have same size with Zk. However, since Zk is a very long vector, this leads to out-of-memory error immediately. </p> <p>Can anyone give some suggestion on how to force <code>Tensorflow</code> perform loop sequentially. Thanks a lot.</p>
0
2016-09-06T13:23:52Z
39,353,834
<p>The simplest way to solve this problem is to use a <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/framework.html#control_dependencies" rel="nofollow"><code>with tf.control_dependencies():</code></a> block:</p> <pre><code>Zk = ... for i in range(100): with tf.control_dependencies([Zk.op]): Zk = Zk + function_call(...) </code></pre> <p>The <code>with tf.control_dependencies():</code> block ensures that the ops created by <code>function_call()</code> do not run until the previous value for <code>Zk</code> has been computed. This effectively causes the loop iterations to run sequentially.</p> <hr> <p>An alternative solution involves using a <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/control_flow_ops.html#while_loop" rel="nofollow"><code>tf.while_loop()</code></a> to define the iteration, rather than a Python loop. The <code>tf.while_loop()</code> function has a <code>parallel_iterations</code> optional argument that allows you to reduce the amount of parallelism between independent iterations of the loop. One advantage of this approach is that it keeps your graph small: the loop would use O(1) nodes rather than O(N) to perform N iterations. However, it can be slightly tricky to re-cast an arbitrary Python <code>function_call()</code> as a TensorFlow loop body, so you'll probably find it easier to use <code>with tf.control_dependencies():</code> at first.</p>
0
2016-09-06T16:32:03Z
[ "python", "parallel-processing", "tensorflow" ]
Software or python package to draw and plot simple objects in 3D?
39,350,176
<p>I am looking for a software package, or even better, a python package that allows me to draw objects by inputing parameters, for example: I want a circle at position x,y, radius r, thickness t, color c and then look at it at different angles.</p> <p>I know that I could use stuff like blender, but I feel that this is overkill and it would take a long time to learn it sufficiently.</p> <p>I just need this to do some ncie looking plots in my thesis.</p> <p>thx.</p>
1
2016-09-06T13:24:46Z
39,350,368
<p>I would recommend <a href="http://www.openscad.org" rel="nofollow">OpenSCad</a>. It is a software to create 3D objects by writing code. Although it isn't a python package, it is quite lightweight, has a nice view and the commands are really easy to learn - take a look at their <a href="http://www.openscad.org/documentation.html" rel="nofollow">Cheat Sheet</a>. The projects can be shared as text files or exported in various 3D formats, to get a prettier view from other software.</p>
3
2016-09-06T13:34:33Z
[ "python", "graphics" ]
Software or python package to draw and plot simple objects in 3D?
39,350,176
<p>I am looking for a software package, or even better, a python package that allows me to draw objects by inputing parameters, for example: I want a circle at position x,y, radius r, thickness t, color c and then look at it at different angles.</p> <p>I know that I could use stuff like blender, but I feel that this is overkill and it would take a long time to learn it sufficiently.</p> <p>I just need this to do some ncie looking plots in my thesis.</p> <p>thx.</p>
1
2016-09-06T13:24:46Z
39,849,559
<p>And I you want to do the same but stick with Python you can combine OpenSCAD with <a href="https://github.com/SolidCode/SolidPython" rel="nofollow">SolidPython</a>.</p>
1
2016-10-04T10:08:07Z
[ "python", "graphics" ]
Dealing with text file containing list and None values
39,350,184
<p>I have a text file similar to this one:</p> <pre><code>a, 1, 2.5, 3 b, 1, 1, 1 1 2 3 4, 1 2, 3 c 1, 2, 2, 2, 2, None, 2 </code></pre> <p>To put it in a nutshell each row starts with its name and is followed by a variable number of floats or list of floats delimited by commas and some float can be None values. and I would like to parse it to get something similar to a dictionnary D</p> <pre><code>D['a']=[1,2.,3] D['b']=[1,1,[1,1,2,3,4],[1,2],3] D['c']=[1,2,2,2,2,None,2] </code></pre> <p>Basically I could have used <code>numpy.loadtxt</code> or <code>numpy.genfromtxt</code> and played with their options but there is not the same number of column in each row for genfromtxt or there are string values.<br> The csv module is helpful but still requires to do engineering on the resulting rows.<br> Do I need to use IO stream/csv and do that manually or is there some clean pythonic way of doing it ? for now my ugly solution looks like this:</p> <pre><code>import csv f=open("text.txt","rb") reader=csv.reader(f) D={} for row in reader: if len(row)!=0: if row[0]=="a": D["a"]=row[1:] elif row[0]=="b": </code></pre> <p>and so on but now I have got to parse convert strings to number and list and floats. </p> <p><strong>EDIT 1</strong> With @Daniel Lee's answer and this poorly written hack it works but clearly I am not doing things right:</p> <pre><code>def convert list_to_float(L): s=[None]*len(L) for index, l in enumerate(L): if len(l.split())&gt;1: s[index]=[float(e) for e in l.split()] elif 'None' in l: s[index]=None else: s[index]=float(l) return s </code></pre>
0
2016-09-06T13:25:13Z
39,350,350
<p>Try this, D is a dictionary, then each row will use its 1st letter as the key and the rest of the list as the value.</p> <pre><code>import csv with open('items.csv', 'rB') as f: csv_reader = csv.reader(f) for row in csv_reader: try: D[row[0]] = [float(x) for x in row[1:]] except ValueError as e: D[row[0]] = [float(f) for f in x.split() if f!='None' for x in row[1:]] </code></pre> <p>This should do what you want.</p>
2
2016-09-06T13:33:19Z
[ "python", "csv", "numpy" ]
Basemap m.fillcontinents() suppresses points on plot
39,350,279
<p>I'd like to change the colour of the land on a map, but doing so overrides any markers I may have on land. The m.fillcontinents() command suppresses any points of interest plotted. How do I get around this?</p>
0
2016-09-06T13:29:40Z
39,385,588
<p>I figured out that the problem was related to the zorder settings, so somethng like:</p> <pre><code>m.scatter(x, y, zorder=2) m.fillcontinents(color='#997766', lake_color='#99ffff', zorder=1) </code></pre> <p>where setting the symbols to a higher priority (zorder=2) than the fillcontinents (zorder=1) seemed to resolve the issue.</p>
0
2016-09-08T08:01:04Z
[ "python", "matplotlib", "colors", "matplotlib-basemap" ]
Run multiple servers in python at same time (Threading)
39,350,300
<p>I have <strong>2 servers</strong> in python, <strong>I want to mix them up in one single .py and run together</strong>: </p> <p>Server.py: </p> <pre><code>import logging, time, os, sys from yowsup.layers import YowLayerEvent, YowParallelLayer from yowsup.layers.auth import AuthError from yowsup.layers.network import YowNetworkLayer from yowsup.stacks.yowstack import YowStackBuilder from layers.notifications.notification_layer import NotificationsLayer from router import RouteLayer class YowsupEchoStack(object): def __init__(self, credentials): "Creates the stacks of the Yowsup Server," self.credentials = credentials stack_builder = YowStackBuilder().pushDefaultLayers(True) stack_builder.push(YowParallelLayer([RouteLayer, NotificationsLayer])) self.stack = stack_builder.build() self.stack.setCredentials(credentials) def start(self): self.stack.broadcastEvent(YowLayerEvent(YowNetworkLayer.EVENT_STATE_CONNECT)) try: logging.info("#" * 50) logging.info("\tServer started. Phone number: %s" % self.credentials[0]) logging.info("#" * 50) self.stack.loop(timeout=0.5, discrete=0.5) except AuthError as e: logging.exception("Authentication Error: %s" % e.message) if "&lt;xml-not-well-formed&gt;" in str(e): os.execl(sys.executable, sys.executable, *sys.argv) except Exception as e: logging.exception("Unexpected Exception: %s" % e.message) if __name__ == "__main__": import sys import config logging.basicConfig(stream=sys.stdout, level=config.logging_level, format=config.log_format) server = YowsupEchoStack(config.auth) while True: # In case of disconnect, keeps connecting... server.start() logging.info("Restarting..") </code></pre> <p>App.py:</p> <pre><code>import web urls = ( '/', 'index' ) app = web.application(urls, globals()) class index: def GET(self): greeting = "Hello World" return greeting if __name__ == "__main__": app.run() </code></pre> <p>I want to <strong>run both together from single .py file together</strong>. If I try to run them from one file, <strong>either of the both starts and other one starts only when first one is done working.</strong></p> <p><strong>How can I run 2 servers</strong> in python together?</p>
1
2016-09-06T13:30:36Z
39,350,834
<pre><code>import thread def run_app1(): #something goes here def run_app2(): #something goes here if __name__=='__main__': thread.start_new_thread(run_app1) thread.start_new_thread(run_app2) </code></pre> <p>if you need to pass args to the functions you can do:</p> <pre><code>thread.start_new_thread(run_app1, (arg1,arg2,....)) </code></pre> <p>if you want more control in your threads you could go:</p> <pre><code>import threading def app1(): #something here def app2(): #something here if __name__=='__main__': t1 = threading.Thread(target=app1) t2 = threading.Thread(target=app2) t1.start() t2.start() </code></pre> <p>if you need to pass args you can go:</p> <pre><code>t1 = threading.Thread(target=app1, args=(arg1,arg2,arg3.....)) </code></pre> <p>What's the differences between thread vs threading? Threading is higher level module than thread and in 3.x thread got renamed to _thread... more info here: <a href="http://docs.python.org/library/threading.html" rel="nofollow">http://docs.python.org/library/threading.html</a> but that's for another question I guess. </p> <p>So in your case, just make a function that runs the first script, and the second script, and just spawn threads to run them.</p>
1
2016-09-06T13:54:52Z
[ "python", "python-2.7", "web.py", "yowsup" ]
How to manipulate list of list of dictionaries
39,350,364
<p>Hi there i have a wired situation here that i want to manipulate a dictionary key value which is list of lists include dictionaries here is the formation of the data i have </p> <pre><code>my_list=[{'data': [[{'name': [0.0, 0.0]}], [{'name': [False, False]}], [{'name': [u'xm', u'xc']}]],'name': u'new',}] </code></pre> <p>what i want to do is to convert this to : </p> <pre><code>my_list=[{'data': [[{'name': 0.0},{'name': 0.0}], [{'name': False},{'name': False}], [{'name': u'xm'},{'name': u'xc'}]],'name': u'new',}] </code></pre> <p>what i have tried so far is : </p> <pre><code>new_lists = [] for new in x[0]['data']: for new_list in new: for g in new_list['name']: new_list['name'][new_list['name'].index(g)] = {'name': g} for stay in x[0]['data']: new_lists.append(stay[0]['name']) x[0]['data']=new_lists print(x) </code></pre> <p>could i have some help here ? </p>
-1
2016-09-06T13:34:10Z
39,350,821
<p>Here we go, a version independant from keys value :</p> <pre><code>my_list=[{'data': [[{'foo': [0.0, 0.0]}], [{'bar': [False, False]}], [{'pop': [u'xm', u'xc']}]]}] buff = [] for elt in my_list[0]['data']: a = [] k = elt[0].keys()[0] val = elt[0][k] for i in val: a.append({k: i}) buff.append(a) output = [{'data': buff}] </code></pre> <p>Results :</p> <pre><code>[{'data': [[{'foo': 0.0}, {'foo': 0.0}], [{'bar': False}, {'bar': False}], [{'pop': u'xm'}, {'pop': u'xc'}]]}] </code></pre>
0
2016-09-06T13:54:18Z
[ "python", "list", "dictionary" ]
Impregnate string with list entries - alternating
39,350,419
<p>So SO, i am trying to "merge" a string (<code>a</code>) and a list of strings (<code>b</code>):</p> <pre><code>a = '1234' b = ['+', '-', ''] </code></pre> <p>to get the desired output (<code>c</code>):</p> <pre><code>c = '1+2-34' </code></pre> <p>The characters in the desired output string alternate in terms of origin between string and list. Also, the list will always contain one element less than characters in the string. I was wondering what the fastest way to do this is. </p> <p>what i have so far is the following:</p> <pre><code>c = a[0] for i in range(len(b)): c += b[i] + a[1:][i] print(c) # prints -&gt; 1+2-34 </code></pre> <p>But i kind of feel like there is a better way to do this..</p>
3
2016-09-06T13:36:36Z
39,350,520
<p>You can use <a href="https://docs.python.org/3.4/library/itertools.html#itertools.zip_longest" rel="nofollow"><code>itertools.zip_longest</code></a> to <code>zip</code> the two sequences, then keep iterating even after the shorter sequence ran out of characters. If you run out of characters, you'll start getting <code>None</code> back, so just consume the rest of the numerical characters.</p> <pre><code>&gt;&gt;&gt; from itertools import chain &gt;&gt;&gt; from itertools import zip_longest &gt;&gt;&gt; ''.join(i+j if j else i for i,j in zip_longest(a, b)) '1+2-34' </code></pre> <p>As <a href="https://stackoverflow.com/users/476/deceze">@deceze</a> suggested in the comments, you can also pass a <code>fillvalue</code> argument to <code>zip_longest</code> which will insert empty strings. I'd suggest his method since it's a bit more readable.</p> <pre><code>&gt;&gt;&gt; ''.join(i+j for i,j in zip_longest(a, b, fillvalue='')) '1+2-34' </code></pre> <p>A further optimization suggested by <a href="https://stackoverflow.com/users/364696/shadowranger">@ShadowRanger</a> is to remove the temporary string concatenations (<code>i+j</code>) and replace those with an <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.from_iterable</code></a> call instead</p> <pre><code>&gt;&gt;&gt; ''.join(chain.from_iterable(zip_longest(a, b, fillvalue=''))) '1+2-34' </code></pre>
7
2016-09-06T13:41:27Z
[ "python" ]
Could not able to make selection in second drop down list using python and selemium
39,350,473
<p>I am trying to make selection on the second drop down list after making a selection on first drop down list</p> <p>The html code used for the first is :</p> <p><a href="http://i.stack.imgur.com/Su6qC.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/Su6qC.jpg" alt="First Drop down and its option values"></a></p> <p>For the second drop down the html code used is :</p> <p><a href="http://i.stack.imgur.com/eO4YO.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/eO4YO.jpg" alt="Second Drop down and its option values"></a></p> <p>The html code for the drop down has 3 attributes namely : <code>id</code>, <code>style</code> and <code>class</code>. I want to make selection on second drop down as <code>INDIA</code>.The problem is I cant use id attribute as it is dynamic and always changes whenever i load the page and i cant be able to use class as both the drop down has same class as <code>StyledDropDown</code>.</p> <p>I have used find element/elements by class and xpath but it is doing selection on the first drop down in first case and giving error in latter.</p> <p>Thanks in advance </p>
0
2016-09-06T13:39:20Z
39,350,742
<p>You can use <code>indexing</code> here to locate desire <code>dropdown</code>, if there is no possibility to locate using any <code>attribute</code> value of these <code>dropdown</code> as below :-</p> <pre><code>dropdown = driver.find_elements_by_class_name("StyledDropDown") #now check first if length is equal to 2 if len(dropdown) == 2 : firstDropdown = dropdown[0] secondDropdown = dropdown[1] #now do your stuff with desire dropdown </code></pre> <p>Or you can also locate these <code>dropdown</code> using <code>xpath</code> with index to desire as below :-</p> <pre><code>#for first drop down firstDropdown = driver.find_element_by_xpath("(.//select[@class = 'StyledDropDown'])[1]") </code></pre> <p>Blockquote</p> <pre><code>#for second drop down secondDropdown = driver.find_element_by_xpath("(.//select[@class = 'StyledDropDown'])[2]") </code></pre>
0
2016-09-06T13:51:16Z
[ "python", "selenium" ]
Split tuple if key is empty and add correspondence value to its previous tuple value
39,350,496
<p>Here i have a list of tuples,whenever key is empty i want to add correspondence value to its previous tuple value.</p> <p>I am able to achieve this in traditional way, but it looks ugly, Is there any pythonic way to achieve the same ?</p> <p>input : </p> <pre><code>data= [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)] </code></pre> <p>expected output :</p> <pre><code>[13, 26, 39, 52] </code></pre> <p>My CODE:</p> <pre><code>data = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)] init = 0 ; splitdata = [] for i in data: init = init+i[1] if i[0] == '': splitdata.append(init) splitdata.append(init) print(splitdata) [13, 26, 39, 52] </code></pre>
1
2016-09-06T13:40:37Z
39,350,658
<pre><code>reduce( lambda lst,item: (((item[0] != '') and lst) or lst[:-1]) + [lst[-1] + item[1]], colLabelGrouped[1:], [colLabelGrouped[0][1]] ) </code></pre> <p>This reduction...</p> <ul> <li>starts with an initial list consisting of the value of the first item in <code>colLabelGrouped</code>, then</li> <li>reduces the remaining items in <code>colLabelGrouped</code> by... <ul> <li>appending the value of each item in turn added to the last element of the list being produced to <em>either</em>... <ul> <li>the complete list (if the item's key is not empty) or</li> <li>the list minus the last element (if the item's key is empty).</li> </ul></li> </ul></li> </ul>
1
2016-09-06T13:47:26Z
[ "python", "list", "tuples" ]
Split tuple if key is empty and add correspondence value to its previous tuple value
39,350,496
<p>Here i have a list of tuples,whenever key is empty i want to add correspondence value to its previous tuple value.</p> <p>I am able to achieve this in traditional way, but it looks ugly, Is there any pythonic way to achieve the same ?</p> <p>input : </p> <pre><code>data= [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)] </code></pre> <p>expected output :</p> <pre><code>[13, 26, 39, 52] </code></pre> <p>My CODE:</p> <pre><code>data = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)] init = 0 ; splitdata = [] for i in data: init = init+i[1] if i[0] == '': splitdata.append(init) splitdata.append(init) print(splitdata) [13, 26, 39, 52] </code></pre>
1
2016-09-06T13:40:37Z
39,350,952
<p>Here's a slightly shorter way of doing it using the accumulate function and list-comprehensions (it might be more readable too):</p> <pre><code>colLabelGrouped = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)] from itertools import accumulate cumsum = list(accumulate([x[1] for x in colLabelGrouped])) result = [cumsum[i] for i,x in enumerate(colLabelGrouped) if x[0] == ""] if colLabelGrouped[-1][0] != "": result.append(cumsum[-1]) print(result) </code></pre>
1
2016-09-06T14:00:27Z
[ "python", "list", "tuples" ]
Split tuple if key is empty and add correspondence value to its previous tuple value
39,350,496
<p>Here i have a list of tuples,whenever key is empty i want to add correspondence value to its previous tuple value.</p> <p>I am able to achieve this in traditional way, but it looks ugly, Is there any pythonic way to achieve the same ?</p> <p>input : </p> <pre><code>data= [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)] </code></pre> <p>expected output :</p> <pre><code>[13, 26, 39, 52] </code></pre> <p>My CODE:</p> <pre><code>data = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)] init = 0 ; splitdata = [] for i in data: init = init+i[1] if i[0] == '': splitdata.append(init) splitdata.append(init) print(splitdata) [13, 26, 39, 52] </code></pre>
1
2016-09-06T13:40:37Z
39,351,017
<p>Using reduce you can do something like this:</p> <pre><code>from functools import reduce data = [('A', 12), ('', 1), ('B', 12), ('', 1), ('C', 12), ('', 1), ('D', 13)] splitdata = reduce( lambda res, i: res[:-1] + [res[-1] + i[1]] * (2 if i[0] == '' else 1), data, [0] ) print(splitdata) </code></pre>
1
2016-09-06T14:03:23Z
[ "python", "list", "tuples" ]
Pycharm won't connect tfs
39,350,517
<p>I'm trying to connect TFS plugin to Pycharm 2016.1.2. I went to settings - plugins - Intellij task interation for microsoft team found then select HTTP Proxy setting. Then select Manua proxy configuration and entered Host name, port as 80 and gave the proxy authentication and select check connection.</p> <p>It is generating an error Connection failed with HTTP code 401 for <a href="http://host:8080/tfs" rel="nofollow">http://host:8080/tfs</a> </p> <p>Does anyone had a success setup for installing and configuring TFS to Pycharm?</p>
0
2016-09-06T13:41:18Z
39,362,248
<ol> <li><p>I don't think this task still works. I have tested by following <a href="https://plugins.jetbrains.com/plugin/7336?pr=dbe" rel="nofollow">article</a> and download the SDK from <a href="http://www.microsoft.com/en-us/download/details.aspx?id=22616" rel="nofollow">http://www.microsoft.com/en-us/download/details.aspx?id=22616</a> and copy the the directory to lib/. But no Server option in Pycharm. Even tried in IntelliJ IDEA, no luck.</p></li> <li><p>Why do you enable HTTP proxy? If to access the Internet PyCharm should use an HTTP proxy, then specify the proxy settings on this page. It's not necessary to use HTTP proxy.</p></li> <li><p>Instead of using Intellij task interation for microsoft team foundation server, try <a href="https://plugins.jetbrains.com/plugin/4578?pr=" rel="nofollow">TFS Integration</a>. It supports PyCharm Professional Edition. When you install PyCharm Professional Edition, TFS Integration plugin is bundled with PyCharm and enabled by default:</p></li> </ol> <p><a href="http://i.stack.imgur.com/VklxQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/VklxQ.png" alt="enter image description here"></a></p> <p>Check this article for more information: <a href="https://www.jetbrains.com/help/idea/2016.2/using-tfs-integration.html" rel="nofollow">https://www.jetbrains.com/help/idea/2016.2/using-tfs-integration.html</a></p>
1
2016-09-07T06:03:52Z
[ "python", "tfs", "pycharm" ]
Python how to delete a specific value from a dictionary key with multiple values?
39,350,527
<p>I have a dictionary with multiple values per key and each value has two elements (possibly more). I would like to iterate over each value-pair for each key and delete those values-pairs that meet some criteria. Here for instance I would like to delete the second value pair for the key A; that is: ('Ok!', '0'):</p> <pre><code>myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]} </code></pre> <p>to:</p> <pre><code>myDict = {'A': [('Yes!', '8')], 'B': [('No!', '2')]} </code></pre> <p>I can iterate over the dictionary by key or value, but can't figure out how I delete a specific value.</p>
0
2016-09-06T13:41:51Z
39,350,689
<p>The code like this:</p> <pre><code>myDict = {'A': [('Yes!', '8'), ('Ok!', '0')], 'B': [('No!', '2')]} for v in myDict.values(): if ('Ok!', '0') in v: v.remove(('Ok!', '0')) print(myDict) </code></pre>
2
2016-09-06T13:48:53Z
[ "python", "dictionary" ]
Celery kills processes
39,350,551
<p>I use celery 3.1.23. </p> <p>Task code is very simple:</p> <pre><code>@app.task(bind=True, max_retries=None, default_retry_delay=settings.CELERY_RECONNECT_TIME) def analize_text(self, **kwargs): print 'test' return 1 </code></pre> <p>I launch celery this command:</p> <blockquote> <p>celery -A tasks worker --loglevel=info --concurrency=4 -n analize_text -Q analize.analize_text -Ofair</p> </blockquote> <p>So, i use 4 CPU. The problem is that celery periodically kills workers and starts new ones instead. New worker has new number in log and new PID. Here is my log <a href="https://dpaste.de/N1Vk" rel="nofollow">https://dpaste.de/N1Vk</a></p> <p>Why does it do it? Is this bug?</p>
3
2016-09-06T13:42:50Z
39,364,407
<p>It depends on CELERY_MAX_TASKS_PER_CHILD i.e. number of tasks a worker shall complete before being recycled, default is no limit.</p> <p><a href="http://docs.celeryproject.org/en/latest/configuration.html#std:setting-CELERYD_MAX_TASKS_PER_CHILD" rel="nofollow">http://docs.celeryproject.org/en/latest/configuration.html#std:setting-CELERYD_MAX_TASKS_PER_CHILD</a></p> <p>So,your celery configuration might be having this limit set as some low number, hence your workers are getting recycled. You can see more information in celery <a href="http://docs.celeryproject.org/en/latest/userguide/workers.html#statistics" rel="nofollow">stats</a>.</p>
1
2016-09-07T08:03:01Z
[ "python", "multiprocessing", "celery" ]
Running scipy.integrate.ode in multiprocessing Pool results in huge performance hit
39,350,557
<p>I'm using python's <code>scipy.integrate</code> to simulate a 29-dimensional linear system of differential equations. Since I need to solve several problem instances, I thought I could speed it up by doing computations in parallel using <code>multiprocessing.Pool</code>. Since there is no shared data or synchronization necessary between threads (the problem is embarrassingly parallel), I thought this should obviously work. After I wrote the code to do this, however, I got very strange performance measurements:</p> <ul> <li>Single-threaded, without jacobian: 20-30 ms per call</li> <li>Single-threaded, with jacobian: 10-20 ms per call</li> <li>Multi-threaded, without jacobian: 20-30 ms per call</li> <li><strong>Multi-threaded, with jacobian: 10-5000 ms per call</strong></li> </ul> <p>What's shocking is that what I thought should be the fastest setup, was actually the slowest, and the variability was <em>two orders of magnitude</em>. It's a deterministic computation; computers aren't supposed to work this way. What could possibly be causing this?</p> <h3>Effect seems system-dependent</h3> <p>I tried the same code on another computer and I didn't see this effect. </p> <p>Both machines were using Ubuntu 64 bit, Python 2.7.6, scipy version 0.18.0, and numpy version 1.8.2. I didn't see the variability with an Intel(R) Core(TM) i5-5300U CPU @ 2.30GHz processor. I did see the issue with an <a href="http://www.cpu-world.com/CPUs/Core_i7/Intel-Core%20i7%20Mobile%20i7-2670QM.html">Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz</a>.</p> <h3>Theories</h3> <p>One thought was that there might be a shared cache among processors, and by running it in parallel I can't fit two instances of the jacobian matrix in the cache, so they constantly battle each other for the cache slowing each other down compared with if they are run serially or without the jacobian. But it's not a million variable system. The jacobian is a 29x29 matrix, which takes up 6728 bytes. The level 1 cache on the processor is <a href="http://www.cpu-world.com/CPUs/Core_i7/Intel-Core%20i7%20Mobile%20i7-2670QM.html">4 x 32 KB</a>, much larger. Are there any other shared resources between processors that might be to blame? How can we test this?</p> <p>Another thing I noticed is that each python process seems to take several hundred percent of the CPU as it's running. This seems to mean that the code is already parallelized at some point (perhaps in the low-level library). This could mean that further parallelization wouldn't help, but I wouldn't expect such a dramatic slowdown.</p> <h3>Code</h3> <p>It would be good to try out the on more machines to see if (1) other people can experience the slowdown at all and (2) what are the common features of systems where the slowdown occurs. The code does 10 trials of two parallel computations using a multiprocessing pool of size two, printing out the time per scipy.ode.integrate call for each of the 10 trials. </p> <pre><code>'odeint with multiprocessing variable execution time demonsrtation' from numpy import dot as npdot from numpy import add as npadd from numpy import matrix as npmatrix from scipy.integrate import ode from multiprocessing import Pool import time def main(): "main function" pool = Pool(2) # try Pool(1) params = [0] * 2 for trial in xrange(10): res = pool.map(run_one, params) print "{}. times: {}ms, {}ms".format(trial, int(1000 * res[0]), int(1000 * res[1])) def run_one(_): "perform one simulation" final_time = 2.0 init_state = [0.1 if d &lt; 7 else 0.0 for d in xrange(29)] (a_matrix, b_vector) = get_dynamics() derivative = lambda dummy_t, state: npadd(npdot(a_matrix, state), b_vector) jacobian = lambda dummy_t, dummy_state: a_matrix #jacobian = None # try without the jacobian #print "jacobian bytes:", jacobian(0, 0).nbytes solver = ode(derivative, jacobian) solver.set_integrator('vode') solver.set_initial_value(init_state, 0) start = time.time() solver.integrate(final_time) dif = time.time() - start return dif def get_dynamics(): "return a tuple (A, b), which are the system dynamics x' = Ax + b" return \ ( npmatrix([ [0, 0, 0, 0.99857378006, 0.053384274244, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 1, -0.003182219341, 0.059524655342, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, -11.570495605469, -2.544637680054, -0.063602626324, 0.106780529022, -0.09491866827, 0.007107574493, -5.20817921341, -23.125876742495, -4.246931301528, -0.710743697134, -1.486697327603, -0.044548215175, 0.03436637817, 0.022990248611, 0.580153205353, 1.047552018229, 11.265023544535, 2.622275290571, 0.382949404795, 0.453076470454, 0.022651889536, 0.012533628369, 0.108399390974, -0.160139432044, -6.115359574845, -0.038972389136, 0, ], [0, 0, 0.439356565475, -1.998182296753, 0, 0.016651883721, 0.018462046981, -0.001187470742, -10.778778281386, 0.343052863546, -0.034949331535, -3.466737362551, 0.013415853489, -0.006501746896, -0.007248032248, -0.004835912875, -0.152495086764, 2.03915052839, -0.169614300211, -0.279125393264, -0.003678218266, -0.001679708185, 0.050812027754, 0.043273505033, -0.062305315646, 0.979162836629, 0.040401368402, 0.010697028656, 0, ], [0, 0, -2.040895462036, -0.458999156952, -0.73502779007, 0.019255757332, -0.00459562242, 0.002120360732, -1.06432932386, -3.659159530947, -0.493546966858, -0.059561101143, -1.953512259413, -0.010939065041, -0.000271004496, 0.050563886711, 1.58833954495, 0.219923768171, 1.821923233098, 2.69319056633, 0.068619628466, 0.086310028398, 0.002415425662, 0.000727041422, 0.640963888079, -0.023016712545, -1.069845542887, -0.596675149197, 0, ], [-32.103607177734, 0, -0.503355026245, 2.297859191895, 0, -0.021215811372, -0.02116791904, 0.01581159234, 12.45916782984, -0.353636907076, 0.064136531117, 4.035326800046, -0.272152744884, 0.000999589868, 0.002529691904, 0.111632959213, 2.736421830861, -2.354540136198, 0.175216915979, 0.86308171287, 0.004401276193, 0.004373406589, -0.059795009475, -0.051005479746, 0.609531777761, -1.1157829788, -0.026305051933, -0.033738880627, 0, ], [0.102161169052, 32.057830810547, -2.347217559814, -0.503611564636, 0.83494758606, 0.02122657001, -0.037879735231, 0.00035400386, -0.761479736492, -5.12933410588, -1.131382179292, -0.148788337148, 1.380741054924, -0.012931029503, 0.007645723855, 0.073796656681, 1.361745395486, 0.150700793731, 2.452437244444, -1.44883919298, 0.076516270282, 0.087122640348, 0.004623192159, 0.002635233443, -0.079401941141, -0.031023369979, -1.225533436977, 0.657926151362, 0, ], [-1.910972595215, 1.713829040527, -0.004005432129, -0.057411193848, 0, 0.013989634812, -0.000906753354, -0.290513515472, -2.060635522957, -0.774845915178, -0.471751979387, -1.213891560083, 5.030515136324, 0.126407660877, 0.113188603433, -2.078420624662, -50.18523312358, 0.340665548784, 0.375863242926, -10.641168797333, -0.003634153255, -0.047962774317, 0.030509705209, 0.027584169642, -10.542357589006, -0.126840767097, -0.391839285172, 0.420788121692, 0, ], [0.126296110212, -0.002898250629, -0.319316070797, 0.785201711657, 0.001772374259, 0.00000584372, 0.000005233812, -0.000097899495, -0.072611454126, 0.001666291957, 0.195701043078, 0.517339177294, 0.05236528267, -0.000003359731, -0.000003009077, 0.000056285381, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [-0.018114066432, 0.077615035084, 0.710897211118, 2.454275059389, -0.012792968774, 0.000040510624, 0.000036282541, -0.000678672106, 0.010414324729, -0.044623231468, 0.564308412696, -1.507321670112, 0.066879720068, -0.000023290783, -0.00002085993, 0.000390189123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [-0.019957254425, 0.007108972111, 122.639137999354, 1.791704310155, 0.138329792976, 0.000000726169, 0.000000650379, -0.000012165459, -8.481152717711, -37.713895394132, -93.658221074435, -4.801972165378, -2.567389718833, 0.034138340146, -0.038880106034, 0.044603217363, 0.946016722396, 1.708172458034, 18.369114490772, 4.275967542224, 0.624449778826, 0.738801257357, 0.036936909247, 0.020437742859, 0.176759579388, -0.261128576436, -9.971904607075, -0.063549647738, 0, ], [0.007852964982, 0.003925745426, 0.287856349997, 58.053471054491, 0.030698062827, -0.000006837601, -0.000006123962, 0.000114549925, -17.580742026275, 0.55713614874, 0.205946900184, -43.230778067404, 0.004227082975, 0.006053854501, 0.006646690253, -0.009138926083, -0.248663457912, 3.325105302428, -0.276578605231, -0.455150962257, -0.005997822569, -0.002738986905, 0.082855748293, 0.070563187482, -0.101597078067, 1.596654829885, 0.065879787896, 0.017442923517, 0, ], [0.011497315687, -0.012583019909, 13.848373855148, 22.28881517216, 0.042287331657, 0.000197558695, 0.000176939544, -0.003309689199, -1.742140233901, -5.959510415282, -11.333020298294, -14.216479234895, -3.944800806497, 0.001304578929, -0.005139259078, 0.08647432259, 2.589998222025, 0.358614863147, 2.970887395829, 4.39160430183, 0.111893402319, 0.140739944934, 0.003938671797, 0.001185537435, 1.045176603318, -0.037531801533, -1.744525005833, -0.972957942438, 0, ], [-16.939142002537, 0.618053512295, 107.92089190414, 204.524147386814, 0.204407545189, 0.004742101706, 0.004247169746, -0.079444150933, -2.048456967261, -0.931989524708, -66.540858220883, -116.470289129818, -0.561301215495, -0.022312225275, -0.019484747345, 0.243518778973, 4.462098610572, -3.839389874682, 0.285714413078, 1.40736916669, 0.007176864388, 0.007131419303, -0.097503691021, -0.083171197416, 0.993922379938, -1.819432085819, -0.042893874898, -0.055015718216, 0, ], [-0.542809857455, 7.081822285872, -135.012404429101, 460.929268260027, 0.036498617908, 0.006937238413, 0.006213200589, -0.116219147061, -0.827454697348, 19.622217613195, 78.553728334274, -283.23862765888, 3.065444785639, -0.003847616297, -0.028984525722, 0.187507140282, 2.220506417769, 0.245737625222, 3.99902408961, -2.362524402134, 0.124769923797, 0.142065016461, 0.007538727793, 0.004297097528, -0.129475392736, -0.050587718062, -1.998394759416, 1.072835822585, 0, ], [-1.286456393795, 0.142279456389, -1.265748910581, 65.74306027738, -1.320702989799, -0.061855995532, -0.055400100872, 1.036269854556, -4.531489334771, 0.368539277612, 0.002487097952, -42.326462719738, 8.96223401238, 0.255676968878, 0.215513465742, -4.275436802385, -81.833676543035, 0.555500345288, 0.612894852362, -17.351836610113, -0.005925968725, -0.078209662789, 0.049750119549, 0.044979645917, -17.190711833803, -0.206830688253, -0.638945907467, 0.686150823668, 0, ], [0, 0, 0, 0, 0, -0.009702263896, -0.008689641059, 0.162541456323, 0, 0, 0, 0, 0, 0, 0, 0, -0.012, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [-8.153162937544, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0.17441246156, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.5, -18, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, -8.153162937544, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.5, -18, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0.699960862226, 0.262038222227, 0.159589891262, 0.41155156501, -1.701619176699, -0.0427567124, -0.038285155304, 0.703045934017, 16.975651534025, -0.115788018654, -0.127109026104, 3.599544290134, 0.001229743857, 0.016223661959, -0.01033400498, -0.00934235613, -6.433934989563, 0.042639567847, 0.132540852847, -0.142338323726, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, -37.001496211974, 0.783588795613, -0.183854784348, -11.869599790688, -0.106084318011, -0.026306590251, -0.027118088888, 0.036744952758, 0.76460150301, 7.002366574508, -0.390318898363, -0.642631203146, -0.005701671024, 0.003522251111, 0.173867535377, 0.147911422248, 0.056092715216, -6.641979472328, 0.039602243105, 0.026181724138, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 1.991401999957, 13.760045912368, 2.53041689113, 0.082528789604, 0.728264862053, 0.023902766734, -0.022896554363, 0.015327568208, 0.370476566397, -0.412566245022, -6.70094564846, -1.327038338854, -0.227019235965, -0.267482033427, -0.008650986307, -0.003394359441, 0.098792645471, 0.197714179668, -6.369398456151, -0.011976840769, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 1.965859332057, -3.743127938662, -1.962645156793, 0.018929412474, 11.145046656101, -0.03600197464, -0.001222148117, 0.602488409354, 11.639787952728, -0.407672972316, 1.507740702165, -12.799953897143, 0.005393102236, -0.014208764492, -0.000915158115, -0.000640326416, -0.03653528842, 0.012458973237, -0.083125038259, -5.472831842357, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], ]) , npmatrix([1.0 if d == 28 else 0.0 for d in xrange(29)]) ) if __name__ == "__main__": main() </code></pre> <h3>Example Output</h3> <p>Here's an example of the output that demonstrates the problem (each run is slightly different). Notice the large variability in execution times (over two orders of magnitude!). Again, this all goes away if I either use a pool of size 1 (or run the code without a pool), or if I don't use an explicit jacobian in the call to <code>integrate</code>.</p> <blockquote> <ol> <li>times: 5847ms, 5760ms</li> <li>times: 4177ms, 3991ms</li> <li>times: 229ms, 36ms</li> <li>times: 1317ms, 1544ms</li> <li>times: 87ms, 100ms</li> <li>times: 113ms, 102ms</li> <li>times: 4747ms, 5077ms</li> <li>times: 597ms, 48ms</li> <li>times: 9ms, 49ms</li> <li>times: 135ms, 109ms</li> </ol> </blockquote>
10
2016-09-06T13:43:04Z
39,488,979
<p>This is intended as a formatted comment regarding the mathematical background raised in <a href="http://stackoverflow.com/questions/39350557/running-scipy-integrate-ode-in-multiprocessing-pool-results-in-huge-performance#comment66277221_39350557">a comment by @Dietrich</a>. As it doesn't address the programming question, I intend to delete this answer in a little while until the bounty blows over.</p> <p>As @Dietrich noted, you can solve your ODE exactly, since if</p> <pre><code>x' = A*x, </code></pre> <p>then the exact solution is</p> <pre><code>x(t) = exp(A*t)*x0 </code></pre> <p>Already I'd say that an exact solution is always superior than a numerical approximation, but this can indeed be faster than a numerical integration. As you noted in a comment, you're worried about efficiency. So don't compute the matrix exponential for each <code>t</code>: compute the eigensystem of <code>A</code> only once:</p> <pre><code>A*v_i = L_i*v_i </code></pre> <p>then</p> <pre><code>x(t) = sum_i c_i*v_i*exp(L_i*t), </code></pre> <p>and the coefficients <code>c_i</code> can be determined from the linear equations</p> <pre><code>x0 = sum_i c_i*v_i. </code></pre> <p>Now, having an inhomogeneous term doesn't change much, as long as your matrix is not singular:</p> <pre><code>x' = A*x + b (x - A^(-1)*b)' = A*(x - A^(-1)*b) </code></pre> <p>so we can solve the homogeneous equation for <code>y = x - A^(-1)*b</code> and in a final step recover <code>x = y + A^(-1)*b</code>.</p> <p>This all works nicely while the matrix is regular, but in your specific case it's singular. But it turns out that this is due to your final dimension:</p> <pre><code>&gt;&gt;&gt; np.linalg.det(A) 0.0 &gt;&gt;&gt; np.linalg.det(A[:-1,:-1]) 1920987.0461154305 </code></pre> <p>And also note that the final row of <code>A</code> is all zeros (this is the reason for the singularity of <code>A</code>). So the last dimension of <code>x</code> is constant (or changes linearly due to <code>b</code>).</p> <p>I suggest eliminating this variable, rewriting your equation for the rest of the variables, and solving the non-singular inhomogeneous linear system of ODEs using the above procedure, exactly. It should be faster and precise.</p> <hr> <p>The following will be a bit speculative, see also the caveat at the end.</p> <p>In case of user-input <code>A</code> and <code>b</code>, things might get trickier. Finding a zero row/column in your matrix would be easy, but <code>A</code> can be singular even though none of its rows/columns are fully zero. I'm not an expert in the subject, but I think your best bet is using something akin to <a href="https://en.wikipedia.org/wiki/Principal_component_analysis" rel="nofollow">principal component analysis</a>: transforming your system of equations according to the eigensystem of <code>A</code>. My following thoughts will still assume that <code>A</code> is diagonalizable, but mostly because I'm unfamiliar with <a href="https://en.wikipedia.org/wiki/Singular_value_decomposition" rel="nofollow">singular value decomposition</a>. In realistic cases I'd expect your matrices to be diagonalizable, even if singular.</p> <p>So I'll assume that the matrix <code>A</code> can be decomposed as</p> <pre><code>A = V * D * V^(-1), </code></pre> <p>where <code>D</code> is a diagonal matrix containing the eigenvalues of <code>A</code>, and columns of <code>V</code> are the eigenvectors of <code>A</code> corresponding to each respective eigenvalue. The very same decomposition can be obtained in numpy using</p> <pre><code>DD,V = np.linalg.eig(A) D = np.asmatrix(np.diag(DD)) </code></pre> <p>I usually prefer using <code>ndarray</code>s instead of matrices, but this way <code>V*D*np.linalg.inv(V)</code> would really correspond to the matrix product of the three matrices, rather than calling <code>np.dot</code> twice.</p> <p>Now, rewrite your equation again:</p> <pre><code>x' = A*x + b x' = V*D*V^(-1)*x + b V^(-1)*x' = D*V^(-1)*x + V^(-1)*b </code></pre> <p>By defining the auxiliary variables</p> <pre><code>X = V^(-1)*x B = V^(-1)*b </code></pre> <p>we obtain</p> <pre><code>X' = D*X + B </code></pre> <p>i.e. the usual inhomogeneous form, but now <code>D</code> is a diagonal matrix containing the eigenvalues of <code>A</code> in the diagonal.</p> <p>Since <code>A</code> is singular, some of the eigenvalues are zero. Look for zero elements in <code>D</code> (well, you can do that already with <code>DD</code> from <code>eig()</code>), and you'll know that they behave trivially during time-evolution. The remaining variables behave well, although at this point we see that the equations for <code>X</code> are decoupled due to <code>D</code> being diagonal, so you could integrate each independently and analytically. For this you need to first go from your initial condition <code>x0</code> to <code>X0 = np.linalg.inv(V)*x0</code>, then after solving the equations, back to <code>x = V*X</code>.</p> <p>Caveat: as I said, I'm not an expert in this subject. I can easily imagine that the inversions involved in the diagonalization can be a numerical issue in practical applications. So I'd first test if the matrix is singular, and only carry on with this procedure if it is (or nearly is). It's possible that the above carries a lot of error, in which case numerical integration might be better (I really can't tell).</p>
2
2016-09-14T11:11:35Z
[ "python", "numpy", "scipy", "python-multiprocessing" ]
Running scipy.integrate.ode in multiprocessing Pool results in huge performance hit
39,350,557
<p>I'm using python's <code>scipy.integrate</code> to simulate a 29-dimensional linear system of differential equations. Since I need to solve several problem instances, I thought I could speed it up by doing computations in parallel using <code>multiprocessing.Pool</code>. Since there is no shared data or synchronization necessary between threads (the problem is embarrassingly parallel), I thought this should obviously work. After I wrote the code to do this, however, I got very strange performance measurements:</p> <ul> <li>Single-threaded, without jacobian: 20-30 ms per call</li> <li>Single-threaded, with jacobian: 10-20 ms per call</li> <li>Multi-threaded, without jacobian: 20-30 ms per call</li> <li><strong>Multi-threaded, with jacobian: 10-5000 ms per call</strong></li> </ul> <p>What's shocking is that what I thought should be the fastest setup, was actually the slowest, and the variability was <em>two orders of magnitude</em>. It's a deterministic computation; computers aren't supposed to work this way. What could possibly be causing this?</p> <h3>Effect seems system-dependent</h3> <p>I tried the same code on another computer and I didn't see this effect. </p> <p>Both machines were using Ubuntu 64 bit, Python 2.7.6, scipy version 0.18.0, and numpy version 1.8.2. I didn't see the variability with an Intel(R) Core(TM) i5-5300U CPU @ 2.30GHz processor. I did see the issue with an <a href="http://www.cpu-world.com/CPUs/Core_i7/Intel-Core%20i7%20Mobile%20i7-2670QM.html">Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz</a>.</p> <h3>Theories</h3> <p>One thought was that there might be a shared cache among processors, and by running it in parallel I can't fit two instances of the jacobian matrix in the cache, so they constantly battle each other for the cache slowing each other down compared with if they are run serially or without the jacobian. But it's not a million variable system. The jacobian is a 29x29 matrix, which takes up 6728 bytes. The level 1 cache on the processor is <a href="http://www.cpu-world.com/CPUs/Core_i7/Intel-Core%20i7%20Mobile%20i7-2670QM.html">4 x 32 KB</a>, much larger. Are there any other shared resources between processors that might be to blame? How can we test this?</p> <p>Another thing I noticed is that each python process seems to take several hundred percent of the CPU as it's running. This seems to mean that the code is already parallelized at some point (perhaps in the low-level library). This could mean that further parallelization wouldn't help, but I wouldn't expect such a dramatic slowdown.</p> <h3>Code</h3> <p>It would be good to try out the on more machines to see if (1) other people can experience the slowdown at all and (2) what are the common features of systems where the slowdown occurs. The code does 10 trials of two parallel computations using a multiprocessing pool of size two, printing out the time per scipy.ode.integrate call for each of the 10 trials. </p> <pre><code>'odeint with multiprocessing variable execution time demonsrtation' from numpy import dot as npdot from numpy import add as npadd from numpy import matrix as npmatrix from scipy.integrate import ode from multiprocessing import Pool import time def main(): "main function" pool = Pool(2) # try Pool(1) params = [0] * 2 for trial in xrange(10): res = pool.map(run_one, params) print "{}. times: {}ms, {}ms".format(trial, int(1000 * res[0]), int(1000 * res[1])) def run_one(_): "perform one simulation" final_time = 2.0 init_state = [0.1 if d &lt; 7 else 0.0 for d in xrange(29)] (a_matrix, b_vector) = get_dynamics() derivative = lambda dummy_t, state: npadd(npdot(a_matrix, state), b_vector) jacobian = lambda dummy_t, dummy_state: a_matrix #jacobian = None # try without the jacobian #print "jacobian bytes:", jacobian(0, 0).nbytes solver = ode(derivative, jacobian) solver.set_integrator('vode') solver.set_initial_value(init_state, 0) start = time.time() solver.integrate(final_time) dif = time.time() - start return dif def get_dynamics(): "return a tuple (A, b), which are the system dynamics x' = Ax + b" return \ ( npmatrix([ [0, 0, 0, 0.99857378006, 0.053384274244, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 1, -0.003182219341, 0.059524655342, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, -11.570495605469, -2.544637680054, -0.063602626324, 0.106780529022, -0.09491866827, 0.007107574493, -5.20817921341, -23.125876742495, -4.246931301528, -0.710743697134, -1.486697327603, -0.044548215175, 0.03436637817, 0.022990248611, 0.580153205353, 1.047552018229, 11.265023544535, 2.622275290571, 0.382949404795, 0.453076470454, 0.022651889536, 0.012533628369, 0.108399390974, -0.160139432044, -6.115359574845, -0.038972389136, 0, ], [0, 0, 0.439356565475, -1.998182296753, 0, 0.016651883721, 0.018462046981, -0.001187470742, -10.778778281386, 0.343052863546, -0.034949331535, -3.466737362551, 0.013415853489, -0.006501746896, -0.007248032248, -0.004835912875, -0.152495086764, 2.03915052839, -0.169614300211, -0.279125393264, -0.003678218266, -0.001679708185, 0.050812027754, 0.043273505033, -0.062305315646, 0.979162836629, 0.040401368402, 0.010697028656, 0, ], [0, 0, -2.040895462036, -0.458999156952, -0.73502779007, 0.019255757332, -0.00459562242, 0.002120360732, -1.06432932386, -3.659159530947, -0.493546966858, -0.059561101143, -1.953512259413, -0.010939065041, -0.000271004496, 0.050563886711, 1.58833954495, 0.219923768171, 1.821923233098, 2.69319056633, 0.068619628466, 0.086310028398, 0.002415425662, 0.000727041422, 0.640963888079, -0.023016712545, -1.069845542887, -0.596675149197, 0, ], [-32.103607177734, 0, -0.503355026245, 2.297859191895, 0, -0.021215811372, -0.02116791904, 0.01581159234, 12.45916782984, -0.353636907076, 0.064136531117, 4.035326800046, -0.272152744884, 0.000999589868, 0.002529691904, 0.111632959213, 2.736421830861, -2.354540136198, 0.175216915979, 0.86308171287, 0.004401276193, 0.004373406589, -0.059795009475, -0.051005479746, 0.609531777761, -1.1157829788, -0.026305051933, -0.033738880627, 0, ], [0.102161169052, 32.057830810547, -2.347217559814, -0.503611564636, 0.83494758606, 0.02122657001, -0.037879735231, 0.00035400386, -0.761479736492, -5.12933410588, -1.131382179292, -0.148788337148, 1.380741054924, -0.012931029503, 0.007645723855, 0.073796656681, 1.361745395486, 0.150700793731, 2.452437244444, -1.44883919298, 0.076516270282, 0.087122640348, 0.004623192159, 0.002635233443, -0.079401941141, -0.031023369979, -1.225533436977, 0.657926151362, 0, ], [-1.910972595215, 1.713829040527, -0.004005432129, -0.057411193848, 0, 0.013989634812, -0.000906753354, -0.290513515472, -2.060635522957, -0.774845915178, -0.471751979387, -1.213891560083, 5.030515136324, 0.126407660877, 0.113188603433, -2.078420624662, -50.18523312358, 0.340665548784, 0.375863242926, -10.641168797333, -0.003634153255, -0.047962774317, 0.030509705209, 0.027584169642, -10.542357589006, -0.126840767097, -0.391839285172, 0.420788121692, 0, ], [0.126296110212, -0.002898250629, -0.319316070797, 0.785201711657, 0.001772374259, 0.00000584372, 0.000005233812, -0.000097899495, -0.072611454126, 0.001666291957, 0.195701043078, 0.517339177294, 0.05236528267, -0.000003359731, -0.000003009077, 0.000056285381, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [-0.018114066432, 0.077615035084, 0.710897211118, 2.454275059389, -0.012792968774, 0.000040510624, 0.000036282541, -0.000678672106, 0.010414324729, -0.044623231468, 0.564308412696, -1.507321670112, 0.066879720068, -0.000023290783, -0.00002085993, 0.000390189123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [-0.019957254425, 0.007108972111, 122.639137999354, 1.791704310155, 0.138329792976, 0.000000726169, 0.000000650379, -0.000012165459, -8.481152717711, -37.713895394132, -93.658221074435, -4.801972165378, -2.567389718833, 0.034138340146, -0.038880106034, 0.044603217363, 0.946016722396, 1.708172458034, 18.369114490772, 4.275967542224, 0.624449778826, 0.738801257357, 0.036936909247, 0.020437742859, 0.176759579388, -0.261128576436, -9.971904607075, -0.063549647738, 0, ], [0.007852964982, 0.003925745426, 0.287856349997, 58.053471054491, 0.030698062827, -0.000006837601, -0.000006123962, 0.000114549925, -17.580742026275, 0.55713614874, 0.205946900184, -43.230778067404, 0.004227082975, 0.006053854501, 0.006646690253, -0.009138926083, -0.248663457912, 3.325105302428, -0.276578605231, -0.455150962257, -0.005997822569, -0.002738986905, 0.082855748293, 0.070563187482, -0.101597078067, 1.596654829885, 0.065879787896, 0.017442923517, 0, ], [0.011497315687, -0.012583019909, 13.848373855148, 22.28881517216, 0.042287331657, 0.000197558695, 0.000176939544, -0.003309689199, -1.742140233901, -5.959510415282, -11.333020298294, -14.216479234895, -3.944800806497, 0.001304578929, -0.005139259078, 0.08647432259, 2.589998222025, 0.358614863147, 2.970887395829, 4.39160430183, 0.111893402319, 0.140739944934, 0.003938671797, 0.001185537435, 1.045176603318, -0.037531801533, -1.744525005833, -0.972957942438, 0, ], [-16.939142002537, 0.618053512295, 107.92089190414, 204.524147386814, 0.204407545189, 0.004742101706, 0.004247169746, -0.079444150933, -2.048456967261, -0.931989524708, -66.540858220883, -116.470289129818, -0.561301215495, -0.022312225275, -0.019484747345, 0.243518778973, 4.462098610572, -3.839389874682, 0.285714413078, 1.40736916669, 0.007176864388, 0.007131419303, -0.097503691021, -0.083171197416, 0.993922379938, -1.819432085819, -0.042893874898, -0.055015718216, 0, ], [-0.542809857455, 7.081822285872, -135.012404429101, 460.929268260027, 0.036498617908, 0.006937238413, 0.006213200589, -0.116219147061, -0.827454697348, 19.622217613195, 78.553728334274, -283.23862765888, 3.065444785639, -0.003847616297, -0.028984525722, 0.187507140282, 2.220506417769, 0.245737625222, 3.99902408961, -2.362524402134, 0.124769923797, 0.142065016461, 0.007538727793, 0.004297097528, -0.129475392736, -0.050587718062, -1.998394759416, 1.072835822585, 0, ], [-1.286456393795, 0.142279456389, -1.265748910581, 65.74306027738, -1.320702989799, -0.061855995532, -0.055400100872, 1.036269854556, -4.531489334771, 0.368539277612, 0.002487097952, -42.326462719738, 8.96223401238, 0.255676968878, 0.215513465742, -4.275436802385, -81.833676543035, 0.555500345288, 0.612894852362, -17.351836610113, -0.005925968725, -0.078209662789, 0.049750119549, 0.044979645917, -17.190711833803, -0.206830688253, -0.638945907467, 0.686150823668, 0, ], [0, 0, 0, 0, 0, -0.009702263896, -0.008689641059, 0.162541456323, 0, 0, 0, 0, 0, 0, 0, 0, -0.012, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [-8.153162937544, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0.17441246156, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.5, -18, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, -8.153162937544, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.5, -18, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0.699960862226, 0.262038222227, 0.159589891262, 0.41155156501, -1.701619176699, -0.0427567124, -0.038285155304, 0.703045934017, 16.975651534025, -0.115788018654, -0.127109026104, 3.599544290134, 0.001229743857, 0.016223661959, -0.01033400498, -0.00934235613, -6.433934989563, 0.042639567847, 0.132540852847, -0.142338323726, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, -37.001496211974, 0.783588795613, -0.183854784348, -11.869599790688, -0.106084318011, -0.026306590251, -0.027118088888, 0.036744952758, 0.76460150301, 7.002366574508, -0.390318898363, -0.642631203146, -0.005701671024, 0.003522251111, 0.173867535377, 0.147911422248, 0.056092715216, -6.641979472328, 0.039602243105, 0.026181724138, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 1.991401999957, 13.760045912368, 2.53041689113, 0.082528789604, 0.728264862053, 0.023902766734, -0.022896554363, 0.015327568208, 0.370476566397, -0.412566245022, -6.70094564846, -1.327038338854, -0.227019235965, -0.267482033427, -0.008650986307, -0.003394359441, 0.098792645471, 0.197714179668, -6.369398456151, -0.011976840769, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 1.965859332057, -3.743127938662, -1.962645156793, 0.018929412474, 11.145046656101, -0.03600197464, -0.001222148117, 0.602488409354, 11.639787952728, -0.407672972316, 1.507740702165, -12.799953897143, 0.005393102236, -0.014208764492, -0.000915158115, -0.000640326416, -0.03653528842, 0.012458973237, -0.083125038259, -5.472831842357, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], ]) , npmatrix([1.0 if d == 28 else 0.0 for d in xrange(29)]) ) if __name__ == "__main__": main() </code></pre> <h3>Example Output</h3> <p>Here's an example of the output that demonstrates the problem (each run is slightly different). Notice the large variability in execution times (over two orders of magnitude!). Again, this all goes away if I either use a pool of size 1 (or run the code without a pool), or if I don't use an explicit jacobian in the call to <code>integrate</code>.</p> <blockquote> <ol> <li>times: 5847ms, 5760ms</li> <li>times: 4177ms, 3991ms</li> <li>times: 229ms, 36ms</li> <li>times: 1317ms, 1544ms</li> <li>times: 87ms, 100ms</li> <li>times: 113ms, 102ms</li> <li>times: 4747ms, 5077ms</li> <li>times: 597ms, 48ms</li> <li>times: 9ms, 49ms</li> <li>times: 135ms, 109ms</li> </ol> </blockquote>
10
2016-09-06T13:43:04Z
39,514,895
<p>Based on the variability of the execution times you posted for the machine showing the problem, I wonder what else that computer is doing at the time you are running your test. Here are times I saw when I ran your code on an AWS r3.large server (2 cores, 15 GB of RAM) that normally runs interactive R sessions but is currently mostly idle:</p> <blockquote> <ol> <li>times: 11ms, 11ms</li> <li>times: 9ms, 9ms</li> <li>times: 9ms, 9ms</li> <li>times: 9ms, 9ms</li> <li>times: 10ms, 10ms</li> <li>times: 10ms, 10ms</li> <li>times: 10ms, 10ms</li> <li>times: 11ms, 10ms</li> <li>times: 11ms, 10ms</li> <li>times: 9ms, 9ms</li> </ol> </blockquote> <p>Is it possible your machine is swapping and you do not know it? <code>vmstat 5</code> will give you a lot of information about swap in and outs, but not about cache evictions.</p> <p>Intel makes some very nice tools for monitoring--two at a time--thousands of different types of operations and errors going on in a processor--including L2 cache evictions--but they are a bit of a firehose: there is information generated every microsecond--or more frequently--and you have to decide what you are going to monitor and how often you want an interrupt to deliver the numbers into your software. Likely it will take many runs just to narrow down the stats you want to track and you still have to filter out the noise generated by the operating system and everything else running at the time. It is a time consuming process, but if you follow it to the end and run many different tests you will come to understand what is going on. </p> <p>But is this--shared cache resources in a processor--really your question? It seems more like you just want to figure out why you have variable run times on one machine and, second, why multi-threaded is slower on both machines than single threaded. Do I have it right? If not I will edit my answer and we can talk about processor cache, cache snooping and cache coherency.</p> <p>So, as to the variability on the i7-2670QM CPU machine, I would start with <code>htop</code>, <code>vmstat 5</code> and <code>iostat 5</code> to see if the machine is doing something you didn't realize. That much variability says the executable is getting stalled because the processor is busy doing something else: going off to the network and not finding a share it expects, unable to connect to a DNS server, getting kerbios failures: it could be a lot of things including hardware failures from a hard disk that is being continually reset. Oh, and move your program to /dev/shm and cd there before you start it. That won't help you if there are Python libraries in a bad place on a disk, but at least you won't have issues with your local directory. Report back what you find and we can make further suggestions.</p> <p>Your second question as I see it, which is perhaps where you started, is why is your program slower when run multi-threaded than single-threaded. This is a big subject that will come a lot more in focus if we can see how you multi-threaded it. But even before we do you have to realize that there are several things that can cause a multi-threaded program to run slower than a single-threaded program, and it can have as much to do with the support infrastructure around your program--libraries and operating system calls you make--as your program. Just because you do not need mutexes does not mean the libraries and operating system do not need them when they are being called from a multi-threaded application. Locking a mutex is an expensive operation, especially as different threads are rotated between different cores. </p> <p>On top of that, since the vode is not re-entrant, if you called it from multiple threads it is possible that it is having trouble finding convergence and having to recalculate the same values many times before it "gets lucky" and has enough processor time to complete an iteration before it is swapped out and intermediate results are overwritten. Give us the code you are using for your multi-threaded runs and I will add to this answer.</p>
2
2016-09-15T15:26:18Z
[ "python", "numpy", "scipy", "python-multiprocessing" ]
Running scipy.integrate.ode in multiprocessing Pool results in huge performance hit
39,350,557
<p>I'm using python's <code>scipy.integrate</code> to simulate a 29-dimensional linear system of differential equations. Since I need to solve several problem instances, I thought I could speed it up by doing computations in parallel using <code>multiprocessing.Pool</code>. Since there is no shared data or synchronization necessary between threads (the problem is embarrassingly parallel), I thought this should obviously work. After I wrote the code to do this, however, I got very strange performance measurements:</p> <ul> <li>Single-threaded, without jacobian: 20-30 ms per call</li> <li>Single-threaded, with jacobian: 10-20 ms per call</li> <li>Multi-threaded, without jacobian: 20-30 ms per call</li> <li><strong>Multi-threaded, with jacobian: 10-5000 ms per call</strong></li> </ul> <p>What's shocking is that what I thought should be the fastest setup, was actually the slowest, and the variability was <em>two orders of magnitude</em>. It's a deterministic computation; computers aren't supposed to work this way. What could possibly be causing this?</p> <h3>Effect seems system-dependent</h3> <p>I tried the same code on another computer and I didn't see this effect. </p> <p>Both machines were using Ubuntu 64 bit, Python 2.7.6, scipy version 0.18.0, and numpy version 1.8.2. I didn't see the variability with an Intel(R) Core(TM) i5-5300U CPU @ 2.30GHz processor. I did see the issue with an <a href="http://www.cpu-world.com/CPUs/Core_i7/Intel-Core%20i7%20Mobile%20i7-2670QM.html">Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz</a>.</p> <h3>Theories</h3> <p>One thought was that there might be a shared cache among processors, and by running it in parallel I can't fit two instances of the jacobian matrix in the cache, so they constantly battle each other for the cache slowing each other down compared with if they are run serially or without the jacobian. But it's not a million variable system. The jacobian is a 29x29 matrix, which takes up 6728 bytes. The level 1 cache on the processor is <a href="http://www.cpu-world.com/CPUs/Core_i7/Intel-Core%20i7%20Mobile%20i7-2670QM.html">4 x 32 KB</a>, much larger. Are there any other shared resources between processors that might be to blame? How can we test this?</p> <p>Another thing I noticed is that each python process seems to take several hundred percent of the CPU as it's running. This seems to mean that the code is already parallelized at some point (perhaps in the low-level library). This could mean that further parallelization wouldn't help, but I wouldn't expect such a dramatic slowdown.</p> <h3>Code</h3> <p>It would be good to try out the on more machines to see if (1) other people can experience the slowdown at all and (2) what are the common features of systems where the slowdown occurs. The code does 10 trials of two parallel computations using a multiprocessing pool of size two, printing out the time per scipy.ode.integrate call for each of the 10 trials. </p> <pre><code>'odeint with multiprocessing variable execution time demonsrtation' from numpy import dot as npdot from numpy import add as npadd from numpy import matrix as npmatrix from scipy.integrate import ode from multiprocessing import Pool import time def main(): "main function" pool = Pool(2) # try Pool(1) params = [0] * 2 for trial in xrange(10): res = pool.map(run_one, params) print "{}. times: {}ms, {}ms".format(trial, int(1000 * res[0]), int(1000 * res[1])) def run_one(_): "perform one simulation" final_time = 2.0 init_state = [0.1 if d &lt; 7 else 0.0 for d in xrange(29)] (a_matrix, b_vector) = get_dynamics() derivative = lambda dummy_t, state: npadd(npdot(a_matrix, state), b_vector) jacobian = lambda dummy_t, dummy_state: a_matrix #jacobian = None # try without the jacobian #print "jacobian bytes:", jacobian(0, 0).nbytes solver = ode(derivative, jacobian) solver.set_integrator('vode') solver.set_initial_value(init_state, 0) start = time.time() solver.integrate(final_time) dif = time.time() - start return dif def get_dynamics(): "return a tuple (A, b), which are the system dynamics x' = Ax + b" return \ ( npmatrix([ [0, 0, 0, 0.99857378006, 0.053384274244, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 1, -0.003182219341, 0.059524655342, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, -11.570495605469, -2.544637680054, -0.063602626324, 0.106780529022, -0.09491866827, 0.007107574493, -5.20817921341, -23.125876742495, -4.246931301528, -0.710743697134, -1.486697327603, -0.044548215175, 0.03436637817, 0.022990248611, 0.580153205353, 1.047552018229, 11.265023544535, 2.622275290571, 0.382949404795, 0.453076470454, 0.022651889536, 0.012533628369, 0.108399390974, -0.160139432044, -6.115359574845, -0.038972389136, 0, ], [0, 0, 0.439356565475, -1.998182296753, 0, 0.016651883721, 0.018462046981, -0.001187470742, -10.778778281386, 0.343052863546, -0.034949331535, -3.466737362551, 0.013415853489, -0.006501746896, -0.007248032248, -0.004835912875, -0.152495086764, 2.03915052839, -0.169614300211, -0.279125393264, -0.003678218266, -0.001679708185, 0.050812027754, 0.043273505033, -0.062305315646, 0.979162836629, 0.040401368402, 0.010697028656, 0, ], [0, 0, -2.040895462036, -0.458999156952, -0.73502779007, 0.019255757332, -0.00459562242, 0.002120360732, -1.06432932386, -3.659159530947, -0.493546966858, -0.059561101143, -1.953512259413, -0.010939065041, -0.000271004496, 0.050563886711, 1.58833954495, 0.219923768171, 1.821923233098, 2.69319056633, 0.068619628466, 0.086310028398, 0.002415425662, 0.000727041422, 0.640963888079, -0.023016712545, -1.069845542887, -0.596675149197, 0, ], [-32.103607177734, 0, -0.503355026245, 2.297859191895, 0, -0.021215811372, -0.02116791904, 0.01581159234, 12.45916782984, -0.353636907076, 0.064136531117, 4.035326800046, -0.272152744884, 0.000999589868, 0.002529691904, 0.111632959213, 2.736421830861, -2.354540136198, 0.175216915979, 0.86308171287, 0.004401276193, 0.004373406589, -0.059795009475, -0.051005479746, 0.609531777761, -1.1157829788, -0.026305051933, -0.033738880627, 0, ], [0.102161169052, 32.057830810547, -2.347217559814, -0.503611564636, 0.83494758606, 0.02122657001, -0.037879735231, 0.00035400386, -0.761479736492, -5.12933410588, -1.131382179292, -0.148788337148, 1.380741054924, -0.012931029503, 0.007645723855, 0.073796656681, 1.361745395486, 0.150700793731, 2.452437244444, -1.44883919298, 0.076516270282, 0.087122640348, 0.004623192159, 0.002635233443, -0.079401941141, -0.031023369979, -1.225533436977, 0.657926151362, 0, ], [-1.910972595215, 1.713829040527, -0.004005432129, -0.057411193848, 0, 0.013989634812, -0.000906753354, -0.290513515472, -2.060635522957, -0.774845915178, -0.471751979387, -1.213891560083, 5.030515136324, 0.126407660877, 0.113188603433, -2.078420624662, -50.18523312358, 0.340665548784, 0.375863242926, -10.641168797333, -0.003634153255, -0.047962774317, 0.030509705209, 0.027584169642, -10.542357589006, -0.126840767097, -0.391839285172, 0.420788121692, 0, ], [0.126296110212, -0.002898250629, -0.319316070797, 0.785201711657, 0.001772374259, 0.00000584372, 0.000005233812, -0.000097899495, -0.072611454126, 0.001666291957, 0.195701043078, 0.517339177294, 0.05236528267, -0.000003359731, -0.000003009077, 0.000056285381, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [-0.018114066432, 0.077615035084, 0.710897211118, 2.454275059389, -0.012792968774, 0.000040510624, 0.000036282541, -0.000678672106, 0.010414324729, -0.044623231468, 0.564308412696, -1.507321670112, 0.066879720068, -0.000023290783, -0.00002085993, 0.000390189123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [-0.019957254425, 0.007108972111, 122.639137999354, 1.791704310155, 0.138329792976, 0.000000726169, 0.000000650379, -0.000012165459, -8.481152717711, -37.713895394132, -93.658221074435, -4.801972165378, -2.567389718833, 0.034138340146, -0.038880106034, 0.044603217363, 0.946016722396, 1.708172458034, 18.369114490772, 4.275967542224, 0.624449778826, 0.738801257357, 0.036936909247, 0.020437742859, 0.176759579388, -0.261128576436, -9.971904607075, -0.063549647738, 0, ], [0.007852964982, 0.003925745426, 0.287856349997, 58.053471054491, 0.030698062827, -0.000006837601, -0.000006123962, 0.000114549925, -17.580742026275, 0.55713614874, 0.205946900184, -43.230778067404, 0.004227082975, 0.006053854501, 0.006646690253, -0.009138926083, -0.248663457912, 3.325105302428, -0.276578605231, -0.455150962257, -0.005997822569, -0.002738986905, 0.082855748293, 0.070563187482, -0.101597078067, 1.596654829885, 0.065879787896, 0.017442923517, 0, ], [0.011497315687, -0.012583019909, 13.848373855148, 22.28881517216, 0.042287331657, 0.000197558695, 0.000176939544, -0.003309689199, -1.742140233901, -5.959510415282, -11.333020298294, -14.216479234895, -3.944800806497, 0.001304578929, -0.005139259078, 0.08647432259, 2.589998222025, 0.358614863147, 2.970887395829, 4.39160430183, 0.111893402319, 0.140739944934, 0.003938671797, 0.001185537435, 1.045176603318, -0.037531801533, -1.744525005833, -0.972957942438, 0, ], [-16.939142002537, 0.618053512295, 107.92089190414, 204.524147386814, 0.204407545189, 0.004742101706, 0.004247169746, -0.079444150933, -2.048456967261, -0.931989524708, -66.540858220883, -116.470289129818, -0.561301215495, -0.022312225275, -0.019484747345, 0.243518778973, 4.462098610572, -3.839389874682, 0.285714413078, 1.40736916669, 0.007176864388, 0.007131419303, -0.097503691021, -0.083171197416, 0.993922379938, -1.819432085819, -0.042893874898, -0.055015718216, 0, ], [-0.542809857455, 7.081822285872, -135.012404429101, 460.929268260027, 0.036498617908, 0.006937238413, 0.006213200589, -0.116219147061, -0.827454697348, 19.622217613195, 78.553728334274, -283.23862765888, 3.065444785639, -0.003847616297, -0.028984525722, 0.187507140282, 2.220506417769, 0.245737625222, 3.99902408961, -2.362524402134, 0.124769923797, 0.142065016461, 0.007538727793, 0.004297097528, -0.129475392736, -0.050587718062, -1.998394759416, 1.072835822585, 0, ], [-1.286456393795, 0.142279456389, -1.265748910581, 65.74306027738, -1.320702989799, -0.061855995532, -0.055400100872, 1.036269854556, -4.531489334771, 0.368539277612, 0.002487097952, -42.326462719738, 8.96223401238, 0.255676968878, 0.215513465742, -4.275436802385, -81.833676543035, 0.555500345288, 0.612894852362, -17.351836610113, -0.005925968725, -0.078209662789, 0.049750119549, 0.044979645917, -17.190711833803, -0.206830688253, -0.638945907467, 0.686150823668, 0, ], [0, 0, 0, 0, 0, -0.009702263896, -0.008689641059, 0.162541456323, 0, 0, 0, 0, 0, 0, 0, 0, -0.012, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [-8.153162937544, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.005, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0.17441246156, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -0.01, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, -3.261265175018, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.5, -18, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, -8.153162937544, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -8.5, -18, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0.699960862226, 0.262038222227, 0.159589891262, 0.41155156501, -1.701619176699, -0.0427567124, -0.038285155304, 0.703045934017, 16.975651534025, -0.115788018654, -0.127109026104, 3.599544290134, 0.001229743857, 0.016223661959, -0.01033400498, -0.00934235613, -6.433934989563, 0.042639567847, 0.132540852847, -0.142338323726, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, -37.001496211974, 0.783588795613, -0.183854784348, -11.869599790688, -0.106084318011, -0.026306590251, -0.027118088888, 0.036744952758, 0.76460150301, 7.002366574508, -0.390318898363, -0.642631203146, -0.005701671024, 0.003522251111, 0.173867535377, 0.147911422248, 0.056092715216, -6.641979472328, 0.039602243105, 0.026181724138, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 1.991401999957, 13.760045912368, 2.53041689113, 0.082528789604, 0.728264862053, 0.023902766734, -0.022896554363, 0.015327568208, 0.370476566397, -0.412566245022, -6.70094564846, -1.327038338854, -0.227019235965, -0.267482033427, -0.008650986307, -0.003394359441, 0.098792645471, 0.197714179668, -6.369398456151, -0.011976840769, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 1.965859332057, -3.743127938662, -1.962645156793, 0.018929412474, 11.145046656101, -0.03600197464, -0.001222148117, 0.602488409354, 11.639787952728, -0.407672972316, 1.507740702165, -12.799953897143, 0.005393102236, -0.014208764492, -0.000915158115, -0.000640326416, -0.03653528842, 0.012458973237, -0.083125038259, -5.472831842357, 0, ], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], ]) , npmatrix([1.0 if d == 28 else 0.0 for d in xrange(29)]) ) if __name__ == "__main__": main() </code></pre> <h3>Example Output</h3> <p>Here's an example of the output that demonstrates the problem (each run is slightly different). Notice the large variability in execution times (over two orders of magnitude!). Again, this all goes away if I either use a pool of size 1 (or run the code without a pool), or if I don't use an explicit jacobian in the call to <code>integrate</code>.</p> <blockquote> <ol> <li>times: 5847ms, 5760ms</li> <li>times: 4177ms, 3991ms</li> <li>times: 229ms, 36ms</li> <li>times: 1317ms, 1544ms</li> <li>times: 87ms, 100ms</li> <li>times: 113ms, 102ms</li> <li>times: 4747ms, 5077ms</li> <li>times: 597ms, 48ms</li> <li>times: 9ms, 49ms</li> <li>times: 135ms, 109ms</li> </ol> </blockquote>
10
2016-09-06T13:43:04Z
39,534,779
<p>on my compiled linux kernel :</p> <ol> <li>times: 8ms, 7ms</li> <li>times: 5ms, 4ms</li> <li>times: 4ms, 4ms</li> <li>times: 8ms, 8ms</li> <li>times: 4ms, 4ms</li> <li>times: 5ms, 4ms</li> <li>times: 4ms, 8ms</li> <li>times: 8ms, 8ms</li> <li>times: 8ms, 8ms</li> <li>times: 4ms, 5ms</li> </ol> <p>Intel(R) Core(TM) i5-4300U CPU @ 1.90GHz</p> <p>be sure your processor runs at fixed speed, noswap. /tmp is mounted in RAM.</p>
0
2016-09-16T15:08:25Z
[ "python", "numpy", "scipy", "python-multiprocessing" ]
Python 2.7: Why does string format not work on double __ fields
39,350,589
<p>I have the following class:</p> <pre><code>class Members(object): def __init__(self, variable=50): self.__myvariable = variable def getVariable(self): return self.__myvariable # attempt 1 def __repr__(self): return """{self.__class__.__name__}({self.getVariable()})""".format(self=self) # attempt 2 def __repr__(self): return """{self.__class__.__name__}({self.__myvariable})""".format(self=self) </code></pre> <p>I cannot find a way to print the __ variables in a format string by using the <strong>self</strong> as a key, why is that so?</p> <p>The error I get is</p> <pre><code>AttributeError: 'Members' object has no attribute 'getVariable()' AttributeError: 'Members' object has no attribute '__myvariable </code></pre>
0
2016-09-06T13:45:00Z
39,350,827
<p>When an attribute is <a href="https://docs.python.org/3/tutorial/classes.html#tut-private" rel="nofollow">private</a> (starting with two underscores <code>__</code>), its real name when running is <code>_ClassName__attribute</code>. So, to get <code>__myvariable</code>, you should ask for <code>_Members__myvariable</code>:</p> <pre><code>def __repr__(self): return '{self.__class__.__name__}({self._Members__myvariable})'.format(self=self) </code></pre> <p>Examples in console:</p> <pre><code>&gt;&gt;&gt; m = Members() &gt;&gt;&gt; m Members(50) &gt;&gt;&gt; m._myvariable 50 &gt;&gt;&gt; m.getVariable() 50 &gt;&gt;&gt; m.__myvariable AttributeError: 'Members' object has no attribute '__myvariable' &gt;&gt;&gt; m._Members__myvariable 50 </code></pre>
3
2016-09-06T13:54:37Z
[ "python", "python-2.7" ]
Python 2.7: Why does string format not work on double __ fields
39,350,589
<p>I have the following class:</p> <pre><code>class Members(object): def __init__(self, variable=50): self.__myvariable = variable def getVariable(self): return self.__myvariable # attempt 1 def __repr__(self): return """{self.__class__.__name__}({self.getVariable()})""".format(self=self) # attempt 2 def __repr__(self): return """{self.__class__.__name__}({self.__myvariable})""".format(self=self) </code></pre> <p>I cannot find a way to print the __ variables in a format string by using the <strong>self</strong> as a key, why is that so?</p> <p>The error I get is</p> <pre><code>AttributeError: 'Members' object has no attribute 'getVariable()' AttributeError: 'Members' object has no attribute '__myvariable </code></pre>
0
2016-09-06T13:45:00Z
39,350,884
<p>You could format it like this instead:</p> <pre><code> def __repr__(self): return "{}({})".format(self.__class__.__name__,self.getVariable()) </code></pre> <p>or like this:</p> <pre><code> def __repr__(self): return "{}({})".format(self.__class__.__name__,self.__myvariable) </code></pre>
0
2016-09-06T13:57:12Z
[ "python", "python-2.7" ]
Python 2.7: Why does string format not work on double __ fields
39,350,589
<p>I have the following class:</p> <pre><code>class Members(object): def __init__(self, variable=50): self.__myvariable = variable def getVariable(self): return self.__myvariable # attempt 1 def __repr__(self): return """{self.__class__.__name__}({self.getVariable()})""".format(self=self) # attempt 2 def __repr__(self): return """{self.__class__.__name__}({self.__myvariable})""".format(self=self) </code></pre> <p>I cannot find a way to print the __ variables in a format string by using the <strong>self</strong> as a key, why is that so?</p> <p>The error I get is</p> <pre><code>AttributeError: 'Members' object has no attribute 'getVariable()' AttributeError: 'Members' object has no attribute '__myvariable </code></pre>
0
2016-09-06T13:45:00Z
39,350,895
<p>You can't access <code>__myvariable</code> because names with two leading __ get mangled (see <a href="http://stackoverflow.com/questions/1641219/does-python-have-private-variables-in-classes">Does Python have “private” variables in classes?</a>)</p> <p>And python doesn't do variable interpolation so the other method is not going to work either (see <a href="http://stackoverflow.com/questions/19796123/python-string-format-calling-a-function">python string format calling a function</a>)</p> <p>You could, instead, do</p> <pre><code>return """{0}({1})""".format(self.__class__.__name__, self.getVariable()) </code></pre>
0
2016-09-06T13:57:32Z
[ "python", "python-2.7" ]
Python 2.7: Why does string format not work on double __ fields
39,350,589
<p>I have the following class:</p> <pre><code>class Members(object): def __init__(self, variable=50): self.__myvariable = variable def getVariable(self): return self.__myvariable # attempt 1 def __repr__(self): return """{self.__class__.__name__}({self.getVariable()})""".format(self=self) # attempt 2 def __repr__(self): return """{self.__class__.__name__}({self.__myvariable})""".format(self=self) </code></pre> <p>I cannot find a way to print the __ variables in a format string by using the <strong>self</strong> as a key, why is that so?</p> <p>The error I get is</p> <pre><code>AttributeError: 'Members' object has no attribute 'getVariable()' AttributeError: 'Members' object has no attribute '__myvariable </code></pre>
0
2016-09-06T13:45:00Z
39,351,038
<p>Attempt 1 fails because <a href="https://docs.python.org/2/library/string.html#format-examples" rel="nofollow">format function</a> does not call method at all </p> <p>Attempt 2 fails because of name mangling behavior, see <a href="https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles" rel="nofollow">PEP8</a></p> <pre><code>- __double_leading_underscore: when naming a class attribute, invokes name mangling (inside class FooBar, __boo becomes _FooBar__boo; see below). </code></pre> <p>By reading <a href="https://www.python.org/dev/peps/pep-0498/" rel="nofollow">498</a>, which is released with 3.60a1, you can do this and you will get "Members(50)":</p> <pre><code>class Members(object): # attempt 3 def __repr__(self): return f'{self.__class__.__name__}({self.getVariable()})' </code></pre>
1
2016-09-06T14:04:37Z
[ "python", "python-2.7" ]
Error accessing my webpage from network
39,350,666
<p>I've just started learning network developing using <strong>Flask</strong>. According to its official tutorial:</p> <blockquote> <p><strong>Externally Visible Server</strong></p> <p>If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.</p> <p>If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding <code>--host=0.0.0.0</code> to the command line:</p> <pre><code>flask run --host=0.0.0.0 </code></pre> <p>This tells your operating system to listen on all public IPs.</p> </blockquote> <p>However, when I try to access <code>0.0.0.0:5000</code> on another device, I got an error: <code>ERR_CONNECTION_REFUSE</code>. In fact, I think this behavior is reasonable, since people all around world can use <code>0.0.0.0:5000</code> for different testing purposes, but isn't the tutorial implying that adding <code>--host=0.0.0.0</code> can make my webpage "accessible not only from your own computer, but also from any other in the network"?</p> <p>So, my question is:</p> <ol> <li>What does adding <code>--host=0.0.0.0</code> do?</li> <li>How can I access my webpage on device B while the server is running on device A?</li> </ol>
0
2016-09-06T13:47:54Z
39,350,815
<p>You don't access the Flask server on another computer by going to <code>0.0.0.0:5000</code>. Instead, you need to put in the IP address of the computer that it is running on.</p> <p>For example, if you are developing on a computer that has IP address <code>10.10.0.1</code>, you can run the server like so:</p> <pre><code>flask run --host=0.0.0.0 --port=5000 </code></pre> <p>This will start the server (on <code>10.10.0.1:5000</code>) and listen for any connections from anywhere. Now your other device (say, on <code>10.10.0.2</code>) can access that server by going to <code>http://10.10.0.1:5000</code> in the browser.</p> <p>If you don't have the <code>host=0.0.0.0</code>, the server on <code>10.10.0.1</code> will only listen for connections from <em>itself</em> (localhost). By adding that parameter, you are telling it to listen from connections external to itself.</p>
2
2016-09-06T13:54:05Z
[ "python", "flask", "hosting", "web-hosting", "host" ]
Python tweet multiple images Twitter API
39,350,671
<p>I'm trying to write a script that will post two images to Twitter using the API, any idea why this doesn't work? It only posts the first image. New to this, thanks! </p> <pre><code>from TwitterAPI import TwitterAPI import urllib api = TwitterAPI('','','','') x = [] file = open('im1.png', 'rb') data = file.read() r = api.request('media/upload', None, {'media': data}) media_id = r.json()['media_id'] print('UPLOAD MEDIA SUCCESS' if r.status_code == 200 else 'UPLOAD MEDIA FAILURE') x.append(str(media_id)) file = open('im2.png', 'rb') data1 = file.read() r = api.request('media/upload', None, {'media': data1}) media_id = r.json()['media_id'] print('UPLOAD MEDIA SUCCESS' if r.status_code == 200 else 'UPLOAD MEDIA FAILURE') x.append(str(media_id)) if r.status_code == 200: media_id = r.json()['media_id'] r = api.request('statuses/update', {'status':'Test', 'media_ids':media_id}) print('UPDATE STATUS SUCCESS' if r.status_code == 200 else 'UPDATE STATUS FAILURE') </code></pre>
3
2016-09-06T13:48:12Z
39,351,279
<p>Use tweepy (much easier);</p> <pre><code>auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) Im1 = urllib.urlretrieve('http://www.meteociel.fr/cartes_obs/temp_uk.png','im1.png') images = ('im1.png', 'im1.png') media_ids = [api.media_upload(i).media_id_string for i in images] api.update_status(status='msg', media_ids=media_ids) </code></pre>
0
2016-09-06T14:17:16Z
[ "python", "twitter" ]
Python tweet multiple images Twitter API
39,350,671
<p>I'm trying to write a script that will post two images to Twitter using the API, any idea why this doesn't work? It only posts the first image. New to this, thanks! </p> <pre><code>from TwitterAPI import TwitterAPI import urllib api = TwitterAPI('','','','') x = [] file = open('im1.png', 'rb') data = file.read() r = api.request('media/upload', None, {'media': data}) media_id = r.json()['media_id'] print('UPLOAD MEDIA SUCCESS' if r.status_code == 200 else 'UPLOAD MEDIA FAILURE') x.append(str(media_id)) file = open('im2.png', 'rb') data1 = file.read() r = api.request('media/upload', None, {'media': data1}) media_id = r.json()['media_id'] print('UPLOAD MEDIA SUCCESS' if r.status_code == 200 else 'UPLOAD MEDIA FAILURE') x.append(str(media_id)) if r.status_code == 200: media_id = r.json()['media_id'] r = api.request('statuses/update', {'status':'Test', 'media_ids':media_id}) print('UPDATE STATUS SUCCESS' if r.status_code == 200 else 'UPDATE STATUS FAILURE') </code></pre>
3
2016-09-06T13:48:12Z
39,351,564
<p>You are almost there. You just forgot to use your array of ids <code>x</code>. Make the following change to the last part of your code.</p> <pre><code>if r.status_code == 200: media_id = ','.join(x) r = api.request('statuses/update', {'status':'Test', 'media_ids':media_id}) print('UPDATE STATUS SUCCESS' if r.status_code == 200 else 'UPDATE STATUS FAILURE') </code></pre>
0
2016-09-06T14:29:18Z
[ "python", "twitter" ]
Need quiz scoring function
39,350,754
<p>I have to create a basic 3 question quiz on farming. It needs to ask the 3 questions, output whether you got it correct or incorrect and if you got it incorrect you can try again. It also needs to have a score function. I have completed the questions and the incorrect/correct part of the specification but no matter what I try I cannot get the score function to work. I have tried:</p> <pre><code>score = 0 def counter(score) score = score + 1 def counter(score) score = 0 score = score + 1 def counter(score) global score score = 0 score = score + 1 </code></pre> <p>and then following that once the answer was correct the line read :</p> <pre><code>counter(score) </code></pre> <p>I have also tried</p> <pre><code>score = 0 </code></pre> <p>then</p> <pre><code>score = score + 1 </code></pre> <p>but nothing is working and I cannot figure out what is going wrong. It also needs to print how many the user got right at the end.</p> <p>CODE:</p> <pre><code>score = 0 def quiz(): print("Here is a quiz to test your knowledge of farming...") print() print() print("Question 1") print("What percentage of the land is used for farming?") print() print("a. 25%") print("b. 50%") print("c. 75%") answer = input("Make your choice: ") if answer == "c": print("Correct!") score = score + 1 else: print("Incorrect.") answer = input("Try again! ") if answer == "c": print("Correct") score = score + 1 else: print("Incorrect! Sorry the answer was C.") print() print() print("Question 2") print("Roughly how much did farming contribute to the UK economy in 2014.") print() print("a. £8 Billion.") print("b. £10 Billion.") print("c. £12 Billion.") answer = input("Make your choice: ") if answer == "b": print("Correct!") score = score + 1 else: print("Incorrect.") answer = input("Try again! ") if answer == "b": print("Ccrrect!") score = score + 1 else: print("Incorrect! Sorry the answer was B.") print() print() print("Question 3.") print("This device, which was invented in 1882 has revolutionised farming. What is it called?") print() print("a. Tractor") print("b. Wagon.") print("c. Combine.") answer == input("Make your choice. ") if answer == "a": print("Correct!") score = score + 1 else: print("Incorrect.") answer == input("Try again! ") if answer == "a": print("Correct!") score = score + 1 else: print("Incorrect! Sorry the answer was A.") print("You got {0}/3 right!".format(score)) </code></pre>
-2
2016-09-06T13:51:36Z
39,350,941
<p>A n00b (and working) way would be to do something like</p> <pre><code>score = 0 def quiz(): global score </code></pre> <p>The <code>global</code> keyword makes use of the global variable (which you declared <em>outside</em> your function <code>quiz</code>). Since you've not indented your code properly it's unclear if you're printing the last statement inside or outside the <code>quiz</code> function, but that doesn't matter. If you place both <code>score</code> and printing inside the quiz function or both outside you'll be fine. Good luck with homework!</p>
1
2016-09-06T13:59:58Z
[ "python" ]
Need quiz scoring function
39,350,754
<p>I have to create a basic 3 question quiz on farming. It needs to ask the 3 questions, output whether you got it correct or incorrect and if you got it incorrect you can try again. It also needs to have a score function. I have completed the questions and the incorrect/correct part of the specification but no matter what I try I cannot get the score function to work. I have tried:</p> <pre><code>score = 0 def counter(score) score = score + 1 def counter(score) score = 0 score = score + 1 def counter(score) global score score = 0 score = score + 1 </code></pre> <p>and then following that once the answer was correct the line read :</p> <pre><code>counter(score) </code></pre> <p>I have also tried</p> <pre><code>score = 0 </code></pre> <p>then</p> <pre><code>score = score + 1 </code></pre> <p>but nothing is working and I cannot figure out what is going wrong. It also needs to print how many the user got right at the end.</p> <p>CODE:</p> <pre><code>score = 0 def quiz(): print("Here is a quiz to test your knowledge of farming...") print() print() print("Question 1") print("What percentage of the land is used for farming?") print() print("a. 25%") print("b. 50%") print("c. 75%") answer = input("Make your choice: ") if answer == "c": print("Correct!") score = score + 1 else: print("Incorrect.") answer = input("Try again! ") if answer == "c": print("Correct") score = score + 1 else: print("Incorrect! Sorry the answer was C.") print() print() print("Question 2") print("Roughly how much did farming contribute to the UK economy in 2014.") print() print("a. £8 Billion.") print("b. £10 Billion.") print("c. £12 Billion.") answer = input("Make your choice: ") if answer == "b": print("Correct!") score = score + 1 else: print("Incorrect.") answer = input("Try again! ") if answer == "b": print("Ccrrect!") score = score + 1 else: print("Incorrect! Sorry the answer was B.") print() print() print("Question 3.") print("This device, which was invented in 1882 has revolutionised farming. What is it called?") print() print("a. Tractor") print("b. Wagon.") print("c. Combine.") answer == input("Make your choice. ") if answer == "a": print("Correct!") score = score + 1 else: print("Incorrect.") answer == input("Try again! ") if answer == "a": print("Correct!") score = score + 1 else: print("Incorrect! Sorry the answer was A.") print("You got {0}/3 right!".format(score)) </code></pre>
-2
2016-09-06T13:51:36Z
39,350,968
<p>So python scope is defined by indents (as mentioned by the comment above). So any statement that creates a layer of scope is seperated by an indent. Examples include classes, functions, loops, and boolean statements. Here is an example of this.</p> <pre><code>Class A: def __init__(self, msg): self.message = msg def print_msg(self): # prints your message print self.message def is_hi(self): if self.message == "hi": return true else: return false </code></pre> <p>This shows the different layers of scope that can exist. Your code is not working right now because you are defining a function and then putting nothing in its scope. You would have to put anything within the scope of the function for that error to go away but that is probably not what you are looking for.</p>
0
2016-09-06T14:01:26Z
[ "python" ]
Need quiz scoring function
39,350,754
<p>I have to create a basic 3 question quiz on farming. It needs to ask the 3 questions, output whether you got it correct or incorrect and if you got it incorrect you can try again. It also needs to have a score function. I have completed the questions and the incorrect/correct part of the specification but no matter what I try I cannot get the score function to work. I have tried:</p> <pre><code>score = 0 def counter(score) score = score + 1 def counter(score) score = 0 score = score + 1 def counter(score) global score score = 0 score = score + 1 </code></pre> <p>and then following that once the answer was correct the line read :</p> <pre><code>counter(score) </code></pre> <p>I have also tried</p> <pre><code>score = 0 </code></pre> <p>then</p> <pre><code>score = score + 1 </code></pre> <p>but nothing is working and I cannot figure out what is going wrong. It also needs to print how many the user got right at the end.</p> <p>CODE:</p> <pre><code>score = 0 def quiz(): print("Here is a quiz to test your knowledge of farming...") print() print() print("Question 1") print("What percentage of the land is used for farming?") print() print("a. 25%") print("b. 50%") print("c. 75%") answer = input("Make your choice: ") if answer == "c": print("Correct!") score = score + 1 else: print("Incorrect.") answer = input("Try again! ") if answer == "c": print("Correct") score = score + 1 else: print("Incorrect! Sorry the answer was C.") print() print() print("Question 2") print("Roughly how much did farming contribute to the UK economy in 2014.") print() print("a. £8 Billion.") print("b. £10 Billion.") print("c. £12 Billion.") answer = input("Make your choice: ") if answer == "b": print("Correct!") score = score + 1 else: print("Incorrect.") answer = input("Try again! ") if answer == "b": print("Ccrrect!") score = score + 1 else: print("Incorrect! Sorry the answer was B.") print() print() print("Question 3.") print("This device, which was invented in 1882 has revolutionised farming. What is it called?") print() print("a. Tractor") print("b. Wagon.") print("c. Combine.") answer == input("Make your choice. ") if answer == "a": print("Correct!") score = score + 1 else: print("Incorrect.") answer == input("Try again! ") if answer == "a": print("Correct!") score = score + 1 else: print("Incorrect! Sorry the answer was A.") print("You got {0}/3 right!".format(score)) </code></pre>
-2
2016-09-06T13:51:36Z
39,352,021
<pre><code>import sys def quiz(): score = 0 print("Here is a quiz to test your knowledge of farming...") print() print() print("Question 1") print("What percentage of the land is used for farming?") print() print("a. 25%") print("b. 50%") print("c. 75%") answer = input("Make your choice: ") if answer == "c": print("Correct!") score = score + 1 else: print("Incorrect! Sorry the answer was C.") print() print() print("Question 2") print("Roughly how much did farming contribute to the UK economy in 2014.") print() print("a. £8 Billion.") print("b. £10 Billion.") print("c. £12 Billion.") answer = input("Make your choice: ") if answer == "b": print("Correct!") score = score + 1 else: print("Incorrect! Sorry the answer was B.") print() print() print("Question 3.") print("This device, which was invented in 1882 has revolutionised farming. What is it called?") print() print("a. Tractor") print("b. Wagon.") print("c. Combine.") answer = input("Make your choice: ") if answer == "a": print("Correct!") score = score + 1 else: print("Incorrect! Sorry the answer was A.") print("You got {}/3 right!".format(score)) def main(): quiz(); if __name__ == "__main__": main() </code></pre> <p>So compare your code and this code and see the changes I made, I hope this helps you. A few things before I go:</p> <ol> <li><p>Know the difference between '=' and '=='. '=' is an assignment operator, you're setting a variable equal to some value. '==' is used for testing purposes, e.g. if 5 == 3+2: print 'True' I noticed some of your if statements had this issue.</p></li> <li><p>The main function at the end will always be run if you have the 'If <strong>name</strong> == "<strong>main</strong>": main()' code.</p></li> </ol>
0
2016-09-06T14:51:44Z
[ "python" ]
How can I terminate a python program from an embedded IPython shell?
39,350,823
<p>I have the problem that for debugging purposes I drop into an IPython shell in a loop:</p> <pre><code>for x in large_list: if x.looks_bad(): import IPython IPython.embed() </code></pre> <p>From there I may want to terminate the <em>parent</em> program, because after debugging the problem cause, <code>embed()</code> would be called a lot of times. <code>sys.exit(1)</code> is caught by IPython, so I cannot use that.</p>
0
2016-09-06T13:54:26Z
39,350,824
<p><code>sys.exit</code> just raises the <code>SystemExit</code> exception. The following works by hard-killing the program:</p> <pre><code>import os os._exit(1) </code></pre>
0
2016-09-06T13:54:26Z
[ "python", "ipython" ]
Inserting formatted string with single quotes with Pypyodbc
39,350,833
<p>I'm trying to insert a network path as a string value using Pypyodbc:</p> <pre><code> def insert_new_result(self, low, medium, high, reportpath): reportpath = "'" + reportpath + "'" self.insertsql = ( """INSERT INTO [dbo].[Results] ([low],[medium], [high], [date]) VALUES ({low},{medium},{high}, GETDATE(),{reportpath})""" .format(low=low, medium=medium, high=high, reportpath=reportpath)) self.conection.cursor().execute(self.insertsql).commit() </code></pre> <p>This is evaluating to</p> <pre><code>'INSERT INTO [dbo].[Results] ([low],[medium], [high], [date]) VALUES (0,2,2, GETDATE(),\\'\\\\share\\dev-temp\\report_10b29ef6-7436-11e6-ab96-534e57000000.html\\')' </code></pre> <p>Notice the extra single quote at the start of the share path, causing an invalid sql error. I have tried a few things like .format(), building the string and escaping however it keeps including the single quote <em>after</em> the first \\. </p> <p>How can I get self.insertsql to evaluate to </p> <pre><code>'INSERT INTO [dbo].[Results] ([low],[medium], [high], [date]) VALUES (0,2,2, GETDATE(),'\\\\share\dev-temp\report_10b29ef6-7436-11e6-ab96-534e57000000.html\')' </code></pre>
0
2016-09-06T13:54:48Z
39,378,205
<p>If you are using <code>string.format()</code> then you are creating <em>dynamic SQL</em> which leaves you open to all the indignities of <em>SQL injection</em>, like messing with string delimiting and escaping. You should simply use a <em>parameterized query</em>, something like this:</p> <pre class="lang-python prettyprint-override"><code>self.insertsql = """\ INSERT INTO [dbo].[Results] ([low],[medium], [high], [date], [reportpath]) VALUES (?, ?, ?, GETDATE(), ?) """ self.params = (low, medium, high, reportpath, ) self.conection.cursor().execute(self.insertsql, self.params).commit() </code></pre> <p><strong>edit re: comment</strong></p> <p>As a simplified, self-contained test, the code</p> <pre class="lang-python prettyprint-override"><code>conn = pypyodbc.connect(conn_str, autocommit=True) crsr = conn.cursor() sql = """\ CREATE TABLE #Results ( id INT IDENTITY PRIMARY KEY, reportpath NVARCHAR(255) ) """ crsr.execute(sql) # test data reportpath = r"\\share\dev-temp\report_10b29ef6-7436-11e6-ab96-534e57000000.html" sql = "INSERT INTO #Results (reportpath) VALUES (?)" params = (reportpath, ) crsr.execute(sql, params) crsr.execute("SELECT * FROM #Results") row = crsr.fetchone() print(row) </code></pre> <p>displays this</p> <pre class="lang-none prettyprint-override"><code>(1, u'\\\\share\\dev-temp\\report_10b29ef6-7436-11e6-ab96-534e57000000.html') </code></pre>
0
2016-09-07T20:08:15Z
[ "python", "sql-server", "pypyodbc" ]
how to make the space between column 1 and 2 the same
39,350,840
<p>I am at the moment trying to filter a lexicon/dictionary such that it only contains the word i need. The dictionary has two column first being the word, and the second being the phonetic pronunciation (see the image below).</p> <p><img src="http://i.stack.imgur.com/VXJMZ.png" alt="Snippet of lexicon"></p> <p>The lexicon is available <a href="http://svn.code.sf.net/p/cmusphinx/code/trunk/cmudict/sphinxdict/cmudict.0.7a_SPHINX_40" rel="nofollow">here</a>.</p> <p>Is there some way I can make this space/delimiter even for all the cases... It would make things a lot more easier.</p>
1
2016-09-06T13:55:07Z
39,351,987
<p>you mean something like the following? <a href="http://pastebin.com/qvyEmbUr" rel="nofollow">here</a></p> <p>In this case, this is the code (without using any particular characters):</p> <pre><code>#!/usr/bin/env python2 import sys path_to_the_file = sys.argv[1] word = [] pron = [] maxword = 0 with open(path_to_the_file) as fr: for line in fr: words = line.split() word.append(words[0]) pron.append(' '.join(words[1:])) if len(words[0]) &gt; maxword: maxword = len(words[0]) format_str = '{:'+str(maxword)+'s} {:s}\n' msg = '' for w,p in zip(word,pron): msg += format_str.format(w,p) print msg </code></pre>
0
2016-09-06T14:50:16Z
[ "python", "unix", "text", "file-handling" ]
Python: os.listdir files are not found
39,350,844
<p>I recently moved my config files to another folder in my Project. I try to load the like this:</p> <pre><code>CONFIG_PATH = os.path.abspath(os.path.dirname(os.path.abspath(__file__))+"/../config/") def load_config(): configs = {} for config in os.listdir(CONFIG_PATH): configs[str(config)[0:-12]] = json.load(open(config)) return configs </code></pre> <p>I'm running the code from</p> <pre><code>D:/.../MyProject/src </code></pre> <p>And the specified <code>CONFIGPATH</code> is correctly set to</p> <pre><code>D:/.../MyProject/config </code></pre> <p>Now in that iteration loop, the <code>open(config)</code> raises an exception:</p> <pre><code>FileNotFoundError: [Errno 2] No such file or directory: 'sample.config.json' </code></pre> <p>I can't see why my program can't open a file, which clearly has to exist since it is given out by <code>os.listdir</code>. Actually, a <code>print(config)</code> in the loop confirms that there is a file with that name. So why won't it open and instead raises a FileNotFoundError?</p> <p>Do I miss the obvious here? The code worked before I moved the files upwards. I'm working with Pycharm on Windows 7, if that is of any relevance.</p>
1
2016-09-06T13:55:17Z
39,351,019
<p><code>os.listdir</code> only return the name of the file, not the complete path.</p> <p>If you're on 3.5 you can use <code>os.scandir</code> where the returned item has a path attribute. If you're not that lucky, you'll have to construct the full path yourself.</p> <p>It would be: <code>json.load(open(os.path.join(CONFIG_PATH, config)))</code> in your case.</p>
0
2016-09-06T14:03:35Z
[ "python", "json", "file" ]
Python library for working with 3D kinematics
39,350,861
<p>I am new at the field of kinematics and I am looking for some Python library that will make my start with 3D kinematics easier. The only library that I found so far is <strong>thLib</strong>, but nothing else. I am not sure if I am using wrong keywords or is python so pour.</p> <p>My goal is to use data from accelerometer, gyroscope and magnetometer to calculate quaternions, position in the space and analyze movement of that object. Do you have any recommendations?</p>
0
2016-09-06T13:56:08Z
39,351,015
<p>you can use <a href="http://matplotlib.org/" rel="nofollow">matplotlib</a> in that <a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html" rel="nofollow">mplot3d</a> and you can also use <a href="https://code.google.com/archive/p/robotics-toolbox-python/" rel="nofollow">robotics-toolbox-python</a></p>
1
2016-09-06T14:03:18Z
[ "python", "analysis", "motion", "kinematics" ]
Python ImportError: No module named
39,350,909
<p>I try to run django project, which has this kind of structure: 2 apps in one project:</p> <p>projectx</p> <pre><code>├──apps │ ├── app1 | | ├── __init__.py | | └── ... │ └── app2 | ├── __init__.py | └── ... ├──project │ ├── settings.py │ ├── urls.py │ ├── __init__.py | └── ... ├── manage.py └── ... </code></pre> <p>It has two apps in one project. Well, while running <code>python manage.py runserver</code> I get <code>ImportError: No module named apps</code></p> <p><code>$ echo $PYTHONPATH</code> gives<br> /home/alexander/Work/projectx</p> <p>Django version 1.9.8</p> <pre><code>INSTALLED_APPS = [ ... 'apps.app1', 'apps.app2' ] </code></pre>
0
2016-09-06T13:58:03Z
39,350,935
<p>You should add <code>__init__.py</code> inside your <code>apps</code> directory</p> <pre><code> ├──apps ├──__init__.py │ ├── app1 | | ├── __init__.py | | └── ... │ └── app2 | ├── __init__.py | └── ... </code></pre>
5
2016-09-06T13:59:38Z
[ "python", "django" ]
Adding Characters to beginning and end of line that matches expression (Python)
39,350,944
<p>Background: I am tasked with taking content from one website (mostly HTML tables), and inserting it into a wiki type site. I am able to poll the content (it is dynamic) using a REST API and get HTML formatted output. I must take this output, and convert it into Wiki Markup in order to then insert it into the new site. I am having issues with the conversion part.</p> <p>Currently I am using the html2text module in my test script as below:</p> <pre><code>import os import sys import html2text file = raw_input("File to convert: ") h = html2text.HTML2Text() with open(file, 'r') as f: dataContent = f.read() dataConverted = h.handle(dataContent) with open('tempconvert', 'w') as f: f.write(dataConverted) #print dataConverted # Add the | to the line beginnings and endings with open('tempconvert', 'r') as f: tempContent = f.readlines() with open('finalconvert', 'w') as f: for line in tempContent: if '|' in line: f.write('|' + line.rstrip('\n') + '| \n') </code></pre> <p>Now, the reason for all this input and output is because the html2text module doesn't insert a beginning or trailing "|" which the wiki syntax needs to recognize it as a table. </p> <p>My questions are:</p> <ol> <li>This is super ugly ... any way to clean this up without writing to so many temporary files?</li> <li>When I use the final search for adding the "|", it only writes the lines it acts upon (which makes sense given the arguments). How would I get it to act upon those lines, but also keep all the other lines that it doesn't act upon?</li> <li>It would also be awesome for me to be able to take the first line in the table instance (you can tell this because of whitespace before and after the table) and append a "||" in order to signify its a header row. Is this also possible?</li> </ol>
0
2016-09-06T14:00:05Z
39,352,033
<p>A first try:</p> <pre><code>html = html2text.HTML2Text() input_file = raw_input('File to convert: ') with open(input_file, 'r') as input_, open('finalconvert', 'w') as output_: data = input_.read() data_converted = html.handle(data) for line in data_converted.split('\n'): if '|' in line: line = "|{}|\n".format(line.rstrip()) output_.write(line.encode()) </code></pre> <p>This code fixes 1 and 2; but I do not understood 3.</p>
0
2016-09-06T14:52:22Z
[ "python" ]
Adding Characters to beginning and end of line that matches expression (Python)
39,350,944
<p>Background: I am tasked with taking content from one website (mostly HTML tables), and inserting it into a wiki type site. I am able to poll the content (it is dynamic) using a REST API and get HTML formatted output. I must take this output, and convert it into Wiki Markup in order to then insert it into the new site. I am having issues with the conversion part.</p> <p>Currently I am using the html2text module in my test script as below:</p> <pre><code>import os import sys import html2text file = raw_input("File to convert: ") h = html2text.HTML2Text() with open(file, 'r') as f: dataContent = f.read() dataConverted = h.handle(dataContent) with open('tempconvert', 'w') as f: f.write(dataConverted) #print dataConverted # Add the | to the line beginnings and endings with open('tempconvert', 'r') as f: tempContent = f.readlines() with open('finalconvert', 'w') as f: for line in tempContent: if '|' in line: f.write('|' + line.rstrip('\n') + '| \n') </code></pre> <p>Now, the reason for all this input and output is because the html2text module doesn't insert a beginning or trailing "|" which the wiki syntax needs to recognize it as a table. </p> <p>My questions are:</p> <ol> <li>This is super ugly ... any way to clean this up without writing to so many temporary files?</li> <li>When I use the final search for adding the "|", it only writes the lines it acts upon (which makes sense given the arguments). How would I get it to act upon those lines, but also keep all the other lines that it doesn't act upon?</li> <li>It would also be awesome for me to be able to take the first line in the table instance (you can tell this because of whitespace before and after the table) and append a "||" in order to signify its a header row. Is this also possible?</li> </ol>
0
2016-09-06T14:00:05Z
39,353,623
<p>1: You can eliminate the temporary files by using <a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><code>split</code></a> to convert from a single string to a list of strings. This has the side effect of removing the <code>\n</code> from each line, which you will have to add back or account for later.</p> <pre><code>tempContent = dataConverted.split('\n') </code></pre> <p>2: There are two ways to fix this. First is to simply use an <code>else</code> to write the lines that you were skipping before. (No need for the <code>rstrip</code> if you use the <code>split</code> hint from above).</p> <pre><code>if '|' in line: f.write('|' + line + '| \n') else: f.write(line + '\n') </code></pre> <p>The other way is to update the line if it needs updating, then write it in either case.</p> <pre><code>if '|' in line: line = '|' + line + '| ' f.write(line + '\n') </code></pre> <p>3: This is harder, because you don't just want to add those bars to <em>any</em> line that follows a blank line, you want to detect that there's a table coming up. This means you need some kind of look-ahead. Here's a little function you can use to see ahead automatically.</p> <pre><code>def lookahead(seq): current = None for upcoming in seq: if current is not None: yield current, upcoming current = upcoming if current is not None: yield current, None </code></pre> <p>You'd use it like this:</p> <pre><code>for line, upcoming in lookahead(tempContent): if (upcoming and '|' in upcoming) or ('|' in line): line = '|' + line + '|' </code></pre>
1
2016-09-06T16:20:32Z
[ "python" ]
Applying Conditions on Pandas DataFrame Columns before reading csv or tsv files
39,351,036
<p>Is it possible to set conditions (filters) for the DataFrame columns before reading a csv or tsv files, If I am already aware of the column names and types? If yes, how?</p> <p>For Example: Consider there are two numerical columns (col1 and col2) in a very big file. I do not want to load whole file in the memory and select only those rows where col1 greater than col2. Therefore, first, I want to set the condition on the dataframe that it should read only those rows from the csv file where col1 is greater than col2. I hope my explanation make sense.</p> <p>Thanks </p>
0
2016-09-06T14:04:26Z
39,351,962
<p>You can use <a href="https://blaze.readthedocs.io/en/latest/" rel="nofollow">blaze</a> for this which is a handy tool to have alongside <code>pandas</code>.</p> <p>Let's assume an input file of:</p> <pre><code>a,b 1,2 3,4 5,3 3,6 6,1 </code></pre> <p>We then open the file and query the data - note that the query isn't executed until you attempt to materialise/access it:</p> <pre><code>import blaze import pandas as pd csv_data = blaze.Data('input.csv') query = csv_data[csv_data['a'] &gt; csv_data['b']] df = pd.DataFrame.from_records(query, columns=query.fields) </code></pre> <p>That then gives <code>df</code> as:</p> <pre><code> a b 0 5 3 1 6 1 </code></pre>
1
2016-09-06T14:49:27Z
[ "python", "pandas", "dataframe", "condition" ]
Run Sqoop with python 3 using subprocess
39,351,139
<p>I am trying to run Sqoop command with python</p> <pre><code>subprocess.call(["sqoop","import","--connect", "jdbc:oracle:thin:@hostname:1521/ARSMTREP","--username", "username" ,"--password", "password","--table","ARADMIN."+line,"--as-textfile","--target-dir","/data/"+line]) </code></pre> <p>able to execute this code but when I am trying to execute with "--fields-terminated-by"+" "+"'~'" it's giving tool import error</p> <pre><code>process=subprocess.call(["sqoop","import","--connect", "jdbc:oracle:thin:@hostname:1521/ARSMTREP","--username", "hadoop_user" ,"--password", "password","--table","ARADMIN."+line,"--fields-terminated-by"+" "+"'~'","--as-textfile","--target-dir","/data/"+line]) </code></pre> <blockquote> <p>Error parsing arguments for import</p> </blockquote>
0
2016-09-06T14:10:29Z
39,351,986
<p>Try:</p> <p><code>process=subprocess.call(["sqoop","import","--connect", "jdbc:oracle:thin:@hostname:1521/ARSMTREP","--username", "hadoop_user" ,"--password", "password","--table","ARADMIN."+line,"--fields-terminated-by","'~'","--as-textfile","--target-dir","/data/"+line])</code></p>
0
2016-09-06T14:50:16Z
[ "python", "python-3.x", "sqoop", "apache-sqoop" ]
Run Sqoop with python 3 using subprocess
39,351,139
<p>I am trying to run Sqoop command with python</p> <pre><code>subprocess.call(["sqoop","import","--connect", "jdbc:oracle:thin:@hostname:1521/ARSMTREP","--username", "username" ,"--password", "password","--table","ARADMIN."+line,"--as-textfile","--target-dir","/data/"+line]) </code></pre> <p>able to execute this code but when I am trying to execute with "--fields-terminated-by"+" "+"'~'" it's giving tool import error</p> <pre><code>process=subprocess.call(["sqoop","import","--connect", "jdbc:oracle:thin:@hostname:1521/ARSMTREP","--username", "hadoop_user" ,"--password", "password","--table","ARADMIN."+line,"--fields-terminated-by"+" "+"'~'","--as-textfile","--target-dir","/data/"+line]) </code></pre> <blockquote> <p>Error parsing arguments for import</p> </blockquote>
0
2016-09-06T14:10:29Z
39,361,835
<pre><code>process=subprocess.call(["sqoop","import","--connect", "jdbc:oracle:thin:@hostname:1521/ARSMTREP","--username", "hadoop_user" ,"--password", "password","--table","ARADMIN."+line,"--fields-terminated-by","~","--as-textfile","--target-dir","/data/"+line]) </code></pre> <p>This code call the sqoop command and executes them from linux terminal . Subprocess call <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">Python subprocess</a> you can also use <code>os.system()</code> to execute the Sqoop query from python . But its preferable the call Subprocess . There is no white space in arguments inside the <code>subprocess.call()</code> or else it will provide the error. </p> <p>In above code all the argument are Sqoop command only the <code>line</code>is variable which takesthe table name from list.</p>
0
2016-09-07T05:30:58Z
[ "python", "python-3.x", "sqoop", "apache-sqoop" ]
basemap returns blank when plotting points
39,351,185
<p>I'm new to basemap and map plots in general. After looking through documentation online, I was able to install basemap and GEOS no problem. I was able to setup my basemap map with the following code:</p> <pre><code>themap = Basemap(projection='gall', resolution='i', llcrnrlon = -135, llcrnrlat = 23, urcrnrlon = -60, urcrnrlat = 50, ) themap.drawcoastlines() themap.drawcountries() themap.drawstates() themap.fillcontinents(color = 'gainsboro') themap.drawmapboundary(fill_color='light blue') </code></pre> <p>This works fine and I get the map of the US exactly as I wanted:</p> <p><img src="http://i.stack.imgur.com/8BZvH.png" alt="map of the US"></p> <p>Now I want to overlay my data. As a test, i'll just try to plot one random point with this code:</p> <pre><code>x,y = themap(37, -95) themap.plot(x,y,'ko') plt.show() </code></pre> <p><img src="http://i.stack.imgur.com/34nwv.png" alt="nada"></p> <p>I get nothing but a blank canvas. Even my original map doesn't render now. There are no error messages, warnings or anything. So I don't know whats going wrong. I've run a lot of the examples from the examples directory of my basemap directory, and they all work fine. So i'm confused as to why i can't get this plot to show. Am I doing something obviously stupid? </p>
0
2016-09-06T14:12:18Z
39,351,789
<p>The order of the points should be (lon, lat). This is working for me:</p> <p><a href="http://i.stack.imgur.com/sQNXX.png" rel="nofollow"><img src="http://i.stack.imgur.com/sQNXX.png" alt="enter image description here"></a></p>
1
2016-09-06T14:41:00Z
[ "python", "matplotlib", "matplotlib-basemap" ]
Python write to csv ignore commas
39,351,222
<p>I am writing to a csv and it works good, except some of the rows have commas in there names and when I write to the csv those commas throw the fields off...how do I write to a csv and ignore the commas in the rows</p> <pre><code>header = "Id, FACID, County, \n" row = "{},{},{}\n".format(label2,facidcsv,County) with open('example.csv', 'a') as wildcsv: if z==0: wildcsv.write(header) wildcsv.write(row) else: wildcsv.write(row) </code></pre>
1
2016-09-06T14:13:58Z
39,351,270
<p>Strip any comma from each field that you write to the row, eg:</p> <pre><code>label2 = ''.join(label2.split(',')) facidcsv = ''.join(facidcsv.split(',')) County = ''.join(County.split(',')) row = "{},{},{}\n".format(label2,facidcsv,County) </code></pre> <hr> <p>Generalized to format a row with any number of fields:</p> <pre><code>def format_row(*fields): row = '' for field in fields: if row: row = row + ', ' + ''.join(field.split(',')) else: row = ''.join(field.split(',')) return row label2 = 'label2, label2' facidcsv = 'facidcsv' county = 'county, county' print(format_row(label2, facidcsv, county)) wildcsv.write(format_row(label2, facidcsv, county)) </code></pre> <p><strong>Output</strong></p> <pre><code>label2 label2, facidcsv, county county </code></pre> <hr> <p>As @TomaszPlaskota and @quapka allude to in the comments, Python's <code>csv</code> <code>writers</code> and <code>readers</code> by default write/read csv fields that contain a delimiter with a surrounding <code>'"'</code>. Most applications that work with csv files follow the same format. So the following is the preferred approach if you want to keep the commas in the output fields:</p> <pre><code>import csv label2 = 'label2, label2' facidcsv = 'facidccv' county = 'county, county' with open('out.csv', 'w') as f: writer = csv.writer(f) writer.writerow((label2, facidcsv, county)) </code></pre> <p><strong>out.csv</strong></p> <pre><code>"label2, label2",facidccv,"county, county" </code></pre>
2
2016-09-06T14:16:40Z
[ "python", "csv" ]
recvfrom function in C on Windows skips UDP data when using MinGW
39,351,233
<p>I have problem with recvfrom function on Windows I cannot resolve.<br> See the following part of code I wrote. I run this code on Linux and Windows and I get different results in udp bitrate value. </p> <p>When compiling it on Windows using Cygwin, I get the same results as on Ubuntu, what is okay. I compared this with reference tool. </p> <p>When compiling it on Windows using MinGW, I get smaller upd bitrate value, which is caused by smaller number of while(1) loop iterations in one second (counter variable) and what is related - smaller amount of data captured in 1 second (data_in_1_sec variable). It seems that recvfrom funtion on Windows with using MinGW is slowest and skips udp data.<br> Please note that in case of upd bitrate about 0.200 Mbps results on both OS are the same using MinGW. Problem is visible on data with UDP bitrate about 20 Mbps.</p> <p>Unfortunately I have to use MinGW due to fact that this code is loaded into Python code as static library. Using CygWin dll I get access violation during running this function under Python.</p> <p>How to deal with this? </p> <p>I use Windows 7 Professional 64.</p> <p>Code I use:</p> <pre><code>while (1) { #ifdef _WIN32 // start timer QueryPerformanceCounter(&amp;t1); #elif __linux clock_gettime(CLOCK_MONOTONIC, &amp;start); #endif udp_packet_len = recvfrom(sock, udp_packet, buff_len, 0, (struct sockaddr *) &amp;addr, &amp;addrlen); #if DEBUG == 1 counter++; #endif #ifdef _WIN32 // stop timer QueryPerformanceCounter(&amp;t2); #elif __linux clock_gettime(CLOCK_MONOTONIC, &amp;finish); #endif data_in_1_sec += (double)udp_packet_len; #ifdef _WIN32 temp = (t2.QuadPart - t1.QuadPart); temp *= 1000000000.0; temp /= frequency.QuadPart; temp /= 1000000000.0; second += temp; #elif __linux temp = (finish.tv_sec - start.tv_sec); temp += (finish.tv_nsec - start.tv_nsec) / 1000000000.0; second += temp; #endif if(second &gt;=1.0) { processing.udp_bitrate = (((data_in_1_sec) * 8.0) /second); #if DEBUG == 1 fprintf(stderr,"\nudp_bitrate: %f\n",processing.udp_bitrate); fprintf(stderr,"data_in_1_sec: %f\n",data_in_1_sec); fprintf(stderr,"second: %f\n",second); fprintf(stderr,"counters: %d\n",counter); counter = 0; #endif data_in_1_sec = 0; second = 0.0; } </code></pre> <p>Results of this code,<br> for Windows:</p> <pre><code>udp_bitrate: 19799823.828382 data_in_1_sec: 2505664.000000 second: 1.012399 counters: 1904 udp_bitrate: 19389475.566430 data_in_1_sec: 2451708.000000 second: 1.011562 counters: 1863 udp_bitrate: 18693904.033320 data_in_1_sec: 2367484.000000 second: 1.013158 counters: 1799 udp_bitrate: 18963187.258098 data_in_1_sec: 2399068.000000 second: 1.012095 counters: 1823 udp_bitrate: 19452989.621014 data_in_1_sec: 2459604.000000 second: 1.011507 counters: 1869 udp_bitrate: 19795284.196391 data_in_1_sec: 2509612.000000 second: 1.014226 counters: 1907 </code></pre> <p>output for Ubuntu for the same data </p> <pre><code>udp_bitrate: 22016976.870087 data_in_1_sec: 2788604.000000 second: 1.013256 counters: 2119 udp_bitrate: 22022223.539749 data_in_1_sec: 2787288.000000 second: 1.012536 counters: 2118 udp_bitrate: 22003055.797884 data_in_1_sec: 2785972.000000 second: 1.012940 counters: 2117 udp_bitrate: 22041580.024322 data_in_1_sec: 2788604.000000 second: 1.012125 counters: 2119 udp_bitrate: 22025510.655441 data_in_1_sec: 2782024.000000 second: 1.010473 counters: 2114 udp_bitrate: 22412560.109513 data_in_1_sec: 2801764.000000 second: 1.000069 counters: 2129 </code></pre>
0
2016-09-06T14:14:53Z
39,352,264
<p>UDP is an unreliable transport. Dropping packets is an allowed behavior, and it is to be expected where the data transmission rate exceeds the rate at which data are handled by the receiver.</p> <p>Cygwin and MinGW are separate projects. They each provide their own <code>recvfrom()</code> wrapper built on top of the Windows kernel and API. It is conceivable that Cygwin's implementation is a bit more efficient, providing 10% greater bandwidth than MinGW's under the conditions of your test.</p> <p>It may also be that your instrumentation is interfering with your measurement. At least some versions of Cygwin do not by default cause <code>_WIN32</code> to be defined by the preprocessor, whereas MinGW does, so it may be that you are using <code>clock_gettime()</code> with Cygwin and a Windows performance counter with MinGW. You would think that Windows performance counters would have low enough overhead for such a difference to be negligible, but you are make a lot of calls to it. You should consider minimizing overhead from both sources by running the test for a <em>fixed</em> number of iterations and timing just the overall total for all those iterations (only one timer start/stop per rate measurement).</p> <p>Bottom line: your test methodology could be improved, but even if the results are a good reflection of the behavior of the different implementations under test, they do not reveal anything fundamentally wrong.</p>
0
2016-09-06T15:03:48Z
[ "python", "c", "windows", "udp", "recvfrom" ]
Is it good practice to exit a thread manually in python?
39,351,271
<p>Is it good practice to exit a thread manually? The below code has commented #sys.exit() because I assume the thread ends there. But is it good practice to end it anyway? If not, is there any overhead created if that thread is called hundres of times without manually exiting with sys.exit()?</p> <pre><code>import time import threading import sys def non_daemon(): print('Test non-daemon') time.sleep(5) #sys.exit() # is this necessary/encouraged? t = threading.Thread(name='non-daemon', target=non_daemon) t.start() print("done") </code></pre>
0
2016-09-06T14:16:47Z
39,351,312
<p><code>sys.exit()</code> has nothing to do with threads. As <a href="https://docs.python.org/3/library/sys.html#sys.exit" rel="nofollow">the docs</a> explain, it only has an effect when called from the main thread. In all other cases, all it does is raise an exception. There's absolutely no reason to call it in a thread.</p>
4
2016-09-06T14:18:49Z
[ "python", "multithreading" ]
Python argaprse optional arguments handling
39,351,272
<p>So, I have a python script for parsing and plotting data from text files. Argument handling is done with argparse module. The problem is, that some arguments are optional, e.g. one of the is used to add text annotations on the plot. This argument is sent to plotting function via **kwargs. My question is - what is the most pythonic way to handle those optional arguments? Some pseudo code here:</p> <pre><code>parser = argparse.ArgumentParser() ... parser.add_argument("-o", "--options", nargs="+", help="additional options") args = parser.parse_args() ... def some_function(arguments, **kwargs): doing something with kwargs['options'] return something ... arguments = ... some_function(arguments, options=args.options) </code></pre> <p>If options are not specified by default None value is assigned. And it causes some problems. What is more pythonic - somehow check 'options' within some_function? Or maybe parse arguments before some_function is called?</p>
0
2016-09-06T14:16:48Z
39,351,322
<p>You can just provide an explicit empty list as the default.</p> <pre><code>parser.add_argument("-o", "--options", nargs="+", default=[]) </code></pre>
3
2016-09-06T14:19:04Z
[ "python", "command-line-arguments", "argparse", "kwargs" ]
Python argaprse optional arguments handling
39,351,272
<p>So, I have a python script for parsing and plotting data from text files. Argument handling is done with argparse module. The problem is, that some arguments are optional, e.g. one of the is used to add text annotations on the plot. This argument is sent to plotting function via **kwargs. My question is - what is the most pythonic way to handle those optional arguments? Some pseudo code here:</p> <pre><code>parser = argparse.ArgumentParser() ... parser.add_argument("-o", "--options", nargs="+", help="additional options") args = parser.parse_args() ... def some_function(arguments, **kwargs): doing something with kwargs['options'] return something ... arguments = ... some_function(arguments, options=args.options) </code></pre> <p>If options are not specified by default None value is assigned. And it causes some problems. What is more pythonic - somehow check 'options' within some_function? Or maybe parse arguments before some_function is called?</p>
0
2016-09-06T14:16:48Z
39,351,403
<p>use <code>get</code> and set a default value if the key is not found in the dict</p> <pre><code>def some_function(arguments, **kwargs): something = kwargs.get('options', 'Not found') return something </code></pre> <p>or an if statement</p> <pre><code>if 'option' in kwargs: pass # do something </code></pre>
1
2016-09-06T14:21:39Z
[ "python", "command-line-arguments", "argparse", "kwargs" ]
Control the mouse click event with a subplot rather than a figure in matplotlib
39,351,388
<p>I have a figure with 5 subplots. I am using a mouse click event to create a shaded area in the 4th and 5th subplot only (see attached pic below).</p> <p><a href="http://i.stack.imgur.com/3G3UO.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/3G3UO.jpg" alt="enter image description here"></a></p> <p>The mouse click event is triggered when I click on any of the subplots in the figure. However, I would ideally like to be able to trigger the mouse click event only when clicked on the 4th and 5th subplots. I am wondering if this is possible using mpl_connect.</p> <p>Here's my code</p> <pre><code>import numpy as np from scipy.stats import norm, lognorm, uniform import matplotlib.pyplot as plt from matplotlib.widgets import Slider, Button, RadioButtons, CheckButtons from matplotlib.patches import Polygon #####Mean and standard deviation##### mu_a1 = 1 mu_b1 = 10 mu_c1 = -13 sigma_a1 = 0.14 sigma_b1 = 1.16 sigma_c1 = 2.87 mu_x01 = -11 sigma_x01 = 1.9 #####_____##### #####Generating random data##### a1 = 0.75*mu_a1 + (1.25 - 0.75)*sigma_a1*np.random.sample(10000) b1 = 8*mu_b1 + (12 - 8)*sigma_b1*np.random.sample(10000) c1 = -12*mu_c1 + 2*sigma_c1*np.random.sample(10000) x01 = (-b1 - np.sqrt(b1**2 - (4*a1*c1)))/(2*a1) #####_____##### #####Creating Subplots##### fig = plt.figure() plt.subplots_adjust(left=0.13,right=0.99,bottom=0.05) ax1 = fig.add_subplot(331) #Subplot 1 ax1.set_xlabel('a' , fontsize = 14) ax1.grid(True) ax2 = fig.add_subplot(334) #Subplot 2 ax2.set_xlabel('b', fontsize = 14) ax2.grid(True) ax3 = fig.add_subplot(337) #Subplot 3 ax3.set_xlabel('c', fontsize = 14) ax3.grid(True) ax4 = fig.add_subplot(132) #Subplot 4 ax4.set_xlabel('x0', fontsize = 14) ax4.set_ylabel('PDF', fontsize = 14) ax4.grid(True) ax5 = fig.add_subplot(133) #Subplot 5 ax5.set_xlabel('x0', fontsize = 14) ax5.set_ylabel('CDF', fontsize = 14) ax5.grid(True) #####_____##### #####Plotting Distributions##### [n1,bins1,patches] = ax1.hist(a1, bins=50, color = 'red',alpha = 0.5, normed = True) [n2,bins2,patches] = ax2.hist(b1, bins=50, color = 'red',alpha = 0.5, normed = True) [n3,bins3,patches] = ax3.hist(c1, bins=50, color = 'red',alpha = 0.5, normed = True) [n4,bins4,patches] = ax4.hist(x01, bins=50, color = 'red',alpha = 0.5, normed = True) ax4.axvline(np.mean(x01), color = 'black', linestyle = 'dashed', lw = 2) dx = bins4[1] - bins4[0] CDF = np.cumsum(n4)*dx ax5.plot(bins4[1:], CDF, color = 'red') #####_____##### #####Event handler for button_press_event##### def enter_axes(event): print('enter_axes', event.inaxes) event.canvas.draw() def leave_axes(event): print('leave_axes', event.inaxes) event.canvas.draw() def onclick(event): ''' Event handler for button_press_event @param event MouseEvent ''' global ix ix = event.xdata if ix is not None: print 'x = %f' %(ix) ax4.clear() ax5.clear() ax4.grid(True) ax5.grid(True) [n4,bins4,patches] = ax4.hist(x01, bins=50, color = 'red',alpha = 0.5, normed = True) ax4.axvline(np.mean(x01), color = 'black', linestyle = 'dashed', lw = 2) xmin = ix xmax = ax4.get_xlim()[1] ax4.axvspan(xmin, xmax, facecolor='0.9', alpha=0.5) dx = bins4[1] - bins4[0] CDF = np.cumsum(n4)*dx ax5.plot(bins4[1:], CDF, color = 'red') ax5.axvspan(xmin, xmax, facecolor='0.9', alpha=0.5) plt.draw() return ix cid = fig.canvas.mpl_connect('button_press_event', onclick) #fig.canvas.mpl_disconnect(cid) plt.show() #####_____##### </code></pre> <p>Thanks in advance :-)</p>
1
2016-09-06T14:21:05Z
39,351,847
<p>You can use the <code>inaxes</code> property of <code>event</code> to find which axes you are in. See the <a href="http://matplotlib.org/users/event_handling.html#event-attributes" rel="nofollow">docs here</a>. If you iterate through your subplot <code>Axes</code>, you can then compare the result of <code>inaxes</code> to each <code>Axes</code> instance, and then only go ahead with drawing the shaded region if you are in <code>ax4</code> or <code>ax5</code>.</p> <p>I've modified your <code>onclick</code> function to do that. For information, it also prints which axes the click was in, but you can turn that off once you satisfy yourself that it is working as planned.</p> <pre><code>def onclick(event): ''' Event handler for button_press_event @param event MouseEvent ''' global ix ix = event.xdata for i, ax in enumerate([ax1, ax2, ax3, ax4, ax5]): # For infomation, print which axes the click was in if ax == event.inaxes: print "Click is in axes ax{}".format(i+1) # Check if the click was in ax4 or ax5 if event.inaxes in [ax4, ax5]: if ix is not None: print 'x = %f' %(ix) ax4.clear() ax5.clear() ax4.grid(True) ax5.grid(True) [n4,bins4,patches] = ax4.hist(x01, bins=50, color = 'red',alpha = 0.5, normed = True) ax4.axvline(np.mean(x01), color = 'black', linestyle = 'dashed', lw = 2) xmin = ix xmax = ax4.get_xlim()[1] ax4.axvspan(xmin, xmax, facecolor='0.9', alpha=0.5) dx = bins4[1] - bins4[0] CDF = np.cumsum(n4)*dx ax5.plot(bins4[1:], CDF, color = 'red') ax5.axvspan(xmin, xmax, facecolor='0.9', alpha=0.5) plt.draw() return ix else: return </code></pre> <p>Note: I took inspiration for this answer from this other <a href="http://stackoverflow.com/questions/14236290/event-connections-and-subplots-in-matplotlib">SO answer</a>.</p>
1
2016-09-06T14:43:56Z
[ "python", "matplotlib", "mouseclick-event" ]
How to get popup content with splash
39,351,458
<p>i'm starting to use scrapy with splash, and i was wondering if splash can handle multiple windows and popups. As an example i would like to use that lua script and try to obtain the google window's content</p> <pre><code>function main(splash) assert(splash:go("http://stackoverflow.com/")) assert(splash:runjs("window.open('http://www.google.com');")) assert(splash:wait(5)) return { ? } end </code></pre>
0
2016-09-06T14:24:23Z
39,352,609
<p>I've found a tiny hack, i do a</p> <pre><code>assert(splash:runjs("window.open = function(url) {window.location.replace(url)};") </code></pre> <p>So instead of opening new windows, you are redirected towards the link, however it's a hack and it might not work if window.open is not used to open the popup</p> <p>I think scrapy with selenium could be a solution too but i want to keep my stuff lightweight</p>
0
2016-09-06T15:20:01Z
[ "python", "web-scraping", "popup", "scrapy", "scrapy-splash" ]
Easy way to continue a failed reindex?
39,351,521
<p>I'm currently trying to reindex a large set of data (around 96 million documents) using the <a href="http://elasticsearch-py.readthedocs.io/en/master/api.html" rel="nofollow">Python API</a>, specifically the <a href="http://elasticsearch-py.readthedocs.io/en/master/helpers.html#reindex" rel="nofollow"><code>reindex</code></a> command.</p> <p>When running the command I eventually get a timeout error from the <code>bulk</code> command. I've tried setting the <code>bulk_kwargs request_timeout</code> to 24 hours, however it still timesout... after 28 hours and 57 million records loaded. Re-running the reindex will just delete the existing ones and start over.</p> <p>Regardless of the reason why the error happens (I think I'm having problems with a disk bottleneck which I can fix. There are no <code>out of memory</code> errors) <strong>is there any easy way to continue the reindex from where it died?</strong></p>
1
2016-09-06T14:27:44Z
39,351,566
<p>If you're saying that you're deleting the existing ones and start over, then just delete index and create new one and feed it. Will be faster.</p> <p><strong>OR</strong></p> <p>If you cannot have empty index, then one by one or using some batch delete items identified by some <code>id</code> and insert updated according to that <code>id</code>.</p>
1
2016-09-06T14:29:19Z
[ "python", "elasticsearch" ]
Load file into Database
39,351,687
<p>I am trying to load a csv file into the database but no success. The issue is that it works when I load the query directly in the mysql shell but it doesn't work when I tried doing from the python code. The code I am using is shown below:</p> <pre><code>db = connect_to_database() cursor = db.cursor() q = "LOAD DATA LOCAL INFILE '/home/ubuntu/load_file.csv' INTO TABLE test_load FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'" db.query(q) cursor.execute(q) db.commit() </code></pre> <p>The error it throws says:</p> <pre><code>File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 281, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1148, 'The used command is not allowed with this MySQL version') </code></pre> <p>When I copied the string into the sql shell, it loads successfully. I'm not sure why its throwing this error.</p>
0
2016-09-06T14:35:42Z
39,418,386
<p>So I managed to solve the problem. All it was missing was the local_infile parameter in the MySQLDB connect:</p> <p>db=MySQLdb.connect(host=raw_host,user=raw_user,passwd=raw_passwd,db=raw_db, local_infile = 1)</p> <p>When I added this parameter, it worked as expected. Thank you all for your efforts in resolving the problem.</p>
0
2016-09-09T19:19:26Z
[ "python", "mysql" ]
Edit a web page with Python
39,351,699
<p>I asked a <a href="http://stackoverflow.com/questions/39283333/python-to-view-and-manipulate-web-page?noredirect=1#comment65902596_39283333">similar question</a> about how to edit a web page with Python before using selenium, but since that didn't get anywhere (I want to be able to do it in a browser that still has all of the saved cookies, passwords, bookmarks, etc) I want to broaden the scope. Using any modules you know of, how can I open a website in my browser, and edit an element using a Python script?</p> <p>For instance I'd like my script to do something like this...</p> <pre><code>open google.com find the element that corresponds to the google logo hide the element </code></pre> <p>If it helps, I'm on a Macbook, using Google Chrome</p>
0
2016-09-06T14:36:26Z
39,351,778
<p>You can still do that via <code>selenium</code>, locate the element and edit the <code>style</code> via "execute script":</p> <pre><code>elm = driver.find_element_by_id("myid") driver.execute_script("arguments[0].style.display = 'none';", elm) </code></pre>
0
2016-09-06T14:40:26Z
[ "python", "python-2.7", "google-chrome" ]
Django - TinyMCE - admin - How to change editor size?
39,351,709
<p>I can't seem to find any way to hange editor size in TinyMCE. I edit posts on my site in Django administration and to make it easier I looked for a better editor than just a textfield. I succesfully installed TinyMCE, but the editor is tiny, which makes editing very annoying.</p> <p><a href="http://i.imgur.com/eaW5CXY.png" rel="nofollow">Here's how it looks like.</a></p> <p>Here is my models.py</p> <pre><code>from django.db import models from tinymce.models import HTMLField class Post(models.Model): title = models.CharField(max_length=140) # body = models.TextField() date = models.DateTimeField() body = HTMLField() def __str__(self): return self.title </code></pre> <p>Here is my admin.py:</p> <pre><code>from django.contrib import admin from blog.models import Post admin.site.register(Post) </code></pre> <p>And here is my urls.py:</p> <pre><code>from django.conf.urls import url, include from django.views.generic import ListView, DetailView from .models import Post urlpatterns = [ url(r'^$', ListView.as_view( queryset=Post.objects.all().order_by("-date")[:25], template_name='blog/blog.html')), url(r'^(?P&lt;pk&gt;\d+)$', DetailView.as_view(model=Post, template_name='blog/post.html')), ] </code></pre> <p>I've been trying and googling for the past 2 hours, but I can't figure it out.</p> <p>Can anyone help me? Thanks.</p>
0
2016-09-06T14:37:01Z
39,364,134
<p>As said in the docs (<a href="http://django-tinymce.readthedocs.io/en/latest/installation.html#configuration" rel="nofollow">http://django-tinymce.readthedocs.io/en/latest/installation.html#configuration</a>), there is the <code>TINYMCE_DEFAULT_CONFIG</code> setting which can be used to configure the editor. Just look for available options here: <a href="https://www.tinymce.com/docs/configure/editor-appearance/" rel="nofollow">https://www.tinymce.com/docs/configure/editor-appearance/</a>.</p> <p>In your case, I think something like this may work:</p> <pre><code>TINYMCE_DEFAULT_CONFIG = { 'theme': "simple", # default value 'relative_urls': False, # default value 'width': '100%', 'height': 300 } </code></pre> <p>Put it in your settings.py</p>
0
2016-09-07T07:49:15Z
[ "python", "django", "tinymce", "django-tinymce" ]
Error: django.core.exceptions.AppRegistryNotReady: The translation infrastructure... in python
39,351,908
<p><strong>What I want to do:</strong> I'm trying to run tests with unittest for functions in my views. </p> <p><strong>Outcome</strong>: I'm getting the following error:</p> <p><em>....env/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 189, in _fetch "The translation infrastructure cannot be initialized before the " django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.</em></p> <p><strong>Imports used:</strong> </p> <pre><code>import unittest from django.test import Client from django.core.wsgi import get_wsgi_application import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") import sys sys.path.append('../../mysite/') from mysite.settings import * from views import * application = get_wsgi_application() </code></pre> <p>As you can see I tried this answer with no success: <a href="http://stackoverflow.com/questions/27630155/appregistrynotready-the-translation-infrastructure-cannot-be-initialized">appregistrynotready-the-translation-infrastructure-cannot-be-initialized</a> </p> <p>I followed this one too: <a href="http://stackoverflow.com/questions/34675593/upgrading-to-django-1-7-getting-appregistrynotready-for-translation-infrastruct">upgrading-to-django-1-7-getting-appregistrynotready-for-translation-infrastruct</a></p> <p><strong>Imports I found with ugettext &amp; ugettext_lazy:</strong></p> <pre><code>from django.utils.translation import ungettext, ugettext_lazy as _ from django.utils.translation import ungettext, ugettext, ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _ </code></pre> <p>I changed them to </p> <pre><code>from django.utils.translation import ugettext_lazy as _ </code></pre> <p>But it didn't work either</p> <p><strong>Some code I found with ugettext</strong></p> <pre><code>return ugettext('%(number)d %(type)s') % {'number': delta.seconds, 100 'type': count(delta.seconds)} </code></pre> <p>I was wondering if there could be a problem with this.</p> <p>I found it worked if I removed this lines from authentication/models.py:</p> <pre><code>last_pass_change = models.DateTimeField(_("last_pass_change"), default=datetime.datetime.now()) last_failed_login = models.DateTimeField(_("last_failed_login"), default=datetime.datetime.now()) </code></pre> <p>But I don't know how to fix it</p>
1
2016-09-06T14:46:44Z
39,352,450
<p>Finally I solved it changing:</p> <pre><code>from django.utils.translation import gettext as _ </code></pre> <p>to:</p> <pre><code>from django.utils.translation import ugettext_lazy as _ </code></pre>
1
2016-09-06T15:12:25Z
[ "python", "django" ]
Error: django.core.exceptions.AppRegistryNotReady: The translation infrastructure... in python
39,351,908
<p><strong>What I want to do:</strong> I'm trying to run tests with unittest for functions in my views. </p> <p><strong>Outcome</strong>: I'm getting the following error:</p> <p><em>....env/lib/python2.7/site-packages/django/utils/translation/trans_real.py", line 189, in _fetch "The translation infrastructure cannot be initialized before the " django.core.exceptions.AppRegistryNotReady: The translation infrastructure cannot be initialized before the apps registry is ready. Check that you don't make non-lazy gettext calls at import time.</em></p> <p><strong>Imports used:</strong> </p> <pre><code>import unittest from django.test import Client from django.core.wsgi import get_wsgi_application import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") import sys sys.path.append('../../mysite/') from mysite.settings import * from views import * application = get_wsgi_application() </code></pre> <p>As you can see I tried this answer with no success: <a href="http://stackoverflow.com/questions/27630155/appregistrynotready-the-translation-infrastructure-cannot-be-initialized">appregistrynotready-the-translation-infrastructure-cannot-be-initialized</a> </p> <p>I followed this one too: <a href="http://stackoverflow.com/questions/34675593/upgrading-to-django-1-7-getting-appregistrynotready-for-translation-infrastruct">upgrading-to-django-1-7-getting-appregistrynotready-for-translation-infrastruct</a></p> <p><strong>Imports I found with ugettext &amp; ugettext_lazy:</strong></p> <pre><code>from django.utils.translation import ungettext, ugettext_lazy as _ from django.utils.translation import ungettext, ugettext, ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _ </code></pre> <p>I changed them to </p> <pre><code>from django.utils.translation import ugettext_lazy as _ </code></pre> <p>But it didn't work either</p> <p><strong>Some code I found with ugettext</strong></p> <pre><code>return ugettext('%(number)d %(type)s') % {'number': delta.seconds, 100 'type': count(delta.seconds)} </code></pre> <p>I was wondering if there could be a problem with this.</p> <p>I found it worked if I removed this lines from authentication/models.py:</p> <pre><code>last_pass_change = models.DateTimeField(_("last_pass_change"), default=datetime.datetime.now()) last_failed_login = models.DateTimeField(_("last_failed_login"), default=datetime.datetime.now()) </code></pre> <p>But I don't know how to fix it</p>
1
2016-09-06T14:46:44Z
39,352,461
<p>Initialize the WSGI application before you import from views and settings.</p> <pre><code>application = get_wsgi_application() from mysite.settings import * from views import * </code></pre>
0
2016-09-06T15:12:54Z
[ "python", "django" ]
How to change number of bins in matplotlib?
39,351,960
<p>I have the following code:</p> <pre><code>ax1.hist(true_time, bins=500, edgecolor="none") ax2.hist(true_time_2, bins=500, edgecolor="none") </code></pre> <p>I expected that it would give me two hists with the same number of bins, but it wouldn't: <a href="http://i.stack.imgur.com/Nkx3k.png" rel="nofollow"><img src="http://i.stack.imgur.com/Nkx3k.png" alt="enter image description here"></a></p> <p>How to do it correctly?</p>
0
2016-09-06T14:49:12Z
39,352,129
<p>If you have some distant outlier in true_time, it may be that the bins were made just really really big to include it.</p>
2
2016-09-06T14:57:05Z
[ "python", "matplotlib", "bins" ]
Python asyncio program won't exit
39,351,988
<p>I have an asyncio/Python program with two asyncio tasks: </p> <ul> <li>one that crashes</li> <li>one that goes on for ever. </li> </ul> <p>I want my entire program to exit after the first crash. I cannot get it to happen.</p> <pre><code>import asyncio import time def infinite_while(): while True: time.sleep(1) async def task_1(): await asyncio.sleep(1) assert False async def task_2(): loop = asyncio.get_event_loop() await loop.run_in_executor(None, lambda: infinite_while()) loop = asyncio.get_event_loop() asyncio.set_event_loop(loop) tasks = asyncio.gather(task_2(), task_1()) try: loop.run_until_complete(tasks) except (Exception, KeyboardInterrupt) as e: print('ERROR', str(e)) exit() </code></pre> <p>It prints ERROR but does not exit. When manually closed, the program prints the following stack trace:</p> <pre><code>Error in atexit._run_exitfuncs: Traceback (most recent call last): File "/usr/lib/python3.5/concurrent/futures/thread.py", line 39, in _python_exit t.join() File "/usr/lib/python3.5/threading.py", line 1054, in join self._wait_for_tstate_lock() File "/usr/lib/python3.5/threading.py", line 1070, in _wait_for_tstate_lock elif lock.acquire(block, timeout): KeyboardInterrupt </code></pre>
4
2016-09-06T14:50:28Z
39,474,956
<p>When an exception is risen in a task, it never propagates to the scope where the task was launched via eventloop, i.e. the <code>loop.run_until_complete(tasks)</code> call. Think of it, as if the exception is thrown only in the context of your task, and that is the top level scope where you have the chance to handle it, otherwise it will be risen in the <em>"background"</em>.</p> <p>This said, you will never catch an <code>Exception</code> from the task with this:</p> <pre><code>try: loop.run_until_complete(tasks) except (Exception, KeyboardInterrupt) as e: print('ERROR', str(e)) exit() </code></pre> <p>...and that is just how the event loop works. Imagine if you would have a service with several tasks, and one of them would fail, that would stop the whole service.</p> <p>What you could do is <a href="https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.stop" rel="nofollow">stop</a> the eventloop manually when you catch an exception in <code>task1</code>, e.g.</p> <pre><code>async def task_1(): await asyncio.sleep(1) try: assert False except Exception: # get the eventloop reference somehow eventloop.stop() </code></pre> <p>However, this is very dirty and kind of hacky, so I would rather suggest to go with the solution that <a href="http://stackoverflow.com/questions/39351988/python-asyncio-program-wont-exit#comment66038061_39351988">@D-Von suggested</a>, which is much cleaner and safer.</p>
1
2016-09-13T16:34:38Z
[ "python", "python-asyncio" ]
Uniquely identifying ManyToMany relationships in Django
39,352,019
<p>I'm trying to figure out how best to uniquely identify a ManyToMany relationship in my Django application. I have models similar to the following:</p> <pre><code>class City(models.Model): name = models.CharField(max_length=255) countries = models.ManyToManyField('Country', blank=True) class Country(models.Model): name = models.CharField(max_length=255) geo = models.ForeignKey('Geo', db_index=True) class Geo(models.Model): name = models.CharField(max_length=255) </code></pre> <p>I use the <code>ManyToManyField</code> type for the <code>countries</code> field because I want to avoid city name duplication (i.e. there may be a city name like "Springfield" that appears in multiple locations).</p> <p>In another place in my application, I want to be able to uniquely identify the city-country-geography relationship. That is, I need to know that a user whose city is "Springfield" resides in the United States, versus Canada, for example. As a result, I need to know which of the <code>ManyToManyField</code> relationships my city maps to. My user looks something like this:</p> <pre><code>class MyUser(models.Model): # ... other fields ... city = models.ForeignKey('City', db_index=True, blank=True, null=True) </code></pre> <p>This setup clearly does not capture the relationship between city and country properly. What's the best way to capture the unique relationship? Would I use a custom <a href="https://docs.djangoproject.com/en/1.10/ref/models/fields/#django.db.models.ManyToManyField.through" rel="nofollow">through-table</a> with an <code>AutoField</code> acting as a key, and change my user to point to that through-table?</p>
2
2016-09-06T14:51:39Z
39,352,156
<p>I think your idea of a <code>through</code> table is the right approach. Then, I would add a <code>unique_together('city', 'country')</code> into the <code>Meta</code>.</p> <p>I don't think there is a need for an <code>AutoField</code></p>
2
2016-09-06T14:58:48Z
[ "python", "django", "orm" ]
Unable to locate element because of a dynamic xpath
39,352,085
<p>So here is the current XPath i'm trying to use.</p> <pre><code>//*[@id="highcharts-33"]/svg/g[3]/g[1]/text </code></pre> <p>The problem is that this is a Dynamic Xpath, so it goes like "highcharts-33", "highcharts-34" etc... I'm making screenshots of theses graphs by clicking on a checkbox. Each time the checkbox is checked/unchecked the next graphs will have a different ID. </p> <p>Here is the error i'm getting in the cmd :</p> <blockquote> <p>NoSuchElementException: Message: Unable to locate element: {"method":"xpath","selector":"//*[contains(@id,'highcharts-')]/svg/g[3]/g[1]/text"}</p> </blockquote> <p>You can see here i'm trying to use "contains". I also tried to use "starts-with" but i'm still unable to locate the graph.</p> <p>Here are the things i've tried :</p> <pre><code>textvote = self.driver.find_element_by_xpath("//*[contains(@id,'highcharts-')]/svg/g[3]/g[1]/text").text textvote = self.driver.find_element_by_xpath("//*[starts-with(@id,'highcharts-')]/svg/g[3]/g[1]/text").text </code></pre> <p>I searched on stack overflow and saw some topics on it and it was always starts-with/contains or an unanswered topic. So i may be using starts-with/contains wrong. </p> <p>If you want me to share more code, don't hesitate. Thank you.</p> <p>Edit : Adding relevent HTML</p> <pre><code>&lt;div id="chartListContainer"&gt; &lt;div id="chart0" class="gauge-chart" data-highcharts-chart="16"&gt;&lt;div class="highcharts-container" id="highcharts-33" &lt;div class="highcharts-container" id="highcharts-33" &lt;svg version="1.1" &lt;g class="highcharts-data-labels highcharts-tracker" &lt;g zIndex="1" &lt;text x="0" zIndex="1" style="font-size:30px;font-family:Open Sans;color:#1abb1a;fill:#1abb1a;" y="32"&gt;&lt;tspan&gt;80.0% (4 votes)&lt;/tspan&gt;&lt;/text&gt; </code></pre> <p>I'm trying to extract the text from that last line.</p>
0
2016-09-06T14:55:00Z
39,353,886
<p>I'm assuming that there's only one <code>&lt;text&gt;</code> element inside your <code>&lt;div id="highcharts-*&gt;</code> element so you could try CSS selector <code>div[id^="highcharts"] text</code></p> <pre><code>textvote = self.driver.find_element_by_css("div[id^='highcharts-'] text").text </code></pre> <p>This CSS selects all <code>&lt;text&gt;</code> elements inside a <code>&lt;div&gt;</code> element with id starting with "highcharts-", but if you have more than one <code>&lt;text&gt;</code> elements you might run into troubles.</p> <p>EDIT:</p> <p>After another look seems that I was wrong to assume that there was only one <code>&lt;text&gt;</code> element there, a fixed CSS selector to mimic your xpath one is:</p> <pre><code>textvote = self.driver.find_element_by_css("div[id^='highcharts-']&gt;svg&gt;g:nth-of-type(3)&gt;g:nth-of-type(1)&gt;text").text </code></pre>
0
2016-09-06T16:35:41Z
[ "python", "xpath", "selenium-webdriver" ]
SQLALCHEMY or_ list comprehension
39,352,202
<p>I'm trying to use list comprehension with or_. I already found a post that showed how to do it with only checking one column, but I'm unsure how to check two columns simultaneously with a list. I tried something like this:</p> <p><code>q = q.filter(or_((model.column.contains(word), model.column2.contains(word))for word in search))</code></p> <p>This gives me a bad request though. Any advice on how to search simultaneously using a list would be appreciated!</p>
0
2016-09-06T15:01:26Z
39,352,294
<p>From what I understand you need to <em>unpack</em> the conditions into positional arguments of <a href="http://docs.sqlalchemy.org/en/latest/core/sqlelement.html#sqlalchemy.sql.expression.or_" rel="nofollow"><code>or_()</code></a>:</p> <pre><code>columns = [model.column, model.column2] conditions = [column.contains(word) for word in search for column in columns] q = q.filter(or_(*conditions)) </code></pre> <p>Assuming you want to "or" every contains for every word and for all given columns.</p>
1
2016-09-06T15:04:47Z
[ "python", "sqlalchemy", "flask-sqlalchemy" ]
Encoding/Encrypting from stdin in Python
39,352,278
<p>I'm trying to encrypt data from stdin to send across a socket, so for testing I'm trying to decrypt what I just encrypted and it's not producing the original message as is.</p> <pre><code>BS = 16 client_cipher = AES.new(client_conf_key, AES.MODE_CBC, randIV) message = sys.stdin.readline() padded_message = message + '$' + (BS - ((len(message)+1)%16))*'#' client_message = base64.b64encode(client_cipher.encrypt(padded_message)) print "Encrypted: " + client_message enc_str = base64.b64decode(client_message) dec_str = client_cipher.decrypt(enc_str) print "Decrypted: " + dec_str </code></pre> <p>Here's what my output looks like now <a href="http://i.stack.imgur.com/XBHHu.png" rel="nofollow"><img src="http://i.stack.imgur.com/XBHHu.png" alt="enter image description here"></a></p> <p>I feel like I'm messing up the encoding somehow, any help would be appreciated</p> <p>Edit: client_cipher is an AES cipher, client_cipher = AES.new(client_conf_key, AES.MODE_CBC, randIV)</p>
0
2016-09-06T15:04:16Z
39,353,325
<p>Here is some code I once wrote to a similar effect;</p> <pre><code>BS = 16 pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS) unpad = lambda s : s[0:-ord(s[-1])] def encrypt(plaintext, key, iv): cipher = AES.new(key, AES.MODE_CBC,iv) plaintext = pad(plaintext) return cipher.encrypt(plaintext) def decrypt(ciphertext, key, iv): cipher = AES.new(key, AES.MODE_CBC, iv) decrypted = cipher.decrypt(ciphertext) return unpad(decrypted) </code></pre> <p>This got the job done for me, make sure you pass in appropriate params!</p> <p>HTH</p>
0
2016-09-06T16:02:51Z
[ "python", "encoding", "aes" ]
How to pull div attributes with BeautifulSoup in Python
39,352,371
<p>I'm trying to pull this data (lat and lng):</p> <pre><code>&lt;div class="location" lat="1234" lng="5678" &gt; </code></pre> <p>This is giving me nothing:</p> <pre><code>print (soup.find_all("div", { "class" : "location"})) </code></pre> <p>My eventual goal is to store these values in a dictionary. Thanks.</p>
0
2016-09-06T15:08:58Z
39,352,483
<p>You can use the <em>dictionary like-access to element attribute</em> in BeautifulSoup:</p> <pre><code>locations = [{'lat': location['lat'], 'lng': location['lng']} for location in soup.find_all("div", {"class": "location"})] </code></pre> <p>If there is a single location, use <code>find()</code> instead:</p> <pre><code>location = soup.find("div", {"class": "location"}) print({'lat': location['lat'], 'lng': location['lng']}) </code></pre> <blockquote> <p>This is giving me nothing</p> </blockquote> <p>This is though a separate problem. You might just not have this element in the parsed HTML.</p>
2
2016-09-06T15:14:28Z
[ "python", "beautifulsoup" ]
How to pull div attributes with BeautifulSoup in Python
39,352,371
<p>I'm trying to pull this data (lat and lng):</p> <pre><code>&lt;div class="location" lat="1234" lng="5678" &gt; </code></pre> <p>This is giving me nothing:</p> <pre><code>print (soup.find_all("div", { "class" : "location"})) </code></pre> <p>My eventual goal is to store these values in a dictionary. Thanks.</p>
0
2016-09-06T15:08:58Z
39,352,585
<p>From BeautifulSoup docs you might be using find_all() wrong. <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-keyword-arguments" rel="nofollow">https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-keyword-arguments</a></p> <p>Try:</p> <pre><code>print (soup.find_all("div",class_="location")) </code></pre> <p>or </p> <pre><code>print (soup.find_all("div",attrs={"class": "location"})) </code></pre>
0
2016-09-06T15:19:08Z
[ "python", "beautifulsoup" ]
How to pull div attributes with BeautifulSoup in Python
39,352,371
<p>I'm trying to pull this data (lat and lng):</p> <pre><code>&lt;div class="location" lat="1234" lng="5678" &gt; </code></pre> <p>This is giving me nothing:</p> <pre><code>print (soup.find_all("div", { "class" : "location"})) </code></pre> <p>My eventual goal is to store these values in a dictionary. Thanks.</p>
0
2016-09-06T15:08:58Z
39,352,602
<p>Your current <code>print</code> is returning a <em>list</em> of results:</p> <pre><code>[&lt;div class="location" lat="1234" lng="5678"&gt;&lt;/div&gt;] </code></pre> <p>You can access these by iterating through each result:</p> <pre><code>for r in results: print(r['lat'], r['lng']) </code></pre> <hr> <p>A full example, with two <code>div</code> elements, looks like this:</p> <pre><code>from bs4 import BeautifulSoup html = """&lt;div class="location" lat="1234" lng="5678" &gt; &lt;div class="location" lat="9101" lng="1213" &gt;""" soup = BeautifulSoup(html, 'html.parser') results = soup.find_all("div", { "class" : "location"}) for r in results: print(r['lat'], r['lng']) </code></pre> <p>This prints out two results:</p> <pre><code>('1234', '5678') ('9101', '1213') </code></pre>
1
2016-09-06T15:19:49Z
[ "python", "beautifulsoup" ]
Pandas Dataframe delete row with certain value until that value changes
39,352,554
<p>I have a dataframe with zeros at the top of the dataframe. These zeroes act as NAs. I would like to delete them until other values begin to appear. </p> <p>So, I would like this dataframe: </p> <pre><code> df_ Out[114]: A B C 2016-08-27 -0.263963 0.000000 0.693514 2016-08-28 -0.085663 0.000000 -0.715981 2016-08-29 1.408283 0.000000 2.513716 2016-08-30 -0.591532 0.000000 -1.468227 2016-08-31 -0.973261 0.000000 0.848670 2016-09-01 0.694384 -0.214615 0.561752 2016-09-02 -1.468527 0.259413 1.195574 2016-09-03 -1.471785 0.006788 0.688078 2016-09-04 -0.817770 0.453037 0.632851 2016-09-05 1.129863 0.000000 -0.296562 </code></pre> <p>to drop just the top 5 rows, but keep the rest (including the last ones) because column 'B' contains zeros in the first five rows.</p>
2
2016-09-06T15:17:24Z
39,352,707
<p>You can test if all rows are not equal to <code>0</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html" rel="nofollow"><code>all</code></a> and <code>axis=1</code>, we use this to mask the df and call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.first_valid_index.html#pandas.DataFrame.first_valid_index" rel="nofollow"><code>first_valid_index</code></a> and use this to slice the df:</p> <pre><code>In [40]: df.loc[df[(df != 0).all(axis=1)].first_valid_index():] Out[40]: A B C 2016-09-01 0.694384 -0.214615 0.561752 2016-09-02 -1.468527 0.259413 1.195574 2016-09-03 -1.471785 0.006788 0.688078 2016-09-04 -0.817770 0.453037 0.632851 2016-09-05 1.129863 0.000000 -0.296562 </code></pre> <p>here is the output from the inner test:</p> <pre><code>In [37]: (df != 0).all(axis=1) Out[37]: 2016-08-27 False 2016-08-28 False 2016-08-29 False 2016-08-30 False 2016-08-31 False 2016-09-01 True 2016-09-02 True 2016-09-03 True 2016-09-04 True 2016-09-05 False dtype: bool </code></pre>
3
2016-09-06T15:26:00Z
[ "python", "pandas", "dataframe" ]
Is it possible to add x-axis labels to *every* plot in the Seaborn Factor Plot (Python)?
39,352,563
<p>I'm using Seaborn to make a Factor Plot. </p> <p>In total, I have 4 'sub plots' (and use <code>col_wrap =2</code>, so I have 2 rows, each containing 2 sub plots). Only the 2 sub plots at the very bottom of the grid have x-axis labels (which I believe is the default). </p> <p>Is it possible to configure the Factor Plot such that each of the 4 plots has x-axis labels? (I couldn't find this option in the Documentation or on StackOverflow)</p> <p><strong>UPDATE</strong>:</p> <p>Here is the code (which generates 4 time series plots on a Factor Grid):</p> <p>The dataframe (df) looks as follows: </p> <pre><code>Company Date Value ABC 08/21/16 500 ABC 08/22/16 600 ABC 08/23/16 650 DEF 08/21/16 625 DEF 08/22/16 675 DEF 08/23/16 680 GHI 08/21/16 500 GHI 08/22/16 600 GHI 08/23/16 650 JKL 08/21/16 625 JKL 08/22/16 675 JKL 08/23/16 680 import matplotlib.pyplot as plt import pandas as pd import seaborn as sns df = pd.read_csv(the_file_name.csv) g = sns.factorplot(data=df, x='Date', y='Value', col='Company', col_wrap=2, sharey=False) g.set_xlabels('') g.set_ylabels('product count') g.set_xticklabels(rotation=45) plt.show() </code></pre> <p>You'll notice that the x-axis dates are shown on the bottom 2 plots. I'd like for the x-axis dates to be shown on the top 2 plots as well.</p> <p>Thanks!</p>
0
2016-09-06T15:17:55Z
39,366,416
<p>I'm not sure of a way to do this in <code>seaborn</code>, but you can play with the matplotlib <code>Axes</code> instances to do this. </p> <p>For example, here we'll use <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.setp" rel="nofollow"><code>setp</code></a> to set the <code>xticklabels</code> to visible for all axes in the <code>FacetGrid</code> (<code>g</code>). Note that I also set the rotation here too, since seaborn would not rotate the <code>ticklabels</code> on the upper row. </p> <p>Finally, I have increased the space between subplots to allow room for the tick labels using <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots_adjust" rel="nofollow"><code>subplots_adjust</code></a>.</p> <pre><code>import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from io import StringIO the_file_name = StringIO(u""" Company,Date,Value ABC,08/21/16,500 ABC,08/22/16,600 ABC,08/23/16,650 DEF,08/21/16,625 DEF,08/22/16,675 DEF,08/23/16,680 GHI,08/21/16,500 GHI,08/22/16,600 GHI,08/23/16,650 JKL,08/21/16,625 JKL,08/22/16,675 JKL,08/23/16,680 """) df = pd.read_csv(the_file_name) g = sns.factorplot(data=df, x='Date', y='Value', col='Company', col_wrap=2, sharey=False) g.set_xlabels('') g.set_ylabels('product count') for ax in g.axes: plt.setp(ax.get_xticklabels(), visible=True, rotation=45) plt.subplots_adjust(hspace=0.3) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/2w69T.png" rel="nofollow"><img src="http://i.stack.imgur.com/2w69T.png" alt="enter image description here"></a></p>
1
2016-09-07T09:40:49Z
[ "python", "matplotlib", "seaborn" ]
NumPy matrix not indexing range correctly [0,0,0,5:53].shape = 43
39,352,634
<p>I have a rather large numpy matrix, and I'm thinking since it is so large this is happening. It has to be some sort of pointer issue.</p> <p>Anyways, I have the following matrix </p> <pre><code>(Pdb) input_4d_volume.shape (26010, 48, 48, 48) </code></pre> <p>When I index like the following, no problem: </p> <pre><code>(Pdb) input_4d_volume[0,0,0,0:48].shape[0] 48 </code></pre> <p>But when I try to do a range, the max always max's out at <code>48</code></p> <p>For example, take these two cases:</p> <pre><code>(Pdb) input_4d_volume[0,0,0,1:1+48].shape[0] 47 (Pdb) input_4d_volume[0,0,0,10:10+48].shape[0] 38 </code></pre> <p>The expected outputs should be:</p> <pre><code>(Pdb) input_4d_volume[0,0,0,1:1+48].shape[0] 48 (Pdb) input_4d_volume[0,0,0,10:10+48].shape[0] 38 </code></pre> <p>Since, <code>(1+48)-1 = 48</code> and <code>(10+48)-10 = 48</code> (see below examples as proof)</p> <p>As proof this works, I have another matrix that works perfectly fine</p> <pre><code>(Pdb) entire_volume.shape (99, 396, 396) (Pdb) entire_volume[0,0,0:100].shape[0] 100 (Pdb) entire_volume[0,0,10:10+100].shape[0] 100 </code></pre> <p>Is this because <code>input_4d_volume</code> is too large?</p>
0
2016-09-06T15:21:42Z
39,352,874
<p>Python will let you index up to a number larger than the length of the object. For example,</p> <pre><code>import numpy as np a = np.arange(0, 10) a[5:100] # array([5, 6, 7, 8, 9]) </code></pre> <p>If your 4-D input array is of shape (26010, 48, 48, 48), and you are slicing on the 4th dimension, you cannot end up with an 1D array large than that dimension's size. For example,</p> <pre><code>a = np.zeros((100,30,30,30)) a[0, 0, 0, 0:5].shape # (5L,) a[0, 0, 0, 0:32].shape # (30L,) </code></pre> <p>In your proof that it works example, you are taking a slice on dimension three of indices 10 to 109 with <code>entire_volume[0,0,10:10+100].shape[0]</code>. These are within the dimension's size of 396, so you get what you expect.</p> <p>If you instead did <code>entire_volume[0,0,390:390+100].shape[0]</code>, the shape of the array returned is the same as if you sliced with <code>entire_volume[0,0,390:396].shape[0]</code>. Python lets you go above the max, but it can't return data that doesn't exist.</p>
3
2016-09-06T15:36:57Z
[ "python", "numpy" ]
NumPy matrix not indexing range correctly [0,0,0,5:53].shape = 43
39,352,634
<p>I have a rather large numpy matrix, and I'm thinking since it is so large this is happening. It has to be some sort of pointer issue.</p> <p>Anyways, I have the following matrix </p> <pre><code>(Pdb) input_4d_volume.shape (26010, 48, 48, 48) </code></pre> <p>When I index like the following, no problem: </p> <pre><code>(Pdb) input_4d_volume[0,0,0,0:48].shape[0] 48 </code></pre> <p>But when I try to do a range, the max always max's out at <code>48</code></p> <p>For example, take these two cases:</p> <pre><code>(Pdb) input_4d_volume[0,0,0,1:1+48].shape[0] 47 (Pdb) input_4d_volume[0,0,0,10:10+48].shape[0] 38 </code></pre> <p>The expected outputs should be:</p> <pre><code>(Pdb) input_4d_volume[0,0,0,1:1+48].shape[0] 48 (Pdb) input_4d_volume[0,0,0,10:10+48].shape[0] 38 </code></pre> <p>Since, <code>(1+48)-1 = 48</code> and <code>(10+48)-10 = 48</code> (see below examples as proof)</p> <p>As proof this works, I have another matrix that works perfectly fine</p> <pre><code>(Pdb) entire_volume.shape (99, 396, 396) (Pdb) entire_volume[0,0,0:100].shape[0] 100 (Pdb) entire_volume[0,0,10:10+100].shape[0] 100 </code></pre> <p>Is this because <code>input_4d_volume</code> is too large?</p>
0
2016-09-06T15:21:42Z
39,352,981
<p>The shape of your numpy array is <code>(26010, 48, 48, 48)</code>, so when you ask for <code>input_4d_volume[0,0,0,n:n+48].shape[0]</code> where <code>n</code> is some positive integer, the answer will be <code>max(48-n,0)</code>. The behaviour you are seeing is correct, because python indexing starts at 0, and accepts indices beyond the end of an array. The numpy docs explain how slicing works: <a href="http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html" rel="nofollow">http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html</a>.</p>
0
2016-09-06T15:42:16Z
[ "python", "numpy" ]
Access AWS API Gateway with IAM roles from Python
39,352,648
<p>I have an AWS API Gateway that I would like to secure using <a href="http://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html" rel="nofollow" title="IAM Roles">IAM Roles</a> .</p> <p>I am looking for a package to help me accessing it using Python. I am trying to avoid implementing the entire <a href="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html" rel="nofollow" title="Version 4 Signing Process">Version 4 Signing Process</a>. I am sure there must be some library I can use.</p> <p>I looked into <a href="https://github.com/DavidMuller/aws-requests-auth" rel="nofollow" title="aws-requests-auth">aws-requests-auth</a> but it requires a "aws_service" to generate the signature. I looked also to boto3 but I am not able to find any way to just add authentication headers to a general request.</p>
0
2016-09-06T15:22:26Z
39,357,370
<p>You can use <a href="https://github.com/DavidMuller/aws-requests-auth" rel="nofollow" title="aws-requests-auth">aws-requests-auth</a> to generate the signature for your request to API Gateway with <strong>execute-api</strong> as the service name. </p> <pre><code>import requests from aws_requests_auth.aws_auth import AWSRequestsAuth auth = AWSRequestsAuth(aws_access_key='YOURKEY', aws_secret_access_key='YOURSECRET', aws_host='restapiid.execute-api.us-east-1.amazonaws.com', aws_region='us-east-1', aws_service='execute-api') headers = {'params': 'ABC'} response = requests.get('https://restapiid.execute-api.us-east-1.amazonaws.com/stage/resource_path', auth=auth, headers=headers) </code></pre>
2
2016-09-06T20:31:01Z
[ "python", "amazon-iam", "aws-api-gateway" ]