Unnamed: 0
int64
0
1.91M
id
int64
337
73.8M
title
stringlengths
10
150
question
stringlengths
21
64.2k
answer
stringlengths
19
59.4k
tags
stringlengths
5
112
score
int64
-10
17.3k
1,906,100
54,145,419
Does string's find() in Python not work when length of the string and substring are equal?
<p>The find() is not recognising 'Bl' at index 0 as a substring. Neither when the string is 'Bl' nor when it is 'BlUeBe1Bl*fjal9jkl'. What could be the possible error in my code?</p> <pre><code>string = 'Bl' #string = 'BlUeBe1Bl*fjal9jkl' sub_string='Bl' length=len(sub_string) count=0 for i in range(0,len(string)-length+1): if string.find(sub_string,i,i+length)&gt;0: count+=1 print(f'Count of {sub_string} in {string} is {count}') </code></pre> <p>When string = 'Bl' , the output should be 1 and when string = 'BlUeBe1Bl*fjal9jkl' , the output should be 2 but I am getting 0 and 1 respectively.</p>
<p>find() returns the index of the found occurance. If the start of the string matches the sub_string that you search for the result will be 0. You must check for >= 0 the fix the problem. find returns -1 when the sub_string is not found.</p> <pre><code>for i in range(0,len(string)-length+1): if string.find(sub_string,i,i+length)&gt;=0: count+=1 </code></pre>
python|string
1
1,906,101
45,698,403
Calculation with a lot of columns from a lot of dataframe
<p>I need to do some operations between some columns of different data frames, i had tried that with the follow code:</p> <pre><code>df_swap['Apropriacao'] = df_sw[(df_sw.loc[:, 'Ativo'] == df_mov.loc[:, 'Ativo']).all() and (df_sw.loc[:, 'Data posicao'] == df_mov.loc[:, 'Data posicao']).all()].sum(axis=1) </code></pre> <p>But I believe that is not the right way to do it (and show a exception).</p> <p>The sample of dataframe are:</p> <p><strong>df_mov</strong></p> <pre><code>idx Data posicao Ativo Valor 0 2017-07-03 RXU7 0.0 1 2017-07-04 RXU7 0.0 2 2017-07-05 RXU7 0.0 3 2017-07-06 RXU7 0.0 4 2017-07-07 RXU7 0.0 5 2017-07-10 RXU7 0.0 ... 21 2017-07-03 GCQ7 0.0 22 2017-07-04 GCQ7 0.0 23 2017-07-05 GCQ7 0.0 24 2017-07-06 GCQ7 0.0 25 2017-07-07 GCQ7 1341.0 26 2017-07-10 GCQ7 0.0 ... 42 2017-07-03 CNHBRL 0.0 43 2017-07-04 CNHBRL 0.0 44 2017-07-05 CNHBRL 0.0 45 2017-07-06 CNHBRL 0.0 46 2017-07-07 CNHBRL 0.0 47 2017-07-10 CNHBRL 0.0 ... </code></pre> <p><strong>df_sw</strong></p> <pre><code> Data posicao Ativo Data vencimento Apropriacao 0 2017-07-03 RXU7 2017-09-07 -1431.17 1 2017-07-04 RXU7 2017-09-07 -788258.59 2 2017-07-05 RXU7 2017-09-07 -4206.24 3 2017-07-06 RXU7 2017-09-07 50062.78 4 2017-07-07 RXU7 2017-09-07 499642.57 5 2017-07-10 RXU7 2017-09-07 49191.00 ... 21 2017-07-03 GCQ7 None 0.00 22 2017-07-04 GCQ7 2017-07-31 1820.06 23 2017-07-05 GCQ7 2017-07-31 -2767.20 24 2017-07-06 GCQ7 2017-07-31 -1648.37 25 2017-07-07 GCQ7 2017-07-31 0.00 26 2017-07-10 GCQ7 None 0.00 ... 42 2017-07-03 CNHBRL None 0.00 43 2017-07-04 CNHBRL None 0.00 44 2017-07-05 CNHBRL None 0.00 45 2017-07-06 CNHBRL None 0.00 46 2017-07-07 CNHBRL None 0.00 47 2017-07-10 CNHBRL None 0.00 </code></pre> <p>How can i sum <code>df_mov['Valor']</code> with <code>df_sw['Apropriacao']</code> where <code>df_mov['Data posicao']</code> is equal to <code>df_sw['Data posicao']</code> and <code>df_mov['Ativo']</code> is equal to <code>df_sw['Ativo']</code>?</p>
<p>I'd suggest merging the dataframes and then performing the summation on the columns (this assumes you're trying to sum the values for each row, rather than sum the columns as a whole):</p> <pre><code>df_mov.merge(df_sw, left_on=['Data posicao', 'Ativo'], right_on=['Data posicao', 'Ativo'], )[['Valor', 'Apropricao']].sum(axis=1) </code></pre>
python|python-3.x|pandas
0
1,906,102
14,696,133
self.redirect causes TypeError when calling grok.View with Plone
<p>I've been using a simple grok and Plone 4.1.4. So far I tried known good configuration for version 1.2.0 and 1.1.1 taken from here <a href="http://good-py.appspot.com/release/five.grok/" rel="nofollow">five.grok</a></p> <p>I attempt to use grok.View with redirects, and whenever redirect code (self.redirect('url')) is run, the following TypeError is raised:</p> <pre><code>TypeError: redirect() got an unexpected keyword argument 'trusted' &gt; /home/alex/projects/eggs/grokcore.view-1.13.5-py2.6.egg/grokcore/view/components.py(50)redirect() -&gt; url, status=status, trusted=trusted) </code></pre> <p>I found this discussion that deals with similar problem but no real solution. <a href="http://comments.gmane.org/gmane.comp.web.zope.grok.devel/10695" rel="nofollow">gmane</a></p> <p>It's really easy to reproduce the error, just have an update method in grok.View-derived class.</p> <pre><code>from five import grok from Products.CMFCore.interfaces import ISiteRoot class RedirectTest(grok.View): grok.context(ISiteRoot) grok.require('zope2.View') grok.name('testredirect') def update(self): self.redirect(self.url('')) def render(self): self.redirect(self.url('')) </code></pre>
<p>To use Grok on the Zope2 platform (used by Plone), you need to install the correct version of the <a href="http://pypi.python.org/pypi/five.grok" rel="noreferrer"><code>five.grok</code> package</a>.</p> <p>Grok is developed against the Zope Toolkit, and the publisher package in the ZTK has a slightly different API than what the Zope2 publisher offers. <code>five.grok</code> bridges that difference. But you need to have the right version to make the correct match.</p> <p>For Plone 4.1 (Zope 2.13), make sure you use <code>five.grok</code> version 1.3.1 or newer:</p> <blockquote> <ul> <li>Fix the redirect method to properly work. Unlike in Zope 3, it doesn't support trusted.</li> </ul> </blockquote> <p>If you were to upgrade to Plone 4.2, the right version pin is included in the included versions.cfg file.</p>
python|plone|grok
5
1,906,103
14,623,762
Download first N bytes of a file in python
<p>I've got a large file somewhere (FTP/HTTP).</p> <p>I want to</p> <ol> <li>Download first <code>N</code> bytes, </li> <li>Check its header which is embedded into the file (whether the version differs) </li> <li>Then decide whether to proceed with <strong>or</strong> abort the download.</li> </ol> <p>It's definitely not such a straightforward task as I've imagined (to my surprise). Even calling <code>wget</code>/<code>curl</code> externally doesn't seem to be a good solution (Maybe I overlooked the right command line option).</p> <p>How could this be done as simple as possible in Python? </p> <p>I'm thinking about a custom handler for <code>ftp.retrbinary</code> which will raise an exception as soon as the sum of blocks will be above defined value, but it's overkill in my eyes. Python code is supposed to be elegant, right?</p>
<p>If you want to check just the headers, send an <strong><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="nofollow noreferrer">HTTP Head</a></strong>, rather than a GET. It will return the same headers as a GET, <em>with no message body.</em></p> <blockquote> <p>The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request.</p> </blockquote> <p>A HEAD can be sent as detailed <a href="https://stackoverflow.com/questions/107405/how-do-you-send-a-head-http-request-in-python">here</a>.</p> <hr> <p><strong>EDIT:</strong></p> <p>If you do need the first N bytes, you could use <a href="http://docs.python.org/2/library/urllib2.html" rel="nofollow noreferrer"><code>urllib2</code></a> in conjunction with the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35" rel="nofollow noreferrer">Range header.</a> <code>Range: bytes=0-N</code>.</p>
python|http|ftp|download
2
1,906,104
14,519,706
Sum elements of a list in Python
<p>I have a list like this:</p> <pre><code>a = [1, 2, 3] </code></pre> <p>I want to add all elements and form:</p> <pre><code>a = [6] Or a = 6 </code></pre>
<p>Use the built in <a href="http://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum</code></a> function:</p> <pre><code>print sum(a) # 6 </code></pre> <p>If you want to assign <code>a</code> to the result, just do <code>a = sum(a)</code></p>
python
4
1,906,105
68,713,844
AWS lambda (python): Dockerfile to install psycopg2?
<p>I'm trying to use <a href="https://docs.aws.amazon.com/lambda/latest/dg/python-image.html#python-image-base" rel="nofollow noreferrer">this tutorial</a> to upload a docker container to AWS ECR for Lambda. My problem is that my python script uses psycopg2, and I couldn't figure out how to install psycopg2 inside the Docker image. I know that I need <code>postgres-devel</code> for the <code>libq</code> library and gcc for compiling, but it still doesn't work.</p> <p>My requirements.txt:</p> <pre><code>pandas==1.3.0 requests==2.25.1 psycopg2==2.9.1 pgcopy==1.5.0 </code></pre> <p>Dockerfile:</p> <pre><code>FROM public.ecr.aws/lambda/python:3.8 WORKDIR /app COPY my_script.py . COPY some_file.csv . COPY requirements.txt . RUN yum install -y postgresql-devel gcc* RUN pip install -r requirements.txt CMD [&quot;/app/my_script.handler&quot;] </code></pre> <p>After building, running the image, and testing the lambda function locally, I get this error message:</p> <p><code>psycopg2.OperationalError: SCRAM authentication requires libpq version 10 or above</code></p> <p>So I think the container has the wrong version of postgres(-devel). But I'm not sure how to install the proper version? Any tips for deploying a psycopg2 script to docker for lambda usage?</p>
<p>This might be a little old and too late to answer but figure I post what worked for me.</p> <pre><code>FROM public.ecr.aws/lambda/python:3.8 COPY . ${LAMBDA_TASK_ROOT} RUN yum install -y gcc python27 python27-devel postgresql-devel RUN pip3 install -r requirements.txt --target &quot;${LAMBDA_TASK_ROOT}&quot; CMD [ &quot;app.handler&quot; ] </code></pre>
python|amazon-web-services|docker|aws-lambda|psycopg2
3
1,906,106
57,114,422
Edit rows of a dataframe given one column has a certain value
<p>I have a large dataframe <code>df_trial</code>, with a row nammed <code>reaction</code>. Within this there are five values which this may be: <code>152Gd-p</code>, <code>154Gd-p</code>, <code>155Gd-p</code>, <code>156Gd-p</code>, <code>15Gd-p</code>, <code>158Gd-p</code>, <code>160Gd-p</code>. The following column contains some irrelevant information for this step, however the following columns I wish to be multiplied by a constant depending on the string present in 'reaction'. I have tried to apply this as: </p> <pre><code>for index, row in df_trial.iterrows(): if row['reaction'] == '152Gd-p': row[2:]*=0.002 if row['reaction'] == '154Gd-p': row[2:]*=0.0218 if row['reaction'] == '155Gd-p': row[2:]*=0.148 if row['reaction'] == '156Gd-p': row[2:]*=0.2047 if row['reaction'] == '157Gd-p': row[2:]*=0.1565 if row['reaction'] == '158Gd-p': row[2:]*=0.2484 if row['reaction'] == '160Gd-p': row[2:]*=0.2186 </code></pre> <p>This is however not multiplying the values in the rows. </p> <p>Here is a sample of how my dataframe looks: </p> <pre><code> reaction product 0.5 1.0 1.5 2.0 2.5 3.0 3.5 4.0 ... 35.5 36.0 36.5 37.0 37.5 38.0 38.5 39.0 39.5 40.0 81 155Gd-p 062150.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 1.101530e-02 1.253720e-02 1.404620e-02 1.562480e-02 1.713510e-02 1.855860e-02 1.989160e-02 2.113160e-02 2.228710e-02 2.333700e-02 82 155Gd-p 065156.L00 0.0 0.0 0.0 0.0 2.842720e-10 4.331690e-09 3.176340e-08 1.873100e-03 ... 1.836500e-01 1.803630e-01 1.728360e-01 1.606180e-01 1.685970e-01 1.679980e-01 1.639340e-01 1.538330e-01 1.639280e-01 1.656980e-01 83 155Gd-p 063149.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 6.990920e+00 7.877440e+00 8.781220e+00 9.594980e+00 1.034780e+01 1.097080e+01 1.156940e+01 1.196730e+01 1.230900e+01 1.241800e+01 84 155Gd-p 061146.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 9.529110e-04 85 155Gd-p 061147.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 1.000000e-07 1.000000e-07 1.000000e-07 1.000000e-07 1.000000e-07 1.063060e-03 1.130870e-03 1.172590e-03 1.180610e-03 1.165960e-03 86 155Gd-p 062151.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 1.000000e-07 1.000000e-07 ... 1.041300e-03 1.076720e-03 1.090690e-03 1.109420e-03 1.137780e-03 1.135450e-03 1.128680e-03 1.149190e-03 1.143860e-03 1.150390e-03 87 155Gd-p 063154.L00 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 3.173660e+00 3.444480e+00 3.724070e+00 4.007600e+00 4.323930e+00 4.673050e+00 4.971810e+00 5.346970e+00 5.661720e+00 6.060110e+00 88 155Gd-p 064150.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 2.579220e-03 4.992070e-03 9.679620e-03 2.035170e-02 3.447910e-02 5.437450e-02 9.089650e-02 1.471190e-01 2.126190e-01 2.896810e-01 89 155Gd-p 064154.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 2.337670e+02 2.386140e+02 2.390300e+02 2.431350e+02 2.413420e+02 2.446070e+02 2.421500e+02 2.447660e+02 2.425080e+02 2.446910e+02 90 155Gd-p 062148.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 1.172560e-03 1.722920e-03 91 155Gd-p 061148.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 1.000000e-07 1.000000e-07 1.000000e-07 1.000000e-07 1.000000e-07 6.300980e-05 6.278910e-05 6.094680e-05 5.998620e-05 5.900480e-05 92 155Gd-p 063153.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 3.136120e+00 3.390600e+00 3.631630e+00 3.958020e+00 4.197170e+00 4.564750e+00 4.762130e+00 4.948580e+00 5.314960e+00 5.549590e+00 93 155Gd-p 063152.tot 0.0 0.0 0.0 0.0 1.000000e-07 1.000000e-07 1.000000e-07 1.000000e-07 ... 2.371420e+00 2.502180e+00 2.629100e+00 2.699470e+00 2.818750e+00 2.972010e+00 3.188610e+00 3.416830e+00 3.648320e+00 3.884690e+00 94 155Gd-p 065151.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 6.969380e+01 1.072870e+02 1.483310e+02 1.996210e+02 2.548350e+02 3.046590e+02 3.501350e+02 3.969820e+02 4.371780e+02 4.748900e+02 95 155Gd-p 063150.L01 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 2.297790e+00 2.303140e+00 2.279280e+00 2.212180e+00 2.171240e+00 2.134990e+00 2.086730e+00 2.017590e+00 1.979700e+00 1.957500e+00 96 155Gd-p 065152.tot 0.0 0.0 0.0 0.0 0.000000e+00 0.000000e+00 0.000000e+00 0.000000e+00 ... 7.834620e+02 7.493000e+02 7.095910e+02 6.583400e+02 6.050390e+02 5.525560e+02 5.055030e+02 4.521510e+02 4.095180e+02 3.664050e+02 </code></pre> <p>Obviously in the full dataframe it includes rows with all of the reactions in. </p>
<p>You can define a function to multiply each row and then apply it to each row with <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.apply.html" rel="nofollow noreferrer"><code>apply</code></a>.</p> <p>Also, to improve the conditions, you can set <code>elif</code> instead of <code>if</code>. That prevents testing all the conditions each time.</p> <p>In the answer, I use a dictionary to save the coefficient. Then, I call it from the <code>reaction</code> key.</p> <p>Here the code:</p> <pre><code># Coefficients multi_coef = { '152Gd-p': 0.002, '154Gd-p': 0.0218, '155Gd-p': 0.148, '156Gd-p': 0.2047, '157Gd-p': 0.1565, '158Gd-p': 0.2484, '160Gd-p': 0.2186, } # Get columns name columns = df.columns # Function to apply to each row def multiply_coef(row): # If the reaction name is in the dictionary if row.reaction in multi_coef.keys(): # Multiply by the reaction coefficient row[columns[2:]] = row[columns[2:]] * multi_coef[row.reaction] return row # Apply the function (axis = 1 means over rows) new_df = df.apply(multiply_coef, axis=1) print(new_df) # reaction product 0.5 1.0 1.5 2.0 ... 37.5 38.0 38.5 39.0 39.5 40.0 # 0 155Gd-p 062150.tot 0.0 0.0 0.0 0.0 ... 2.535995e-03 0.002747 0.002944 0.003127 0.003298 0.003454 # 1 155Gd-p 065156.L00 0.0 0.0 0.0 0.0 ... 2.495236e-02 0.024864 0.024262 0.022767 0.024261 0.024523 # 2 155Gd-p 063149.tot 0.0 0.0 0.0 0.0 ... 1.531474e+00 1.623678 1.712271 1.771160 1.821732 1.837864 # 3 155Gd-p 061146.tot 0.0 0.0 0.0 0.0 ... 0.000000e+00 0.000000 0.000000 0.000000 0.000000 0.000141 # 4 155Gd-p 061147.tot 0.0 0.0 0.0 0.0 ... 1.480000e-08 0.000157 0.000167 0.000174 0.000175 0.000173 # 5 155Gd-p 062151.tot 0.0 0.0 0.0 0.0 ... 1.683914e-04 0.000168 0.000167 0.000170 0.000169 0.000170 # 6 155Gd-p 063154.L00 0.0 0.0 0.0 0.0 ... 6.399416e-01 0.691611 0.735828 0.791352 0.837935 0.896896 # 7 155Gd-p 064150.tot 0.0 0.0 0.0 0.0 ... 5.102907e-03 0.008047 0.013453 0.021774 0.031468 0.042873 # 8 155Gd-p 064154.tot 0.0 0.0 0.0 0.0 ... 3.571862e+01 36.201836 35.838200 36.225368 35.891184 36.214268 # 9 155Gd-p 062148.tot 0.0 0.0 0.0 0.0 ... 0.000000e+00 0.000000 0.000000 0.000000 0.000174 0.000255 # 10 155Gd-p 061148.tot 0.0 0.0 0.0 0.0 ... 1.480000e-08 0.000009 0.000009 0.000009 0.000009 0.000009 # 11 155Gd-p 063153.tot 0.0 0.0 0.0 0.0 ... 6.211812e-01 0.675583 0.704795 0.732390 0.786614 0.821339 # 12 155Gd-p 063152.tot 0.0 0.0 0.0 0.0 ... 4.171750e-01 0.439857 0.471914 0.505691 0.539951 0.574934 # 13 155Gd-p 065151.tot 0.0 0.0 0.0 0.0 ... 3.771558e+01 45.089532 51.819980 58.753336 64.702344 70.283720 # 14 155Gd-p 063150.L01 0.0 0.0 0.0 0.0 ... 3.213435e-01 0.315979 0.308836 0.298603 0.292996 0.289710 # 15 155Gd-p 065152.tot 0.0 0.0 0.0 0.0 ... 8.954577e+01 81.778288 74.814444 66.918348 60.608664 54.227940 </code></pre>
python|pandas|dataframe
1
1,906,107
57,028,901
How to pass contenteditable text to value attribute in django html file
<p>I have tried finding resource but couldn't get any.</p> <p>I have a html file in templates folder in my django app as</p> <pre><code>{% for comment in comments %} &lt;li contenteditable = "TRUE" &gt;{{comment.text}} &lt;form contenteditable = "FALSE" action = "{% url 'clickedaccept' %}" method = "POST"&gt; {% csrf_token %} &lt;input type = "hidden" name = "acceptedvalue" value = "{{comment.id}}"&gt; &lt;input type = "hidden" name = "selected_option" value = "{{selected_option}}"&gt; &lt;input type = "hidden" name = "selected_autocomplete" value = "{{selected_autocomplete}}"&gt; &lt;input type = "submit" value = "Accept" id = "{{comment.id}}" &gt; &lt;/form&gt; {% endfor %} &lt;/li&gt; </code></pre> <p>Here the comment.text is extracted from model and is editable. User can edit the text value. There is a form with post method. I want to send the value of content editable text in value attribute of hidden input. How can I achieve it?</p>
<p>Something along these lines, assuming your model has a Charfield called 'selected_option'. </p> <p>forms.py</p> <pre><code>class PracticeForm(forms.Form): selected_value = forms.CharField(max_length=202, required=True) selected_option = forms.CharField(max_length=202, required=True) </code></pre> <p>views.py</p> <pre><code>if request.method == 'POST': form = PracticeForm(request.POST, request.FILES) if form.is_valid(): foo1 = form.cleaned_data.get("selected_value") foo2 = form.cleaned_data.get("selected_option") </code></pre> <p>html</p> <pre><code>&lt;form contenteditable = "FALSE" action = "{% url 'clickedaccept' %}" enctype="multipart/form-data" method = "POST"&gt; {% csrf_token %} &lt;input type = "hidden" name = "selected_value" value = "{{comment.id}}"&gt; &lt;input type = "hidden" name = "selected_option" value = "{{selected_option}}"&gt; &lt;button type = "submit"&gt;Click this to submit&lt;/button&gt; &lt;/form&gt; </code></pre>
javascript|python|django
1
1,906,108
56,903,139
converting series to array
<p>I was just playing with a data-set of restaurants and I counted the values of locations of different restaurants using <code>count_values()</code>, now I need to extract it into array form my code:</p> <pre><code>location_to_keep = dataset['location'].value_counts() print(location_to_keep) output: BTM 2181 Koramangala 5th Block 1987 Indiranagar 1394 HSR 1329 Jayanagar 1281 JP Nagar 1163 Whitefield 916 Koramangala 7th Block 838 Koramangala 6th Block 813 Marathahalli 762 Koramangala 4th Block 706 Brigade Road 699 MG Road 641 Bannerghatta Road 609 Ulsoor 597 Koramangala 1st Block 568 Bellandur 542 Sarjapur Road 534 Kalyan Nagar 532 Banashankari 480 Residency Road 465 Church Street 464 Richmond Road 457 Malleshwaram 454 Lavelle Road 437 Basavanagudi 416 Electronic City 386 Cunningham Road 383 New BEL Road 338 Frazer Town 33 </code></pre> <p>Need to extract this in array form with the name of the restaurants? Some reply fast....</p>
<p>I think @Quang Hoang got it right and <code>list(location_to_keep.index)</code> should solve your problem. For the sake of completeness, here is a minimal reproducible example.</p> <pre><code>import pandas as pd import numpy as np dataset = pd.DataFrame() locations = ['A', 'B', 'C', 'D'] dataset['location'] = np.random.choice(locations, 1000) </code></pre> <p>By using <code>value_counts</code> we should get something like below.</p> <pre><code>In [1]: location_to_keep = dataset['location'].value_counts() print(location_to_keep) Out[1]: B 272 C 259 D 247 A 222 Name: location, dtype: int64 </code></pre> <p>Then you can get the names with <code>index</code> and the counts with <code>values</code>.</p> <pre><code>In [2]: list(location_to_keep.values) Out[2]: [272, 259, 247, 222] In [3]: list(location_to_keep.index) Out[3]: ['B', 'C', 'D', 'A'] </code></pre>
python|pandas
0
1,906,109
54,055,422
How to run unit tests with "pip install"?
<p>At work, we are considering configuring a local pypi repository for internal software deployment. Deploying with "pip install" would be convenient, but I am concerned that unit tests should be executed after adding a new package to ensure proper installation. I had always assumed pip was doing this, but I see nothing related to testing in the pip documentation.</p>
<p>You can pass a parameter to setup.py via pip: </p> <p>--install-option Extra arguments to be supplied to the setup.py install command (use like –install-option=”–install-scripts=/usr/local/bin”). Use multiple –install-option options to pass multiple options to setup.py install. If you are using an option with a directory path, be sure to use absolute path.</p> <pre><code>pip install --install-option test </code></pre> <p>will issue </p> <pre><code>setup.py test </code></pre> <p>then You need setup.cfg in the same directory as setup.py:</p> <pre><code># setup.cfg [aliases] test=pytest </code></pre> <p>sample setup.py:</p> <pre><code># setup.py """Setuptools entry point.""" import codecs import os try: from setuptools import setup except ImportError: from distutils.core import setup CLASSIFIERS = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Software Development :: Libraries :: Python Modules' ] dirname = os.path.dirname(__file__) long_description = ( codecs.open(os.path.join(dirname, 'README.rst'), encoding='utf-8').read() + '\n' + codecs.open(os.path.join(dirname, 'CHANGES.rst'), encoding='utf-8').read() ) setup( name='your_package', version='0.0.1', description='some short description', long_description=long_description, long_description_content_type='text/x-rst', author='Your Name', author_email='your@email.com', url='https://github.com/your_account/your_package', packages=['your_package'], install_requires=['pytest', 'typing', 'your_package'], classifiers=CLASSIFIERS, setup_requires=['pytest-runner'], tests_require=['pytest']) </code></pre>
python|pip
2
1,906,110
25,887,587
Size of the file via ftp url using python
<p>I've got a ftp url like <code>ftp://xyz/file.csv</code> and I need to get the size of the file before downloading it.</p> <p>I tried using the urllib2,</p> <pre><code>&gt;&gt;&gt; f = urllib2.urlopen("ftp://xyz/file.csv") &gt;&gt;&gt; f.info().getheader('Content-Length') &gt;&gt;&gt; </code></pre> <p>But it returns nothing, maybe because not all url(s) have a content-length header. Hence, this technique fails. Is there any other way to fetch the size information of the file without actually reading it in Python?</p> <p>Python version is - <strong>2.6.6</strong></p>
<p>use <a href="https://docs.python.org/2/library/ftplib.html" rel="nofollow">ftplib</a> by python for retrieving files over FTP protocol.</p> <pre><code>from ftplib import FTP ftp = FTP('ftp.univie.ac.at') ftp.login() print ftp.size('applications/vim/runtime/dos/syntax/abc.vim') </code></pre> <p>ftp.size() returns file size in bytes. in above example comlete file path is '<a href="ftp://ftp.univie.ac.at/applications/vim/runtime/dos/syntax/abc.vim" rel="nofollow">ftp://ftp.univie.ac.at/applications/vim/runtime/dos/syntax/abc.vim</a>'</p>
python|python-2.7|ftp
0
1,906,111
71,953,786
Calculate the number of quarters between two ending dates of quarters in Python
<p>I am wondering how to calculate the number of quarters between two dates - these two dates are the end date of a quarter but they're just different in year.</p> <p><code>2014-12-31</code> and <code>2017-09-30</code></p>
<p>Convert values to quarter periods, subtract and for integers use attribute <code>n</code>:</p> <pre><code>d1 = pd.Timestamp('2017-09-30') d2 = pd.Timestamp('2014-12-31') a = (pd.Period(d1, 'q') - pd.Period(d2, 'q')).n print (a) 11 </code></pre> <p>If need working with Periods in same year use <code>replace</code>:</p> <pre><code>a = (pd.Period(d2, 'q') - pd.Period(d1.replace(year=d2.year), 'q')).n print (a) 1 </code></pre>
python|pandas
1
1,906,112
15,024,674
Displaying the text file data in dictionary format
<p>I have a text file(new.txt) which has data like:</p> <pre><code>{ "String1": { "Value1": {"One":"a","Two":"b","Three":"c"}, "Value2": {"One":"aa","Two":"bb","Three":"cc"}, } "String2": { "Value1": {"One":"a1","Two":"b1","Three":"c1"}, "Value2": {"One":"aa1","Two":"bb1","Three":"cc1"}, } } </code></pre> <p>I want to display the value of: String1,value1 that is {"One":"a","Two":"b","Three":"c"} String2,value2 and One that is "aa1"</p> <p>How can i display it..</p>
<pre><code>import ast with open('new.txt') as f: d = ast.literal_eval(f.read()) print d['String2']['Value2']['One'] </code></pre>
python|dictionary
3
1,906,113
46,544,725
Python 3.5.1 re.sub not working on Multiline
<p>Can anyone explain why all of the re.sub command below fail to find and replace the match, while a re.search with the same input does at least find a match?</p> <pre><code>import re a = re.sub(b"^#define", b"***FOUND***", b"#pragma once\r\n\r\n#define WIBBLE\t10\r\n\r\n#include &lt;string.h&gt;\r\n\r\n", re.MULTILINE) b = re.sub(b"^#define", b"***FOUND***", b"#pragma once\n\n#define WIBBLE\t10\n\n#include &lt;string.h&gt;\n\n", re.MULTILINE) c = re.sub("^#define", "***FOUND***", "#pragma once\r\n\r\n#define WIBBLE\t10\r\n\r\n#include &lt;string.h&gt;\r\n\r\n", re.MULTILINE) d = re.sub("^#define", "***FOUND***", "#pragma once\n\n#define WIBBLE\t10\n\n#include &lt;string.h&gt;\n\n", re.MULTILINE) e = re.search(b"^#define", b"#pragma once\r\n\r\n#define WIBBLE\t10\r\n\r\n#include &lt;string.h&gt;\r\n\r\n", re.MULTILINE) f = re.search(b"^#define", b"#pragma once\n\n#define WIBBLE\t10\n\n#include &lt;string.h&gt;\n\n", re.MULTILINE) g = re.search("^#define","#pragma once\r\n\r\n#define WIBBLE\t10\r\n\r\n#include &lt;string.h&gt;\r\n\r\n", re.MULTILINE) h = re.search("^#define", "#pragma once\n\n#define WIBBLE\t10\n\n#include &lt;string.h&gt;\n\n", re.MULTILINE) </code></pre> <p>PyCharm reports the following to me as the answers:</p> <pre><code>a = {bytes} b'#pragma once\r\n\r\n#define WIBBLE\t10\r\n\r\n#include &lt;string.h&gt;\r\n\r\n' b = {bytes} b'#pragma once\n\n#define WIBBLE\t10\n\n#include &lt;string.h&gt;\n\n' c = {str} '#pragma once\r\n\r\n#define WIBBLE\t10\r\n\r\n#include &lt;string.h&gt;\r\n\r\n' d = {str} '#pragma once\n\n#define WIBBLE\t10\n\n#include &lt;string.h&gt;\n\n' e = {SRE_Match} &lt;_sre.SRE_Match object; span=(16, 23), match=b'#define'&gt; f = {SRE_Match} &lt;_sre.SRE_Match object; span=(14, 21), match=b'#define'&gt; g = {SRE_Match} &lt;_sre.SRE_Match object; span=(16, 23), match='#define'&gt; h = {SRE_Match} &lt;_sre.SRE_Match object; span=(14, 21), match='#define'&gt; </code></pre> <p>a - d are wrong because nothing has been replaced as expected.</p> <p>e - f are all correct because the same match was found.</p> <p>I'm completely at a loss here as to what the problem is. I know another way of doing this that will work, but the above should do what I want.</p>
<p>I found the problem. When specifying re.MULTILINE as the flags parameter I was actually specifying the value of re.MULTILINE as the count parameter by mistake!</p> <pre><code> a = re.sub(b"^#define", b"***FOUND***", b"#pragma once\r\n\r\n#define WIBBLE\t10\r\n\r\n#include &lt;string.h&gt;\r\n\r\n", flags=re.MULTILINE) b = re.sub(b"^#define", b"***FOUND***", b"#pragma once\n\n#define WIBBLE\t10\n\n#include &lt;string.h&gt;\n\n", flags=re.MULTILINE) c = re.sub("^#define", "***FOUND***", "#pragma once\r\n\r\n#define WIBBLE\t10\r\n\r\n#include &lt;string.h&gt;\r\n\r\n", flags=re.MULTILINE) d = re.sub("^#define", "***FOUND***", "#pragma once\n\n#define WIBBLE\t10\n\n#include &lt;string.h&gt;\n\n", flags=re.MULTILINE) </code></pre> <p>PyCharm returns this which is the expected result:</p> <pre><code> a = {bytes} b'#pragma once\r\n\r\n***FOUND*** WIBBLE\t10\r\n\r\n#include &lt;string.h&gt;\r\n\r\n' b = {bytes} b'#pragma once\n\n***FOUND*** WIBBLE\t10\n\n#include &lt;string.h&gt;\n\n' c = {str} '#pragma once\r\n\r\n***FOUND*** WIBBLE\t10\r\n\r\n#include &lt;string.h&gt;\r\n\r\n' d = {str} '#pragma once\n\n***FOUND*** WIBBLE\t10\n\n#include &lt;string.h&gt;\n\n' </code></pre>
python|regex
3
1,906,114
49,575,466
TypeError: 'in <string>' requires string as left operand, not list (list comprehension)
<p>I'm trying to check if the words in the list show up in my column if words show up in the column, then convert to 1 else 0. but Im getting <code>TypeError: 'in &lt;string&gt;' requires string as left operand, not list</code> error. </p> <pre><code>top_words_list = ['great', 'love', 'good', 'story', 'loved', 'excellent', 'series', 'best', 'one'] [1 if re.search(top_words_list) in i else 0 for i in amazon['reviewer_summary']] </code></pre>
<p>You are looking for </p> <pre><code>[1 if any(word in i for word in top_words_list) else 0 for i in amazon['reviewer_summary']] </code></pre> <p><code>re.search()</code> returns a <code>list</code> of all the matches. So, when you do <code>if re.search() in i</code>, you are checking <code>if &lt;list&gt; in &lt;string&gt;</code> which is why it's raising <code>TypeError</code>.</p> <p>A small demonstration for the same:</p> <pre><code>&gt;&gt;&gt; chars_to_check = ['a', 'b', 'c'] &gt;&gt;&gt; sentence = 'this is a sentence' &gt;&gt;&gt; chars_to_check in sentence Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: 'in &lt;string&gt;' requires string as left operand, not list &gt;&gt;&gt; &gt;&gt;&gt; any(c in sentence for c in chars_to_check) True </code></pre>
python|string|python-3.x|list-comprehension|typeerror
2
1,906,115
53,560,638
Unusual order of dimensions of an image matrix in python
<p>I downloaded a dataset which contains a MATLAB file called 'depths.mat' which contains a 3-dimensional matrix with the dimensions 480 x 640 x 1449. These are actually 1449 images, each with the dimension 640 x 480. I successfully loaded it into python using the scipy library but the problem is the unusual order of the dimensions. This makes Python think that there are 480 images with the dimensions 640 x 1449. I tried to reshape the matrix in python, but a simple reshape operation did not solve my problem.</p> <p>Any suggestions are welcome. Thank you.</p>
<p>You misunderstood. You do not want to reshape, you want to transpose it. In MATLAB, arrays are <code>A(x,y,z)</code> while in python they are <code>P[z,y,x]</code>. Make sure that once you load the entire matrix, you change the first and last dimensions. </p> <p>You can do this with the <code>swapaxes</code> function, but beware! it does not make a copy nor change the the data, just changes how the higher level indices of <code>nparray</code> access the internal memory. Your best chances if you have enough RAM is to make a copy and dump the original. </p>
python-3.x|matlab
2
1,906,116
53,704,464
AttributeError: 'ContactUs' object has no attribute 'model'
<p>can any body help me, i try create contact form on python-django, and when i try make migrations on data base i recieve error "AttributeError: 'ContactUs' object has no attribute 'model'"</p> <p>vievs.py</p> <pre><code>from django.shortcuts import render from .forms import ContactForm, ContactUs from django.core.mail import EmailMessage from django.shortcuts import redirect from django.template.loader import get_template def contact(request): form_class = ContactForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): first_name = request.POST.get('first_name', '') last_name = request.POST.get('last_name', '') date = request.POST.get('date', '') month = request.POST.get('month', '') year = request.POST.get('year', '') sender = request.POST.get('sender', '') message = request.POST.get('message', '') licence = request.POST.get('licence', '') phoneNumber = request.POST.get('phoneNumber', '') zipCode = request.POST.get('zipCode', '') cdlType = request.POST.get('cdlType', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = { 'first_name': first_name, 'last_name': last_name, 'date': date, 'month': month, 'year': year, 'sender': sender, 'message': message, 'licence': licence, 'phoneNumber': phoneNumber, 'zipCode': zipCode, 'cdlType': cdlType, } content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" + '', ['youremail@gmail.com'], headers={'Reply-To': sender} ) email.send() return redirect('contact') return render(request, 'email.html', { 'form': form_class, }) def contact_us(request): form_class = ContactUs # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): first_name = request.POST.get('first_name', '') last_name = request.POST.get('last_name', '') sender = request.POST.get('sender', '') message = request.POST.get('message', '') phoneNumber = request.POST.get('phoneNumber', '') # Email the profile with the # contact information template = get_template('contact_us_template.txt') context = { 'first_name': first_name, 'last_name': last_name, 'sender': sender, 'message': message, 'phoneNumber': phoneNumber, } content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" + '', ['youremail@gmail.com'], headers={'Reply-To': sender} ) email.send() return redirect('contact_us') return render(request, 'email2.html', { 'form': form_class, }) </code></pre> <p>models.py</p> <pre><code>from django.db import models class Form(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date = models.DateTimeField() month = models.DateTimeField() year = models.DateTimeField() sender = models.EmailField() message = models.CharField() licence = models.CharField(max_length=100) zipCode = models.CharField(max_length=100) phoneNumber = models.CharField(max_length=100) cdlType = models.CharField(max_length=100) class ContactUs(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) sender = models.EmailField() message = models.CharField() phoneNumber = models.CharField(max_length=100) </code></pre> <p>forms.py</p> <pre><code>from django import forms class ContactForm(forms.Form): first_name = forms.CharField(max_length=100, required=True) last_name = forms.CharField(max_length=100, required=True) date = forms.DateTimeField(required=True) month = forms.DateTimeField(required=True) year = forms.DateTimeField(required=True) sender = forms.EmailField(required=True) message = forms.CharField(required=True) licence = forms.CharField(max_length=100, required=True) zipCode = forms.CharField(max_length=100, required=True) phoneNumber = forms.CharField(max_length=100, required=True) cdlType = forms.CharField(max_length=100, required=True) class ContactUs(forms.Form): first_name = forms.CharField(max_length=100, required=True) last_name = forms.CharField(max_length=100, required=True) sender = forms.EmailField(required=True) message = forms.CharField(required=True) phoneNumber = forms.CharField(max_length=100, required=True) </code></pre> <p>traceback</p> <pre><code>C:\Contact_Form\back&gt;python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "C:\Contact_Form\testenv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Contact_Form\testenv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Contact_Form\testenv\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Contact_Form\testenv\lib\site-packages\django\core\management\base.py", line 350, in execute self.check() File "C:\Contact_Form\testenv\lib\site-packages\django\core\management\base.py", line 379, in check include_deployment_checks=include_deployment_checks, File "C:\Contact_Form\testenv\lib\site-packages\django\core\management\base.py", line 366, in _run_checks return checks.run_checks(**kwargs) File "C:\Contact_Form\testenv\lib\site-packages\django\core\checks\registry.py", line 71, in run_checks new_errors = check(app_configs=app_configs) File "C:\Contact_Form\testenv\lib\site-packages\django\contrib\admin\checks.py", line 26, in check_admin_app errors.extend(site.check(app_configs)) File "C:\Contact_Form\testenv\lib\site-packages\django\contrib\admin\sites.py", line 81, in check if modeladmin.model._meta.app_config in app_configs: AttributeError: 'ContactUs' object has no attribute 'model' </code></pre> <p>admin.py</p> <pre><code>from django.contrib import admin from .models import Form, ContactUs admin.site.register(Form, ContactUs) </code></pre> <p>At start i made contact form just for sending mails but then i modificate it because i need display data in site admin.</p>
<pre><code>from django.contrib import admin from .models import Form, ContactUs admin.site.register(Form, ContactUs) </code></pre> <p>change your admin file to this</p> <pre><code>from django.contrib import admin from .models import Form, ContactUs admin.site.register(Form) admin.site.register(ContactUs) </code></pre>
python|django|attributeerror
8
1,906,117
45,754,993
BeautifulSoup, ignore <a> </a> tags and get al the text inside <p> </p>
<p>I want to get all the text inside every <code>&lt;p&gt;</code> tag which belongs to <code>news1</code></p> <pre><code>import requests from bs4 import BeautifulSoup r1 = requests.get("http://www.metalinjection.net/shocking-revelations/machine-heads-robb-flynn-addresses-controversial-photo-from-his-past-in-the-wake-of-charlottesville") data1 = r1.text soup1 = BeautifulSoup(data1, "lxml") news1 = soup1.find_all("div", {"class": "article-detail"}) for x in news1: print x.find("p").text </code></pre> <p>this get the first <code>&lt;p&gt;</code> text and only that..when called find_all it gives following error</p> <pre><code>AttributeError: ResultSet object has no attribute 'find_all'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()? </code></pre> <p>so I made a list.but still getting the same error??</p> <pre><code>text1 = [] for x in news1: text1.append(x.find_all("p").text) print text1 </code></pre>
<p>The error i get when running your code is: <code>AttributeError: 'ResultSet' object has no attribute 'text'</code>, which is reasonable as a bs4 <code>ResultSet</code> is basically a list of <code>Tag</code> elements. You can get the text of every 'p' tag if you loop over that iterable. </p> <pre><code>text1 = [] for x in news1: for i in x.find_all("p"): text1.append(i.text) </code></pre> <p>Or as a one-liner, using list comprehensions: </p> <pre><code>text1 = [i.text for x in news1 for i in x.find_all("p")] </code></pre>
python-2.7|web-scraping|beautifulsoup
1
1,906,118
45,768,292
How to open another pyqt gui and retrieve value from it?
<p>I am working on developing a file selection dialog using Python 3.6 and pyqt5. The basic idea of the dialog is that it has the option to preview files before selecting. It can preview any kinds of registered windows files. The design was done using QtDesigner MainWindow. Now I can open this preview file browser from another pyqt/python3 file. But how can I retrieve the selected filename and file path from that script? Here is the test file where I am opening the preview browser file:</p> <pre><code>class TestBrowser(QtWidgets.QMainWindow, design.Ui_MainWindow): def __init__(self,browser): super(self.__class__, self).__init__() self.setupUi(self) # This is defined in design.py file automatically # It sets up layout and widgets that are defined self.browser=browser self.pushButton.clicked.connect(self.dario) def dario(self): self.browser.exec_() def main(): app = QApplication(sys.argv) browser=bd.BrowserDialog() main=TestBrowser(browser) main.show() sys.exit(app.exec_()) if __name__ == '__main__': # if we're running file directly and not importing it main() </code></pre>
<p>I personally use globals on a different .py file (for sanity purposes) for stuff like this when I get stuck on "how can I move a value from another class/function/something".</p> <p><strong>On new .py file:</strong></p> <pre><code>file_name = None file_path = None # Save function def save_filename(selected_file, selected_path): global file_name, file_path file_name = selected_file file_path = selected_path </code></pre> <p><strong>And on your browser when you select a file, add:</strong></p> <pre><code>mynewpyfile.save_filename(file, path) </code></pre> <p><strong>Then from your main window you can get the file data as:</strong></p> <pre><code>self.pushTestbutton.clicked.connect(self.do_something) def do_something(self): print("the selected file is" + mynewpyfile.file_path + "/" + mynewpyfile.file_name) </code></pre> <p><strong>Other alternatives:</strong> <a href="http://doc.qt.io/qt-5/qfiledialog.html" rel="nofollow noreferrer">http://doc.qt.io/qt-5/qfiledialog.html</a><br> In this approach you just add a QlineEdit and... athough limited, it can't be easier than this.</p> <pre><code>self.lineTest.setText(QtWidgets.QFileDialog.getOpenFileName()[0]) </code></pre>
python|python-3.x|pyqt5
0
1,906,119
54,946,697
psycopg2 - Inserting list of dictionaries into PosgreSQL database. Too many executions?
<p>I am inserting a list of dictionaries to a PostgreSQL database. The list will be growing quickly and the number of dict values (columns) is around 30. The simplified data:</p> <pre><code>projects = [ {'name': 'project alpha', 'code': 12, 'active': True}, {'name': 'project beta', 'code': 25, 'active': True}, {'name': 'project charlie', 'code': 46, 'active': False} ] </code></pre> <p>Inserting the data into the PostgreSQL database with the following code does work (as in this <a href="https://stackoverflow.com/a/29471241/7547749">answer</a>), but I am worried about executing too many queries.</p> <pre class="lang-py prettyprint-override"><code>for project in projects: columns = project.keys() values = project.values() query = &quot;&quot;&quot;INSERT INTO projects (%s) VALUES %s;&quot;&quot;&quot; # print(cursor.mogrify(query, (AsIs(','.join(project.keys())), tuple(project.values())))) cursor.execute(query, (AsIs(','.join(columns)), tuple(values))) conn.commit() </code></pre> <p>Is there a better practice? Thank you so much in advance for your help!</p>
<p>Use <a href="http://initd.org/psycopg/docs/extras.html#psycopg2.extras.execute_values" rel="noreferrer">execute_values()</a> to insert hundreds of rows in a single query.</p> <pre><code>import psycopg2 from psycopg2.extras import execute_values # ... projects = [ {'name': 'project alpha', 'code': 12, 'active': True}, {'name': 'project beta', 'code': 25, 'active': True}, {'name': 'project charlie', 'code': 46, 'active': False} ] columns = projects[0].keys() query = "INSERT INTO projects ({}) VALUES %s".format(','.join(columns)) # convert projects values to sequence of seqeences values = [[value for value in project.values()] for project in projects] execute_values(cursor, query, values) conn.commit() </code></pre>
python|postgresql|psycopg2
15
1,906,120
54,761,203
Get dictionary value from a List inside a dictionary
<p>I am looking to get the value of the description field inside the weather.</p> <pre><code>{'coord': {'lon': 73.85, 'lat': 18.52}, 'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky', 'icon': '01d'}], 'base': 'stations', 'main': {'temp': 305.381, 'pressure': 949.7, 'humidity': 31, 'temp_min': 305.381, 'temp_max': 305.381, 'sea_level': 1023.73, 'grnd_level': 949.7} </code></pre> <p>i have seen many posts and i am trying to do the below:</p> <pre><code>r1 = requests.get('http://api.openweathermap.org/data/2.5/weather?q=Pune,in&amp;APPID=5ad6ec2537bfb0d574363e115c2d0041') print(r1.status_code) json_data = json.loads(r1.text) print(json_data) print("Weather is" ,json_data["weather"][0]) </code></pre> <p>But the above is fetching me all the values inside the dictionary. What's the best way to achieve that? Thanks.</p>
<p>Use <code>json_data["weather"][0]['description']</code> to access the description field.</p>
python-3.x
1
1,906,121
33,459,068
Enabling 10QPS vs 1QPS on Google AppEngine (Google Analytics)
<p>I saw that per the <a href="https://developers.google.com/analytics/devguides/reporting/core/v2/limits-quotas" rel="nofollow">Configuration and Reporting Limits</a> it's possible to obtain more than 1 Query per Second </p> <blockquote> <p>In the Developers Console this quota is referred to as the per-user limit. By default, <strong>it is set to 1 query per second (QPS) and can be adjusted to a maximum value of 10. If the per-user limit is set to a value larger than 10 QPS</strong>, the Google Analytics quota policy will still take effect and limit per-user requests to 10 QPS.</p> </blockquote> <p>I was unable to find where that might be done in the Console so was hoping for some help on where it might be. I've searched everywhere and asked on #appengine to no avail. </p> <p>I'm attempting to access via. python/pandas, and just to confirm I was getting only one query per second I ran a few tests and the general runtime of any query was 0.9*n where n was the number of queries I ran (I a loop of queries that iterated over a date range to escape Google's 10,000 records per query limit.)</p> <p>Any help would be greatly appreciated!</p>
<p>From the developer console start page: <a href="https://console.developers.google.com/start" rel="nofollow noreferrer">https://console.developers.google.com/start</a></p> <ol> <li>Click <code>Enable and Manage APIs</code>. It should be in a blue box. <ul> <li>If you haven't done so already it will prompt you to select a project. <a href="https://i.stack.imgur.com/Wthby.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wthby.png" alt="enter image description here"></a></li> </ul></li> <li>Search for <code>Analytics</code> <ul> <li>if you haven't done so already it will prompt you to enable the API.</li> </ul></li> <li>Click <code>Quotas</code> <a href="https://i.stack.imgur.com/k4hAd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k4hAd.png" alt="enter image description here"></a></li> </ol> <p>Once there you can see the default <code>1 query per second</code> <strong>Per-user Limit</strong>. And you can also see a link to a form to apply for a quota increase - read the form carefully and answer every question.</p> <p>And finally you linked to the deprecated reporting API limits and quota page. It is mostly the same but the <a href="https://developers.google.com/analytics/devguides/reporting/core/v3/limits-quotas" rel="nofollow noreferrer">V3 Core Reporting API Limits and Quotas</a> will have the most up to date information.</p>
python|google-app-engine|google-analytics
1
1,906,122
73,641,116
Combiner Functions Seemingly Not emitting correct results
<p>So I'm working on a test streaming case. Reading from pubsub and for now, sending to stdout for some visuals on the pipeline and transforms.</p> <p>I believe I'm getting some unusual output, and believe I'm likely missing something so hoping someone can help.</p> <p>Take my code (stripped back to debug):</p> <pre><code>with beam.Pipeline(options=opts)as p: ( p | ReadFromPubSub(topic=topic_name ,timestamp_attribute='timestamp') | beam.WindowInto(beam.window.FixedWindows(beam.window.Duration(5)), trigger=beam.trigger.AfterWatermark(), accumulation_mode=beam.trigger.AccumulationMode.ACCUMULATING) | beam.CombineGlobally(beam.combiners.CountCombineFn()).without_defaults() | beam.Map(print) ) </code></pre> <p>I am generating an arbitrary number of events and pushing those to my topic - currently 40. I can confirm through the generation of the events that they all succeed in reaching the topic. Upon simply printing the results of the topic (using beam), I can see what I would expect.</p> <p>However, what I wanted to try was some basic window aggregation and using both <code>beam.CombineGlobally(beam.combiners.CountCombineFn())</code> and <code>beam.combiners.Count.Globally()</code>, I notice 2 things happening (not strictly at the same time).</p> <p>The first issue:</p> <ul> <li>When I print additional window start/ end timestamps, I am getting more than 1 instance of the same window returned. My expectation on a local runner, would be that there is a single fixed window collecting the number of events and emitting a result.</li> <li>This is the DoFn I've used to get a picture of the windowing data.</li> </ul> <pre><code>class ShowWindowing(beam.DoFn): def process(self, elem, window = beam.DoFn.WindowParam): yield f'I am an element: {elem}\nstart window time:{window.start.to_utc_datetime()} and the end window time: {window.end.to_utc_datetime()}' </code></pre> <ul> <li>And to reiterate, the issue is that I am not getting 'duplicate' results, it is rather I am getting multiple semi-grouped results.</li> </ul> <p>The second issue I have (which I feel is related to the above but I've seen this occur without the semi-grouping of elements):</p> <ul> <li>When I execute my pipeline through the CLI (I use notebooks a lot), and generate events to my topic, I am getting considerably less output back which appear to be just partial results.</li> <li>Example: I produce 40 events - each event has a lag of half a second. My window is set to 5 seconds, I expect (give or take) a combined result of 10 each 5 seconds over 20 seconds. What I <em>get</em> is a completely partial result. This could be a count of 1 over a window or a count of 8.</li> </ul> <p>I've read and re-read the docs (admittedly skipping over some of it just to seek an answer) but I've referenced the katas and the Google Dataflow quest to look for examples/ alternatives and I cannot identify where I'm going wrong.</p> <p>Thanks</p>
<p>I think this boils down to a <a href="https://github.com/apache/beam/blob/release-2.36.0/sdks/python/apache_beam/runners/direct/transform_evaluator.py#L725" rel="nofollow noreferrer">TODO in the Python local runner</a> in handling watermarks for PubSub subscriptions. Essentially, it thinks it has received all the data up until now, but there is still data in PubSub that has a timestamp less than <code>now()</code> which becomes <a href="https://beam.apache.org/documentation/programming-guide/#watermarks-and-late-data" rel="nofollow noreferrer">late data</a> once it is actually read.</p> <p>A real runner such as Dataflow won't have this issue.</p>
python|streaming|google-cloud-dataflow|apache-beam|google-cloud-pubsub
1
1,906,123
41,123,980
plot contrast of a linear model in python
<p>In python I am trying to plot the effect of a linear model</p> <pre><code>data = pd.read_excel(input_filename) data.sexe = data.sexe.map({1:'m', 2:'f'}) data.diag = data.diag.map({1:'asd', 4:'hc'}) data.site = data.site.map({ 10:'USS', 20:'UYU', 30:'CAM', 40:'MAM', 2:'Cre'}) lm_full = sm.formula.ols(formula= L_bankssts_thickavg ~ diag + age + sexe + site' % var, data=data).fit() </code></pre> <p>I used a linear model, which works well : </p> <pre><code>print(lm_full.summary()) </code></pre> <p>Gives : </p> <pre><code> OLS Regression Results =============================================================================== Dep. Variable: L_bankssts_thickavg R-squared: 0.156 Model: OLS Adj. R-squared: 0.131 Method: Least Squares F-statistic: 6.354 Date: Tue, 13 Dec 2016 Prob (F-statistic): 7.30e-07 Time: 15:40:28 Log-Likelihood: 98.227 No. Observations: 249 AIC: -180.5 Df Residuals: 241 BIC: -152.3 Df Model: 7 Covariance Type: nonrobust =================================================================================== coef std err t P&gt;|t| [95.0% Conf. Int.] ----------------------------------------------------------------------------------- Intercept 2.8392 0.055 51.284 0.000 2.730 2.948 diag[T.hc] -0.0567 0.021 -2.650 0.009 -0.099 -0.015 sexe[T.m] -0.0435 0.029 -1.476 0.141 -0.102 0.015 site[T.Cre] -0.0069 0.036 -0.189 0.850 -0.078 0.065 site[T.MAM] -0.0635 0.040 -1.593 0.112 -0.142 0.015 site[T.UYU] -0.0948 0.038 -2.497 0.013 -0.170 -0.020 site[T.USS] 0.0145 0.037 0.396 0.692 -0.058 0.086 age -0.0059 0.001 -4.209 0.000 -0.009 -0.003 ============================================================================== Omnibus: 0.698 Durbin-Watson: 2.042 Prob(Omnibus): 0.705 Jarque-Bera (JB): 0.432 Skew: -0.053 Prob(JB): 0.806 Kurtosis: 3.175 Cond. No. 196. ============================================================================== </code></pre> <p>I know would like to plot the effect for example of the "diag" variable : As it appears in my model, the diagnosis has an effect on the dependent variable, I would like to plot this effect. I want to have a graphical representation with the two possible values of diag (ie : 'asd' and 'hc') showing which group has the lowest value (ie a graphical representation of a contrast)</p> <p>I would like something similar as the allEffect library in R</p> <p>Do you think there are similar functions in python ? </p>
<p>The best way to plot this effect is to do a CCPR Plots with matplot lib. </p> <pre><code># Component-Component plus Residual (CCPR) Plots (= partial residual plot) fig, ax = plt.subplots(figsize=(5, 5)) fig = sm.graphics.plot_ccpr(lm_full, 'diag[T.sz]', ax=ax) plt.close </code></pre> <p>Which gives </p> <p><a href="https://i.stack.imgur.com/1dl1A.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1dl1A.png" alt="Plot"></a></p>
python|statsmodels
0
1,906,124
38,393,156
Alarm clock that interacted with google calendar API
<p>I am looking for some help on an alarm clock that interacted with google calendar.</p> <p>I have some problem with the code now where is not pulling down the events.</p> <p>here is the errore i get now:</p> <p>INFO:<strong>main</strong>:Polling calendar for events... INFO:googleapiclient.discovery:URL being requested: GET <a href="https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json&amp;singleEvents=true" rel="nofollow">https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json&amp;singleEvents=true</a> INFO:<strong>main</strong>:Polling calendar for events... INFO:googleapiclient.discovery:URL being requested: GET <a href="https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json&amp;singleEvents=true" rel="nofollow">https://www.googleapis.com/calendar/v3/calendars/primary/events?alt=json&amp;singleEvents=true</a></p> <p>Process finished with exit code -1</p> <pre><code># Inspired from 'Raspberry Pi as a Google Calender Alarm Clock' # http://www.esologic.com/?p=634 #and this link as well https://github.com/ehamiter/get-on-the-bus from datetime import datetime import logging, os, platform, re, time from apiclient import discovery import httplib2 from oauth2client.client import flow_from_clientsecrets from oauth2client.file import Storage from oauth2client.tools import run_flow SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Google Calendar API Python Quickstart' FREQUENCY_CHECK = 5 # in second MP3_FOLDER = 'E:\Users\Andrew.Price\PycharmProjects\SimpleAlarm\MP3' CALENDAR_ID ='primary' logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) class Alarm(): system = platform.system().lower() flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.params['access_type'] = 'offline' flow.params['approval_prompt'] = 'force' storage = Storage('calendar.dat') credentials = storage.get() if credentials is None or credentials.invalid == True: credentials = run_flow(flow, storage) http = httplib2.Http() http = credentials.authorize(http) service = discovery.build('calendar', 'v3', http=http) #service = build(serviceName='calendar', version='v3', http=http, developerKey=API_KEY) def check_credentials(self): if self.credentials is None or self.credentials.invalid == True: credentials = run_flow(self.flow, self.storage) def calendar_event_query(self): self.check_credentials() today = datetime.today() events = self.service.events().list(singleEvents=True, calendarId=CALENDAR_ID).execute() #events = self.service.events().list(singleEvents=True).execute() for i, event in enumerate(events['items']): name = event['summary'].lower() try: start = event['start']['dateTime'][:-9] except KeyError: start = '' description = event.get('description', '') repeat = True if description.lower() == 'repeat' else False now = today.strftime('%Y-%m-%dT%H:%M') if start &gt;= now: logger.debug('Event #%s, Name: %s, Start: %s', i, name, start) if start == now: if name.startswith('say'): name = re.sub(r'[^a-zA-Z0-9\s\']', '', name) command = '{0} "{1}"'.format('say' if system == 'darwin' else 'espeak -ven+m2', name[4:]) logger.info('Event starting. Announcing \'%s\'...', name[4:]) else: mp3_files = os.listdir(MP3_FOLDER) mp3_name = name.replace(' ', '_') + '.mp3' mp3_name = mp3_name if mp3_name in mp3_files else 'default.mp3' command = 'mpg123 \'{}/{}\''.format(MP3_FOLDER, mp3_name) logger.info('Event %s starting. Playing mp3 file %s...', name, mp3_name) os.system(command) if repeat == False: time.sleep(60) def poll(self): logger.info('Polling calendar for events...') self.calendar_event_query() while True: a = Alarm() a.poll() time.sleep(FREQUENCY_CHECK) </code></pre>
<p>I have changed the code and got it to work using this code from Matt <a href="http://mattdyson.org/projects/alarmpi/#comment-20249" rel="nofollow noreferrer">http://mattdyson.org/projects/alarmpi/#comment-20249</a></p> <p>This is the code that I have changed. It is not pretty yet just works for now</p> <pre><code>from __future__ import print_function import pytz import dateutil.parser import httplib2 from oauth2client import tools from oauth2client import client import datetime import logging from googleapiclient.discovery import build from apiclient import discovery from oauth2client.file import Storage import Settings import os try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None log = logging.getLogger('root') # If modifying these scopes, delete your previously saved credentials # at ~/.credentials/calendar-python-quickstart.json SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Smart-Alarm' class AlarmGatherer: def __init__(self): #home_dir = os.path.expanduser('~') #credential_dir = os.path.join(home_dir, 'calendar.dat') #if not os.path.exists(credential_dir): # os.makedirs(credential_dir) #credential_path = os.path.join(credential_dir, 'client_secret.json') SCOPES = 'https://www.googleapis.com/auth/calendar.readonly' CLIENT_SECRET_FILE = 'client_secret.json' APPLICATION_NAME = 'Smart-Alarm' self.FLOW = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) self.storage = Storage('calendar.dat') self.credentials = self.storage.get() if not self.checkCredentials(): log.error("GCal credentials have expired") log.warn("Remove calendar.dat and run 'python AlarmGatherer.py' to fix") return http = httplib2.Http() http = self.credentials.authorize(http) self.service = build('calendar', 'v3', http=http) def checkCredentials(self): return not (self.credentials is None or self.credentials.invalid == True) def generateAuth(self): self.credentials = tools.run_flow(self.FLOW, self.storage) def getNextEvent(self, today=False): log.debug("Fetching details of next event") if not self.checkCredentials(): log.error("GCal credentials have expired") log.warn("Remove calendar.dat and run 'python AlarmGatherer.py' to fix") raise Exception("GCal credentials not authorized") #time = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time = datetime.datetime.now() if not today: # We want to find events tomorrow, rather than another one today log.debug("Skipping events from today") #time += datetime.timedelta(days=1) # Move to tomorrow time = time.replace(hour=10, minute=0, second=0, microsecond=0) # Reset to 10am the next day # 10am is late enough that a night shift from today won't be caught, but a morning shift # from tomorrow will be caught result = self.service.events().list( calendarId='primary', timeMin="%sZ" % (time.isoformat()), maxResults=1, singleEvents=True, orderBy='startTime' ).execute() events = result.get('items', []) return events[0] def getNextEventTime(self, includeToday=False): log.debug("Fetching next event time (including today=%s)" % (includeToday)) nextEvent = self.getNextEvent(today=includeToday) start = dateutil.parser.parse(nextEvent['start']['dateTime']) # start = dateutil.parser.parse(nextEvent['start']['dateTime'],ignoretz=True) # start = start.replace(tzinfo=pytz.timezone('Africa/Johannesburg')) return start def getNextEventLocation(self, includeToday=False): log.debug("Fetching next event location (including today=%s)" % (includeToday)) nextEvent = self.getNextEvent(today=includeToday) if (nextEvent['location']): return nextEvent['location'] return None def getDefaultAlarmTime(self): defaultTime = ('0600') #defaultTime = self.settings.getint('default_wake') #defaultTime = self.settings.getint('default_wake') defaultHour = int(defaultTime[:2]) defaultMin = int(defaultTime[2:]) alarm = datetime.datetime.now(pytz.timezone('Africa/Johannesburg')) alarm += datetime.timedelta(days=1) # Move to tomorrow alarm = alarm.replace(hour=defaultHour, minute=defaultMin, second=0, microsecond=0) return alarm if __name__ == '__main__': print("Running credential check") a = AlarmGatherer() try: if not a.checkCredentials(): raise Exception("Credential check failed") except: print("Credentials not correct, please generate new code") a.generateAuth() a = AlarmGatherer() print(a.getNextEventTime()) print(a.getNextEventLocation()) </code></pre>
python-2.7|calendar|raspberry-pi
0
1,906,125
30,985,786
Adding new python type : TypeError: can't set attributes of built-in/extension type
<p>Below python-c code which compiles properly </p> <pre><code>#include &lt;Python.h&gt; #include &lt;structmember.h&gt; struct rangerr { long min; long max; }; //Python type to represent rangerr struct py_rangerr { PyObject_HEAD struct rangerr range; }; // * get &amp; set methods for py_rangerr static PyObject * py_rangerr_min_get(struct py_rangerr *self) { self-&gt;range.min = 1; return PyLong_FromLong(self-&gt;range.min); } static PyObject * py_rangerr_min_set(struct py_rangerr *self) { printf("Setter called"); self-&gt;range.min = 1; } static PyObject * py_rangerr_max_get(struct py_rangerr *self) { self-&gt;range.max = 10; return PyLong_FromLong(self-&gt;range.max); } //* GetSet method definition for py_rangerr static PyGetSetDef py_rangerr_getset[] = { {"min",(getter)py_rangerr_min_get, (setter)py_rangerr_min_set, "min",NULL}, {"max",(getter)py_rangerr_max_get, NULL, "max",NULL}, /* Sentinel */ {NULL}, }; /****************************************************************************** */ static void py_rangerr_dealloc(struct py_rangerr *self) { self-&gt;ob_type-&gt;tp_free((PyObject *)self); } static PyTypeObject py_rangerr_type = { PyObject_HEAD_INIT(NULL) .tp_name = "rangerr", .tp_basicsize = sizeof(struct py_rangerr), .tp_dealloc = (destructor) py_rangerr_dealloc, .tp_flags = Py_TPFLAGS_DEFAULT, .tp_alloc = PyType_GenericAlloc, .tp_doc = "rangerr", .tp_getset = py_rangerr_getset, }; void initrangerr(void) { PyObject* mod; mod = Py_InitModule3("rangerr", NULL, "An extension with a type."); if (mod == NULL) { return; } py_rangerr_type.tp_new = PyType_GenericNew; if (PyType_Ready(&amp;py_rangerr_type) &lt; 0){ return; } Py_INCREF(&amp;py_rangerr_type); PyModule_AddObject(mod, "rangerr", (PyObject*)&amp;py_rangerr_type); } </code></pre> <p>but when I try to invoke set/get method It throws below errors:</p> <pre><code>&gt;&gt;&gt; import rangerr as r &gt;&gt;&gt; r.rangerr.min &lt;attribute 'min' of 'rangerr' objects&gt; &gt;&gt;&gt; r.rangerr.min=2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: can't set attributes of built-in/extension type 'rangerr' &gt;&gt;&gt; type(r.rangerr.min) &lt;type 'getset_descriptor'&gt; </code></pre> <p>Do I need add something like "PyMemberDef" ? Thanks for any pointers or help. </p>
<p>It's not directly possible to have a default value for arguments. You could add a function to your module to set global default values as static variables.</p> <p>If you only want to initialize your instance, you should define <code>PyTypeObject.tp_init</code> like</p> <pre><code>static int py_rangerr_init(struct py_rangerr *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = {"min", "max", NULL}; int min = 0, max = 1; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii", kwlist, &amp;min, &amp;max)) return -1; self-&gt;range.min = min; self-&gt;range.max = max; return 0; } static PyTypeObject py_rangerr_type = { PyObject_HEAD_INIT(NULL) [...] .tp_init = (initproc) py_rangerr_init, }; </code></pre> <p>If you don't give values for <code>min</code> or <code>max</code>, the default values from the line <code>int min = 0, max = 1;</code> will be used.</p> <p>In relation to your question about the usage of <code>PyMemberDef</code>, it is, that for types like <code>int</code> it might be and less repetitive less error-prone to use <code>PyTypeObject.tp_members</code> instead of <code>PyTypeObject.tp_getset</code>.</p> <p>Besides the typedef of setter is:</p> <pre><code>typedef int (*setter)(PyObject *, PyObject *, void *); </code></pre>
python|python-c-api|python-c-extension
2
1,906,126
39,893,420
python - pandas - check if date exists in dataframe
<p>I have a dataframe like this:</p> <pre><code> category date number 0 Cat1 2010-03-01 1 1 Cat2 2010-09-01 1 2 Cat3 2010-10-01 1 3 Cat4 2010-12-01 1 4 Cat5 2012-04-01 1 5 Cat2 2013-02-01 1 6 Cat3 2013-07-01 1 7 Cat4 2013-11-01 2 8 Cat5 2014-11-01 5 9 Cat2 2015-01-01 1 10 Cat3 2015-03-01 1 </code></pre> <p>I would like to check if a date is exist in this dataframe but I am unable to. I tried various ways as below but still no use:</p> <pre><code>if pandas.Timestamp("2010-03-01 00:00:00", tz=None) in df['date'].values: print 'date exist' if datetime.strptime('2010-03-01', '%Y-%m-%d') in df['date'].values: print 'date exist' if '2010-03-01' in df['date'].values: print 'date exist' </code></pre> <p>The 'date exist' never got printed. How could I check if the date exist? Because I want to insert the none-existed date with number equals 0 to all the categories so that I could plot a continuously line chart (one category per line). Help is appreciated. Thanks in advance. </p> <p>The last one gives me this: <code>FutureWarning: elementwise comparison failed; returning scalar instead, but in the future will perform elementwise comparison</code> And the <code>date exist</code> not get printed. </p>
<p>I think you need convert to datetime first by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow noreferrer"><code>to_datetime</code></a> and then if need select all rows use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p> <pre><code>df.date = pd.to_datetime(df.date) print (df.date == pd.Timestamp("2010-03-01 00:00:00")) 0 True 1 False 2 False 3 False 4 False 5 False 6 False 7 False 8 False 9 False 10 False Name: date, dtype: bool print (df[df.date == pd.Timestamp("2010-03-01 00:00:00")]) category date number 0 Cat1 2010-03-01 1 </code></pre> <p>For return <code>True</code> use check value converted to <code>numpy array</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.values.html" rel="nofollow noreferrer"><code>values</code></a>:</p> <pre><code>if ('2010-03-01' in df['date'].values): print ('date exist') </code></pre> <p>Or at least one <code>True</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.any.html" rel="nofollow noreferrer"><code>any</code></a> as comment <a href="https://stackoverflow.com/questions/39893420/python-pandas-check-if-date-exists-in-dataframe#comment67072665_39893420">Edchum</a>:</p> <pre><code>if (df.date == pd.Timestamp("2010-03-01 00:00:00")).any(): print ('date exist') </code></pre>
python|datetime|pandas|dataframe
6
1,906,127
40,280,146
Python: Why do plots of functions with two variables look spurious?
<p>I am using the following code to plot a function of two variables</p> <pre><code>import numpy as np from mpl_toolkits.mplot3d import Axes3D from pylab import meshgrid import matplotlib.pyplot as plt x = np.arange(0,1.0,0.01) y = np.arange(0,1.0,0.01) X,Y = meshgrid(x, y) Z = np.sin(2*np.abs(X-0.3)+2*np.sin(5*Y)) fig = plt.figure() ax = fig.gca(projection='3d') ax.plot_surface(X, Y, Z) plt.show() </code></pre> <p>The result looks like this:<a href="https://i.stack.imgur.com/Zukpc.png" rel="nofollow"><img src="https://i.stack.imgur.com/Zukpc.png" alt="enter image description here"></a></p> <p>What are those lines that bump out of the surface coming from? They are not in my data. Changing the resolution to 0.001 fixes them, but this makes the plotting really slow.</p>
<p>By default, ax.plot_surface, ignores some of the data. The problem is that it does not ignore this data to draw the black lines. Therefore, the black lines are based on different data than the connecting blue patches.</p> <p>This can be turned by passing optional arguments:</p> <pre><code>ax.plot_surface(X, Y, Z,cstride=1,rstride=1) </code></pre> <p>It is not clear to me what the idea behind the default settings is. I would be happy to be illuminated.</p>
python|matplotlib|plot
1
1,906,128
40,228,020
assigning to a wrapped slice of a numpy array
<p>I have a large image <code>A</code> and a smaller image <code>B</code>, both expressed as 2-D <code>numpy</code> arrays. I want to use <code>A</code> as the canvas, and write translated copies of <code>B</code> all over it, packed in a hexagonal arrangement. The part I can't get my head around is how to handle it such that the image wraps both vertically and horizontally—essentially what I want is regular tessellation of a (padded, as necessary) sub-image onto a torus.</p> <p>I've seen the discussion of <code>numpy.take</code> and <code>numpy.roll</code> at <a href="https://stackoverflow.com/questions/17739543/">wrapping around slices in Python / numpy</a> and that shows me how to access and return a <strong><em>copy</em></strong> of a wrapped slice of an array, but I want to assign to that—i.e., for arbitrary integers <code>rowOffset</code> and <code>columnOffset</code> I want to do the equivalent of:</p> <pre><code> A = numpy.zeros((5,11), int) B = numpy.array([[1,2,3,4,5,6,7]]) * numpy.array([[10,100,1000]]).T # OK, we wouldn't be able to fit more than one or two copies of B into A, but they demonstrate the wrapped placement problem wrappedRowIndices = ( numpy.arange(B.shape[0]) + rowOffset ) % A.shape[0] wrappedColumnIndices = ( numpy.arange(B.shape[1]) + columnOffset ) % A.shape[1] A[ wrappedRowIndices, : ][ :, wrappedColumnIndices ] = B </code></pre> <p>I see from a comment <a href="https://stackoverflow.com/questions/17739543/">on the question</a>, and from a moment's reflection on the way <code>numpy</code> arrays are represented, that there's no way a wrapped slice can be returned as a <code>view</code> in the way this demands.</p> <p>Is there (Y) a way of assigning to wrapped slices of an array in this way, or (X) an existing utility for performing the kind of tessellation I'm trying to achieve?</p>
<p><code>np.put</code> is a 1d equivalent to <code>np.take</code>:</p> <pre><code>In [1270]: A=np.arange(10) In [1271]: np.take(A,[8,9,10,11],mode='wrapped') Out[1271]: array([8, 9, 0, 1]) In [1272]: np.put(A,[8,9,10,11],[10,11,12,13],mode='wrapped') In [1273]: A Out[1273]: array([12, 13, 2, 3, 4, 5, 6, 7, 10, 11]) In [1274]: np.take(A,[8,9,10,11],mode='wrapped') Out[1274]: array([10, 11, 12, 13]) </code></pre> <p>Its docs suggest <code>np.place</code> and <code>np.putmask</code> (and <code>np.copyto</code>). I haven't used those much, but it might be possible to construct a mask, and rearrangement of <code>B</code> that would do the copy.</p> <p>=================</p> <p>Here's an experiment with <code>place</code>:</p> <pre><code>In [1313]: A=np.arange(24).reshape(4,6) In [1314]: mask=np.zeros(A.shape,bool) In [1315]: mask[:3,:4]=True In [1316]: B=-np.arange(12).reshape(3,4) </code></pre> <p>So I have <code>mask</code> the same size as <code>A</code>, with a 'hole' the size of <code>B</code>.</p> <p>I can roll both the <code>mask</code> and <code>B</code>, and <code>place</code> the values in <code>A</code> in a <code>wrapped</code> fashion.</p> <pre><code>In [1317]: np.place(A, np.roll(mask,-2,0), np.roll(B,1,0).flat) In [1318]: A Out[1318]: array([[ -8, -9, -10, -11, 4, 5], [ 6, 7, 8, 9, 10, 11], [ 0, -1, -2, -3, 16, 17], [ -4, -5, -6, -7, 22, 23]]) </code></pre> <p>And with 2d rolls</p> <pre><code>In [1332]: m=np.roll(np.roll(mask,-2,0),-1,1) In [1333]: m Out[1333]: array([[ True, True, True, False, False, True], [False, False, False, False, False, False], [ True, True, True, False, False, True], [ True, True, True, False, False, True]], dtype=bool) In [1334]: b=np.roll(np.roll(B,1,0),-1,1) In [1335]: b Out[1335]: array([[ -9, -10, -11, -8], [ -1, -2, -3, 0], [ -5, -6, -7, -4]]) In [1336]: A=np.zeros((4,6),int) In [1337]: np.place(A, m, b.flat) In [1338]: A Out[1338]: array([[ -9, -10, -11, 0, 0, -8], [ 0, 0, 0, 0, 0, 0], [ -1, -2, -3, 0, 0, 0], [ -5, -6, -7, 0, 0, -4]]) </code></pre>
python|numpy|indexing
3
1,906,129
52,431,937
How to count frequency in a time period by group using pandas
<p>Suppose I have sorted sample dataframe looks like this</p> <pre><code>CustomerID CallID Date 123 1 01/30/2017 123 2 01/31/2017 123 3 02/03/2017 123 4 02/07/2017 123 5 02/08/2017 </code></pre> <p>I want to count how many calls did I received from the same customer in the past 7 days as of each date. The desired output dataframe would be</p> <pre><code>CustomerID CallID Date NumOfCallsOneWeek 123 1 01/30/2017 1 123 2 01/31/2017 2 123 3 02/03/2017 3 123 4 02/07/2017 2 123 5 02/08/2017 3 </code></pre> <p>Note as of 02/07/2017, the 2 calls on 01/30/2017 are received over a week ago, so they are not counted.</p> <p>How do I do this in pandas? Thank you for your help.</p>
<p>Using <code>rolling</code> with <code>groupby</code> </p> <pre><code>df['NumOfCallsOneWeek']=df.groupby('CustomerID').apply(lambda x : x.set_index('Date').rolling('7D').count())['CallID'].values df Out[951]: CustomerID CallID Date NumOfCallsOneWeek 0 123 1 2017-01-30 1.0 1 123 2 2017-01-31 2.0 2 123 3 2017-02-03 3.0 3 123 4 2017-02-07 2.0 4 123 5 2017-02-08 3.0 </code></pre>
python|pandas
2
1,906,130
52,103,408
Seaborn pairplot hue parameter not working as expected
<p>If "C" was assigned as value for the "hue" parameter, it was expected Seaborn not displayed column "C". Am I wrong?</p> <pre><code>sns.pairplot(df, hue='C') </code></pre> <p><a href="https://i.stack.imgur.com/UnlkQ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UnlkQ.png" alt="enter image description here"></a></p> <p>DataFrame:</p> <p><a href="https://i.stack.imgur.com/1xeOV.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/1xeOV.jpg" alt="enter image description here"></a></p>
<p>By default, seaborn will show all numeric columns!</p> <p>So if your 'hue' column ('C' in your case) column as string(object) type, it will not be visible on the graph</p> <p>For instance:</p> <pre><code>import numpy as np import pandas as pd import seaborn as sns data = { 'A': [*np.random.random(5)], 'B': [*np.random.random(5)], 'C': ['X', 'Y', 'X', 'X', 'Y'] } df = pd.DataFrame(data) </code></pre> <p><a href="https://i.stack.imgur.com/SYIEE.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/SYIEE.jpg" alt="enter image description here"></a></p> <pre><code>sns.set(style="ticks", color_codes=True) sns.pairplot(df, hue='C') </code></pre> <p><a href="https://i.stack.imgur.com/itHcD.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/itHcD.jpg" alt="enter image description here"></a></p> <p>However, if you have 'C' column as the numerical values, you have to use 'vars' to specify what columns you are going to use:</p> <blockquote> <p><a href="https://seaborn.pydata.org/generated/seaborn.pairplot.html" rel="noreferrer">vars</a> : list of variable names, optional</p> <p>Variables within data to use, otherwise use every column with a numeric datatype.</p> </blockquote> <pre><code>data = { 'A': [*np.random.random(5)], 'B': [*np.random.random(5)], 'C': [*np.random.randint(1, 3, 5)] } df = pd.DataFrame(data) </code></pre> <p><a href="https://i.stack.imgur.com/DT4S0.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/DT4S0.jpg" alt="enter image description here"></a></p> <pre><code>sns.set(style="ticks", color_codes=True) sns.pairplot(df, hue='C', vars=['A', 'B']) </code></pre> <p><a href="https://i.stack.imgur.com/6ocVA.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/6ocVA.jpg" alt="enter image description here"></a></p>
python|plot|seaborn
21
1,906,131
52,409,584
Replace substring of given indices range
<p>I am new in Python programming. I am stuck at one point. Let's say I have string "hello-world". I want to replace all the characters of this string with "*" except first &amp; last. so the result will be <code>"h***-****d"</code>.</p> <p>One way to do this as below:</p> <pre><code>In [1]: s = "hello-world" In [2]: s[0] + "*"*(len(s)-2) + s[-1] Out[2]: 'h*********d' </code></pre> <p>If I want to replace all characters with "*" except first &amp; last 2 characters</p> <pre><code>In [3]: s[:2] + "*"*(len(s)-4) + s[-2:] Out[3]: 'he*******ld' </code></pre> <p>Is there any pretty way to handle these type of problems. Any help would be appreciated. Thanks.</p>
<p>You can use <code>str.join</code> (and the <code>string</code> module to check against letters):</p> <pre><code>s[0] + ''.join(['*' if i in string.ascii_letters else i for i in s[1:-1]]) + s[-1] </code></pre> <p>Since you said you wanted <code>h****-****d</code> where the hyphen isn't replaced, you would need to test whether the characters are letters or not. You could change <code>string.ascii_letters</code> to:</p> <pre><code>chars = 'abcdefghijklmnopqrstuvwxyz' chars = chars + chars.upper() + '0123456789' # + 'some_other_chars' </code></pre> <p>...if you want to include other characters like numbers or punctuation. Or you can write out the letters you want to replace manually. </p> <p>You may also want to perform a check to see whether the string is 3 characters or more so that no errors are raised. </p>
python|python-3.x
0
1,906,132
51,813,955
Time series plot with week, year and number of hits
<pre><code> In[1] df Out[0] week year number_of_cases 8 2010 583.0 9 2010 116.0 10 2010 358.0 11 2010 420.0 ... ... ... 52 2010 300.0 1 2011 123.0 2 2011 145.0 </code></pre> <p>How may I create a timeline graph where my y-axis is the number of cases and my x axis is increasing week number that corresponds with the year? I want it to go from week 1 to 52 in the year 2010 then week 1 to 52 in the year 2011. And have this as one large graph to see how the number of cases vary each year according to week. </p> <p>Python 3, Pandas. </p>
<p>You can create a <code>datetime</code> column based on the year and the week, plot <code>'number_of_cases'</code> against the date, and then use <code>mdates</code> to format the x-ticks.</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates # Determine the date df['date'] = pd.to_datetime(df.assign(day=1, month=1)[['year', 'month', 'day']])+pd.to_timedelta(df.week*7, unit='days') # Plot fig, ax = plt.subplots() df.plot(x='date', y='number_of_cases', marker='o', ax=ax) # Format the x-ticks myFmt = mdates.DateFormatter('%Y week %U') ax.xaxis.set_major_formatter(myFmt) </code></pre> <p><a href="https://i.stack.imgur.com/cR2k9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cR2k9.png" alt="enter image description here"></a></p>
python|python-3.x|pandas|time-series|timeserieschart
0
1,906,133
62,135,617
Generating Positive Kinetic Energy (PKE) from car velocity
<p>I have a data frame with 3 columns, Time (each second), Dpeed(KM/H) in each second, from this data frame I want to calculate positive kinetic energy. This formula i found in this research : </p> <blockquote> <p><a href="https://www.researchgate.net/publication/235721432_Quality_assurance_of_exhaust_emissions_test_data" rel="nofollow noreferrer">https://www.researchgate.net/publication/235721432_Quality_assurance_of_exhaust_emissions_test_data</a></p> </blockquote> <p>PKE = pow(Vf,2) - pow(Vi,2) / distance I'm new to python and I'm wondering how to implement it. any help will be appreciated . what i have tried : </p> <p>this to calculate the time in hour </p> <pre><code>start=df['Time'].iloc[0] end=df['Time'].iloc[df.shape[0]-1] diff = end - start hr = diff.seconds/3600 #to hr hr </code></pre> <p>and this to calculate distance</p> <pre><code>avgspeed = df['Vehicle Speed Sensor [km/h]'].mean() dis = avgspeed * hr dis </code></pre> <p>and this to calculate pke :</p> <pre><code>z = 0 df['pke'] = 0 for i in range(1,len(df)): z = pow(df['Vehicle Speed Sensor [km/h]'].loc[i],2) - pow(df['Vehicle Speed Sensor [km/h]'].loc[i-1],2) pke = z / dis df['pke'].loc[i] = pke </code></pre> <p>this is the data how its presented <a href="https://i.stack.imgur.com/TcY8z.png" rel="nofollow noreferrer">enter image description here</a></p>
<p>I recommend to do calculations over Excel then compare code output to Excel output to assure your results.</p>
python|data-science|data-extraction
0
1,906,134
63,361,396
Convert CSV file into 2D Table in Python
<p>I have a CSV file with the following structure:</p> <pre><code>Configuration ID, Value (1), Value (2), ......., Value (N) Config (1) , X (1) , X (2) , ......., X (N) Config (2) , Y (1) , Y (2) , ......., Y (N) </code></pre> <p>The configuration ID for each row is unique across the file.</p> <p>I want to read this CSV file in Python (v3.8) and be able to lookup for a particular value by passing both the Config ID and Value ID (Something like 2D dictionary)</p> <pre><code>print(dataStucture[Config (1)][Value (2)]) </code></pre> <p>The previous syntax should print: X(2)</p> <p>Is there any embedded function in Python that parses a CSV file and converts it into 2D dictionary or any data structure that allows me to pass two unique keys to fetch a value from the CSV file? Any hint would be highly appreciated.</p>
<p>If you do not want to use <code>pandas</code> but <code>csv</code> instead, you can use the following code:</p> <pre class="lang-py prettyprint-override"><code>import csv data_stucture = {} with open('sample.csv') as csvfile: spamreader = csv.reader(csvfile) header = next(spamreader, None) # skip the headers for row in spamreader: data_stucture[row[0].strip()] = { key.strip(): value.strip() for key, value in zip(header[1:], row[1:]) } </code></pre> <p>Considering how the file is structured, the content of <code>data_structure</code> will be</p> <pre><code>{'Config (1)': {'Value (1)': 'X (1)', 'Value (2)Value (N)': 'X (2)'}, 'Config (2)': {'Value (1)': 'Y (1)', 'Value (2)Value (N)': 'Y (2)'}} </code></pre> <p>This means you will be able to get <code>&quot;X (1)&quot;</code> by using <code>data_stucture['Config (1)']['Value (1)']</code>.</p>
python|python-3.x|csv|parsing|data-structures
1
1,906,135
63,635,111
Filling up a coordinate list in Python
<p>I have a sorted list of coordinates, e.g.</p> <pre><code>coords = [[19, 52], [20, 52], [24, 52], [25, 52], [20, 53], [22, 53], [20, 54], [21, 54]] </code></pre> <p>I want to fill in the coordinates &quot;in between&quot;, such that the resulting list is:</p> <pre><code>result = [[19, 52], [20, 52], [21, 52], [22, 52], [23, 52], [24, 52], [25, 52], [20, 53], [21, 53], [22, 53], [20, 54], [21, 54]] </code></pre> <p>How can I do that? We can assume that the &quot;gap&quot; in the coordinates is always either continuous or zero, as in the case of the last two &quot;tuples&quot; in coords. We are also only dealing with integers here. I have managed to write a function that can do so for exactly 1 y-coordinate:</p> <pre><code>def fillElements(sequence): k=0 while (sequence[k][0]+1) == (sequence[(k+1) % len(sequence)][0]): k+=1 if k == len(sequence): return sequence else: dummy = list(range((sequence[k][0]+1), sequence[k+1][0])) for l in range(len(dummy)): sequence.append([dummy[l], sequence[0][1]]) return sequence </code></pre> <p>This function first finds the &quot;break&quot; where coordinates are missing by comparing the x-value of the current element with the x-value of the next; if they are more than 1 apart, there is the break. I also already took care of some edge cases where (i+1) would be outside of the length of the list; instead, it goes back and compares to the first entry. In that case, when the while loop ends, the running index k should be exactly the length of the sequence, and the sequence is returned unchanged. If the running index is smaller than the length of the sequence, it means the break exists. In that case, I create a dummy list that includes all the missing x-values by using range(), with the boundaries being the k-th &quot;tuple&quot;, where the loop was broken, +1 because I do not want to have the same x-value twice, and the next element. I then append these values in sublists with the y-coordinate.</p> <p>However, while this function works, the code is both kind of ugly, and like I said, it only works for one y-coordinate. Solving the latter is the most important part, but if somebody has suggestions to improve this code or use another approach in the first place, please let me know. The ordering of the coordinates in the resulting list is not important.</p> <p>e: In case of a &quot;unique y-coordinate&quot;, e.g. the &quot;tuple&quot; [20, 51], nothing should be changed, since there is no element &quot;in between&quot;.</p>
<p>If I understand correctly, you want to fill in gaps in the <code>x</code> co-ordinates, resetting each time the <code>y</code> co-ordinate changes.</p> <p>The following is a Python 3 solution which will do that:</p> <pre class="lang-py prettyprint-override"><code>def fill_gaps(coordinates): last_x, last_y = None, None for x, y in coordinates: if y == last_y: # Fill in any potential gaps between the last value and us yield from ([new_x, y] for new_x in range(last_x + 1, x)) last_x, last_y = x, y yield [x, y] </code></pre> <p>This uses a generator to make the code a bit easier, so if you want a list you will need to wrap the call with <code>list()</code> to make that happen:</p> <pre class="lang-py prettyprint-override"><code>result = list(fill_gaps(coords)) </code></pre> <p>This solution requires the co-ordinates to be sorted as you stated.</p>
python
2
1,906,136
63,675,650
problems getting links from youtube channel with beautifulsoup
<p>I am trying to scrape a youtube channel and return all of the links for each video of this channel, however when I try to print out these links, I only get a few links that have nothing to do with the videos. I am suspecting the videos may be loaded by Javascript, so would there we a way to even do this with beautifulsoup? Will I have to use selenium? Can somebody please help me and do some testing. Here is my code so far:</p> <pre><code>import requests from bs4 import BeautifulSoup print('scanning page...') youtuber = 'memeulous' result = requests.get('https://www.youtube.com/c/' + youtuber + '/videos') status = result.status_code src = result.content soup = BeautifulSoup(src, 'lxml') links = soup.find_all('a') if status == 200: print('valid URL, grabbing uploads...') else: print('invalid URL, status code: ' + str(status)) quit() print(links) </code></pre> <p>and here is my output:</p> <pre><code>scanning page... valid URL, grabbing uploads... [&lt;a href=&quot;https://www.youtube.com/about/&quot; slot=&quot;guide-links-primary&quot; style=&quot;display: none;&quot;&gt;About&lt;/a&gt;, &lt;a href=&quot;https://www.youtube.com/about/press/&quot; slot=&quot;guide-links-primary&quot; style=&quot;display: none;&quot;&gt;Press&lt;/a&gt;, &lt;a href=&quot;https://www.youtube.com/about/copyright/&quot; slot=&quot;guide-links-primary&quot; style=&quot;display: none;&quot;&gt;Copyright&lt;/a&gt;, &lt;a href=&quot;/t/contact_us&quot; slot=&quot;guide-links-primary&quot; style=&quot;display: none;&quot;&gt;Contact us&lt;/a&gt;, &lt;a href=&quot;https://www.youtube.com/creators/&quot; slot=&quot;guide-links-primary&quot; style=&quot;display: none;&quot;&gt;Creators&lt;/a&gt;, &lt;a href=&quot;https://www.youtube.com/ads/&quot; slot=&quot;guide-links-primary&quot; style=&quot;display: none;&quot;&gt;Advertise&lt;/a&gt;, &lt;a href=&quot;https://developers.google.com/youtube&quot; slot=&quot;guide-links-primary&quot; style=&quot;display: none;&quot;&gt;Developers&lt;/a&gt;, &lt;a href=&quot;/t/terms&quot; slot=&quot;guide-links-secondary&quot; style=&quot;display: none;&quot;&gt;Terms&lt;/a&gt;, &lt;a href=&quot;https://www.google.co.uk/intl/en-GB/policies/privacy/&quot; slot=&quot;guide-links-secondary&quot; style=&quot;display: none;&quot;&gt;Privacy&lt;/a&gt;, &lt;a href=&quot;https://www.youtube.com/about/policies/&quot; slot=&quot;guide-links-secondary&quot; style=&quot;display: none;&quot;&gt;Policy and Safety&lt;/a&gt;, &lt;a href=&quot;https://www.youtube.com/howyoutubeworks?utm_campaign=ytgen&amp;amp;utm_source=ythp&amp;amp;utm_medium=LeftNav&amp;amp;utm_content=txt&amp;amp;u=https%3A%2F%2Fwww.youtube.com%2Fhowyoutubeworks%3Futm_source%3Dythp%26utm_medium%3DLeftNav%26utm_campaign%3Dytgen&quot; slot=&quot;guide-links-secondary&quot; style=&quot;display: none;&quot;&gt;How YouTube works&lt;/a&gt;, &lt;a href=&quot;/new&quot; slot=&quot;guide-links-secondary&quot; style=&quot;display: none;&quot;&gt;Test new features&lt;/a&gt;] [Finished in 4.0s] </code></pre> <p>as you can see, no video links.</p>
<p>One way of doing this would be with the following code:</p> <pre><code>import requests api_key = &quot;PASTE_YOUR_API_KEY_HERE!&quot; yt_user = &quot;memeulous&quot; api_url = f&quot;https://www.googleapis.com/youtube/v3/channels?part=contentDetails&amp;forUsername={yt_user}&amp;key={api_key}&quot; response = requests.get(api_url).json() playlist_id = response[&quot;items&quot;][0][&quot;contentDetails&quot;][&quot;relatedPlaylists&quot;][&quot;uploads&quot;] channel_url = f&quot;https://www.googleapis.com/youtube/v3/playlistItems?&quot; \ f&quot;part=snippet%2CcontentDetails&amp;maxResults=50&amp;playlistId={playlist_id}&amp;key={api_key}&quot; def get_video_ids(vid_data: dict) -&gt; list: return [_id[&quot;contentDetails&quot;][&quot;videoId&quot;] for _id in vid_data[&quot;items&quot;]] def build_links(vid_ids: list) -&gt; list: return [f&quot;https://www.youtube.com/watch?v={_id}&quot; for _id in vid_ids] def get_all_links() -&gt; list: all_links = [] url = channel_url while True: res = requests.get(url).json() all_links.extend(build_links(get_video_ids(res))) try: paging_token = res[&quot;nextPageToken&quot;] url = f&quot;{channel_url}&amp;pageToken={paging_token}&quot; except KeyError: break return all_links print(get_all_links()) </code></pre> <p>This gets you all the video links (<code>469</code>) for the <code>memeulous</code> user.</p> <pre><code>['https://www.youtube.com/watch?v=4L8_isnyGfg', 'https://www.youtube.com/watch?v=ogpaiD2e-ss', 'https://www.youtube.com/watch?v=oH-nJe9XMN0', 'https://www.youtube.com/watch?v=kUcbKl4qe5g', ... </code></pre> <p>You can get the total video count from the <code>videos_data</code> object likes this:</p> <p><code>print(f&quot;Total videos: {videos_data['pageInfo']['totalResults']}&quot;)</code></p> <p>I hope this helps and will get you started. All you need to do, is get the API key for the YouTube Data API.</p>
python|python-3.x|beautifulsoup|youtube|python-requests
1
1,906,137
63,471,158
Define aiohttp ClientSession on class __init__ for later reuse
<p>I want to create a persistent session that last until the program ends, I have the following code.</p> <pre class="lang-py prettyprint-override"><code>import asyncio import aiohttp import atexit class Session: def __init__(self): self._session = aiohttp.ClientSession() atexit.register(self._close_session) async def get(self, url): response = await self._session.request(&quot;GET&quot;, url) return await response.json() def _close_session(self): asyncio.run(self._session.close()) async def pullit(): print(await session.get(&quot;https://raw.communitydragon.org/latest/game/data/characters/aatrox/aatrox.bin.json&quot;)) session = Session() asyncio.run(pullit()) # THIS THROWS: Timeout context manager should be used inside a task asyncio.get_event_loop().run_until_complete(pullit()) #THIS RUNS OK </code></pre> <p>This throws me an exception on the <code>self._session.request</code> line with <code>Timeout context manager should be used inside a task</code>, I've searched for other answers but it is still giving the same error.</p> <p><strong>Question:</strong> What is the cause of this error? If I want to open a session that last the lifetime of a program, and I need it to be defined inside a class (obligatory), how would that be ?</p> <p><strong>Extra:</strong> Currently I am using <code>atexit</code> to close the session when the program ends (refer above code), is this a <em>good</em> way of doing so ? if not, what is a better practice</p> <p><strong>UPDATE:</strong> I found the solution to this, it was to use <code>asyncio.get_event_loop().run_until_complete(...)</code>, but isn't <code>asyncio.run()</code> the same as above ? why does one runs without problem and the 3.7+ <code>asyncio.run()</code> doesn't run ?</p> <hr /> <p><strong>UPDATE 2:</strong> I ended up with the following code:</p> <pre class="lang-py prettyprint-override"><code>#runner.py import aiohttp import asyncio class Runner: def __init__(self, coro): self.coro = coro async def run(self): session = aiohttp.ClientSession() client.start_session(session) await self.coro client.close_session() await session.close() def run(coro): runner = Runner(coro) return asyncio.run(runner.run()) </code></pre> <pre class="lang-py prettyprint-override"><code>#client.py class Client: def __init__(self): self._session = None async def get(self, url): response = await self._session.request(&quot;GET&quot;, url) return await response.json() def start_session(self, session): self._session = session def close_session(self): self._session = None </code></pre> <pre class="lang-py prettyprint-override"><code>from .runner import run from .client import Client client = Client() async def pullit(): print(await client.get(&quot;https://raw.communitydragon.org/latest/game/data/characters/aatrox/aatrox.bin.json&quot;)) run(pullit()) </code></pre> <p>OK, this runs and everything but after it runs it throws me <code>RuntimeError: Event loop is closed</code>, which I never closed a loop.</p>
<p>Here's my solution to your problem:</p> <pre><code>import aiohttp import asyncio import atexit class HTTPClient(): def __init__(self): self._session = aiohttp.ClientSession() atexit.register(self._shutdown) print('session created') async def request(self, *args, **kwargs): async with self._session.request(*args, **kwargs) as response: return (response.status, await response.text()) def _shutdown(self): asyncio.run(self._session.close()) print('session closed') async def main(): http_client = HTTPClient() status, text = await http_client.request(url='http://example.com', method='GET') print(status) asyncio.run(main()) </code></pre> <p>On the other hand, I guess, the best approach should be some wrapper around the following code:</p> <pre><code>async with aiohttp.ClientSession() as session: # perform all needed http calls inside pass </code></pre>
python|python-asyncio
0
1,906,138
43,502,386
Error while importing XGBOOST in jupyter nb v5,win 10, p2.7. Installed via conda mndrake
<p>Any Help regarding the same would be appreciated!</p> <p>Windows 10 Jupyter version 5 Anaconda installed mndrake xgboost</p> <p>I am not able to import xgboost inside the kernel. It throws up the following error .</p> <pre><code>WindowsError Traceback (most recent call last) &lt;ipython-input-2-afdaff4619ce&gt; in &lt;module&gt;() ----&gt; 1 import xgboost C:\Anaconda2\lib\site-packages\xgboost\__init__.py in &lt;module&gt;() 9 import os 10 ---&gt; 11 from .core import DMatrix, Booster 12 from .training import train, cv 13 from . import rabit # noqa C:\Anaconda2\lib\site-packages\xgboost\core.py in &lt;module&gt;() 110 111 # load the XGBoost library globally --&gt; 112 _LIB = _load_lib() 113 114 C:\Anaconda2\lib\site-packages\xgboost\core.py in _load_lib() 104 if len(lib_path) == 0: 105 return None --&gt; 106 lib = ctypes.cdll.LoadLibrary(lib_path[0]) 107 lib.XGBGetLastError.restype = ctypes.c_char_p 108 return lib C:\Anaconda2\lib\ctypes\__init__.pyc in LoadLibrary(self, name) 441 442 def LoadLibrary(self, name): --&gt; 443 return self._dlltype(name) 444 445 cdll = LibraryLoader(CDLL) C:\Anaconda2\lib\ctypes\__init__.pyc in __init__(self, name, mode, handle, use_errno, use_last_error) 363 364 if handle is None: --&gt; 365 self._handle = _dlopen(self._name, mode) 366 else: 367 self._handle = handle WindowsError: [Error 126] The specified module could not be found </code></pre>
<p>create an environment variable XGBOOST_BUILD_DOC = 'C:\Users\xxxxxx\Anaconda2\lib\site-packages\xgboost;'</p> <pre><code>import os os.environ['XGBOOST_BUILD_DOC'] = 'C:\\Users\\xxxxxx\\Anaconda2\\lib\\site-packages\\xgboost;' </code></pre>
python|machine-learning|anaconda|jupyter-notebook|xgboost
0
1,906,139
54,280,513
New to Linux: need some help installing wxpython development environment on ubuntu 18.04
<p>I'm coming from a windows background and am making programs under python 2.7.15 and wxpython 2.8.12.1 for work projects (that is their established configuration). </p> <p>The learning curve on linux is steep for me. I started by trying to get the same environment on ubuntu.... for many hours. I hate to admit I basically gave up trying to compile my exact version from source after much frustration. </p> <p>I now simply desire to get started programming with wxpython of any current recommended configuration (python 3.7 and wxpython 4.0 would be fine)</p> <p>I have Ubuntu 18.04, which comes with python3: 3.6.7. I have python 2.7.15 as well. I also installed python 3.7.2 via sudo apt-get install python3-pip</p> <p>I use wing IDE on windows so I figured I would do the same on Ubuntu. I am trying to get that going in parallel. </p> <p>In the meantime I installed PyCharm from the Ubuntu software store.. it is quite a bit different than wing and tries to get me to use virtual environments for projects. I am trying to get it going but I can't seem to line up the environment with the right python / wxpython packages. Even simple code examples don't run. </p> <p>OK, so can someone help point me towards methods for getting this going? what versions should I use? </p> <p>Should I use apt-get? should I use pip? This install is just for fun, I want to get programming! </p> <p>--update: So I got wing going and if I use python3.6 as the environment my "hello world" test with wxpython works fine. if I switch to 3.7 I can't get it to work ("missing _core") and other errors. I guess I need help trying to set up 3.7. Trying to use pip "python3.7 pip install wxpython" gives</p> <blockquote> <p>Error running configure ERROR: failed building wxWidgets Traceback (most recent call last): File "build.py", line 1321, in cmd_build_wx wxbuild.main(wxDir(), build_options) File "/tmp/pip-build-begnss0_/wxpython/buildtools/build_wxwidgets.py", line 375, in main "Error running configure") File "/tmp/pip-build-begnss0_/wxpython/buildtools/build_wxwidgets.py", line 85, in exitIfError raise builder.BuildError(msg) buildtools.builder.BuildError: Error running configure Finished command: build_wx (0m9.551s) Finished command: build (0m9.551s) Command '"/usr/bin/python3.7" -u build.py build' failed with exit code 1.</p> <pre><code>---------------------------------------- Command "/usr/bin/python3.7 -u -c "import setuptools, </code></pre> <p>tokenize;<strong>file</strong>='/tmp/pip-build-begnss0_/wxpython/setup.py';f=getattr(tokenize, 'open', open)(<strong>file</strong>);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, <strong>file</strong>, 'exec'))" install --record /tmp/pip-wfsndtdv-record/install-record.txt --single-version-externally-managed --compile --user --prefix=" failed with error code 1 in /tmp/pip-build-begnss0_/wxpython/</p> </blockquote>
<p>here is what I ended up doing and it now works: Please excuse my &quot;noobishness&quot;</p> <p><a href="https://linuxize.com/post/how-to-install-python-3-7-on-ubuntu-18-04/" rel="nofollow noreferrer">https://linuxize.com/post/how-to-install-python-3-7-on-ubuntu-18-04/</a></p> <pre><code>$sudo apt update $sudo apt install software-properties-common $sudo add-apt-repository ppa:deadsnakes/ppa $sudo apt install python3.7 </code></pre> <p><a href="https://linuxize.com/post/how-to-install-pip-on-ubuntu-18.04/" rel="nofollow noreferrer">https://linuxize.com/post/how-to-install-pip-on-ubuntu-18.04/</a></p> <h1>pip for python 3:</h1> <pre><code>$sudo apt install python3-pip </code></pre> <h1>pip for python 2: (and installs python 2.7.15)</h1> <pre><code>$sudo apt install python-pip </code></pre> <p><a href="https://wiki.wxpython.org/How%20to%20install%20wxPython" rel="nofollow noreferrer">https://wiki.wxpython.org/How%20to%20install%20wxPython</a></p> <h1>install python3.7 wxpython phoenix (4.0):</h1> <pre><code>$sudo python3.7 pip install -U \ -f https://extras.wxpython.org/wxPython4/extras/linux/gtk3/ubuntu-18.04 \ wxPython </code></pre> <p>Now install IDE (I chose wing): <a href="https://wingware.com/download-file&amp;prod=wingper&amp;target=https://wingware.com/pub/wingide-personal/6.1.4/wingide-personal6_6.1.4-1_amd64.deb" rel="nofollow noreferrer">https://wingware.com/download-file&amp;prod=wingper&amp;target=https://wingware.com/pub/wingide-personal/6.1.4/wingide-personal6_6.1.4-1_amd64.deb</a></p> <p>Thanks for the tip on virtual environments, I get it now!<br /> Everything I have seen recommends the creation of virtual environments which I will do if I start a serious project.</p> <p>Doing it this way and setting wing's project to the 3.7 distribution uses python 3.7.2 and wxpython 4.0.4</p> <pre><code>3.7.2 (default, Dec 25 2018, 03:50:46) [GCC 7.3.0] Python Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. import wx wx.version() '4.0.4 gtk3 (phoenix) wxWidgets 3.0.5' import sys sys.version_info sys.version_info(major=3, minor=7, micro=2, releaselevel='final', serial=0) </code></pre>
python|ubuntu|wxpython
1
1,906,140
9,185,329
Using a conditional conditional in python
<p>I have a python function that contains an if-statement to check something.</p> <pre><code>def my_func(a, b, c): if a &lt; b and b &lt; c: #do complicated stuff </code></pre> <p>I want to modify the function so that the caller can determine whether or not to perform the if-statement check, by passing in a boolean.</p> <pre><code>def my_func(a, b, c, perform_check=True): </code></pre> <p>I'm trying to figure out how to make the conditional only be invoked sometimes, or skipped other times.</p>
<p>I guess something like this is what you need:</p> <pre><code>if include_already_seen or not data[person].get(item, 0): </code></pre>
python|conditional
3
1,906,141
52,527,482
Positional error when trying to specify member
<p>Hi I'm trying to get a member name rather than the author name </p> <p>I've tried a few methods like <code>for member is message.server.members:</code> which returned multiple results with every member in the server and tried <code>member: discord.Member</code> as a signature which produced an error:</p> <p>Heres what I'm working with:</p> <pre><code>async def on_message_delete(self, message): server = message.server author = message.author role = get(server.roles, name="Powerbot") channel = get(message.server.channels, name="mod-log") time = datetime.utcnow() cleanmsg = message.content for i in message.mentions: cleanmsg = cleanmsg.replace(i.mention, str(i)) fmt = '%H:%M:%S' name = author name = " ~ ".join((name.name, name.nick)) if name.nick else name.name if role not in author.roles: infomessage = "A message by {}, was deleted in {} by {}".format(message.author.mention, message.channel.mention, member,mention) delmessage = discord.Embed(description=infomessage, colour=discord.Color.purple(), timestamp=time) delmessage.add_field(name="Message:", value=cleanmsg) delmessage.set_footer(text="User ID: {}".format(message.author.id)) delmessage.set_author(name=name + " message deleted.", icon_url=message.author.avatar_url) delmessage.set_thumbnail(url="http://i.imgur.com/fJpAFgN.png") try: await self.bot.send_message(channel, embed=delmessage) except: pass </code></pre> <p>The line specifically where member.mention is. </p> <p><code>infomessage = "A message by {}, was deleted in {} by {}".format(message.author.mention, message.channel.mention, member.mention)</code></p> <p>Example output: A message by author was deleted in channel by member. </p> <p>If anyone could help that would be appreciated.</p>
<p>Viewing the person who deleted the message is not possible from the discord release that you’re using, since the stable discord.py does not contain support for audit logs. <strong>You will need discord.py rewrite</strong> to use the following solution:</p> <pre><code>@bot.event() async def on_message_delete(msg): audits = await msg.guild.audit_logs(limit=10, action=discord.AuditLogAction.message_delete) async for audit in audits: try: await audit.target.get_message(msg.id) except discord.NotFound: continue print(audit.user) break </code></pre> <p>That’s under the assumption that messages are kept even after being deleted. If the above does not work, I guess the best we can do is:</p> <pre><code>@bot.event() async def on_message_delete(msg): audits = await msg.guild.audit_logs(limit=10, action=discord.AuditLogAction.message_delete) audit = await audits.get(extra__channel=msg.channel) print(audit.user) </code></pre> <p>For further information, see:</p> <p><a href="https://discordapp.com/developers/docs/resources/audit-log" rel="nofollow noreferrer">https://discordapp.com/developers/docs/resources/audit-log</a></p> <p><a href="https://discordpy.readthedocs.io/en/rewrite/api.html#discord.AuditLogAction" rel="nofollow noreferrer">https://discordpy.readthedocs.io/en/rewrite/api.html#discord.AuditLogAction</a></p>
python|python-3.x|discord|discord.py
1
1,906,142
37,199,780
Seaborn boxplot box assign custom edge colors from Python list
<p>I am trying to change the appearance of boxes in Seaborn's boxplot. I would like all boxes to be transparent and for the box borders to be specified from a list. Here is the code I am working with:</p> <pre><code>import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt fig, ax = plt.subplots() df = pd.DataFrame(np.random.rand(10,4),columns=list('ABCD')) df['E'] = [1,2,3,1,1,4,3,2,3,1] sns.boxplot(x=df['E'],y=df['C']) # Plotting the legend outside the plot (above) box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * 0.1, box.width, box.height * 0.9]) handles, labels = ax.get_legend_handles_labels() leg = plt.legend(handles[0:2], labels[0:2], loc='upper center', bbox_to_anchor=(0.5, 1.10), ncol=2) plt.show() </code></pre> <p>This <a href="https://stackoverflow.com/questions/36305695/assign-a-color-to-a-specific-box-in-seaborn-boxplot">post</a> shows how to change the color and box edgecolor of one single box. However, I would like to assign box edgecolors based on a list like this <code>box_line_col = ['r','g',b','purple']</code>. The above code produces 4 boxes in the plot - I would like to assign custom box edge colors starting from the first (leftmost) box and continuing through to the last (rightmost) box.</p> <p>Is it possible to to specify the box edge colors from a list, while keeping the boxes themselves transparent (facecolor = white)?</p>
<p>Looping through the boxes and setting their colors should work. At the end of your code, just before <code>plt.show()</code> add:</p> <pre><code>box_line_col = ['r','g','b','purple'] # As many boxplots as you have for i,box_col in enumerate(box_line_col): mybox = g.artists[i] # Or g.patches, in newer versions # Might want to skip any Rectangles (from legend) mybox.set_edgecolor(box_col) mybox.set_facecolor(None) #or white, if that's what you want # If you want the whiskers etc to match, each box has 6 associated Line2D objects (to make the whiskers, fliers, etc.) # Loop over them here, and use the same colour as above for j in range(i*6,i*6+6): line = g.lines[j] line.set_color(box_col) line.set_mfc(box_col) line.set_mec(box_col) plt.show() </code></pre> <p>The first part is based on the post you referenced and and the whisker-coloring directions came from <a href="https://stackoverflow.com/a/36893152/721432" title="whisker colors">this post</a>.</p>
python-2.7|matplotlib|seaborn
3
1,906,143
34,257,149
django rest swagger is pulling the comments, as seen in raw. Clicking: show/hide, list operations, expand operations show nowthing
<p>django-rest-swagger is pulling the comments from view class and its methods: list, retrieve etc, as seen in click raw> JSON. <br> However, Clicking: show/hide, list operations, expand operations show nothing. <br>Note: I am using <strong>viewsets.ViewSet</strong></p> <p>This means it is being able to extract the docstring but not publish them.</p> <p>I am using:</p> <ul> <li>Python 2.6.6</li> <li>django 1.5.2</li> <li>djangorestframework 2.4.8</li> <li>yaml 3.11</li> <li>rest_framework_swagger 0.3.4</li> <li>markdown 2.4.1</li> <li>django-filter 0.11.0</li> <li>six 1.10.0</li> </ul> <p>Am I missing something here?</p>
<pre><code>class SomeViewSet(viewsets.ModelViewSet): """ Some Operations HTTP_200_OK will be send after a successful operation Post --&gt; create Get --&gt; list !! Put --&gt; update Patch --&gt; partial update """ </code></pre> <p>This works for me. Django 1.8, rest framework 3.1.2</p>
python|django|django-rest-framework|swagger
0
1,906,144
7,351,614
How to notify myself when a python script runs into an error or just stops?
<p>I have a python script which runs on Ubuntu and processes the content of a MySQL Database. I want to be informed when the script runs into an unhandled <code>exception</code> or when it is done processing.</p> <p><strong>What is the appropriate way to make this happen?</strong></p> <p>I thought of sending myself an email from within python using the method shown in <a href="https://stackoverflow.com/questions/348392/receive-and-send-emails-in-python/348551#348551">this SO-Answer</a>, but to be able to do that I have to hardcode my logindata - which I am not comfortable with (the script runs on a public server within the company).</p> <p>Any suggestions to bypass that or to make it happen using a more appropriate way?</p>
<p>This worked as charm: <a href="https://www.quora.com/How-can-I-send-a-push-notification-to-my-Android-phone-with-a-Python-script" rel="noreferrer">https://www.quora.com/How-can-I-send-a-push-notification-to-my-Android-phone-with-a-Python-script</a></p> <p>ON PC: install notify-me</p> <pre><code>pip install notify-run </code></pre> <p>then register it as: <code>notify-run register</code></p> <p>now on your mobile scan the code and allow notification from this site.</p> <p>Then your script can notify you like this:</p> <pre><code>from notify_run import Notify notify = Notify() notify.send('any message you want') </code></pre>
python|ubuntu|notifications
7
1,906,145
39,546,552
How do I make text go on to the next line (enter/return effect)? Python
<p>I have numerous strings which I am writing into a notepad txt.file via python using</p> <pre><code>x = open("File", "w") </code></pre> <p>However i want the strings to be written in the text file in the format:</p> <pre><code>('Hello') ('Hey') ('Whatever') </code></pre> <p>Instead of this:</p> <pre><code>('Hello')('Hey')('Whatever') </code></pre> <p>I'm missing specific code to achieve the 'keyboard enter/return' affect, so if anyone knows please drop me an answer. Also, I don't want to manually press enter in the actual text file, I want to do it via python. Thanks!</p>
<p>I thought I'd put my comment as an answer. </p> <p>Here is a related question: <a href="https://stackoverflow.com/questions/11497376/new-line-python">stackoverflow.com/questions/11497376/new-line-python</a>. </p> <p>Essentially you should use a new line character which is <code>\n</code>. "<code>\</code>" is an escape character.</p>
python|string|text|keyboard|enter
0
1,906,146
16,259,603
How can I nest an arbitrary number of Python file context managers?
<p>I want to take an arbitrary number of paths that represent nested tar archives, and perform an operation on the innermost archive. The trouble is, the nesting can be arbitrary, so the number of context managers I need is also arbitrary.</p> <p>Take, for example:</p> <pre><code>ARCHIVE_PATH = "path/to/archive.tar" INNER_PATHS = ( "nested/within/archive/one.tar", "nested/within/archive/two.tar", # Arbitary number of these ) def list_inner_contents(archive_path, inner_paths): with TarFile(archive_path) as tf1: with TarFile(fileobj=tf1.extractfile(inner_paths[0])) as tf2: with TarFile(fileobj=tf2.extractfile(inner_paths[1])) as tf3: # ...arbitary level of these! return tfX.getnames() contents = list_inner_contents(ARCHIVE_PATH, INNER_PATHS)) </code></pre> <p>I can't use the <code>with</code> statement's <a href="http://docs.python.org/2.7/reference/compound_stmts.html#with" rel="noreferrer">nesting syntax</a> because there could be any number of levels to nest. I can't use <a href="http://docs.python.org/2.7/library/contextlib.html#contextlib.nested" rel="noreferrer"><code>contextlib.nested</code></a> because the docs say right there:</p> <blockquote> <p>...using <code>nested()</code> to open two files is a programming error as the first file will not be closed promptly if an exception is thrown when opening the second file.</p> </blockquote> <p>Is there a way to use language constructs to do this, or do I need to manually manage my own stack of open file objects?</p>
<p>For this case you may use recursion. It feels to be most natural for the case (of course if there's no special treatment in Python yet):</p> <pre><code>ARCHIVE_PATH = "path/to/archive.tar" INNER_PATHS = [ "nested/within/archive/one.tar", "nested/within/archive/two.tar", # Arbitary number of these ] def list_inner_contents(archive_path, inner_paths): def rec(tf, rest_paths): if not rest_paths: return tf.getnames() with TarFile(fileobj=tf.extractfile(rest_paths[0])) as tf2: return rec(tf2, rest_paths[1:]) with TarFile(archive_path) as tf: try: return rec(tf, inner_paths) except RuntimeError: # We come here in case the inner_paths list is too long # and we go too deeply in the recursion return None </code></pre>
python|python-2.7|contextmanager
5
1,906,147
9,909,249
Pygame collision between player and block
<p>I'm making a game and I want to check collision between player and block, and push back player if neccesary.</p> <pre><code>def collide(self,player): if self.solid: if self.rect.colliderect(player.rect): if self.rect.bottom-1 &lt;= player.rect.top and player.pos == 'up': player.up = 0 player.rect.move(0,1) if self.rect.top+1 &gt;= player.rect.bottom and player.pos == 'down': player.down = 0 player.rect.move_ip(0,-1) if self.rect.left+1 &lt;= player.rect.right and player.pos == 'right': player.right = 0 player.rect.move_ip(-1,0) if self.rect.right-1 &gt;= player.rect.left and player.pos == 'left': player.left = 0 player.rect.move_ip(1,0) </code></pre> <p>but for some reason it doesn't work. Can someone help me? Thanks in advance</p>
<p>Try replacing </p> <pre><code>def Collide(player,self): </code></pre> <p>by </p> <pre><code>def collide(self, player): </code></pre> <p>if this is a method of some kind of <code>Obstacle</code> class. Just guessing ... :)</p>
python|pygame
1
1,906,148
1,646,017
Setting mod_python's interperter
<p>I have mod_python installed on a debian box with python 2.4 and 2.6 installed. I want mod_python to use 2.6 but it is finding 2.4. How can set it to use the other version. </p>
<p>The version of Python used is set when mod_python is compiled. If you need to use a version other than the default, you'll need to recompile it, or you may be able to find a different package from the repository.</p>
python|apache|mod-python
1
1,906,149
2,067,749
Efficient method to store Python dictionary on disk?
<p>What is the most efficient method to store a Python dictionary on the disk? The only methods I know of right now are plain-text and the <code>pickle</code> module.</p> <p><strong>Edit:</strong> Sorry for not being very clear. By efficient I meant fastest execution speed. The dictionary will contain mutable objects that will hold information to be parsed and modified.</p>
<p><a href="http://docs.python.org/library/shelve.html" rel="noreferrer">shelve</a> is pretty nice as well</p> <p>or <a href="http://code.activestate.com/recipes/576642/" rel="noreferrer">this persistent dictionary recipe</a></p> <p>for a convenient method that keeps your objects synchronized with storage, there's the ORM <a href="http://www.sqlalchemy.org/" rel="noreferrer">SQLAlchemy</a> for python</p> <p>if you just need a way to store string values by some key, theres the dbm.ndbm and dbm.gnu modules.</p> <p>if you need a hyper efficient, distributed key value cache, something like <a href="http://www.tummy.com/Community/software/python-memcached/" rel="noreferrer">memcached for python</a>...</p>
python|dictionary|disk|pickle
9
1,906,150
1,995,602
How can I turn 000000000001 into 1?
<p>I need to turn a formatted integer into a regular integer:</p> <ul> <li>000000000001 needs to be turned into 1</li> <li>000000000053 needs to be turned into 53</li> <li>000000965948 needs to be turned into 965948</li> </ul> <p>And so on.</p> <p>It seems that a simple <code>int(000000000015)</code> results in the number 13. I understand there is some weird stuff behind the scenes. What is the best way to do this accurately every time?</p>
<p>Numbers starting with <code>0</code> are considered <a href="http://en.wikipedia.org/wiki/Octal" rel="nofollow noreferrer">octal</a>.</p> <pre><code>&gt;&gt;&gt; 07 7 &gt;&gt;&gt; 08 File "&lt;stdin&gt;", line 1 08 ^ SyntaxError: invalid token </code></pre> <p>You can wrap your zero-padded number into a string, then it should work.</p> <pre><code>&gt;&gt;&gt; int("08") 8 </code></pre> <p><code>int()</code> takes an optional argument, which is the base, so the above would be the equivalent of:</p> <pre><code>&gt;&gt;&gt; int("08", 10) 8 </code></pre>
python|parsing|integer
11
1,906,151
1,747,130
Sum and Division example (Python)
<pre><code>&gt;&gt;&gt; sum((1, 2, 3, 4, 5, 6, 7)) 28 &gt;&gt;&gt; 28/7 4.0 &gt;&gt;&gt; sum((1,2,3,4,5,6,7,8,9,10,11,12,13,14)) 105 &gt;&gt;&gt; 105/7 15.0 &gt;&gt;&gt; </code></pre> <p>How do I automate this sum and division using a loop maybe?</p> <p>Edit: Maybe I wasn't clear - I want a loop to keep doing the sum (of multiples of 7, eg 1-7, 1-14, 1-21 etc..) until it reaches x (x is the user input)</p> <p>Okay, figured it out:</p> <pre><code>def sum_and_div_of_multiples_of_7(x): y = 7 while (y &lt;= x): mof7 = range(1,y) print ('mof7 is', mof7) total = sum(mof7) print ('total =', total) div = total/7 print ('div =', int(div), '\n') y = y+7 # increase y x = 70 sum_and_div_of_multiples_of_7(x) </code></pre>
<p>The direct answer:</p> <pre><code>def sum_to_number_divided_by_seven(i): return sum(range(i+1)) / 7 </code></pre> <p>The more efficient answer:</p> <pre><code>def sum_to_number_divided_by_seven(i): return (i*(i+1))/14 </code></pre>
python|sum|division
5
1,906,152
32,170,078
Efficiently matching different possible substrings to the same value
<p>I have a CSV file, one column of which is called Operating System and contains a string with values that look like this:</p> <pre><code>win-abc123 def456-windows 123123-WIN-ghi789 rhel-jkl012 45u8234dgf-redhat-mno345 pqr678-RHEL </code></pre> <p>In other words, the column value contains a substring somewhere inside of the string (front, middle, or end) indicating the operating system. The values could be one of <code>win</code>,<code>windows</code>,<code>WIN</code>,<code>rhel</code>,<code>redhat</code>,<code>RHEL</code>.</p> <p>I want to examine the column value, and clean it up by replacing the entire column with either <code>WIN</code> or <code>RHEL</code>.</p> <p>I have a clunky solution. Iterate over each row in the CSV, and iterate over each <code>key, value</code> pair in a operating system map. If it matches, replace the CSV value.</p> <pre><code>os_map = {'win':'WIN', 'windows': 'WIN', 'WIN':'WIN', 'rhel': 'RHEL', 'redhat': 'RHEL', 'RHEL': 'RHEL'} for row in rows: os = row[OPERATING_SYSTEM] for key, value in os_map.iteritems(): if key in os: row[OPERATING_SYSTEM] = value break </code></pre> <p>Or, in java:</p> <pre><code>Map&lt;String, String&gt; osMap = new HashMap&lt;String, String&gt;(); osMap.put("win", "WIN"); osMap.put("windows", "WIN"); osMap.put("WIN", "WIN"); // Repeat for RHEL values String os; for (String[] row : rows) { os = row[OPERATING_SYSTEM]; for (Map.Entry&lt;String, String&gt; entry: osMap.entrySet()) { if (os.contains(entry.getKey())) { row[OPERATING_SYSTEM] = entry.getValue(); break; } } } </code></pre> <p>I don't like this because I'm iterating through the entire map (in the worst case) before I find a match. What is a more efficient way to solve this?</p> <p>If the CSV columns were simply either <code>win</code> or <code>windows</code>, without the alphanumeric characters, I could instead do this:</p> <pre><code>os_map = {'win,windows,WIN': 'WIN', 'rhel,redhat,RHEL': 'RHEL'} for key, value in os_map: if key.contains(row[OPERATING_SYSTEM]): row[OPERATING_SYSTEM] = value break </code></pre> <p>But this is not the case.</p>
<p>In Python, you can do something along these lines:</p> <pre><code>test='''\ win-abc123 def456-windows 123123-WIN-ghi789 rhel-jkl012 45u8234dgf-redhat-mno345 pqr678-RHEL''' from itertools import chain os_map = {frozenset(['win', 'windows', 'WIN']):'WIN', frozenset(['rhel', 'redhat', 'RHEL',]): 'RHEL'} all_os=set(chain(*os_map.keys())) for line in test.splitlines(): tgt=filter(lambda e: e in all_os, line.split('-')) if tgt: print os_map[filter(lambda k: tgt[0] in k, os_map.keys())[0]] </code></pre> <p>You could also do a dict of regex:</p> <pre><code>import re os_reg={re.compile(r'\b(win|windows|WIN)\b'):'WIN', re.compile(r'\b(rhel|redhat|RHEL)\b'): 'RHEL'} for line in test.splitlines(): for pat, v in os_reg.items(): if pat.search(line): print line, v break </code></pre> <p>Or combine set and regex to do something like this:</p> <pre><code>os_map = {frozenset(['win', 'windows', 'WIN']):'WIN', frozenset(['rhel', 'redhat', 'RHEL',]): 'RHEL'} for k, v in os_map.items(): test=re.sub(r'\b({})\b'.format('|'.join(k)), v, test) for line in test.splitlines(): m=re.search(r'\b({})\b'.format('|'.join(os_map.values())), line) if m: print line, m.group(0) </code></pre>
java|python|regex
1
1,906,153
32,594,889
Reshape/pivot pandas dataframe
<p>I have a dataframe with variables: <code>id, 2001a, 2001b, 2002a, 2002b, 2003a, 2003b, etc.</code></p> <p>I am trying to figure out a way to pivot the data so the variables are: <code>id, year, a, b</code></p> <p>The 16.2 documentation refers to some reshaping and pivoting, but that seemed to speak more towards hierarchical columns.</p> <p>Any suggestions?</p> <p>I am thinking about creating a hierarchical dataframe, but am not sure how to map the <code>year</code> in the original variable names to a created hierarchical column</p> <p>sample df:</p> <pre><code>id 2001a 2001b 2002a 2002b 2003a etc. 1 242 235 5735 23 1521 2 124 168 135 1361 1 3 436 754 1 24 5124 etc. </code></pre>
<p>Here is a way to create hierarchical columns.</p> <pre><code>df = pd.DataFrame({'2001a': [242,124,236], '2001b':[242,124,236], '2002a': [242,124,236], '2002b': [242,124,236], '2003a': [242,124,236]}) df.columns = df.columns.str.split('(\d+)', expand=True) df 2001 2002 2003 a b a b a 0 242 242 242 242 242 1 124 124 124 124 124 2 236 236 236 236 236 </code></pre>
python-2.7|pandas|pivot|reshape
1
1,906,154
43,934,882
Why NodeMCU sends data with unwanted number?
<p>I am trying to send a serial data from NodeMCU to Arduino. I use MicroPython to program. As well as <code>Serial.read</code> on Arduino. I can send and receive successfully. But the problem is the NodeMCU sends data along with number which is not needed. And Arduino receives data along with number. For Example, if I send "<em>Hello</em>" it sends as "<em>Hello5</em>". I understood that the number is nothing but the number of alphabets in the string. How can I remove this?</p> <p>MicroPython on NodeMCU:</p> <pre><code>import os import machine from machine import UART uart = UART(0) import time while True: uart.write('1') </code></pre> <p>Arduino program:</p> <pre class="lang-cpp prettyprint-override"><code>String received; String msg; void setup() { Serial.begin(115200); attachInterrupt(0, light, FALLING);//When arduino Pin 2 is FALLING from HIGH to LOW, run light procedure! } void light() { Serial.println(msg); } void loop() { if (Serial.available() &gt; 0){ received = Serial.readStringUntil('\n'); msg = received; } } </code></pre>
<p>I just checked the microPython's UART (<a href="http://docs.micropython.org/en/latest/wipy/library/machine.UART.html" rel="nofollow noreferrer">http://docs.micropython.org/en/latest/wipy/library/machine.UART.html</a>) and Arduino's Serial (<a href="https://www.arduino.cc/en/Reference/Serial" rel="nofollow noreferrer">https://www.arduino.cc/en/Reference/Serial</a> ), and it seems you're missing one initialization line for UART. UART document states the default baud rate it sets is 9600, and you expect a 115200 on serial receiver. I believe setting the baud rate different on each side will have undefined behavior.</p> <p>In your python code, could you try uart.init(115200) after uart = UART(0) call (and the default values for the rest seems same as the Serial's expectations on receiver)?</p> <p>Also, Serial document says that if it can't find the char you define in the readStringUntil(), then it'll try until it times out. So I guess your function call times-out because it won't find an endline ('\n') in the stream, because you didn't inject any.</p> <p>In addition, although the help documents of the functionality you're using don't state such a thing, if you really always get the number of characters as the first char at the receiver, it might be worthwhile to try using that to your advantage. I wonder if you can try to get that number first, then read that many chars afterwards (at the Arduino receiver site). Here's some code I hope may help (I'm afraid I didn't try using it):</p> <pre><code>#include &lt;string.h&gt; char buffer[256]; // buffer to use while reading the Serial memset(buffer, (char)0, 256); // reset the buffer area to all zeros void loop() { if (Serial.available() &gt; 0){ int count = Serial.read(); // the first byte that shows the num of chars to read after, assuming that this is a 'byte' - which means we can have max 256 chars in the stream Serial.readBytes(buffer, count); msg = String(buffer); } } </code></pre>
python|c++|arduino|nodemcu|micropython
0
1,906,155
27,290,858
Django: related_name Reverse accessor
<p>I have this model where InstitutePerson is a subclass of Person.</p> <ul> <li>Person <ul> <li>InstitutePerson</li> </ul></li> <li>Project</li> </ul> <p>In Project:</p> <pre><code>participants_institite = models.ManyToManyField(InstitutePerson, blank = True, null = True) participants_exterior = models.ManyToManyField(Person, blank = True, null = True) </code></pre> <p>I get an error:</p> <pre><code>Project.participants_institute: (fields.E304) Reverse accessor for 'Project.participants_institute' clashes with reverse accesor for 'Project.participants_exterior'. </code></pre> <p>I thought that related_name would solve the problem but after seeing some posts (<a href="https://stackoverflow.com/questions/5611410/related-name-argument-not-working-as-expected-in-django-model">related_name argument not working as expected in Django model?</a>) I'm not sure how to proceed because of the inheritance among the classes.</p>
<p>Use <code>related_name</code> arg and define it manually <a href="https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name" rel="nofollow">https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.related_name</a></p> <p>If you have two M2M field with same type Django can't generate properties on target modela automatically.</p> <p>if you are not intereset in reversed direction, you can simply ise</p> <p><code> models.ManyToManyField(..., related_name='+r1') models.ManyToManyField(..., related_name='+r2') </code></p>
python|django
0
1,906,156
8,091,641
Python : How `len()` is executed
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1115313/cost-of-len-function">Cost of len() function</a> </p> </blockquote> <p>How Python calculates length of a list(using <code>len()</code> function )?Does it go through a <code>for</code> or <code>while</code> <em>loop</em> to do the same or it has some internal variable that stores the length of the list ?</p>
<p>Yes, CPython lists have an internal variable for the length.</p> <p>It's called <a href="http://hg.python.org/cpython/file/edf944ab87c5/Include/listobject.h#l22" rel="noreferrer"><code>ob_size</code></a>; all <a href="http://hg.python.org/cpython/file/edf944ab87c5/Include/object.h#l110" rel="noreferrer">variable-sized objects</a> have it.</p>
python
5
1,906,157
102,394
Sorting a dict on __iter__
<p>I am trying to sort a dict based on its key and return an iterator to the values from within an overridden iter method in a class. Is there a nicer and more efficient way of doing this than creating a new list, inserting into the list as I sort through the keys?</p>
<p>How about something like this:</p> <pre><code>def itersorted(d): for key in sorted(d): yield d[key] </code></pre>
python|optimization|refactoring
9
1,906,158
41,860,332
How to programmatically obtain openstack resource usage metrics from python?
<p>As a non-admin user of open-stack, I do want to obtain how many vms our of the total quota are running at a specific time.</p> <p>I do want to monitor usage of such resources by writing a collectd plugin for it. </p> <p>I observed that there are already two types of collect plugins related to open-stack but none of seems seem to address this simple use case: a user that wants to monitor his own usage of these resources. </p> <ul> <li><a href="https://github.com/rochaporto/collectd-openstack" rel="nofollow noreferrer">collectd-openstack</a> which seems not to be maintained and that seems to <a href="https://github.com/rochaporto/collectd-openstack/issues/21" rel="nofollow noreferrer">require admin rights</a>, a deal-breaker limitation</li> <li><a href="https://github.com/openstack/collectd-ceilometer-plugin" rel="nofollow noreferrer">collectd-ceilometer-plugin</a> which is mostly the oppisitve thing: feeding data captured by collectd to ceilometer.</li> </ul> <p>I don't care about the state of the entire cloud, I am interested only about usage inside my project.</p> <p>How API should I use in order to obtain this informations? Funny, most of the information I need is already published on the web dashboard. Still, I need to capture it with python/collect in order to send it to other systems for processing.</p>
<p>You need use nova client API for that. Have a look at <a href="http://docs.openstack.org/developer/python-novaclient/api.html" rel="nofollow noreferrer">http://docs.openstack.org/developer/python-novaclient/api.html</a></p>
python|openstack|collectd
1
1,906,159
41,797,953
How to find the intersection of two lines given a point on each line and a parallel vector
<p>I need an algorithm that can find the intersection of two 2D lines. Each line will come in the form of <strong>a point on the line and the dx/dy of a parallel vector</strong>. I've tried parameterizing each line and solving the system of equations to solve for the parameterized variable which I could plug back into the parametric equation of the lines and get my x/y, but my attempt failed. Any ideas? I'm programming in Python but the language doesn't much matter.</p>
<p>You basically have to solve the following equation:</p> <p>x = x<sub>0,a</sub>+dx<sub>a</sub>&times;t<br> y = y<sub>0,a</sub>+dy<sub>a</sub>&times;t<br> x = x<sub>0,b</sub>+dx<sub>b</sub>&times;u<br> y = y<sub>0,b</sub>+dy<sub>b</sub>&times;u</p> <p>Or:</p> <p>x<sub>0,a</sub>+dx<sub>a</sub>&times;t = x<sub>0,b</sub>+dx<sub>b</sub>&times;u<br> x<sub>0,a</sub>+dx<sub>a</sub>&times;t = x<sub>0,b</sub>+dx<sub>b</sub>&times;u</p> <p>Now if you do some algebraic manipulation, you will find that:</p> <p>t=dy<sub>b</sub>&times;(x<sub>0,b</sub>-x<sub>0,a</sub>)-dx<sub>b</sub>&times;(y<sub>0,b</sub>-y<sub>0,a</sub>)/d<br> u=dy<sub>a</sub>&times;(x<sub>0,b</sub>-x<sub>0,a</sub>)-dx<sub>a</sub>&times;(y<sub>0,b</sub>-y<sub>0,a</sub>)/d; where<br> d=dx<sub>a</sub>&times;dy<sub>b</sub>-dx<sub>b</sub>&times;dy<sub>a</sub></p> <p>Now it is thus only a matter to determine either <code>t</code> or <code>u</code> (you do not have to calculate both), and plug then into the formula above. So</p> <pre><code>def intersect(x0a,y0a,dxa,dya,x0b,y0b,dxb,dyb): t = (dyb*(x0b-x0a)-dxb*(y0b-y0a))/(dxa*dyb-dxb*dya) return (x0a+dxa*t,y0a+dya*t) </code></pre> <p>If the <code>d</code> in the equation (the denominator) is equal to zero, this means there is no intersection (the two lines are parallel). You can decide to alter the function and for instance return <code>None</code> or raise an exception in such case.</p> <p>If you test it, for instance with a vector (1,0) offset and direction (0,1); and a vector with offset (0,2) and direction (1,1); you get the not very surprising result of:</p> <pre><code>$ python3 Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; def intersect(x0a,y0a,dxa,dya,x0b,y0b,dxb,dyb): ... t = (dyb*(x0b-x0a)-dxb*(y0b-y0a))/(dxa*dyb-dxb*dya) ... return (x0a+dxa*t,y0a+dya*t) ... &gt;&gt;&gt; intersect(1,0,0,1,0,2,1,1) (1.0, 3.0) </code></pre>
python|algorithm|math|graphics|intersection
2
1,906,160
41,936,773
Python float formatting with no exponent and max precision not fixed precision
<p>I have a long list of floating point numbers to be formatted as follows:</p> <p>Examples:</p> <p>case 1) <code>6.0 -&gt; 6.0</code> (No trailing zeros)</p> <p>case 2) <code>1.23456789 -&gt; 1.234567</code> (or <code>1.234568</code>) (Max precision of 6)</p> <p>case 3) <code>0.000004 -&gt; 0.000004</code> (No exponent)</p> <p>I can use </p> <pre><code>'{}'.format(round(x, 6)) </code></pre> <p>for cases 1 &amp; 2 but 3 gives 4e-06</p> <p>If I use </p> <pre><code>'{:6f}'.format(6.0) </code></pre> <p>I get 6.000000 for case 1)</p> <p>Is there a clean way to get the formatting I want?</p>
<p>Perhaps you can consider <a href="https://stackoverflow.com/questions/2440692/formatting-floats-in-python-without-superfluous-zeros">this</a> solution.</p> <p>Your case:</p> <pre><code>print ('%.6f' % data).rstrip('0').rstrip('.') </code></pre>
python|floating-point|formatting
-1
1,906,161
47,278,529
How to combine two similar functions that convert between hiragana and katakana?
<p>I have two functions that convert between katakana and hiragana and they look the same:</p> <pre><code>katakana_minus_hiragana = 0x30a1 - 0x3041 # KATAKANA LETTER A - HIRAGANA A def is_hirgana(char): return 0x3040 &lt; ord(char[0]) and ord(char[0]) &lt; 0x3097 def is_katakana(char): return 0x30a0 &lt; ord(char[0]) and ord(char[0]) &lt; 0x30f7 def hiragana_to_katakana(hiragana_text): katakana_text = "" max_len = 0 for i, char in enumerate(hiragana_text): if is_hirgana(char): katakana_text += chr(ord(char) + katakana_minus_hiragana) max_len += 1 else: break return katakana_text, max_len def katakana_to_hiragana(katakana_text): hiragana_text = "" max_len = 0 for i, char in enumerate(katakana_text): if is_katakana(char): hiragana_text += chr(ord(char) - katakana_minus_hiragana) max_len += 1 else: break return hiragana_text, max_len </code></pre> <p>Is there a way to simplify <code>hiragana_to_katakana()</code> and <code>katakana_to_hiragana()</code> into a duck-type function or a super/meta function?</p> <p>E.g. something like</p> <pre><code>def convert_hk_kh(text, charset_range, offset): charset_start, charset_end = charset_range output_text = "" max_len = 0 for i, char in enumerate(text): if charset_start &lt; ord(char[0]) and ord(char[0]) &lt; charset_end: output_text += chr(ord(char) + offset) max_len +=1 else: break return output_text, max_len def katakana_to_hiragana(katakana_text): return convert_hk_kh(katakana_text, (0x30a0, 0x30f7), -katakana_minus_hiragana) def hiragana_to_katakana(hiragana_text): return convert_hk_kh(hiragana_text, (0x3040, 0x3097), katakana_minus_hiragana) </code></pre> <p>Are there other pythonic ways to simplify the two functions that are very similar?</p> <h1>EDITED</h1> <p>There's also <a href="https://github.com/olsgaard/Japanese_nlp_scripts" rel="nofollow noreferrer">https://github.com/olsgaard/Japanese_nlp_scripts</a> which seems to do the same thing with <code>str.translate</code>. Is that more efficient? More pythonic?</p>
<p>I'd do something like this:</p> <pre><code>KATAKANA_HIRGANA_SHIFT = 0x30a1 - 0x3041 # KATAKANA LETTER A - HIRAGANA A def shift_chars_prefix(text, amount, condition): output = '' for last_index, char in enumerate(text): if not condition(char): break output += chr(ord(char) + amount) return output, last_index def katakana_to_hiragana(text): return shift_chars_prefix(text, -KATAKANA_HIRGANA_SHIFT, lambda c: '\u30a0' &lt; c &lt; '\u30f7') def hiragana_to_katakana(text): return shift_chars_prefix(text, KATAKANA_HIRGANA_SHIFT, lambda c: '\u3040' &lt; c &lt; '\u3097') </code></pre> <p>You can also use regex if you don't return the length of the replaced prefix:</p> <pre><code>import re KATAKANA_HIRGANA_SHIFT = 0x30a1 - 0x3041 # KATAKANA LETTER A - HIRAGANA A def shift_by(n): def replacer(match): return ''.join(chr(ord(c) + n) for c in match.group(0)) return replacer def katakana_to_hiragana(text): return re.sub(r'^[\u30a1-\u30f6]+', shift_by(KATAKANA_HIRGANA_SHIFT), text) def hiragana_to_katakana(text): return re.sub(r'^[\u3041-\u3096]+', shift_by(-KATAKANA_HIRGANA_SHIFT), text) </code></pre>
python|unicode|char|ord
1
1,906,162
70,808,505
Find the number of days since a max value
<p>Given the following DataFrame:</p> <pre><code>+----+--------+------------+------+---------------------+ | id | player | match_date | stat | days_since_max_stat | +----+--------+------------+------+---------------------+ | 1 | 1 | 2022-01-01 | 1500 | NaN | | 2 | 1 | 2022-01-03 | 1600 | 2 | | 3 | 1 | 2022-01-10 | 2100 | 7 | | 4 | 1 | 2022-01-11 | 1800 | 1 | | 5 | 1 | 2022-01-18 | 1700 | 8 | | 6 | 2 | 2022-01-01 | 1600 | NaN | | 7 | 2 | 2022-01-03 | 1800 | 2 | | 8 | 2 | 2022-01-10 | 1600 | 7 | | 9 | 2 | 2022-01-11 | 1900 | 8 | | 10 | 2 | 2022-01-18 | 1500 | 7 | +----+--------+------------+------+---------------------+ </code></pre> <p>How would I calculate the <code>days_since_max_stat</code> column? The calculation of this column is exclusive of the <code>stat</code> in that row and per <code>player</code>.</p> <p>For example the value for the row where <code>id</code> = 5 is 8 because the max <code>stat</code> was in the row where <code>id</code> = 3. The <code>days_since_max_stat</code> = 2022-01-18 - 2022-01-10 = 8.</p> <p>Here's the base DataFrame:</p> <pre><code>import datetime as dt import pandas as pd dates = [ dt.datetime(2022, 1, 1), dt.datetime(2022, 1, 3), dt.datetime(2022, 1, 10), dt.datetime(2022, 1, 11), dt.datetime(2022, 1, 18), ] df = pd.DataFrame( { &quot;id&quot;: range(1, 11), &quot;player&quot;: [1 for i in range(5)] + [2 for i in range(5)], &quot;match_date&quot;: dates + dates, &quot;stat&quot;: (1500, 1600, 2100, 1800, 1700, 1600, 1800, 1600, 1900, 1500) } ) </code></pre>
<p>First imagine you have only one <code>id</code>, then you can use <code>expanding</code> to find the cummulative max/idxmax. then you can subtract:</p> <pre><code>def day_since_max(data): maxIdx = data['stat'].expanding().apply(pd.Series.idxmax) date_at_max = data.loc[maxIdx, 'match_date'].shift() return data['match_date'] - date_at_max.values </code></pre> <p>Now, we can use <code>groupby().apply</code> to apply that function for each <code>id</code>:</p> <pre><code>df['days_since_max'] = df.groupby('player').apply(day_since_max).reset_index(level=0, drop=True) </code></pre> <p>Output:</p> <pre><code> id player match_date stat days_since_max 0 1 1 2022-01-01 1500 NaT 1 2 1 2022-01-03 1600 2 days 2 3 1 2022-01-10 2100 7 days 3 4 1 2022-01-11 1800 1 days 4 5 1 2022-01-18 1700 8 days 5 6 2 2022-01-01 1600 NaT 6 7 2 2022-01-03 1800 2 days 7 8 2 2022-01-10 1600 7 days 8 9 2 2022-01-11 1900 8 days 9 10 2 2022-01-18 1500 7 days </code></pre>
python|pandas
2
1,906,163
33,669,471
Where to setup Python environment attributes for a Django project?
<p>For example the Python <code>decimal.Decimal()</code> class has a context. You can view the current context with <code>getcontext()</code> and set new values for precision, rounding, or enable traps.</p> <p>If you wanted to set a new value for the context so this is visible throughout a Django project, where would be best to do so?</p> <p>e.g. Throughout the project the <code>FloatOperation</code> signal should be trapped.</p> <pre><code>from decimal import FloatOperation, getcontext context = getcontext() context.traps[FloatOperation] = True </code></pre> <p>Also using <code>getcontext()</code> return the current context for the <em>active thread</em>. Aside from explicitly creating new threads in a project, are there any additional consideration to make with Django creating additional threads.</p>
<p>I'd suggest an application <code>core</code>, or <code>common</code>, that includes your setup as part of <code>AppConfig.ready()</code>.</p> <p><a href="https://docs.djangoproject.com/en/1.7/ref/applications/#django.apps.AppConfig.ready" rel="nofollow">https://docs.djangoproject.com/en/1.7/ref/applications/#django.apps.AppConfig.ready</a></p>
python|django|decimal|environment
2
1,906,164
33,683,343
Django - Javascript internationalization: translation not rendered in site
<p>I have followed the <a href="https://docs.djangoproject.com/en/dev/topics/i18n/translation/#internationalization-in-javascript-code" rel="nofollow">docs</a>.</p> <p><code>./manage.py makemessages -d djangojs</code> works fine.</p> <p><code>./manage.py compilemessages</code> created the relevant <code>.po</code> files</p> <p>However, the translation is not performed on site.</p> <p>urls.py</p> <pre><code>js_info_dict = { 'packages': ('market',), } urlpatterns = [url(r'^jsi18n/$', javascript_catalog, js_info_dict), ] urlpatterns += i18n_patterns( url(r'^$', HomePage.as_view(), name='home'), ) </code></pre> <p>settings.py</p> <pre><code>LOCALE_PATHS = ( pjoin(BASE_DIR, '00', 'locale'), ) # Middleware =================================================================== MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) # Internationalization ========================================================= LANGUAGE_CODE = 'en' TIME_ZONE = 'Europe/Paris' USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = ( ('en', gettext_noop('English')), ('fr', gettext_noop('French')), ) </code></pre> <p>home.html (The script is successfully loaded)</p> <pre><code>&lt;script type="text/javascript" src="{% url 'django.views.i18n.javascript_catalog' %}"&gt;&lt;/script&gt; </code></pre>
<p>The solution was provided in <a href="https://stackoverflow.com/questions/19625102/django-javascript-translation-not-working/27147542#comment55164743_27147542">this post</a>, which states that</p> <blockquote> <p>javascript catalog should be added to i18n urls patterns, not to normal patterns.</p> </blockquote> <p>Therefore urls.py must be changed to:</p> <pre><code>js_info_dict = { 'packages': ('market',), } urlpatterns += i18n_patterns( url(r'^$', HomePage.as_view(), name='home'), url(r'^jsi18n/$', javascript_catalog, js_info_dict), ) </code></pre> <p><a href="https://docs.djangoproject.com/en/dev/topics/i18n/translation/#internationalization-in-javascript-code" rel="nofollow noreferrer">Django documentation</a> will be <a href="https://code.djangoproject.com/ticket/25751" rel="nofollow noreferrer">updated</a> accordingly:</p> <blockquote> <p>We should add a note in the i18n_patterns documentation stating: if used all translated content views must also be placed within it.</p> </blockquote>
javascript|python|django|internationalization
0
1,906,165
47,078,961
Create an orphan branch without using the orphan flag
<p>I have an existing repo with some branches. I want to create a new branch without any history on that repo. I'm trying to do this using Dulwich, which supports most git operations, though not the orphan flag.</p> <p>What are the equivalent Git operations to create an orphan branch without actually using that flag? Ideally i'd like to:</p> <ul> <li>clone the repo</li> <li>make a new branch with the contents of the repo, but without history</li> <li>push the branch to the repo</li> </ul> <p>Is this possible or do I need to create a new branch that's empty, clone to a separate directory and copy the contents back?</p>
<p>Note: I don't use Dulwich and cannot say for sure anything about it. Depending on how much of Git it re-implements from scratch, what <em>Git</em> does may be irrelevant.</p> <p>An orphan branch, in Git, is actually a branch that doesn't exist. What <code>git checkout --orphan newbranch</code> does is to write the name <code>newbranch</code> into <code>HEAD</code>, without actually creating <code>newbranch</code>.</p> <p>More specifically, aside from consistency and error checking,<sup>1</sup> the difference between:</p> <pre><code>git checkout -b newbranch </code></pre> <p>and:</p> <pre><code>git checkout --orphan newbranch </code></pre> <p>is that the former runs:</p> <pre><code>git update-ref refs/heads/newbranch HEAD &amp;&amp; \ git symbolic-ref HEAD refs/heads/newbranch </code></pre> <p>and the latter runs:</p> <pre><code>git symbolic-ref HEAD refs/heads/newbranch </code></pre> <p>The first step, <code>git update-ref</code>, actually creates the branch.</p> <p>The second step, <code>git symbolic-ref</code>, sets us up to be "on" the branch.</p> <p>An orphan branch, then, is one that we are "on" that does not exist.</p> <p>The actual branch <em>creation</em> happens later, when we make a new commit. So it's not <code>git checkout</code> that creates these; it's <code>git commit</code>! The commit operation fundamentally consists of:</p> <ol> <li>turn the current index into a tree object (<code>git write-tree</code>);</li> <li>find the parent ID(s) for the current commit (read <code>HEAD</code> and check for pending merges);</li> <li>collect the remaining metadata (author, committer, email addresses ,time stamps, log message);</li> <li>create a commit object that has the information from the earlier steps;</li> <li>write the new commit object's hash ID through <code>HEAD</code> into the current branch name (or directly into <code>HEAD</code> if <code>HEAD</code> is detached).</li> </ol> <p>Step 5 is where the branch gets created. During step 2, if <code>HEAD</code> names a branch that does not exist, it contributes no parent hash ID, so that the new commit has no parents (presumably there are no recorded additional parents for merges at this time).</p> <p><em>If</em> Dulwich behaves the same as Git here—it very well might, because this peculiar state, of being on a branch that does not exist, is how Git bootstraps an <em>empty</em> repository, and it's the obvious way to do it—then all you have to do to implement what you want directly is to rewrite the <code>HEAD</code> information (however Dulwich stores it) so that it points to this non-existent branch.</p> <hr> <p><sup>1</sup><code>git checkout -b newbranch</code> also offers <code>git checkout -b newbranch startpoint</code>. Using a different starting point has a whole cascade of side effects: Git first attempts to do <code>git checkout startpoint</code> internally, which may make arbitrary modifications to index and work-tree.</p>
python|git|dulwich
5
1,906,166
37,786,742
Execute python code on uploaded files
<p>I have a django application where I upload 2 files and want to run a python script on them (proto2.py).</p> <p>In my html code I added a button to execute a file but it didn't work :</p> <pre><code>&lt;div&gt;Relay 1: &lt;form action="{% url "nettoyage"%}" method="POST"&gt; {% csrf_token %} &lt;input type="submit" value="Toggle" id="toggle1" /&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p>Reason given for failure: CSRF token missing or incorrect.</p> <p>urls.py :</p> <pre><code>url(r'^nettoyage/$', 'nettoyage',name='nettoyage'), </code></pre> <p>views.py :</p> <pre><code>def nettoyage(request): if request.method == 'POST': import proto2 return #Something, normally a HTTPResponse, using django </code></pre> <p>proto2.py :</p> <pre><code>file = xlrd.open_workbook('~/Paye_P5_test.xlsx',encoding_override='utf-8') sheet = file.sheet_by_name('Feuil1') headers = [str(cell.value) for cell in sheet.row(0)] values = [] for rowind in range(sheet.nrows)[1:]: values.append([ cell.value for cell in sheet.row(rowind)]) data2=pandas.DataFrame(data=values,columns=headers) resume=data2['Résumé'] resume = resume.str.lower() resume = resume.str.replace("'", " ") remov_punct = str.maketrans({key: None for key in string.punctuation}) resume = resume.str.translate(remov_punct) resume = html.unescape(resume) stop_words = get_stop_words('french') resume = resume.str.split() resume = resume.apply(lambda x: [item for item in x if item not in stop_words]) # Porter Stemmer Algo stemmer = SnowballStemmer("french") resume = resume.apply(lambda x: [stemmer.stem(item) for item in x]) resume[0] </code></pre>
<p>Problem lies here :</p> <pre><code>&lt;form action="{% url "nettoyage"%}" method="POST"&gt; </code></pre> <p>Change it by :</p> <pre><code>&lt;form action="{% url 'nettoyage'%}" method="POST"&gt; </code></pre> <p>The doubles quotes interfere with the <code>action</code> attribute, therefore closing it and leaving a quote open. Changing it by a simple <code>'</code> quote will resolve your issue.</p>
python|html|django
0
1,906,167
37,046,033
Unable to authenticate ,enable the user in active Directory ,the user account created by using python ldap
<p>Here i'm attached the python files to create user and authenticating user in windows active Directory 2008 r2</p> <p>create.py</p> <pre><code>import ldap import ldap.modlist as modlist name='testing3' password='p@ssw0rd' l = ldap.initialize('ldap://##2.168.3#.##') l.simple_bind_s('Administrator@example.local', 'p@ssw0rd1') dn="cn="+name+",ou=oli,dc=example,dc=local" attrs = {} attrs['objectclass'] = ['Top','person','organizationalPerson','user'] attrs['cn'] = name attrs['displayName'] = name attrs['name'] = name attrs['givenName'] = name attrs['mail'] = name attrs['ou'] = "Users" #attrs['pwdLastSet'] = "-1" attrs['userPrincipalName'] = name + "@naanal.local attrs['userAccountControl'] = '514' attrs['sAMAccountName'] = name attrs['userPassword'] = password ldif = modlist.addModlist(attrs) l.add_s(dn,ldif) l.unbind_s() </code></pre> <p>Using this program create user in the Active directory but unable to create the enabled user account. i can user the userAccountcontrol=''512` but it not working .userAccountcontrol='514' its working but user account was disabled. using ldap modify change the userAccountcontrol getting error "when i'm try to enable the user account getting error "{'info': '0000052D: SvcErr: DSID-031A120C, problem 5003 (WILL_NOT_PERFORM), data 0\n', 'desc': 'Server is unwilling to perform'}""</p> <p>Authe.py</p> <pre><code>import ldap username='shan' password='p@ssw0rd' LDAP_SERVER = 'ldap://###.##.##.##' LDAP_USERNAME = '%s@example.local' % username LDAP_PASSWORD = password base_dn = 'DC=example,DC=example' ldap_filter = 'userPrincipalName=%s@example.local' % username attrs = ['memberOf'] try: ldap_client = ldap.initialize(LDAP_SERVER) ldap_client.set_option(ldap.OPT_REFERRALS,0) ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD) print 'successfull' except ldap.INVALID_CREDENTIALS: ldap_client.unbind() print 'Wrong username ili password' except ldap.SERVER_DOWN: print 'AD server not awailable' </code></pre> <p>create the user account using create.py .then enable the user account manually in the active directory.after i'm try to authenticate the created user account not detected.but manually created account detected by using authe.py file i'm using Ubuntu 14.04 64 bit</p>
<p>There are two problems with your code:</p> <ol> <li><p>Active Directory stores the password in the <code>unicodePwd</code> attribute and not <code>userPassword</code>. See this <a href="https://msdn.microsoft.com/en-us/library/cc223248.aspx" rel="nofollow">link</a> for more details. This article also explains how the value for <code>unicodePwd</code> must be encoded (UTF-16)</p></li> <li><p>The other problem (this is also explained in the referenced article) is that you must connect over a secure connection to Active Directory whenever you are making changes to the password attribute (including creating a user). The URL starting with <code>ldap://</code> makes me believe that your connection is not secure.</p></li> </ol> <p>I hope this helps.</p>
python|ldap
0
1,906,168
66,778,193
add new rows to dataframe based on condition python pandas
<p>Need to add new rows to dataframe based on condition.</p> <p>Current dataframe:</p> <p><a href="https://i.stack.imgur.com/3yVSg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3yVSg.png" alt="enter image description here" /></a></p> <p>In this dataframe there are 4 columns. what i want to do ischeck the 'Time' column and check the nearest value for 12PM mid night in every night shift and add two new row as 11:59:59 and 00:00:01 with <strong>same values as the that nearest datapoint.</strong></p> <p>For examle: Closest value(to 12PM) for 03-01 Night is 21:46:54. so need to add two rows,</p> <pre><code>W25 03-01 Night RUNNING 23:59:59 W25 03-01 Night RUNNING 00:00:01 </code></pre> <p>so final expected dataframe should be like this:</p> <p><a href="https://i.stack.imgur.com/RNpd4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RNpd4.png" alt="enter image description here" /></a></p> <p>Sample data:</p> <pre><code>data={'Machine': {0: 'W5', 343: 'W5', 344: 'W5', 586: 'W5', 587: 'W5'}, 'State': {0: 'start', 343: 'STOPPED', 344: 'RUNNING', 586: 'STOPPED', 587: 'MAINT'}, 'Day-Shift': {0: '03-01 Night', 343: '03-01 Night', 344: '03-01 Night', 586: '03-01 Night', 587: '03-01 Night'}, 'Time': {0: Timestamp('2021-03-01 21:00:00'), 343: Timestamp('2021-03-01 22:16:54'), 344: Timestamp('2021-03-01 23:16:54'), 586: Timestamp('2021-03-01 23:48:45'), 587: Timestamp('2021-03-02 02:28:54')}} </code></pre> <p>Really appreciate your support !!!!!</p>
<p>you can use <code>idxmax()</code> to find the max record per day, then create a datetime object.</p> <pre><code>df1 = df.loc[df.groupby([df['Time'].dt.normalize()])['Time'].idxmax()] df1 = pd.concat([df1] * 2) df1['Time'] = pd.to_datetime((df1['Time'].dt.normalize().astype(str) + [' 23:59:59', ' 00:00:01'])) </code></pre> <hr /> <pre><code>print(df1) Machine State Day-Shift Time 587 W25 MAINT 03-01 Day 2021-03-01 23:59:59 587 W25 MAINT 03-01 Day 2021-03-01 00:00:01 </code></pre> <hr /> <pre><code>df = pd.concat([df,df1]).sort_index().reset_index(drop=True) Machine State Day-Shift Time 0 W25 start 03-01 Day 2021-03-01 07:00:00 1 W25 STOPPED 03-01 Day 2021-03-01 07:16:54 2 W25 RUNNING 03-01 Day 2021-03-01 07:16:54 3 W25 STOPPED 03-01 Day 2021-03-01 07:28:45 4 W25 MAINT 03-01 Day 2021-03-01 07:28:54 5 W25 MAINT 03-01 Day 2021-03-01 23:59:59 6 W25 MAINT 03-01 Day 2021-03-01 00:00:01 </code></pre>
python|pandas|dataframe|datetime|pandas-groupby
1
1,906,169
51,295,644
How can I gradually morph one list into another (cartesian product of 2 lists)?
<p>Say I have two lists, </p> <pre><code>one = ['a1', 'b1', 'c1'] two = ['a2', 'b2', 'c2'] </code></pre> <p>I want to generate a collection of all possible combinations of these items, without changing their positions in their respective lists. So for the example above, it'd be: </p> <pre><code>['a1', 'b1', 'c1'] ['a1', 'b1', 'c2'] ['a1', 'b2', 'c2'] ['a2', 'b1', 'c1'] ['a2', 'b2', 'c1'] ['a2', 'b2', 'c2'] </code></pre> <p>I'm looking through <code>itertools</code> hoping to find something that matches this description, but I haven't found one yet. </p>
<p>The function you are looking for is <code>product</code> but you need to set it up first. The problem is that you have your values "sideways"--you want to put all possible values for the first position together, then those for the second, etc. You can "transpose" your data with the <code>*zip()</code> maneuver.</p> <pre><code>from itertools import product list(product(*zip(one, two))) </code></pre> <p>The result from that is</p> <pre><code>[('a1', 'b1', 'c1'), ('a1', 'b1', 'c2'), ('a1', 'b2', 'c1'), ('a1', 'b2', 'c2'), ('a2', 'b1', 'c1'), ('a2', 'b1', 'c2'), ('a2', 'b2', 'c1'), ('a2', 'b2', 'c2')] </code></pre> <p>If you really want lists rather than tuples, use</p> <pre><code>[list(v) for v in product(*zip(one, two))] </code></pre> <p>which gives you</p> <pre><code>[['a1', 'b1', 'c1'], ['a1', 'b1', 'c2'], ['a1', 'b2', 'c1'], ['a1', 'b2', 'c2'], ['a2', 'b1', 'c1'], ['a2', 'b1', 'c2'], ['a2', 'b2', 'c1'], ['a2', 'b2', 'c2']] </code></pre> <p>Note that these are not exactly what you listed as the desired output, since you left out a couple of possibilities.</p>
python
5
1,906,170
51,356,604
How to scatter plot where X axis is continuous and Y axis categorical with 1 and 0 with 2 different colours?
<p>X=[10,20,30,40,50] y=[1,0,1,0,1]</p> <p>How to get a plot with 1's in green and 0's in red?<a href="https://i.stack.imgur.com/zo8D1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zo8D1.jpg" alt="resultant graph"></a></p>
<p>You can create a list of colors to be passed to <code>plt.scatter</code> using a simple list comprehension.</p> <pre><code>x=[10,20,30,40,50] y=[1,0,1,0,1] colors = ["seagreen" if i == 1 else "red" for i in y] plt.scatter(x, y, color=colors) plt.show() </code></pre> <p>Which gives:</p> <p><a href="https://i.stack.imgur.com/Jtdr9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Jtdr9.png" alt="enter image description here"></a></p>
pandas|matplotlib
1
1,906,171
17,613,851
Polynomial fitting problems in numpy
<p>I was trying to implement a standard polynomial fitting program, and came across a problem that I could not understand. Here is the code where I have a sample x and y data, which I fit using the normal equations, and also using the polyfit function in numpy.</p> <pre><code>def mytest(N): print "\nPolynomial order (N): {}".format(N) mVals = [5, 10, 15, 20] a_orig = [198.764, 13.5, 0.523] for M in mVals: x = arange(-M, M+1) y = matrix(a_orig[0]+ a_orig[1]*x + a_orig[2]*x**2).T # Code implementing the solution from the normal equations nArray = arange(N+1) A = matrix([[n**i for i in nArray] for n in x]) B = (A.T*A).I a_myfit = B*(A.T*y) # numpy's polyfit a_polyfit = polyfit(x, y, N) print "M: {}".format(M) print ["{0:0.3f}".format(i) for i in a_orig] print ["{0:0.3f}".format(i) for i in array(a_myfit)[:,0]] print ["{0:0.3f}".format(i) for i in list(array(a_polyfit)[:,0])[::-1]] mytest(N=5) mytest(N=6) </code></pre> <p>Here is the output</p> <pre><code>Polynomial order (N): 5 M: 5 ['198.764', '13.500', '0.523'] ['198.764', '13.500', '0.523', '0.000', '0.000', '-0.000'] ['198.764', '13.500', '0.523', '-0.000', '0.000', '0.000'] M: 10 ['198.764', '13.500', '0.523'] ['198.764', '13.500', '0.523', '-0.000', '0.000', '-0.000'] ['198.764', '13.500', '0.523', '0.000', '0.000', '0.000'] M: 15 ['198.764', '13.500', '0.523'] ['198.764', '13.500', '0.523', '0.000', '0.000', '-0.000'] ['198.764', '13.500', '0.523', '-0.000', '-0.000', '0.000'] M: 20 ['198.764', '13.500', '0.523'] ['198.764', '13.500', '0.523', '0.000', '-0.000', '-0.000'] ['198.764', '13.500', '0.523', '0.000', '0.000', '0.000'] Polynomial order (N): 6 M: 5 ['198.764', '13.500', '0.523'] ['198.764', '13.500', '0.523', '0.000', '0.000', '-0.000', '-0.000'] ['198.764', '13.500', '0.523', '-0.000', '0.000', '0.000', '-0.000'] M: 10 ['198.764', '13.500', '0.523'] ['198.764', '13.500', '0.523', '-0.000', '-0.000', '-0.000', '-0.000'] ['198.764', '13.500', '0.523', '0.000', '0.000', '-0.000', '-0.000'] M: 15 ['198.764', '13.500', '0.523'] ['294.451', '13.500', '-0.061', '0.000', '-0.001', '-0.000', '-0.000'] ['198.764', '13.500', '0.523', '0.000', '0.000', '0.000', '-0.000'] M: 20 ['198.764', '13.500', '0.523'] ['369.135', '13.500', '-0.046', '0.000', '-0.000', '-0.000', '-0.000'] ['198.764', '13.500', '0.523', '0.000', '0.000', '-0.000', '-0.000'] </code></pre> <p>The values of the polynomial fit gives wrong values for N > 5 and for M > 13.</p> <p>Where am I going wrong? What is different in the polyfit implementation?</p>
<p><code>A</code> is of dtype <code>int32</code>. </p> <p>The maximum value representable is:</p> <pre><code>In [10]: np.iinfo(np.dtype('int32')).max Out[10]: 2147483647 </code></pre> <p>When the exponent is very large, <code>n**i</code> can become larger than 2147483647. At this point you get an incorrect result.</p> <p><a href="http://comments.gmane.org/gmane.comp.python.numeric.general/29300" rel="nofollow">NumPy does not check for arithmetic overflows</a> (when performing operations on arrays) since this would hinder performance. It is up to you to select a dtype which avoids arithmetic overflow.</p> <p>To fix the problem, declare a different dtype which can represent larger numbers:</p> <pre><code>A = np.matrix([[n**i for i in nArray] for n in x], dtype='float64') </code></pre> <p>Note that the problem still exists, it will just occur at a much larger value of <code>N</code>.</p>
python|numpy
4
1,906,172
73,131,992
Problem with replacing tick marks on the x axis using bar plot
<p>I'm trying to graph this bar graph using <code>plt.bar</code> . This is my code</p> <pre><code>x_axis = np.arange(0,len(drug_name)) tick_locations = [] for x in x_axis: tick_locations.append(x) plt.bar(x_axis, total_tp_per_drug, facecolor = &quot;orangered&quot;, alpha = 0.75, align = &quot;center&quot;) plt.xticks(tick_locations, drug_name) plt.show() </code></pre> <p>Everything is perfect except for when I'm trying to replace the tick marks on the x axis with the drug name labels it's not doing it. Can someone help me?</p> <p>This is what's in <code>drug_name</code></p> <p><a href="https://i.stack.imgur.com/sgIH8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sgIH8.png" alt="enter image description here" /></a></p> <p>and this is the output</p> <p><a href="https://i.stack.imgur.com/yv1lW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yv1lW.png" alt="enter image description here" /></a></p>
<p>The drug names are there, in your bar chart, but the default orientation is horizontal, so they're overlapping and unreadable. Try rotating the labels:</p> <pre><code>plt.xticks(tick_locations, drug_name, rotation=90) </code></pre> <p>(<code>rotation=45</code> would put them at an angle and might make them more readable)</p>
python|pandas|matplotlib|plot|bar-chart
1
1,906,173
66,446,441
Plotly legend click event
<p>For a plotly graph (plotly express scatter, for example), how can I trigger an event/function/callback when I click on an item in the legend of that graph? Specifically, my purpose is to change the colors of the points in the graph by clicking the legend. Thank you in advance!</p>
<p>Based on this thread: <a href="https://community.plotly.com/t/hide-a-component-with-one-event-and-make-it-visible-with-another/19290" rel="nofollow noreferrer">https://community.plotly.com/t/hide-a-component-with-one-event-and-make-it-visible-with-another/19290</a> I use the following callback:</p> <pre><code>@app.callback(Output('your_figure_id', 'figure'), [Input('your_figure_id', 'restyleData')]) def update(x): #modify/create new figure as you wish, x contains the legend entry you clicked return figure </code></pre> <p>Since the input and output figure id is the same this callback will update the oeiginal figure, if you want to keep the input figure as it is, you just have to give another output id.</p>
python|plotly|plotly-dash|plotly-python|ggplotly
0
1,906,174
52,918,107
tensorflow tf.maximum(0, x) returns error
<p>When trying to use <code>tf.maximum</code> as one would expect:</p> <pre><code>loss = tf.maximum(0, basic_loss) </code></pre> <p>this error is obtained</p> <blockquote> <p>--------------------------------------------------------------------------- ValueError Traceback (most recent call last) /opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py in apply_op(self, op_type_name, name, **keywords) 489 as_ref=input_arg.is_ref, --> 490 preferred_dtype=default_dtype) 491 except TypeError as err:</p> <p>/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in internal_convert_to_tensor(value, dtype, name, as_ref, preferred_dtype) 740 if ret is None: --> 741 ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref) 742 </p> <p>/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py in _TensorTensorConversionFunction(t, dtype, name, as_ref) 613 "Tensor conversion requested dtype %s for Tensor with dtype %s: %r" --> 614 % (dtype.name, t.dtype.name, str(t))) 615 return t</p> <p>ValueError: Tensor conversion requested dtype int32 for Tensor with dtype float32: 'Tensor("add_13:0", shape=(), dtype=float32)'</p> <p>During handling of the above exception, another exception occurred:</p> <p>TypeError Traceback (most recent call last) in () 5 tf.random_normal([3, 128], mean=1, stddev=1, seed = 1), 6 tf.random_normal([3, 128], mean=3, stddev=4, seed = 1)) ----> 7 loss = triplet_loss(y_true, y_pred) 8 9 print("loss = " + str(loss.eval()))</p> <p> in triplet_loss(y_true, y_pred, alpha) 26 basic_loss = pos_dist - neg_dist + alpha 27 # Step 4: Take the maximum of basic_loss and 0.0. Sum over the training examples. ---> 28 loss = tf.maximum(0, basic_loss) 29 ### END CODE HERE ### 30 </p> <p>/opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/gen_math_ops.py in maximum(x, y, name) 1261 A <code>Tensor</code>. Has the same type as <code>x</code>. 1262 """ -> 1263 result = _op_def_lib.apply_op("Maximum", x=x, y=y, name=name) 1264 return result 1265 </p> <p>/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py in apply_op(self, op_type_name, name, **keywords) 524 "%s type %s of argument '%s'." % 525 (prefix, dtypes.as_dtype(attrs[input_arg.type_attr]).name, --> 526 inferred_from[input_arg.type_attr])) 527 528 types = [values.dtype]</p> <p>TypeError: Input 'y' of 'Maximum' Op has type float32 that does not match type int32 of argument 'x'.</p> </blockquote> <p>What seems to be the problem?</p>
<p><a href="https://www.tensorflow.org/api_docs/python/tf/math/maximum" rel="nofollow noreferrer">The tensor flow doc</a> does not state that the <code>maximum</code> function is <strong>non-commutative</strong>. </p> <p>It works only if the type of the 1st argument is a Tensor, but not if its type is int.</p> <p>Need to call this function with replaced positions of the arguments for constants:</p> <p><code>tf.maximum(basic_loss, 0)</code></p> <p>instead of</p> <p><code>tf.maximum(0, basic_loss)</code></p>
tensorflow
4
1,906,175
52,953,736
Adding axes to polar plot with matplotlib
<p>I know it should be as simple as hell, but actually I can't figure out how to add an additional axis (let's say at 22.5°) on a polar graph. What I actually have is <img src="https://i.stack.imgur.com/buuSO.png" alt="this">, while I would like to obtain something like <img src="https://i.stack.imgur.com/5lDhO.png" alt="this"> (obviously not in red, is just to emphasize).</p> <p>Here is part of the code I'm using:</p> <pre><code> ax = plt.subplot(111, projection='polar') ax.set_theta_zero_location("N") ax.set_theta_direction(-1) r = np.array(...) t = [] theta = np.array(...) ax.plot(theta, r) max_value = np.amax(out) ax.set_rmax(max_value) ax.set_rticks([int(max_value/5), int(max_value*2/5),int(max_value*3/5), int(max_value*4/5)]) # ax.set_rlabel_position(-22.5) ax.grid(True) </code></pre> <p>Thanks in advance for your support!</p>
<p>You can use <code>set_thetagrids</code> see the definition at <a href="https://matplotlib.org/api/projections_api.html" rel="nofollow noreferrer">https://matplotlib.org/api/projections_api.html</a></p> <p>in your case</p> <pre><code>ax = plt.subplot(111, projection='polar') ax.set_theta_zero_location("N") ax.set_theta_direction(-1) r = np.array([33, 22,50,15]) t = [] theta = np.array([33, 22,50,15]) ax.plot(theta, r) max_value = np.amax(r) ax.set_rmax(max_value) ax.set_rticks([int(max_value / 5), int(max_value * 2 / 5), int(max_value * 3 / 5), int(max_value * 4 / 5)]) ax.set_thetagrids(np.arange(0, 360, 22.5)) # ax.set_rlabel_position(-22.5) ax.grid(True) plt.show() </code></pre> <p><a href="https://i.stack.imgur.com/caBBD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/caBBD.png" alt="result image"></a></p>
python|matplotlib
0
1,906,176
67,573,874
Convert excel file to PDF using Python (MacOS) while retaining source formatting
<p>I am working on a task to automate the conversion of an excel file to a PDF using Python. I was able to achieve this by:</p> <ol> <li>Converting the raw excel data (based on a defined range) into a pandas data frame.</li> <li>Converting the data frame to an HTML file (intermediate step).</li> <li>Converting the HTML file to a PDF.</li> </ol> <p>I am doing this in the MacOS and it is working as expected. Code for reference:</p> <pre><code>from openpyxl import load_workbook import pdfkit as pdf import pandas as pd wb = load_workbook(filename = '4-Grain Advertising Report.xlsx', read_only = True, data_only=True) ws = wb['Advertising 4 Grain P&amp;L'] data_rows = [] for row in ws['K9':'S31']: data_cols = [] for cell in row: data_cols.append(cell.value) data_rows.append(data_cols) df = pd.DataFrame(data_rows) df = df.replace([None], [''], regex = True) df.to_html('test.html', header=None, index=False) output = 'test_output.pdf' pdf.from_file('test.html', output) </code></pre> <p>However, I am unable to retain the formatting options (for example - cell coloring / bold headers etc.) that were set in the original excel spreadsheet if I follow this method. This gives me a raw table with the values in PDF format.</p> <p>Any recommendations on how I can retain the source formatting and automate the conversion to PDF via Python would be really helpful. Thanks!</p>
<p>You won't be able to retain the formatting using Pandas. It does not support styles at all. You can try use other tools like <a href="https://blog.aspose.com/2021/04/02/convert-excel-files-to-pdf-in-python/" rel="nofollow noreferrer">this</a>.</p>
python|python-3.x|excel
1
1,906,177
60,474,172
List of Column names having at least 1 Null value and total number of null values corresponding to each column pandas
<p>Hi I have a code which prints column names along with null values in columns:</p> <pre><code>A B C D 1 1 4 NAN 2 2 5 NAN 3 NAN 6 NAN </code></pre> <p><strong>My Code</strong></p> <pre><code>[IN]res = list(df.isnull().sum().items()) [IN]print(res) </code></pre> <p><strong>Current Output</strong></p> <pre><code>[('A', 0), ('B', 1), ('C', 0), ('D', 3)] </code></pre> <p><strong>Expected output:</strong></p> <pre><code>[('B', 1), ('D', 3)] </code></pre> <p>So basically I wish to remove columns where there are 0 null values and <strong>return only columns with at least 1 null value.</strong></p>
<p>First idea is use <a href="http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#boolean-indexing" rel="nofollow noreferrer"><code>boolean indexing</code></a>:</p> <pre><code>s = df.isnull().sum() res = list(s[s &gt; 0].items()) print (res) [('B', 1), ('D', 3)] </code></pre> <p>Or filter using <a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#selection-by-callable" rel="nofollow noreferrer"><code>callable</code></a>:</p> <pre><code>res = list(df.isnull().sum()[lambda x: x &gt; 0].items()) </code></pre> <p>Or filter in list comprehension:</p> <pre><code>res = [(k, v) for k, v in df.isnull().sum().items() if v &gt; 0] </code></pre>
python|pandas|numpy|null
2
1,906,178
60,851,508
random iteration over the items of the list
<p>I want to iterate randomly over some given items in my list for example:</p> <pre><code>items = ['rock', 'paper', 'scissors'] for item in items: print(random.shuffle(items)) </code></pre> <p>I want in each iteration it splits out a random item from my list but everytime it gives 'None' </p>
<p><code>random.shuffle()</code> shuffles the list in-place and it returns <code>None</code>.</p> <p>You need to:</p> <pre><code>import random items = ['rock', 'paper', 'scissors'] for item in random.sample(items,3): # get list of n=3 random shuffled values no dupes print(item) # or random.shuffle(items) # shuffle in place (might get the same order as well) for item in items: print(item) </code></pre> <p>See differences between:</p> <ul> <li><a href="https://docs.python.org/3.8/library/random.html#random.shuffle" rel="nofollow noreferrer">https://docs.python.org/3.8/library/random.html#random.shuffle</a> (in place)</li> <li><a href="https://docs.python.org/3.8/library/random.html#random.sample" rel="nofollow noreferrer">https://docs.python.org/3.8/library/random.html#random.sample</a> (no dupes)</li> <li><a href="https://docs.python.org/3.8/library/random.html#random.choices" rel="nofollow noreferrer">https://docs.python.org/3.8/library/random.html#random.choices</a> (maybe dupes)</li> </ul>
python-3.x
3
1,906,179
60,861,495
Process Pool unreliable, it either gets stuck or it runs fine
<p>Hello and thanks for your help :) </p> <p>The program I was writing basically disassembles executables. I just wanted to see if I could make it faster by using <code>pathos</code>. The problem is that it does not run reliably. I'll explain in a second what I mean by <em>reliable</em>.</p> <p>The program is run like this:</p> <pre class="lang-py prettyprint-override"><code>from ControlFlow import Disassembler, DisassemblerWorker from ControlFlow import FlowGraph import networkx as nx import time file_path = "/vagrant/SimpleTestBinaries/example3-x64" start = time.time() flow = Disassembler(file_path) graph = FlowGraph(flow) end = time.time() print("Finished in: ", end - start, " seconds") </code></pre> <p>Normally it would reply with:</p> <pre><code>Finished in: 0.8992343274389473 seconds </code></pre> <p>But sometimes it just seems like it is stuck. After all, as you can see above it should take less than a second. So I proceed to kill it and it gives me a bunch of errors, which maybe hints where it's getting stuck.</p> <pre><code>Process ForkPoolWorker-11: Process ForkPoolWorker-13: Process ForkPoolWorker-10: Traceback (most recent call last): Traceback (most recent call last): Process ForkPoolWorker-12: File "/usr/local/lib/python3.6/dist-packages/multiprocess/process.py", line 258, in _bootstrap self.run() Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/multiprocess/process.py", line 258, in _bootstrap self.run() Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/multiprocess/process.py", line 258, in _bootstrap self.run() File "/usr/local/lib/python3.6/dist-packages/multiprocess/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/dist-packages/multiprocess/pool.py", line 108, in worker task = get() File "/usr/local/lib/python3.6/dist-packages/multiprocess/queues.py", line 337, in get with self._rlock: File "/usr/local/lib/python3.6/dist-packages/multiprocess/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/dist-packages/multiprocess/process.py", line 258, in _bootstrap self.run() File "/usr/local/lib/python3.6/dist-packages/multiprocess/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/dist-packages/multiprocess/process.py", line 93, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.6/dist-packages/multiprocess/pool.py", line 108, in worker task = get() File "/usr/local/lib/python3.6/dist-packages/multiprocess/synchronize.py", line 101, in __enter__ return self._semlock.__enter__() File "/usr/local/lib/python3.6/dist-packages/multiprocess/pool.py", line 108, in worker task = get() File "/usr/local/lib/python3.6/dist-packages/multiprocess/pool.py", line 108, in worker task = get() File "/usr/local/lib/python3.6/dist-packages/multiprocess/queues.py", line 337, in get with self._rlock: File "/usr/local/lib/python3.6/dist-packages/multiprocess/synchronize.py", line 101, in __enter__ return self._semlock.__enter__() File "/usr/local/lib/python3.6/dist-packages/multiprocess/queues.py", line 337, in get with self._rlock: KeyboardInterrupt File "/usr/local/lib/python3.6/dist-packages/multiprocess/queues.py", line 338, in get res = self._reader.recv_bytes() File "/usr/local/lib/python3.6/dist-packages/multiprocess/synchronize.py", line 101, in __enter__ return self._semlock.__enter__() KeyboardInterrupt File "/usr/local/lib/python3.6/dist-packages/multiprocess/connection.py", line 219, in recv_bytes buf = self._recv_bytes(maxlength) KeyboardInterrupt File "/usr/local/lib/python3.6/dist-packages/multiprocess/connection.py", line 410, in _recv_bytes buf = self._recv(4) File "/usr/local/lib/python3.6/dist-packages/multiprocess/connection.py", line 382, in _recv chunk = read(handle, remaining) KeyboardInterrupt --------------------------------------------------------------------------- KeyboardInterrupt Traceback (most recent call last) in 6 file_path = "/vagrant/SimpleTestBinaries/example3-x64" 7 start = time.time() ----&gt; 8 flow = Disassembler(file_path) 9 graph = FlowGraph(flow) 10 end = time.time() /vagrant/BinaryResearch/ControlFlow.py in __init__(self, path) 34 self.regs_write_map = {} 35 self.section_map = {} ---&gt; 36 self._analyze_flow() 37 38 def disassembler_setup(self, architecture, details=True): /vagrant/BinaryResearch/ControlFlow.py in _analyze_flow(self) 77 jumps = p.amap(worker.get_jump_map, imagebase) 78 returns = p.amap(worker.get_return_map, imagebase) ---&gt; 79 p.close(), p.join() 80 81 call_results, jump_results, return_results = calls.get()[0], jumps.get()[0], returns.get()[0] /usr/local/lib/python3.6/dist-packages/pathos/multiprocessing.py in join(self) 206 _pool = __STATE.get(self._id, None) 207 if _pool and self.__nodes == _pool.__nodes: --&gt; 208 _pool.join() 209 return 210 # interface /usr/local/lib/python3.6/dist-packages/multiprocess/pool.py in join(self) 544 util.debug('joining pool') 545 assert self._state in (CLOSE, TERMINATE) --&gt; 546 self._worker_handler.join() 547 self._task_handler.join() 548 self._result_handler.join() /usr/lib/python3.6/threading.py in join(self, timeout) 1054 1055 if timeout is None: -&gt; 1056 self._wait_for_tstate_lock() 1057 else: 1058 # the behavior of a negative timeout isn't documented, but /usr/lib/python3.6/threading.py in _wait_for_tstate_lock(self, block, timeout) 1070 if lock is None: # already determined that the C code is done 1071 assert self._is_stopped -&gt; 1072 elif lock.acquire(block, timeout): 1073 lock.release() 1074 self._stop() KeyboardInterrupt: </code></pre> <p>So, I went to check the portion of code that it is referencing. I don't know if this means that it is getting stuck somewhere between the <code>p.close()</code> and <code>p.join()</code>. This is the snippet within <code>ControlFlow.py</code> that it points to.</p> <pre class="lang-py prettyprint-override"><code>from pathos.multiprocessing import ProcessPool # More code ... p = ProcessPool() for section in available_sections: worker = DisassemblerWorker(self.architecture, section.content, section.virtual_address) p.clear() calls = p.amap(worker.get_call_map, imagebase) jumps = p.amap(worker.get_jump_map, imagebase) returns = p.amap(worker.get_return_map, imagebase) p.close(), p.join() call_results, jump_results, return_results = calls.get()[0], jumps.get()[0], returns.get()[0] # More code ... </code></pre> <p>So I really don't know what it is causing it to be unreliable. I know this sounds crazy but once the program has it's first "success" it seems to run fine afterwards. Also, I should say that I am running this in a Jupyter Notebook. I've read that <code>multiprocessing</code> is incompatible with notebooks so I'm using <code>multiprocess</code> instead. </p> <p>Any ideas as to what is going on?</p> <p>Thanks once again!</p>
<p>I have had the same issue with the underlying python multiprocessing library (Pool): works great many times, and sometimes seems to get stuck.</p> <p>The documentation points at the requirement to have the method you call with pool outside the call multiprocessing it. <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow noreferrer">https://docs.python.org/2/library/multiprocessing.html</a></p> <p>In practice, if seems you need to define your method outside the if main. I don't know why the behaviour appears inconsistent, but following the guideline made it work in some cases for me.</p> <p>I found yet other cases that didn't work, and the ultimate solution seems to be to write the methods you parallelise in a separate file. I found this last bit in the question below, and that solved it for me: <a href="https://stackoverflow.com/questions/47313732/jupyter-notebook-never-finishes-processing-using-multiprocessing-python-3">Jupyter notebook never finishes processing using multiprocessing (Python 3)</a></p> <p>Below is an example of having your function <code>f</code> in a separate file, and outside the main.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>**file 1: my_methods.py** def f(x): return x.count() **file 2: main.py or your jupyter notebook, in the same directory here** import multiprocessing as mp from my_methods import f def parallelize(df, func, n_cores=4): df_split = np.array_split(df, n_cores) pool = mp.Pool(n_cores) df = pd.concat(pool.map(func, df_split)) pool.close() pool.join() return df if __name__ == '__main__': output = parallelize( df=chosen_input_dataframe, func = f, n_cores=4, ) print(output)</code></pre> </div> </div> </p>
python|jupyter-notebook|multiprocessing|multiprocess|pathos
0
1,906,180
66,293,889
Pygame Output : Black Background
<p>I want to view my <code>blit()</code> however once i add the line <code>self.screen_dim.fill([255, 255, 255])</code> <code>pygame.display.update()</code> it overlaps</p> <pre><code>def __init__(self): self.width = 500 self.height = 500 self.screen_dim = pygame.display.set_mode((self.width, self.height)) self.mole = pygame.image.load(&quot;mole.png&quot;) self.mole_hit = pygame.image.load(&quot;mole-hit.png&quot;) </code></pre> <p>I am confused on how to get my pygame screen the images within that function is working however it overlaps if i added a new background color</p> <pre><code>def start(self): stat = True num_display = 1 x_array = [] y_array = [] for i in self.mole_pos: x_array.append(i[0]) y_array.append(i[1]) while stat: Rand_Pos = random.randint(0, 8) if num_display == 1: self.screen_dim.blit(self.mole, (x_array[Rand_Pos], y_array[Rand_Pos])) for Event in pygame.event.get(): if Event.type == pygame.QUIT: stat = False if self.mouse_clicked(mouse.get_pos(), self.mole_pos[Rand_Pos]): num_display = 0 self.screen_dim.blit(self.mole_hit, (x_array[Rand_Pos], y_array[Rand_Pos])) continue pygame.display.flip() </code></pre>
<p>This ahs nothing to to with <code>class</code>. It is just a matter of <a href="https://docs.python.org/3/reference/lexical_analysis.html" rel="nofollow noreferrer">Indentation</a>. You have to draw <code>self.mole_hit</code> in the application loop rather than the event loop:</p> <pre class="lang-py prettyprint-override"><code>def start(self): # [...] while stat: # [...] for Event in pygame.event.get(): if Event.type == pygame.QUIT: stat = False #&lt;--| INDENTATION if self.mouse_clicked(mouse.get_pos(), self.mole_pos[Rand_Pos]): num_display = 0 self.screen_dim.blit(self.mole_hit, (x_array[Rand_Pos], y_array[Rand_Pos])) pygame.display.flip() </code></pre>
python|pygame
0
1,906,181
59,082,151
Why are tensorflow sessions and graph so difficult to understand?
<p>I am new to tensorflow, and need to use some legacy code to finish a project. I use PyTorch before. I feel so difficult to understand TensorFlow. I use 1.14.0 version.<br> 1. I use Jupyter Notebook. When I create some operations, sometimes I need to same cell multi times due to debug. Then I find it my graph is very weird. What happened when I run these cells which create some ops in the graph multi times? It cause my confusion about graph and sessions. From my current understanding, I need to build a static graph to run code. So what the purpose of sessions? When I in Jupyter, I find something wrong and edit the runned code, do I need to reset the graph and sessions?<br> 2. Debug is a disaster. When there is something wrong with the dimension. Tensorflow has some long complains but never tell me why go wrong. I need to look carefully to find out out errors.<br> 3. It seems API has changed greatly. I always recieved some warning, these interfacees has be degraded.<br> 4. Print something is hard. I need to call <code>sess.run</code> to get a list. Or add <code>tf.summary</code> op in the graph to run and see it in tensorboard. </p> <p>I am deal with those old code. What is the correct way to use Tensorflow? I love the convinence brought by PyTorch. I can set some breakpoint and print anything I need easily. I want to do the samething with Tensorflow. Debugin Tensorflow waste me so much time. Is this true that only utils I flush my graph and open tensorboard can I see my computation graph? It is really unconvinient. </p>
<p>TLDR: Though early versions of TensorFlow are hard to use, TensorFlow 2.0 is much better and has moved towards more dynamic graphs with features like AutoGraph. So don't be discouraged to use TensorFlow.</p> <blockquote> <ol> <li>I use Jupyter Notebook. When I create some operations, sometimes I need to same cell multi times due to debug. Then I find it my graph is very weird. What happened when I run these cells which create some ops in the graph multi times? It cause my confusion about graph and sessions. From my current understanding, I need to build a static graph to run code. So what the purpose of sessions? When I in Jupyter, I find something wrong and edit the runned code, do I need to reset the graph and sessions?</li> </ol> </blockquote> <p>Graph is the computational graph you build. TensorFlow uses GraphDef format to represent the graph. Essentially when you write,</p> <pre><code>tf_a = tf.placeholder(dtype=tf.float32) tf_b = tf.placeholder(dtype=tf.float32) tf_c = tf_a + (2.0 * tf_b) </code></pre> <p>TensorFlow builds the following graph in the background.</p> <pre><code> tf_a tf_b tf_constant(2) \ \ / \ tf.mul \ / tf.add | tf_c </code></pre> <p>It just sits there and does not execute anything. That's why if you try to run print(tf_c) you won't see anything.</p> <p>The session goes in, looks at the graph and execute bits and pieces of that graph. For example, when you say <code>sess.run(tf_c, feed_dict={tf_a:2.0, tf_b: 3.0})</code>. The session manager will look at the graph, understand that you need to feed values to both <code>tf_a</code> and <code>tf_b</code> to successfully evaluate <code>tf_c</code> and check if those values are provided and continues to execute the graph and fetch <code>tf_c</code>.</p> <p>And if you want to rerun your code without blowing up your computational graph, you should use <code>tf.reset_defualt_graph()</code> at the beginning of the cell. This will clean up the graph. Otherwise, you will keep adding items to the graph and even end up with errors (e.g trying to create a variable with same name twice).</p> <p>Having said that TensorFlow 2.0 is much better. TensorFlow 2.0 has got rid of the concept of sessions and immediately executes things as you call them.</p> <blockquote> <ol start="2"> <li>Debug is a disaster. When there is something wrong with the dimension. Tensorflow has some long complains but never tell me why go wrong. I need to look carefully to find out out errors.</li> </ol> </blockquote> <p>Can't say much here. But when you get used to it, it gets easier (at least that's my personal experience). </p> <p>However, in TensorFlow 2.0 you can debug in real time using a preferred debugger, as operations and tensors are executed immediately as they are called.</p> <blockquote> <ol start="3"> <li>It seems API has changed greatly. I always recieved some warning, these interfacees has be degraded.</li> </ol> </blockquote> <p>Yes, TensorFlow is evolving quite rapidly. And did went though some major design changes over the years.</p> <blockquote> <ol start="4"> <li>Print something is hard. I need to call sess.run to get a list. Or add tf.summary op in the graph to run and see it in tensorboard.</li> </ol> </blockquote> <p>That's how TensorFlow was designed. The reason is that having a static graph requires less complexity than dynamically building the graph. If the graph was build dynamically it does have to parse pythonic syntax (e.g. For loops / while loops / if else conditions) to infer the flow of data. And on top of that make sure the graph doesn't grow abitarily large (e.g. expanding a for loop).</p> <p>I'm sure there are performance differences as well. But I haven't tested nor competent enough to elaborate on that.</p> <p>This is my take on your questions. Hope it clears things up.</p>
tensorflow|deep-learning
2
1,906,182
59,384,199
Fool-proof algorithm for uniformly distributing points on a sphere's surface?
<p>I've been trying to generate points on the surface of a sphere of radius "inner_radius", such that they're uniformly spread out. The algorithm works as expected for a radius of 1, but generates lesser than expected points for greater radii. I have looked through similar questions on here, but they seem to be for generating points throughout the volume and not just on the surface of the sphere.</p> <pre><code>import numpy as np PI=np.pi def spherical_to_cartesian(pol_ang,azim_ang,radius): #This function converts given spherical coordinates (theta, phi and radius) to cartesian coordinates. return np.array((radius*np.sin(pol_ang) * np.cos(azim_ang), radius*np.sin(pol_ang) * np.sin(azim_ang), radius*np.cos(pol_ang)) ) def get_electron_coordinates_list(inner_radius,electron_count): #Algorithm used was mostly taken from https://www.cmu.edu/biolphys/deserno/pdf/sphere_equi.pdf . Explanations in code added by me. electron_coordinate_list=[] inner_area=4*(PI*inner_radius**2) area_per_electron=inner_area/electron_count pseudo_length_per_electron=np.sqrt(area_per_electron) #This is the side length of a square where the area of it is the area per electron on the sphere. #Now, we need to get a value of angular space, such that angular space between electrons on latitude and longitude per electron is equal #As a first step to obtaining this, we must make another value holding a whole number approximation of the ratio between PI and the pseudo_length. This will give the number of #possible latitudes. possible_count_of_lats=np.round(PI/pseudo_length_per_electron) approx_length_per_electron_lat=PI/possible_count_of_lats #This is the length between electrons on a latitude approx_length_per_electron_long=area_per_electron/approx_length_per_electron_lat #This is the length between electrons on a longitude for electron_num_lat in range(int(possible_count_of_lats.item())): #The int(somenumpyvalue.item()) is used because Python cannot iterate over a numpy integer and it must be converted to normal int. pol_ang=PI*(electron_num_lat+0.5)/possible_count_of_lats #The original algorithm recommended pol_ang=PI*(electron_num_lat+0.5)/possible_count_of_lats. The 0.5 appears to be added in order to get a larger number of coordinates. #not sure if removing the 0.5 affects results. It didnt do so drastically, so what gives? Anyway, this gets the polar angle as PI*(latitudenumber)/totalnumberoflatitudes. possible_count_of_longs=np.round(2*PI*np.sin(pol_ang)/approx_length_per_electron_long) for electron_num_long in range(int(possible_count_of_longs.item())): azim_ang=(2*PI)*(electron_num_long)/possible_count_of_longs #This gets the azimuthal angle as 2PI*longitudenumber/totalnumberoflongitudes electron_coordinate=spherical_to_cartesian(pol_ang, azim_ang,inner_radius) #Converts the recieved spherical coordinates to cartesian so Manim can easily handle them. electron_coordinate_list.append(electron_coordinate) #Add this coordinate to the electron_coordinate_list print("Got coordinates: ",electron_coordinate) #Print the coordinate recieved. print(len(electron_coordinate_list)," points generated.") #Print the amount of electrons will exist. Comment these two lines out if you don't need the data. return electron_coordinate_list get_electron_coordinates_list(1,100) get_electron_coordinates_list(2,100) </code></pre> <p>Spherical_to_Cartesian() does nothing other than convert the spherical points to Cartesian.</p> <p>For 100 points and radius 1, it generates 99 points. But, only 26 points are made if the radius is 2 and 100 points are requested.</p>
<p>If you can generate points uniformly in the sphere's volume, then to get a uniform distribution on the sphere's surface, you can simply normalize the vectors so their radius equals the sphere's radius.</p> <p>Alternatively, you can use the fact that independent identically-distributed normal distributions are <a href="https://en.wikipedia.org/wiki/Maxwell%27s_theorem" rel="nofollow noreferrer">rotationally-invariant</a>. If you sample from 3 normal distributions with mean 1 and standard deviation 0, and then likewise normalize the vector, it will be uniform on the sphere's surface. Here's an example:</p> <pre class="lang-py prettyprint-override"><code>import random def sample_sphere_surface(radius=1): x, y, z = (random.normalvariate(0, 1) for i in range(3)) scalar = radius / (x**2 + y**2 + z**2) ** 0.5 return (x * scalar, y * scalar, z * scalar) </code></pre> <p>To be <em>absolutely</em> foolproof, we can handle the astronomically unlikely case of a division-by-zero error when <code>x</code>, <code>y</code> and <code>z</code> all happen to be zero:</p> <pre class="lang-py prettyprint-override"><code>def sample_sphere_surface(radius=1): while True: try: x, y, z = (random.normalvariate(0, 1) for i in range(3)) scalar = radius / (x**2 + y**2 + z**2) ** 0.5 return (x * scalar, y * scalar, z * scalar) except ZeroDivisionError: pass </code></pre>
python|numpy|computational-geometry
2
1,906,183
58,652,491
How do you make a car move in the direction it is facing? (Using python and turtle graphics)
<p>I am building a simple python game using turtle graphics that is a car that goes around a track. I have built the track and the car, and I know how to turn the car in different directions, but I don't know how to get the car to move in the specific direction that it is facing. Does anyone have any ideas? This is what I have so far:</p> <pre><code> import turtle #Screen wn = turtle.Screen() wn.title('Car') wn.bgcolor('black') wn.setup(width=1200, height=1200) wn.tracer(0) #Track track = turtle.Turtle() track.color('white') track.speed(0) track.penup() track.goto(-550, 0) track.pendown() track.goto(-550, 300) track.goto(-100,370) track.goto(100, 210) track.goto(300, 380) track.goto(580, 100) track.goto(570, -300) track.goto(300, -370) track.goto(0, -250) track.goto(-300, -200) track.goto(-570, -250) track.goto(-550, 0) track.hideturtle() #Track 2 track2 = turtle.Turtle() track2.color('white') track2.speed(0) track2.penup() track2.goto(-450, 0) track2.pendown() track2.goto(-450, 230) track2.goto(-150, 250) track2.goto(100, 100) track2.goto(300, 200) track2.goto(460, 100) track2.goto(450, -220) track2.goto(300, -250) track2.goto(0, -130) track2.goto(-300, -100) track2.goto(-450, 0) track2.hideturtle() #Start line line = turtle.Turtle() line.color('white') line.speed(0) line.penup() line.goto(-550, 0) line.pendown() line.goto(-450,0) line.hideturtle() #Car car = turtle.Turtle() car.color('red') car.speed(0) car.penup() car.shape('square') car.shapesize(stretch_wid=1, stretch_len=2) car.goto(-500, 0) car.setheading(90) #Move car def turn_right(): car.right(20) def turn_left(): car.left(20) #Key Bindings wn.listen() wn.onkey(turn_right, 'd') wn.onkey(turn_left, 'a') while True: wn.update() turtle.mainloop() </code></pre>
<p>The simple answer is to change this:</p> <pre><code>while True: wn.update() </code></pre> <p>to instead be:</p> <pre><code>while True: car.forward(1) wn.update() </code></pre> <p>and you'll find your car moves foward and requires you to steer it to stay on the track. The more complicated answer is that <code>while True:</code> has no business in an event-driven environment like turtle and that what you need is a timer event:</p> <pre><code>from turtle import Screen, Turtle, mainloop # Move car def turn_right(): car.right(20) def turn_left(): car.left(20) def move(): car.forward(1) screen.update() screen.ontimer(move, 25) # Screen screen = Screen() screen.title('Car') screen.bgcolor('black') screen.setup(width=1200, height=1200) screen.tracer(0) # Track track = Turtle() track.hideturtle() track.color('white') track.penup() track.goto(-550, 0) track.pendown() track.goto(-550, 300) track.goto(-100, 370) track.goto(100, 210) track.goto(300, 380) track.goto(580, 100) track.goto(570, -300) track.goto(300, -370) track.goto(0, -250) track.goto(-300, -200) track.goto(-570, -250) track.goto(-550, 0) track.penup() track.goto(-450, 0) track.pendown() track.goto(-450, 230) track.goto(-150, 250) track.goto(100, 100) track.goto(300, 200) track.goto(460, 100) track.goto(450, -220) track.goto(300, -250) track.goto(0, -130) track.goto(-300, -100) track.goto(-450, 0) # Start line line = Turtle() line.hideturtle() line.color('white') line.penup() line.setx(-550) line.pendown() line.setx(-450) # Car car = Turtle() car.shape('square') car.shapesize(stretch_wid=1, stretch_len=2) car.color('red') car.setheading(90) car.penup() car.setx(-500) # Key Bindings screen.onkey(turn_right, 'd') screen.onkey(turn_left, 'a') screen.listen() move() mainloop() </code></pre>
python|python-2.7|turtle-graphics
0
1,906,184
31,367,097
How to restore the index of a QComboBox delegate in a QTableView?
<p>There is a <code>QTableView()</code>, one of it's column is filled with <code>QComboBox</code>es. The question is how to select item in combobox that is in <code>QTableView()</code> according to data taken from dictionary</p> <p>I see that I should apply <code>self.combo.setCurrentIndex(self.combo.findText( status_str))</code> but can't understand how to get that variable <code>status_str</code> in <code>comboBox</code> or place in code where to apply it. Also I cannot understand how make <code>comboBox</code> appear only after double clicking. If cell was not double clicked it must looks like any other cell.</p> <p>The sample of code:</p> <pre><code>data = {"first":{"status":"closed"},"second":{"status":"expired"},"third":{ "status":"cancelled"}} class ComboDelegate(QItemDelegate): def __init__(self, parent): QItemDelegate.__init__(self, parent) def paint(self, painter, option, index): self.combo = QComboBox(self.parent()) li = [] li.append("closed") li.append("expired") li.append("cancelled") li.append("waiting") self.combo.addItems(li) #self.combo.setCurrentIndex(self.combo.findText( status_str )) if not self.parent().indexWidget(index): self.parent().setIndexWidget( index, self.combo ) class TableView(QTableView): def __init__(self, *args, **kwargs): QTableView.__init__(self, *args, **kwargs) self.setItemDelegateForColumn(1, ComboDelegate(self)) class MainFrame(QWidget): def __init__(self): QWidget.__init__(self) table = TableView(self) self.model = QStandardItemModel() table.setModel(self.model) MainWindow = QVBoxLayout() MainWindow.addWidget(table) self.setLayout(MainWindow) self.fillModel() def fillModel(self): for i in data: print i name_str = i status_str = data[i]["status"] name = QStandardItem(name_str) status = QStandardItem(status_str) items = [name, status] self.model.appendRow(items) if __name__ == "__main__": app = QApplication(sys.argv) main = MainFrame() main.show() main.move(app.desktop().screen().rect().center() - main.rect().center()) sys.exit(app.exec_()) </code></pre>
<p>Overriding <code>QItemDelegate.paint</code> is not the recommended method for creating a delegate. <code>QItemDelegate</code> has methods such as <code>createEditor</code> and <code>setEditorData</code> which you should override instead. These methods are called appropriately by Qt.</p> <p>In <code>createEditor</code> you should create your <code>comboBox</code>, and return it. For example:</p> <pre><code>def createEditor(self, parent, option, index): editor = QComboBox(parent) li = [] li.append("closed") li.append("expired") li.append("cancelled") li.append("waiting") editor.addItems(li) return editor </code></pre> <p>In <code>setEditorData</code> you query your model for the current index of the combobox. This will be called For example:</p> <pre><code>def setEditorData(self, editor, index): value = index.model().data(index, Qt.EditRole) editor.setCurrentIndex(editor.findText(value)) </code></pre> <p>Note that in this example, I've relied on the default implementation of <code>QItemDelegate.setModelData()</code> to save the current text of the <code>combobox</code> into the <code>EditRole</code>. If you want to do something more complex (for example saving the <code>combobox</code> index instead of the text), you can save/restore data to a different role (for example <code>Qt.UserRole</code>) in which case you would modify where you get the role in the <code>setEditorData</code> method as well as overriding <code>setModelData</code> like so:</p> <pre><code>def setEditorData(self, editor, index): value = index.model().data(index, Qt.UserRole) editor.setCurrentIndex(int(value)) def setModelData(self, editor, model, index): model.setData(index, editor.currentIndex(), Qt.UserRole) </code></pre> <p>Here is a minimal working example of the above code! Note that I've turned off support for <code>QVariant</code> using <code>sip</code> so that the model returns native Python types. </p> <pre><code>import sys import sip sip.setapi('QVariant', 2) from PyQt4.QtGui import * from PyQt4.QtCore import * data = {"first":{"status":"closed"},"second":{"status":"expired"},"third":{ "status":"cancelled"}} class ComboDelegate(QItemDelegate): def createEditor(self, parent, option, index): editor = QComboBox(parent) li = [] li.append("closed") li.append("expired") li.append("cancelled") li.append("waiting") editor.addItems(li) return editor def setEditorData(self, editor, index): value = index.model().data(index, Qt.EditRole) editor.setCurrentIndex(editor.findText(value)) class Example(QMainWindow): def __init__(self): super(Example, self).__init__() self.tableview = QTableView() self.tableview.setItemDelegateForColumn(1, ComboDelegate()) self.setCentralWidget(self.tableview) self.model = QStandardItemModel() self.tableview.setModel(self.model) self.fillModel() self.show() def fillModel(self): for i in data: name_str = i status_str = data[i]["status"] name = QStandardItem(name_str) status = QStandardItem(status_str) items = [name, status] self.model.appendRow(items) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) </code></pre> <hr> <h2>EDIT</h2> <p>I've just noticed your other question about automatically showing the the <code>comboBox</code>after you double click. I have a hack for doing that to which I've used before. It relies on passing the view into the delegate and adding the following lines to the <code>createEditor</code> method:</p> <pre><code> editor.activated.connect(lambda index, editor=editor: self._view.commitData(editor)) editor.activated.connect(lambda index, editor=editor: self._view.closeEditor(editor,QAbstractItemDelegate.NoHint)) QTimer.singleShot(10,editor.showPopup) </code></pre> <p>Full working example:</p> <pre><code>import sys import sip sip.setapi('QVariant', 2) from PyQt4.QtGui import * from PyQt4.QtCore import * data = {"first":{"status":"closed"},"second":{"status":"expired"},"third":{ "status":"cancelled"}} class ComboDelegate(QItemDelegate): def __init__(self, view): QItemDelegate.__init__(self) self._view = view def createEditor(self, parent, option, index): editor = QComboBox(parent) li = [] li.append("closed") li.append("expired") li.append("cancelled") li.append("waiting") editor.addItems(li) editor.activated.connect(lambda index, editor=editor: self._view.commitData(editor)) editor.activated.connect(lambda index, editor=editor: self._view.closeEditor(editor,QAbstractItemDelegate.NoHint)) QTimer.singleShot(10,editor.showPopup) return editor def setEditorData(self, editor, index): value = index.model().data(index, Qt.EditRole) editor.setCurrentIndex(editor.findText(value)) class Example(QMainWindow): def __init__(self): super(Example, self).__init__() self.tableview = QTableView() self.tableview.setItemDelegateForColumn(1, ComboDelegate(self.tableview)) self.setCentralWidget(self.tableview) self.model = QStandardItemModel() self.tableview.setModel(self.model) self.fillModel() self.show() def fillModel(self): for i in data: name_str = i status_str = data[i]["status"] name = QStandardItem(name_str) status = QStandardItem(status_str) items = [name, status] self.model.appendRow(items) if __name__ == '__main__': app = QApplication(sys.argv) ex = Example() sys.exit(app.exec_()) </code></pre>
python|qt|model|pyqt|qcombobox
5
1,906,185
49,268,756
Python precision issues with float formatting
<p>Please look at the below Python code that I've entered into a Python 3.6 interpreter:</p> <pre><code>&gt;&gt;&gt; 0.00225 * 100.0 0.22499999999999998 &gt;&gt;&gt; '{:.2f}'.format(0.00225 * 100.0) '0.22' &gt;&gt;&gt; '{:.2f}'.format(0.225) '0.23' &gt;&gt;&gt; '{:.2f}'.format(round(0.00225 * 100.0, 10)) '0.23' </code></pre> <p>Hopefully you can immediately understand why I'm frustrated. I am attempting to display <code>value * 100.0</code> on my GUI, storing the full precision behind a cell but only displaying 2 decimal points (or whatever the users precision setting is). The GUI is similar to an Excel spreadsheet.</p> <p>I'd prefer not to lose the precision of something like <code>0.22222444937645</code> and round by <code>10</code>, but I also don't want a value such as <code>0.00225 * 100.0</code> displaying as <code>0.22</code>.</p> <p>I'm interested in hearing about a standard way of approaching a situation like this or a remedy for my specific situation. Thanks ahead of time for any help.</p>
<p>Consider using the <a href="https://docs.python.org/3/library/decimal.html" rel="nofollow noreferrer">Decimal module</a>, which &quot;provides support for fast correctly-rounded decimal floating point arithmetic.&quot; The primary advantages of <code>Decimal</code> relevant to your use case are:</p> <blockquote> <ul> <li><p>Decimal numbers can be represented exactly. In contrast, numbers like <code>1.1</code> and <code>2.2</code> do not have exact representations in binary floating point. End users typically would not expect <code>1.1 + 2.2</code> to display as <code>3.3000000000000003</code> as it does with binary floating point.</p> </li> <li><p>The exactness carries over into arithmetic. In decimal floating point, <code>0.1 + 0.1 + 0.1 - 0.3</code> is exactly equal to zero. In binary floating point, the result is <br><code>5.5511151231257827e-017</code>. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal is preferred in accounting applications which have strict equality invariants.</p> </li> </ul> </blockquote> <p>Based on the information you've provided in the question, I cannot say how much of an overhaul migrating to <code>Decimal</code> would require. However, if you're creating a spreadsheet-like application and always want to preserve maximal precision, then you will probably want to refactor to use <code>Decimal</code> sooner or later to avoid unexpected numbers in your user-facing GUI.</p> <p>To get the behavior you desire, you may need to change the rounding mode (which defaults to <code>ROUND_HALF_EVEN</code>) for <code>Decimal</code> instances.</p> <pre><code>from decimal import getcontext, ROUND_HALF_UP getcontext().rounding = ROUND_HALF_UP n = round(Decimal('0.00225') * Decimal('100'), 2) print(n) # prints Decimal('0.23') m = round(Decimal('0.00225') * 100, 2) print(m) # prints Decimal('0.23') </code></pre>
python|floating-point|precision
2
1,906,186
25,416,819
Array of strings using a range
<p>I want to make an array of filenames to loop through in python. In Perl I would write it like this:</p> <pre><code>my @array = qw (name00 .. name100) </code></pre> <p>or</p> <pre><code>foreach my $i (01..100) { push(@array,$i); } </code></pre> <p>Is there a similar way to do this in Python?</p>
<p>I'm not that familiar with <code>Perl</code> but if I understand the gist of what you are doing:</p> <p>One-line list comprehension</p> <pre><code>&gt;&gt;&gt; myArray = ['file' + str(i) for i in range(1,101)] &gt;&gt;&gt; myArray ['file1', 'file2', 'file3', 'file4', 'file5', 'file6', 'file7', 'file8', 'file9', 'file10', 'file11', 'file12', 'file13', 'file14', 'file15', 'file16', 'file17', 'file18', 'file19', 'file20', 'file21', 'file22', 'file23', 'file24', 'file25', 'file26', 'file27', 'file28', 'file29', 'file30', 'file31', 'file32', 'file33', 'file34', 'file35', 'file36', 'file37', 'file38', 'file39', 'file40', 'file41', 'file42', 'file43', 'file44', 'file45', 'file46', 'file47', 'file48', 'file49', 'file50', 'file51', 'file52', 'file53', 'file54', 'file55', 'file56', 'file57', 'file58', 'file59', 'file60', 'file61', 'file62', 'file63', 'file64', 'file65', 'file66', 'file67', 'file68', 'file69', 'file70', 'file71', 'file72', 'file73', 'file74', 'file75', 'file76', 'file77', 'file78', 'file79', 'file80', 'file81', 'file82', 'file83', 'file84', 'file85', 'file86', 'file87', 'file88', 'file89', 'file90', 'file91', 'file92', 'file93', 'file94', 'file95', 'file96', 'file97', 'file98', 'file99', 'file100'] </code></pre> <p>For learning purposes, here is a more step-by-step way to do it in Python</p> <pre><code>myArray = [] # initialize an empty array for i in range(1,101): # range produces a list [1,2,3, ... 99, 100] fileName = 'file' + str(i) # converts i to string, then performs concatenation myArray.append(fileName) # appends the concatenated string to the array </code></pre>
python|arrays|list
7
1,906,187
67,914,257
Using while to grab the next not null value
<p>I have this Pandas dataframe in Python which is a list of all actions that have been made by a team in a football match. If there's a score resulting of a play, I have the amount of points scored in the column &quot;Score&quot;, otherwise this column remains empty:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>play_id</th> <th>Score</th> </tr> </thead> <tbody> <tr> <td>1</td> <td></td> </tr> <tr> <td>2</td> <td></td> </tr> <tr> <td>3</td> <td></td> </tr> <tr> <td>4</td> <td>6</td> </tr> <tr> <td>5</td> <td>1</td> </tr> <tr> <td>6</td> <td></td> </tr> <tr> <td>7</td> <td></td> </tr> <tr> <td>8</td> <td>3</td> </tr> <tr> <td>9</td> <td></td> </tr> <tr> <td>10</td> <td></td> </tr> </tbody> </table> </div> <p>I would like to create a new column called &quot;next_score&quot; based on those conditions:</p> <ul> <li>If the play results in points, I want to grab those points</li> <li>If the play doesn't result in points (i.e. the value is null), I want to grab the next point scored.</li> </ul> <p>The table would look like this:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>play_id</th> <th>Score</th> <th>next_score</th> </tr> </thead> <tbody> <tr> <td>1</td> <td></td> <td>6</td> </tr> <tr> <td>2</td> <td></td> <td>6</td> </tr> <tr> <td>3</td> <td></td> <td>6</td> </tr> <tr> <td>4</td> <td>6</td> <td>6</td> </tr> <tr> <td>5</td> <td>1</td> <td>1</td> </tr> <tr> <td>6</td> <td></td> <td>3</td> </tr> <tr> <td>7</td> <td></td> <td>3</td> </tr> <tr> <td>8</td> <td>3</td> <td>3</td> </tr> <tr> <td>9</td> <td></td> <td>6</td> </tr> <tr> <td>10</td> <td>6</td> <td>6</td> </tr> </tbody> </table> </div> <p>I have been using this code:</p> <pre><code>next_score = [] for point in df['Score']: if point == &quot;&quot;: while point+1 == &quot;&quot;: continue else: next_score.append(point) break else: next_score.append(point) df['next_score'] = next_score </code></pre> <p>But that gives me the same results as the column &quot;Score&quot;. I'm not able to tell my code to grab the next scoring results. Could anyone help me with this?</p>
<p>Pandas comes with batteries included:</p> <pre><code>df['next_score'] = df['Score'].fillna(method='backfill') </code></pre>
python|pandas|while-loop
1
1,906,188
67,898,849
Control flow for looking for object and stopping once object found
<p>I have a camera rig where I initialise the stages and need to then move the camera and find the range over which an object is detectable. I cannot predict where the object is going to be. If no object detected by camera I increment the camera stage and look again. When I find the position where the object starts to be detectable I append the current camera location to a list. I repeat this over the whole range. What I would like to do is stop the unnecessary attempts to look for an object once it is no longer within view, i.e. once it stops being found. I have thought of a list which might read like: y_list = [100,150,200,250,300,...500] and I couldn't figure out how to check if the list had stopped growing in length for a few iterations of the for loop. I thought of using another list to show when an object had been detected but don't know how to implement it.</p> <p>y_list_flags = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0]</p> <p><strong>Code</strong></p> <pre><code>y_list = [] len_y = len(y_list) for i in list(range(1,70): my_obj = obj_present()#returns True if object detected, False otherwise if my_obj: y_list.append(current_cam_position) move_cam_stage() elif my_obj not True: move_cam_stage() </code></pre> <p><strong>Desired output</strong></p> <pre><code>y_list = [100,150,200,250,300, 350,400,450,500,550,600] # list stops growing when object not found and test has stopped </code></pre> <p>or</p> <pre><code>y_list = [100,150,200,250,300, 350,400,450,500,550,600] # list stops growing when object not found and test has stopped a few attempts after drop is no longer found </code></pre>
<p>the <code>move_cam_stage</code> and <code>obj_present</code> are dummy functions.</p> <p>loop break and list stops growing when object not found again.</p> <p>code:</p> <pre><code>def move_cam_stage(): print(&quot;move cam stage&quot;) def obj_present(i): y_list_flags = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0] return y_list_flags[i] == 1 y_list = [] for i in range(1,70): my_obj = obj_present(i)#returns True if object detected, False otherwise if my_obj: y_list.append(50 + 50*i) move_cam_stage() else: if len(y_list)&gt;1: break print(y_list) </code></pre> <p>result:</p> <pre><code>move cam stage move cam stage move cam stage move cam stage move cam stage move cam stage move cam stage move cam stage move cam stage move cam stage move cam stage [450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950] </code></pre>
python|nested-loops|control-flow
1
1,906,189
35,023,456
List comprehension in python for a multiline for loop
<p>need a help on list comprehension on following scenario code. </p> <pre><code>a = "e00-5" x = [] for i in range(4): tmp = a+"-"+str(i) x.append(tmp) </code></pre> <p>I tried the following but failing with this error</p> <pre><code>x = [ tmp = a+"-"+str(i) for i in range(4)] File "&lt;stdin&gt;", line 1 x = [ tmp = a+"-"+str(i) for i in range(4)] ^ SyntaxError: invalid syntax enter code here </code></pre> <p>Can anybody suggest what gonna wrong here.. Thank you !!</p>
<p>Remove <code>tmp =</code> </p> <pre><code>x = [ a+"-"+str(i) for i in range(4)] </code></pre>
python-2.7|list-comprehension
2
1,906,190
54,175,457
How to randomly shuffle asyncio.Queue in Python?
<p>When I want to randomly shuffle a list in Python, I do:</p> <pre><code>from random import shuffle shuffle(mylist) </code></pre> <p>How would I do the equivalent to an instance of <a href="https://docs.python.org/3.7/library/asyncio-queue.html" rel="nofollow noreferrer">asyncio.Queue</a>? Do I have to convert the queue to a list, shuffle the list, and then put them back on the Queue? Or is there a way to do it directly?</p>
<p>As you can see in <code>Queue</code> <a href="https://github.com/python/cpython/blob/master/Lib/asyncio/queues.py#L51" rel="nofollow noreferrer">source code</a>, items in <code>Queue</code> are actually stored in <code>_queue</code> attribute. It can be used to extend <code>Queue</code> through inheritance:</p> <pre><code>import asyncio from random import shuffle class MyQueue(asyncio.Queue): def shuffle(self): shuffle(self._queue) async def main(): queue = MyQueue() await queue.put(1) await queue.put(2) await queue.put(3) queue.shuffle() while not queue.empty(): item = await queue.get() print(item) if __name__ == '__main__': asyncio.run(main()) </code></pre> <hr> <p>If you want to shuffle existing <code>Queue</code> instance, you can do it directly:</p> <pre><code>queue = asyncio.Queue() shuffle(queue._queue) </code></pre> <p>It's usually not a good solution for obvious reason, but on the other hand probability that <code>Queue</code>'s implementation will change in future in a way to make it problem seems relatively low (to me at least).</p>
queue|python-asyncio|shuffle
4
1,906,191
41,329,374
How to translate this Python code to Node.js
<p>I got a very nice answer on here about how to clear a line / delete a line in a file without having to truncate the file or replace the file with a new version of the file, here's the Python code:</p> <pre><code>#!/usr/bin/env python import re,os,sys logfile = sys.argv[1] regex = sys.argv[2] pattern = re.compile(regex) with open(logfile,"r+") as f: while True: old_offset = f.tell() l = f.readline() if not l: break if pattern.search(l): # match: blank the line new_offset = f.tell() if old_offset &gt; len(os.linesep): old_offset-=len(os.linesep) f.seek(old_offset) f.write(" "*(new_offset-old_offset-len(os.linesep))) </code></pre> <p>this script can be called like:</p> <pre><code>./clear-line.py &lt;file&gt; &lt;pattern&gt; </code></pre> <p>For educational purposes, I am trying to figure out if I can write this in Node.js. I can certainly read a file with Node.js line-by-line. But I am not sure if Node.js has the equivalent calls for tell/seek in this case.</p> <p>the equivalent for write is surely</p> <p><a href="https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback" rel="nofollow noreferrer">https://nodejs.org/api/fs.html#fs_fs_write_fd_buffer_offset_length_position_callback</a></p> <p>Here is my attempt</p> <pre><code>#!/usr/bin/env node const readline = require('readline'); const fs = require('fs'); const file = process.argv[2]; const rgx = process.argv[3]; const fd = fs.openSync(file, 'r+'); const rl = readline.createInterface({ input: fs.createReadStream(null, {fd: fd}) }); let position = 0; const onLine = line =&gt; { position += line.length; if (String(line).match(rgx)) { let len = line.length; rl.close(); rl.removeListener('line', onLine); // output the line that will be replaced/removed process.stdout.write(line); fs.write(fd, new Array(len + 1).join(' '), position, 'utf8', err =&gt; { if (err) { process.stderr.write(err.stack || err); process.exit(1); } else { process.exit(0); } }); } }; rl.on('line', onLine); </code></pre> <p>It's not quite right - I don't think I am calculating the offset/position correctly. Perhaps someone who know both Python and Node can help me out. I am not very familiar with calculating position/offset in files, especially in terms of buffers.</p> <p>Here is the data in a text file that I am working with. All I want to do is read the first line that is not empty, and then remove that line from the file and write that line to stdout.</p> <p>This could really any non-whitespace data, but here is the JSON that I am working with:</p> <pre><code>{"dateCreated":"2016-12-26T09:52:03.250Z","pid":5371,"count":0,"uid":"7133d123-e6b8-4109-902b-7a90ade7c655","isRead":false,"line":"foo bar baz"} {"dateCreated":"2016-12-26T09:52:03.290Z","pid":5371,"count":1,"uid":"e881b0a9-8c28-42bb-8a9d-8109587777d0","isRead":false,"line":"foo bar baz"} {"dateCreated":"2016-12-26T09:52:03.390Z","pid":5371,"count":2,"uid":"065e51ff-14b8-4454-9ae5-b85152cfcb64","isRead":false,"line":"foo bar baz"} {"dateCreated":"2016-12-26T09:52:03.491Z","pid":5371,"count":3,"uid":"5af80a95-ff9d-4252-9c4e-0e421fd9320f","isRead":false,"line":"foo bar baz"} {"dateCreated":"2016-12-26T09:52:03.595Z","pid":5371,"count":4,"uid":"961e578f-288b-413c-b933-b791f833c037","isRead":false,"line":"foo bar baz"} {"dateCreated":"2016-12-26T09:52:03.696Z","pid":5371,"count":5,"uid":"a65cbf78-2ea1-4c3a-9beb-b4bf56e83a6b","isRead":false,"line":"foo bar baz"} {"dateCreated":"2016-12-26T09:52:03.799Z","pid":5371,"count":6,"uid":"d411e917-ad25-455f-9449-ae4d31c7b1ad","isRead":false,"line":"foo bar baz"} {"dateCreated":"2016-12-26T09:52:03.898Z","pid":5371,"count":7,"uid":"46f8841d-c86c-43f2-b440-8ab7feea7527","isRead":false,"line":"foo bar baz"} {"dateCreated":"2016-12-26T09:52:04.002Z","pid":5371,"count":8,"uid":"81b5ce7e-2f4d-4acb-884c-442c5ac4490f","isRead":false,"line":"foo bar baz"} {"dateCreated":"2016-12-26T09:52:04.101Z","pid":5371,"count":9,"uid":"120ff45d-74e7-464e-abd5-94c41e3cd089","isRead":false,"line":"foo bar baz"} </code></pre>
<p>You should take into consideration the newline character at the end of each line, that is not included in the 'line' you're getting via the readline module. That is, you should update position to <code>position += (line.length + 1)</code>, and then when writing, just use <code>position</code> (without the <code>-1</code>).</p>
javascript|python|node.js|readline|seek
1
1,906,192
40,620,185
How to access additional file streams of the unix shell in Python?
<p>How can I access the additional file streams like the <code>comm</code> command in Python?</p> <pre><code>comm -23 &lt;(sort -n Asub|uniq) &lt;(sort -n A|uniq) </code></pre> <p>I know that I can access stdin via <code>sys.stdin</code>, but how to access the other input stream?</p>
<p>Thanks for asking this question, as I actually didn't understand the behavior of <code>&lt;()</code> myself. It appears after some digging, however, that what it actually does it creates a temporary virtual file descriptor that it pipes the information from the subcommand into, then returns the name of that file descriptor. To see what I mean, look at this python program:</p> <pre><code>import sys for arg in sys.argv: print('|{}|'.format(repr(arg))) </code></pre> <p>When it is invoked like <code>python3 thing.py &lt;(cat a.txt) &lt;(cat b.txt)</code>, you should see that the output is something like:</p> <pre><code>|'thing.py'| |'/proc/self/fd/11'| |'/proc/self/fd/12'| </code></pre> <p>So finally, to answer your question, what you need to do to read the data from that subprocess is to simply open that file descriptor as you would any other file. For example:</p> <pre><code>with open(sys.argv[1]) as f: for line in f: print(line.strip()) </code></pre> <p>Which gives me an output like:</p> <pre><code>A B C </code></pre> <p>(Matching the contents of a.txt)</p> <p>Hope that helps!</p>
python|stdin|comm
1
1,906,193
47,163,935
Django admin display filter depending on other filters
<p>Here is an example of models:</p> <pre><code>class Books(models.Model): ... class Chapter(models.Model): ... book = models.ForeignKey('Books') class Exercise(models.Model): ... book = models.ForeignKey('Books') chapter = models.ForeignKey('Chapter') </code></pre> <p>And here is the Admin class for exercise:</p> <pre><code>class ExerciseAdmin(admin.ModelAdmin): ... list_filter = (('book',admin.RelatedOnlyFieldListFilter),('chapter',admin.RelatedOnlyFieldListFilter)) admin.site.register(Exercise, ExerciseAdmin) </code></pre> <p>I now have the filters <code>book</code> and <code>chapter</code> for <code>exercise</code>. When I click on a <code>book</code> in the filter <code>book</code>, it shows me all the <code>exercises</code> of the selected <code>book</code> accordingly. But in the list of filter <code>chapter</code>, it still shows all the <code>chapters</code> of all the <code>books</code>.</p> <p>Is there a way to only display, in the filter <code>chapter</code>, the <code>chapters</code> of the <code>book</code> that I selected in the first filter <code>book</code>? How?</p>
<p>I'm not sure if it's the best way to do it, but here I use the GET parameter of the url from the admin panel to get the ID of the book then I can select the corresponding chapters. And it works!</p> <pre><code>class ChapterFilter(admin.SimpleListFilter): title = 'chapter' parameter_name = 'chapter' def lookups(self, request, model_admin): if 'book__id__exact' in request.GET: id = request.GET['book__id__exact'] chapters = set([c.chapter for c in model_admin.model.objects.all().filter(book=id)]) else: chapters = set([c.chapter for c in model_admin.model.objects.all()]) return [(b.id, b.titre) for b in chapters] def queryset(self, request, queryset): if self.value(): return queryset.filter(chapter__id__exact=self.value()) class ExerciseAdmin(admin.ModelAdmin): list_filter = (('book',admin.RelatedOnlyFieldListFilter), (ChapterFilter)) </code></pre>
python|django|django-admin
3
1,906,194
46,823,445
Error when trying to pull row based on index value in the dataframe
<p>I'am reading a data off a csv file. The columns are as below:</p> <p>Date , Buy, Sell, Price</p> <p>1/10/2011, 1 , 5, 500</p> <p>1/15/2011, 4, 2, 500</p> <p>When I tried to pull data based on index like df["2011-01-10"], I got an error KeyError: '2011-01-10'</p> <p>Anyone know what this is might be the case?</p> <p>Thanks,</p>
<p>I think the way you are passing your argument is wrong, try passing it in the same pattern as its in csv. Like ["1/10/2011"], it should work. Good luck :)</p>
python|dataframe
0
1,906,195
64,409,511
Replace multiple try codes with loop function - searching in HTML
<p>I am trying to download files from a website. The URL is in HTML of the page, I am able to find the right one, but the various videos are in different frame per second (fps). I had multiple try functions as seen <a href="https://stackoverflow.com/questions/17322208/multiple-try-codes-in-one-block">here</a> but it was difficult to follow, so I tried the loop function seen <a href="https://stackoverflow.com/questions/59124162/explicit-exception-problem-with-try-function">here</a>.</p> <p>This is what I have:</p> <pre><code> import re for [j] in range(23,24,25,26,27,28,29,30,31): try: result = re.search('&quot;width&quot;:1280,&quot;mime&quot;:&quot;video/mp4&quot;,&quot;fps&quot;:[j],&quot;url&quot;:(.*),', s) extractedword=result.group(1) commapos=extractedword.find(&quot;,&quot;) link=extractedword[:commapos].replace('&quot;',&quot;&quot;) except: pass print(title) print(link) </code></pre> <p>The output message states <code>range expected at most 3 arguments, got 9</code></p> <p>Any advice how I can search for the correct URL? I've been trying to get this done for days. Thank you!</p> <p>EDIT: I should add the URL for one title only exists in one FPS at the set resolution. The various titles exist in a variety of FPS, but each title is only available in one FPS for the required resolution. Some of the solutions are returned &quot;download error retrying&quot; in a loop.</p>
<p>Use this code instead:</p> <pre class="lang-py prettyprint-override"><code>import re s = # Put what s equals here for j in range(23, 32): try: result = re.search('&quot;width&quot;:1280,&quot;mime&quot;:&quot;video/mp4&quot;,&quot;fps&quot;:[j],&quot;url&quot;:(.*),', s) extractedword = result.group(1) commapos = extractedword.find(&quot;,&quot;) link = extractedword[:commapos].replace('&quot;', &quot;&quot;) except: pass else: print(title) # Also make sure to define title somewhere print(link) </code></pre>
python|selenium|loops|beautifulsoup
0
1,906,196
64,303,825
Accessing intermediate tensors of a Keras Model that were not explicitly exposed as layers in TF 2.0
<p>Is it possible to access pre-activation tensors in a Keras Model? For example, given this model:</p> <pre class="lang-python prettyprint-override"><code>import tensorflow as tf image_ = tf.keras.Input(shape=[224, 224, 3], batch_size=1) vgg19 = tf.keras.applications.VGG19(include_top=False, weights='imagenet', input_tensor=image_, input_shape=image_.shape[1:], pooling=None) </code></pre> <p>the usual way to access layers is:</p> <pre class="lang-python prettyprint-override"><code>intermediate_layer_model = tf.keras.models.Model(inputs=image_, outputs=[vgg19.get_layer('block1_conv2').output]) intermediate_layer_model.summary() </code></pre> <p>This gives the ReLU outputs for a layer, while I would like the ReLU inputs. I tried doing this:</p> <pre class="lang-python prettyprint-override"><code>graph = tf.function(vgg19, [tf.TensorSpec.from_tensor(image_)]).get_concrete_function().graph outputs = [graph.get_tensor_by_name(tname) for tname in [ 'vgg19/block4_conv3/BiasAdd:0', 'vgg19/block4_conv4/BiasAdd:0', 'vgg19/block5_conv1/BiasAdd:0' ]] intermediate_layer_model = tf.keras.models.Model(inputs=image_, outputs=outputs) intermediate_layer_model.summary() </code></pre> <p>but I get the error</p> <pre class="lang-python prettyprint-override"><code>ValueError: Unknown graph. Aborting. </code></pre> <p>The only workaround I've found is to edit the model file to manually expose the intermediates, turning every layer like this:</p> <pre class="lang-python prettyprint-override"><code>x = layers.Conv2D(256, (3, 3), activation=&quot;relu&quot;, padding=&quot;same&quot;, name=&quot;block3_conv1&quot;)(x) </code></pre> <p>into 2 layers where the 1st one can be accessed before activations:</p> <pre class="lang-python prettyprint-override"><code>x = layers.Conv2D(256, (3, 3), activation=None, padding=&quot;same&quot;, name=&quot;block3_conv1&quot;)(x) x = layers.ReLU(name=&quot;block3_conv1_relu&quot;)(x) </code></pre> <p>Is there a way to acces pre-activation tensors in a Model without essentially editing Tensorflow 2 source code, or reverting to Tensorflow 1 which had full flexibility accessing intermediates?</p>
<p>There is a way to access pre-activation layers for pretrained Keras models using TF version 2.7.0. Here's how to access two intermediate pre-activation outputs from VGG19 in a <em>single</em> forward pass.</p> <p>Initialize VGG19 model. We can omit top layers to avoid loading unnecessary parameters into memory.</p> <pre class="lang-py prettyprint-override"><code>vgg19 = tf.keras.applications.VGG19( include_top=False, weights=&quot;imagenet&quot; ) </code></pre> <p><strong>This is the important part: Create a deepcopy of the intermediate layer form which you like to have the features, change the activation of the conv layers to linear (i.e. no activation), rename the layer (otherwise two layers in the model will have the same name which will raise errors) and finally pass the output of the <em>previous</em> through the copied conv layer.</strong></p> <pre class="lang-py prettyprint-override"><code># for more intermediate features wrap a loop around it to avoid copy paste b5c4_layer = deepcopy(vgg19.get_layer(&quot;block5_conv4&quot;)) b5c4_layer.activation = tf.keras.activations.linear b5c4_layer._name = b5c4_layer.name + str(&quot;_preact&quot;) b5c4_preact_output = b5c4_layer(vgg19.get_layer(&quot;block5_conv3&quot;).output) b2c2_layer = deepcopy(vgg19.get_layer(&quot;block2_conv2&quot;)) b2c2_layer.activation = tf.keras.activations.linear b2c2_layer._name = b2c2_layer.name + str(&quot;_preact&quot;) b2c2_preact_output = b2c2_layer(vgg19.get_layer(&quot;block2_conv1&quot;).output) </code></pre> <p>Finally, get the outputs and check if they equal post-activation outputs when we apply ReLU-activation.</p> <pre class="lang-py prettyprint-override"><code>vgg19_features = Model(vgg19.input, [b2c2_preact_output, b5c4_preact_output]) vgg19_features_control = Model(vgg19.input, [vgg19.get_layer(&quot;block2_conv2&quot;).output, vgg19.get_layer(&quot;block5_conv4&quot;).output]) b2c2_preact, b5c4_preact = vgg19_features(tf.keras.applications.vgg19.preprocess_input(img)) b2c2, b5c4 = vgg19_features_control(tf.keras.applications.vgg19.preprocess_input(img)) print(np.allclose(tf.keras.activations.relu(b2c2_preact).numpy(),b2c2.numpy())) print(np.allclose(tf.keras.activations.relu(b5c4_preact).numpy(),b5c4.numpy())) </code></pre> <pre><code>True True </code></pre> <p>Here's a visualization similar to Fig. 6 of <a href="https://arxiv.org/pdf/1809.00219.pdf" rel="nofollow noreferrer">Wang et al.</a> to see the effect in the feature space. <a href="https://i.stack.imgur.com/QjAyJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QjAyJ.png" alt="VGG19-intermediate" /></a></p> <p>Input image</p> <p><a href="https://i.stack.imgur.com/CJ3PA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CJ3PA.png" alt="input image" /></a></p>
python|tensorflow|keras|tensorflow2.0
1
1,906,197
70,584,914
Python script: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
<p>I forked this <a href="https://github.com/kitsandkats/ArchiveDiscourse" rel="nofollow noreferrer">repo</a> in order to make my discourse site into a static one. But, I keep getting this message:</p> <pre><code>json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) </code></pre> <p>It works for most posts, so it could be because the forum I am trying to archive is too large.</p> <p>This line is most likely causing trouble <code>posts_json = response.json()['post_stream']['posts']</code>. Any help would be greatly appreciated!</p> <p>EDIT: I added <code>print(response.raise_for_status())</code> and got this message</p> <pre><code>requests.exceptions.HTTPError: 429 Client Error: Too Many Requests for url: https://www.phylobabble.org//t/matrix-data-types/219.json </code></pre> <p>I added <code>time.sleep(1)</code> and now it works!</p> <pre><code># Function that writes out each individual topic page def write_topic(topic_json): topic_download_url = base_url + '/t/' + topic_json['slug'] + '/' + str(topic_json['id']) topic_relative_url = 't/' + topic_json['slug'] + '/' + str(topic_json['id']) try: os.makedirs(topic_relative_url) except Exception as err: print ('in write_topic error:', 'make directory') response = requests.get(topic_download_url + '.json', cookies=jar) # posts_json will contain only the first 20 posts in a topic posts_json = response.json()['post_stream']['posts'] # posts_stream will grab all of the post ids for that topic posts_stream = response.json()['post_stream']['stream'] # get rid of first 20 in stream, as they are already in posts_json posts_stream = posts_stream[20:] # break stream into a list of list chunks of n posts each for lighter requests n = 9999999 chunked_posts_stream = [posts_stream[i * n:(i + 1) * n] for i in range((len(posts_stream) + n - 1) // n)] posts_download_url = base_url + '/t/' + str(topic_json['id']) + '/posts.json?' # make a request for the content associated with each post id # chunk and append it to the posts_json list for chunk in chunked_posts_stream: formatted_posts_list = &quot;&quot; for post_id in chunk: formatted_posts_list = formatted_posts_list + 'post_ids[]=' + str(post_id) + '&amp;' response = requests.get(posts_download_url + formatted_posts_list, cookies=jar) posts_2_json = response.json()['post_stream']['posts'] posts_json.extend(posts_2_json) # generate that HTML post_list_string = &quot;&quot; for post_json in posts_json: post_list_string = post_list_string + post_row(post_json) topic_file_string = topic_template \ .replace(&quot;&lt;!-- TOPIC_TITLE --&gt;&quot;, topic_json['fancy_title']) \ .replace(&quot;&lt;!-- JUST_SITE_TITLE --&gt;&quot;, str(site_title.text)) \ .replace(&quot;&lt;!-- ARCHIVE_BLURB --&gt;&quot;, archive_blurb) \ .replace(&quot;&lt;!-- POST_LIST --&gt;&quot;, post_list_string) f = open(topic_relative_url + '/index.html', 'w') f.write(topic_file_string) f.close() </code></pre>
<p>It might be that you don't get back a valid json from the get request. Have you checked the status code that you got here if it is a 2xx code? You can also add</p> <pre class="lang-py prettyprint-override"><code>response.raise_for_status() </code></pre> <p>to see if that fails and which exception you get.</p>
python|json|promise|webapi|discourse
1
1,906,198
70,535,245
Is there a way to wrap every single entry of an numpy.ndarray into a separate array?
<p>I'm facing some problems getting an array into the right shape to use it as an input into a convolutional neural net:</p> <p>My array has the shape <code>(100,64,64)</code>, but I'd need it to be <code>(100,64,64,1)</code>. I realize it looks a bit odd, but I basically want to pack every single entry into a separate array.</p> <p>A simplified example, with a 2D array, where the analogous would be from <code>(3,3)</code> to <code>(3,3,1)</code>:</p> <pre><code>[[0,1,0], [[[0],[1],[0]], [1,1,1], [[1],[1],[1]], [0,0,1]] [[0],[0],[1]]] </code></pre> <p>Is there a convenient way to do this using numpy?</p> <p>I've tried to use the function <code>numpy.reshape</code>: With which I know, how to &quot;add&quot; another array wrapping the original one.</p> <pre><code>import numpy as np data = data.reshape((1,)+data.shape) </code></pre> <p>This gives the output for <code>data.shape</code>: <code>(1,100,64,64)</code>. Is there a way to add a dimension at the &quot;inner end&quot;?</p> <p>If I try <code>data.reshape(data.shape+(,1))</code>, I get an invalid syntax error.</p>
<p>You can pass an <a href="https://docs.python.org/3/library/constants.html?highlight=ellipsis#Ellipsis" rel="nofollow noreferrer">Ellipsis</a> plus <code>None</code> to the arrays indexer:</p> <pre><code>&gt;&gt;&gt; a array([[0, 1, 0], [1, 1, 1], [0, 0, 1]]) &gt;&gt;&gt; a[..., None] array([[[0], [1], [0]], [[1], [1], [1]], [[0], [0], [1]]]) </code></pre> <p>(Credit to <a href="https://stackoverflow.com/questions/70535245/is-there-a-way-to-wrap-every-single-entry-of-an-numpy-ndarray-into-a-separate-ar/70535313?noredirect=1#comment124685570_70535313">@hpaulj</a>)</p>
python|arrays|numpy|multidimensional-array
2
1,906,199
70,566,339
I have used odeint in python to solve a differential equation, why does my position of my masses diverge to infinity?
<p>I have acquired my equations of motion for a certain problem involving three springs and two masses. The two springs on each side are non linear while the spring in the middle is linear. They are also mass-less. <a href="https://i.stack.imgur.com/Iuifg.jpg" rel="nofollow noreferrer">See the picture for clarity</a></p> <p>I have also put it in a code to be able to solve the second order differential equation, my code is the following:</p> <pre><code> import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt initial=[-5,0,5,0] # [x,xdot,x2,x2dot] t = np.linspace(0,5,10000) # Creating a vector which will represent time. 10 seconds divided in to 10000 intervals def func(initials,t): # Defining function which is used in the odeint for solving diff.eq m1=5 #Mass of M_1 m2=5 #Mass of M_2 k12=10 #Spring constant of spring connected and inbetween M_1 and M_2 k1=10 #Spring constant of spring connected to M_1 k2=10 #Spring constant of spring connected to M_2 c1=2 #constant of C for eq related to M_1 c2=2 #constant of C for eq related to M_2 L1=5 #Length of spring connected to M_1 L2=5 #Length of spring connected to M_2 x1=initials[0] #Initial values as chosen in row 5 x2=initials[2] #Initial values as chosen in row 5 x1dotdot=(-k12*(x1-x2)/m1)-(k1*x1/m1)+(c1*2*np.pi/(L1*m1)*np.sin(2*np.pi*x1/L1)) x2dotdot=(k12/m2*(x1-x2))-(k2*x2/m2)+(c2*2*np.pi/(L2*m2)*np.sin(2*np.pi*x2/L2)) return(initials[1],x1dotdot,initials[3],x2dotdot) output = odeint(func,initial,t) plt.plot(t,output[:,0],'g:',linewidth = 2, label = 'M_1') plt.plot(t,output[:,2],'y:',linewidth = 2, label = 'M_2') plt.legend() plt.xlabel('Time') plt.ylabel('Velocities of the masses M_1 and M_2') plt.show() </code></pre> <p>The problem here is that when I choose to plot the <a href="https://i.stack.imgur.com/CU5YK.png" rel="nofollow noreferrer">velocities</a> by returning initials(1) and initials(3), they start with the initial values -5 and 5 rather than 0 which is what I've given them from the start. I expect the -5 and 5 when I plot the positions.</p> <p>The other problem is also the positions. when I choose to plot them by returning initials(0) and initials(2) they diverge to <a href="https://i.stack.imgur.com/WmbR7.png" rel="nofollow noreferrer">infinity</a>.</p> <p>I don't know how to make sense of this.</p>
<p>I think your only problem is confusing what to expect in the <code>output</code> which is returned from <code>odeint</code>. It will return the state vector (here: <code>X = [x1, x1dot, x2, x2dot]</code>), in the order which it's been defined - not the derivative of the state vector.</p> <p>I've put a few extra labels/comments in the below which hopefully clarifies, and returns the following <a href="https://i.stack.imgur.com/GJT2q.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GJT2q.png" alt="plot" /></a></p> <pre><code>import numpy as np from scipy.integrate import odeint import matplotlib.pyplot as plt # State vector: X = [x1, x1dot, x2, x2dot] initial=[-5,0,5,0] # [x,xdot,x2,x2dot] t = np.linspace(0,5,10000) # Creating a vector which will represent time. 10 seconds divided in to 10000 intervals def func(X,t): # Defining function which is used in the odeint for solving diff.eq m1=5 #Mass of M_1 m2=5 #Mass of M_2 k12=10 #Spring constant of spring connected and inbetween M_1 and M_2 k1=10 #Spring constant of spring connected to M_1 k2=10 #Spring constant of spring connected to M_2 c1=2 #constant of C for eq related to M_1 c2=2 #constant of C for eq related to M_2 L1=5 #Length of spring connected to M_1 L2=5 #Length of spring connected to M_2 x1=X[0] #Current value of x1 x2=X[2] #Current value of x2 x1dotdot=(-k12*(x1-x2)/m1)-(k1*x1/m1)+(c1*2*np.pi/(L1*m1)*np.sin(2*np.pi*x1/L1)) x2dotdot=(k12/m2*(x1-x2))-(k2*x2/m2)+(c2*2*np.pi/(L2*m2)*np.sin(2*np.pi*x2/L2)) # Need to return derivate of State vector X, # X = [x1, x1dot, x2, x2dot] # Xdot = [x1dot, x1dotdot, x2dot, x2dotdot] return(X[1], x1dotdot, X[3], x2dotdot) output = odeint(func,initial,t) fig, (ax1, ax2) = plt.subplots(2 ,1) # Positions are in columns 0 and 2, X = [x1, x1dot, x2, x2dot] ax1.plot(t,output[:,0],'g:',linewidth = 2, label = 'M_1') ax1.plot(t,output[:,2],'y:',linewidth = 2, label = 'M_2') ax1.set_xlabel('Time') ax1.set_ylabel('Positions of the masses') ax1.legend() # Velocities are in columns 1 and 3, X = [x1, x1dot, x2, x2dot] ax2.plot(t,output[:,1],'g:',linewidth = 2, label = 'M_1') ax2.plot(t,output[:,3],'y:',linewidth = 2, label = 'M_2') ax2.set_xlabel('Time') ax2.set_ylabel('Velocities of the masses') ax2.legend() plt.show() </code></pre>
python|plot|physics
1