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
|
---|---|---|---|---|---|---|
0 | 20,581,479 | Can python or JS hide video embedded source? | <p>I'm doing a video website right now and I would like to hide the embedded source of the video from being seen by beginner programmer. (I know they are no 100% way to hide the video embeded source).</p>
<p>Any experience programmer knows how python or JS can help to do this? or it can't?</p> | <p>For Javascript, hiding code (almost) cannot be done!</p>
<p>However, if your code is sensetive in any manner, try using obfuscators so that the code will not be readable by human eye.</p>
<p>Here are few obfuscation services:</p>
<ol>
<li><p>Free Javascript Obfuscator: <a href="http://javascriptobfuscator.com/" rel="nofollow">Javascript Obfuscator</a></p></li>
<li><p>Uglify JS: <a href="https://github.com/mishoo/UglifyJS" rel="nofollow">Uglify JS</a></p></li>
<li><p><a href="http://www.jsobfuscate.com/" rel="nofollow">JSObfuscate to Obfuscate JS/jQuery</a></p></li>
<li><p>JScrambler 3: <a href="https://jscrambler.com/" rel="nofollow">JScrambler 3</a></p></li>
</ol>
<p><strong>UPDATE</strong>: Use this tutorial to get a heads-up: <a href="http://techcrunch.com/2013/04/17/improved-jscramber-3-helps-javascript-and-html5-developers-obfuscate-their-code/" rel="nofollow">Improved JScrambler 3 Helps JavaScript And HTML5 Developers Obfuscate Their Code</a></p> | javascript|jquery|python|video|video-streaming | 3 |
1 | 71,894,592 | How to concatenate database elements to a string | <p>I'm currently trying to take elements from a database to be displayed in a string by iterating through each row and adding it to an empty string.</p>
<pre><code> def PrintOverdueBooks():
printed_message = ""
for row in db_actions.GetAllOverdue():
printed_message += row
printed_message += " \n"
print(printed_message)
</code></pre>
<p>Whenever the function is called I receive an error stating that "row" is a tuple and cannot be concatenated to a string. Using <strong>.join</strong> also creates an error.</p> | <p>You can try this:</p>
<pre><code>def PrintOverdueBooks():
printed_message = ''
for row in db_actions.GetAllOverdue():
stup = ''.join(row)
printed_message += stup
print(printed_message)
</code></pre> | python|database|concatenation | 0 |
2 | 36,150,410 | 'DataFrame' object has no attribute 'value_counts' | <p>My dataset is a DataFrame of dimension (840,84). When I write the code:
<code>ds[ds.columns[1]].value_counts()</code><br>
I get a correct output:</p>
<pre><code>Out[82]:
0 847
1 5
Name: o_East, dtype: int64
</code></pre>
<p>But when I write a loop to store values, I get <em>'DataFrame' object has no attribute 'value_counts'</em>. I can't explain why ... </p>
<pre><code>wind_vec = []
wind_vec = [(ds[x].value_counts()) for x in ds.columns]
</code></pre>
<p><strong>UPDATE FOR THE CODE</strong></p>
<pre><code>import pandas as pd
import numpy as np
import numpy.ma as ma
import statsmodels.api as sm
import matplotlib
import matplotlib.pyplot as plt
from sklearn.preprocessing import OneHotEncoder
dataset = pd.read_csv('data/dataset.csv')
ds = dataset
o_wdire = pd.get_dummies(ds['o_wdire'])
s_wdire = pd.get_dummies(ds['s_wdire'])
t_wdire = pd.get_dummies(ds['t_wdire'])
k_wdire = pd.get_dummies(ds['k_wdire'])
b_wdire = pd.get_dummies(ds['b_wdire'])
o_wdire.rename(columns={'ENE': 'o_ENE','ESE': 'o_ESE', 'East': 'o_East', 'NE': 'o_NE', 'NNE': 'o_NNE', 'NNW': 'o_NNW', \
'NW': 'o_NW', 'North': 'o_North', 'SE': 'o_SE', 'SSE': 'o_SSE', 'SSW': 'o_SSW', 'SW': 'o_SW', \
'South': 'o_South', 'Variable': 'o_Variable', 'WSW': 'o_WSW','West':'o_West'}, inplace=True)
s_wdire.rename(columns={'ENE': 's_ENE','ESE': 's_ESE', 'East': 's_East', 'NE': 's_NE', 'NNE': 's_NNE', 'NNW': 's_NNW', \
'NW': 's_NW', 'North': 's_North', 'SE': 's_SE', 'SSE': 's_SSE', 'SSW': 's_SSW', 'SW': 's_SW', \
'South': 's_South', 'Variable': 's_Variable', 'West': 's_West','WSW': 's_WSW'}, inplace=True)
k_wdire.rename(columns={'ENE': 'k_ENE','ESE': 'k_ESE', 'East': 'k_East', 'NE': 'k_NE', 'NNE': 'k_NNE', 'NNW': 'k_NNW', \
'NW': 'k_NW', 'North': 'k_North', 'SE': 'k_SE', 'SSE': 'k_SSE', 'SSW': 'k_SSW', 'SW': 'k_SW', \
'South': 'k_South', 'Variable': 'k_Variable', 'WNW': 'k_WNW', 'West': 'k_West','WSW': 'k_WSW'}, inplace=True)
b_wdire.rename(columns={'ENE': 'b_ENE','ESE': 'b_ESE', 'East': 'b_East', 'NE': 'b_NE', 'NNE': 'b_NNE', 'NNW': 'b_NNW', \
'NW': 'b_NW', 'North': 'b_North', 'SE': 'b_SE', 'SSE': 'b_SSE', 'SSW': 'b_SSW', 'SW': 'b_SW', \
'South': 'b_South', 'Variable': 'b_Variable', 'WSW': 'b_WSW', 'WNW': 'b_WNW', 'West': 'b_West'}, inplace=True)
t_wdire.rename(columns={'ENE': 't_ENE','ESE': 't_ESE', 'East': 't_East', 'NE': 't_NE', 'NNE': 't_NNE', 'NNW': 't_NNW', \
'NW': 't_NW', 'North': 't_North', 'SE': 't_SE', 'SSE': 't_SSE', 'SSW': 't_SSW', 'SW': 't_SW', \
'South': 't_South', 'Variable': 't_Variable', 'WSW': 't_WSW', 'WNW': 't_WNW', 'West':'t_West'}, inplace=True)
#WIND
ds_wdire = pd.DataFrame(pd.concat([o_wdire,s_wdire,t_wdire,k_wdire,b_wdire],axis=1))
ds_wdire = ds_wdire.astype('float64')
In [93]: ds_wdire.shape
Out[93]: (852, 84)
In[101]: ds_wdire[ds_wdire.columns[0]].head()
Out[101]:
0 0
1 0
2 0
3 0
4 0
Name: o_ENE, dtype: float64
In[103]: ds_wdire[ds_wdire.columns[0]].value_counts()
Out[103]:
0 838
1 14
Name: o_ENE, dtype: int64
In[104]: [ds_wdire[x].value_counts() for x in ds_wdire.columns]
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-104-d9756c468818> in <module>()
1 #Filtering for the wind direction based on the most frequent ones.
----> 2 [ds_wdire[x].value_counts() for x in ds_wdire.columns]
<ipython-input-104-d9756c468818> in <listcomp>(.0)
1 #Filtering for the wind direction based on the most frequent ones.
----> 2 [ds_wdire[x].value_counts() for x in ds_wdire.columns]
/home/florian/anaconda3/lib/python3.5/site-packages/pandas/core/generic.py in __getattr__(self, name)
2358 return self[name]
2359 raise AttributeError("'%s' object has no attribute '%s'" %
-> 2360 (type(self).__name__, name))
2361
2362 def __setattr__(self, name, value):
AttributeError: 'DataFrame' object has no attribute 'value_counts'
</code></pre> | <p>Thanks to @EdChum adviced, I checked :</p>
<pre><code>len(ds_wdire.columns),len(ds_wdire.columns.unique())
Out[100]: (83,84)
</code></pre>
<p>Actually, there was a missing name value in the dict that should have been modified from 'WNW' to 'o_WNW'.:</p>
<pre><code>o_wdire.rename(columns={'ENE': 'o_ENE','ESE': 'o_ESE', 'East': 'o_East', 'NE': 'o_NE', 'NNE': 'o_NNE', 'NNW': 'o_NNW', \
'NW': 'o_NW', 'North': 'o_North', 'SE': 'o_SE', 'SSE': 'o_SSE', 'SSW': 'o_SSW', 'SW': 'o_SW', \
'South': 'o_South', 'Variable': 'o_Variable', 'WSW': 'o_WSW','West':'o_West', **[MISSING VALUE WNW]**}, inplace=True)
</code></pre>
<p>Maybe it would be better to write a loop that inserts a prefix to the wind direction variables, this way, I would avoid that kind of problem.</p> | python|python-2.7|pandas|dataframe | 1 |
3 | 46,529,659 | How to find ellipses in text string Python? | <p>Fairly new to Python (And Stack Overflow!) here. I have a data set with subject line data (text strings) that I am working on building a bag of words model with. I'm creating new variables that flags a 0 or 1 for various possible scenarios, but I'm stuck trying to identify where there is an ellipsis ("...") in the text. Here's where I'm starting from:</p>
<pre><code>Data_Frame['Elipses'] = Data_Frame.Subject_Line.str.match('(\w+)\.{2,}(.+)')
</code></pre>
<p>Inputting ('...') doesn't work for obvious reasons, but the above RegEx code was suggested--still not working. Also tried this:</p>
<pre><code>Data_Frame['Elipses'] = Data_Frame.Subject_Line.str.match('.\.\.\')
</code></pre>
<p>No dice.</p>
<p>The above code shell works for other variables I've created, but I'm also having trouble creating a 0-1 output instead of True/False (would be an 'as.numeric' argument in R.) Any help here would also be appreciated.</p>
<p>Thanks!</p> | <p>Using <code>search()</code> instead of <code>match()</code> would spot an ellipses at any point in the text. If you need <code>0</code> or <code>1</code> to be returned, convert to bool and then int.</p>
<pre><code>import re
for test in ["hello..", "again... this", "is......a test", "...def"]:
print int(bool(re.search(r'(\w+)\.{3,}', test)))
</code></pre>
<p>This matches on the middle two tests:</p>
<pre class="lang-none prettyprint-override"><code>0
1
1
0
</code></pre>
<p>Take a look at <a href="https://docs.python.org/2/library/re.html#search-vs-match" rel="nofollow noreferrer">search-vs-match</a> for a good explanation in the Python docs.</p>
<hr>
<p>To display the matching words:</p>
<pre><code>import re
for test in ["hello..", "again... this", "is......a test", "...def"]:
ellipses = re.search(r'(\w+)\.{3,}', test)
if ellipses:
print ellipses.group(1)
</code></pre>
<p>Giving you:</p>
<pre class="lang-none prettyprint-override"><code>again
is
</code></pre> | python|regex | 2 |
4 | 60,791,304 | google.cloud namespace import error in __init__.py | <p>I have read through at least a dozen different stackoverflow questions that all present the same basic problem and have the same basic answer: either the module isn't installed correctly or the OP is doing the import wrong.</p>
<p>In this case, I am trying to do <code>from google.cloud import secretmanager_v1beta1</code>. </p>
<p>It works in my airflow container when I run <code>airflow dags</code> or if I run <code>pytest tests/dags/test_my_dag.py</code>. However, if I run <code>cd dags; python -m my_dag</code> or <code>cd dags; python my_dag.py</code> I get this error:</p>
<pre><code>from google.cloud import secretmanager as secretmanager
ImportError: cannot import name 'secretmanager' from 'google.cloud' (unknown location)
</code></pre>
<p>I can add <code>from google.cloud import bigquery</code> in the line right above this line and that works OK. It appears to literally just be a problem with this particular package. </p>
<p>Why does it matter if pytest and airflow commands succeed? Because, I have another environment where I am trying to run dataflow jobs from the command-line and I get this same error. And unfortunately I don't think I can bypass this error in that environment for several reasons.</p>
<p><strong>UPDATE 6</strong></p>
<p>I have narrowed down the error to an issue with the <code>google.cloud</code> namespace and the <code>secretmanager</code> package within that namespace in the <code>__init__.py</code> file.</p>
<p>If I add <code>from google.cloud import secretmanager</code> to <code>airflow/dags/__init__.py</code> and then try to run <code>python -m dags.my_dag.py</code>, I receive this error but with a slightly different stacktrace:</p>
<pre><code>Traceback (most recent call last):
File "/usr/local/lib/python3.7/runpy.py", line 183, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
File "/usr/local/lib/python3.7/runpy.py", line 109, in _get_module_details
__import__(pkg_name)
File "/workspace/airflow/dags/__init__.py", line 3, in <module>
from google.cloud import secretmanager
ImportError: cannot import name 'secretmanager' from 'google.cloud' (unknown location)
</code></pre>
<p><strong>OLD INFORMATION</strong></p>
<p><s>I am 95% sure that it's still a path problem and that pytest and airflow are fixing something I'm not aware of that isn't handled when I try to manually run the python script.</s></p>
<p>Things I have tried:</p>
<pre><code>cd /airflow; python setup.py develop --user
cd /airflow; pip install -e . --user
cd /airflow/dags; pip install -r requirements.txt --user
</code></pre>
<p><strong>UPDATE</strong></p>
<p>As per requests in the comments, here are the contents of <code>requirements.txt</code>:</p>
<pre><code>boto3>=1.7.84
google-auth==1.11.2
google-cloud-bigtable==1.2.1
google-cloud-bigquery==1.24.0
google-cloud-spanner==1.14.0
google-cloud-storage==1.26.0
google-cloud-logging==1.14.0
google-cloud-secret-manager>=0.2.0
pycloudsqlproxy>=0.0.15
pyconfighelper>=0.0.7
pymysql==0.9.3
setuptools==45.2.0
six==1.14.0
</code></pre>
<p>And I accidentally omitted the <code>--user</code> flags from the pip and python installation command examples above. In my container environment everything is installed into the user's home directory using <code>--user</code> and <strong>NOT</strong> in the global <code>site-packages</code> directory.</p>
<p><strong>UPDATE 2</strong></p>
<p>I've added the following code to the file that is generating the error:</p>
<pre><code>print('***********************************************************************************')
import sys
print(sys.path)
from google.cloud import secretmanager_v1beta1 as secretmanager
print('secretmanager.__file__: {}'.format(secretmanager.__file__))
</code></pre>
<p>From <code>airflow list_dags</code>:</p>
<pre><code>['/home/app/.local/bin', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/home/app/.local/lib/python3.7/site-packages', '/home/app/.local/lib/python3.7/site-packages/Jeeves-0.0.1-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/google_cloud_secret_manager-0.2.0-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/pyconfighelper-0.0.7-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/click-7.1.1-py3.7.egg', '/workspace/airflow', '/usr/local/lib/python3.7/site-packages', '/workspace/airflow/dags', '/workspace/airflow/config', '/workspace/airflow/plugins']
secretmanager.__file__: /home/app/.local/lib/python3.7/site-packages/google_cloud_secret_manager-0.2.0-py3.7.egg/google/cloud/secretmanager_v1beta1/__init__.py
</code></pre>
<p>From <code>python my_dag.py</code>:</p>
<pre><code>['/workspace/airflow/dags', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/home/app/.local/lib/python3.7/site-packages', '/home/app/.local/lib/python3.7/site-packages/Jeeves-0.0.1-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/google_cloud_secret_manager-0.2.0-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/pyconfighelper-0.0.7-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/click-7.1.1-py3.7.egg', '/home/app/.local/lib/python3.7/site-packages/icentris_ml_airflow-0.0.0-py3.7.egg', '/usr/local/lib/python3.7/site-packages']
</code></pre>
<p><strong>UPDATE 3</strong>
<code>tree airflow/dags</code></p>
<pre><code>airflow/dags
βββ __init__.py
βββ __pycache__
βΒ Β βββ __init__.cpython-37.pyc
βΒ Β βββ bq_to_cs.cpython-37.pyc
βΒ Β βββ bq_to_wrench.cpython-37.pyc
βΒ Β βββ fetch_cloudsql_tables-bluesun.cpython-37.pyc
βΒ Β βββ fetch_cloudsql_tables.cpython-37.pyc
βΒ Β βββ fetch_app_tables-bluesun.cpython-37.pyc
βΒ Β βββ fetch_app_tables.cpython-37.pyc
βΒ Β βββ gcs_to_cloudsql.cpython-37.pyc
βΒ Β βββ gcs_to_s3.cpython-37.pyc
βΒ Β βββ lake_to_staging.cpython-37.pyc
βΒ Β βββ schedule_dfs_sql_to_bq-bluesun.cpython-37.pyc
βΒ Β βββ schedule_dfs_sql_to_bq.cpython-37.pyc
βΒ Β βββ app_to_bq_initial_load-bluesun.cpython-37.pyc
βΒ Β βββ app_to_lake-bluesun.cpython-37.pyc
βΒ Β βββ app_to_lake.cpython-37.pyc
βββ bq_to_wrench.py
βββ composer_variables.json
βββ my_ml_airflow.egg-info
βΒ Β βββ PKG-INFO
βΒ Β βββ SOURCES.txt
βΒ Β βββ dependency_links.txt
βΒ Β βββ top_level.txt
βββ lake_to_staging.py
βββ libs
βΒ Β βββ __init__.py
βΒ Β βββ __pycache__
βΒ Β βΒ Β βββ __init__.cpython-37.pyc
βΒ Β βΒ Β βββ checkpoint.cpython-37.pyc
βΒ Β βΒ Β βββ utils.cpython-37.pyc
βΒ Β βββ checkpoint.py
βΒ Β βββ io
βΒ Β βΒ Β βββ __init__.py
βΒ Β βΒ Β βββ __pycache__
βΒ Β βΒ Β βΒ Β βββ __init__.cpython-37.pyc
βΒ Β βΒ Β βββ gcp
βΒ Β βΒ Β βββ __init__.py
βΒ Β βΒ Β βββ __pycache__
βΒ Β βΒ Β βΒ Β βββ __init__.cpython-37.pyc
βΒ Β βΒ Β βΒ Β βββ storage.cpython-37.pyc
βΒ Β βΒ Β βββ storage.py
βΒ Β βββ shared -> /workspace/shared/
βΒ Β βββ utils.py
βββ requirements.txt
βββ table_lists
βΒ Β βββ table-list.json
βββ templates
βββ sql
βββ lake_to_staging.contacts.sql
βββ lake_to_staging.orders.sql
βββ lake_to_staging.users.sql
11 directories, 41 files
</code></pre>
<p><strong>UPDATE 4</strong></p>
<p>I tried fixing it so that <code>sys.path</code> looked the same when running <code>python dags/my_dag.py</code> as it does when running <code>airflow list_dags</code> or <code>pytest test_my_dag.py</code>.</p>
<p>Still get the same error. </p>
<p>Looking at a more recent version of documentation, I noticed that you <em>should</em> be able to just do <code>from google.cloud import secretmanager</code>. Which gave me the same result (works with airflow and pytest, not when trying to run directly). </p>
<p>At this point, my best guess is that it has something to do with namespace magic, but I'm not sure?</p> | <p>It have to be installed via terminal: <code>pip install google-cloud-secret-manager</code>
Because package name is not secretmanager but google-cloud-secret-manager</p> | python-3.x|google-cloud-platform|python-import|google-secret-manager | 8 |
5 | 49,532,854 | Python - Multiple 'split' Error | <p>I posted here 4-5 days ago, about one problem to sort some numbers from file.
Now, is the same of the other problem but, I want to sort numbers from one file (x) to another file (y). For example: In x i have: (5,6,3,11,7), and I want to sort this numbers to y (3,5,6,7,11). But I have some errors and can't resolve on my own, I do not understand them, can you help me?</p>
<pre><code>from sys import argv
try:
with open(argv[1],"r") as desti:
cad = desti.readlines()
k= list(cad)
for n in range(len(cad)):
k = n.split(',')
k = (int, cad)
k = sorted(cad)
with open("nums_ordenats.txt","w") as prl:
prl.write(k)
except Exception as err:
print(err, "Error")
</code></pre>
<p>Actually, the error message is " 'int' object has no attribute 'split' Error
".
I think the code is correct. Also, the program says me other errors, but how im changintg code everytime, they also change. </p>
<p>Tanks a lot! </p> | <p>There are too many problems with your code for me to address. Try this:</p>
<pre><code>from sys import argv
with open(argv[1], "r") as infile:
with open("nums_ordenats.txt", "w") as outfile:
for line in infile:
nums = [int(n) for n in line.split(',')]
nums.sort()
outfile.write(','.join([str(n) for n in nums]))
outfile.write('\n')
</code></pre> | python|python-3.x|list|sorting|tuples | 0 |
6 | 62,587,462 | PyQT - QlistWidget with infinite scroll | <p>I have a QlistWidget and I need to implement on this an Infinite Scroll, something like this HTML example:</p>
<p><a href="https://scrollmagic.io/examples/advanced/infinite_scrolling.html" rel="nofollow noreferrer">https://scrollmagic.io/examples/advanced/infinite_scrolling.html</a></p>
<p>Basically, when the user scrolls to the last item of the list, I need to load more items and dynamically append it in the QlistWidget.</p>
<p>Is it possible? I didn't find any example yet.</p> | <p>There are likely many ways to achieve this task, but the easiest I found is to watch for changes in the scroll bar, and detect if we're at the bottom before adding more items to the list widget.</p>
<pre><code>import sys, random
from PyQt5.QtWidgets import QApplication, QListWidget
class infinite_scroll_area(QListWidget): #https://doc.qt.io/qt-5/qlistwidget.html
def __init__(self):
super().__init__() #call the parent constructor if you're overriding it.
#connect our own function the valueChanged event
self.verticalScrollBar().valueChanged.connect(self.valueChanged)
self.add_lines(15)
self.show()
def valueChanged(self, value): #https://doc.qt.io/qt-5/qabstractslider.html#valueChanged
if value == self.verticalScrollBar().maximum(): #if we're at the end
self.add_lines(5)
def add_lines(self, n):
for _ in range(n): #add random lines
line_text = str(random.randint(0,100)) + ' some data'
self.addItem(line_text)
if __name__ == "__main__":
app = QApplication(sys.argv)
widget = infinite_scroll_area()
sys.exit(app.exec_())
</code></pre>
<p>You can directly grab scroll wheel events by overriding the <a href="https://doc.qt.io/qt-5/qlistview.html#wheelEvent" rel="nofollow noreferrer"><code>wheelEvent</code></a> method of <code>QListWidget</code>, then do the logic there which solves the potential problem of not starting out with enough list items for the scrollbar to appear. If it's not there, it can't change value, and the event can't fire. It introduces a new problem however as scrolling with the mouse wheel is not the only way to scroll the view (arrow keys, page up/down keys, etc). With the number of classes and subclasses in any gui library, it becomes imperative to get really familiar with the documentation. It's a little inconvenient that it isn't as comprehensive for python specifically, but I think the c++ docs are second to none as far as gui library documentation goes.</p> | python|pyqt|pyqt5|qlistwidget | 1 |
7 | 53,736,868 | How to correctly import custom widgets in kivy | <p>I have a widget(W2), made of other widgets (W1). Each has a corresponding .kv file as below. Running main.py, I expect to see a black background with two labels, vertically stacked. Instead, I get both labels on top of each other, so something has gone wrong.</p>
<pre><code>kivy.factory.FactoryException: Unknown class <W1>
</code></pre>
<p>So I thought, "Maybe I should import w1.py in w2.py even though it's not explicitly used in the py file? That ... sort of worked. I get both labels on top of each other, as in the following image.</p>
<p><a href="https://i.stack.imgur.com/Nn8yy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nn8yy.png" alt="enter image description here"></a></p>
<p>What am I doing wrong? What is the correct way to write a widget that is expected to be imported/included by another widget? And the correct way to import it?</p>
<p>I tried using <code>Builder.load_file()</code> in the .py file and just importing the .py file but that had similar results.</p>
<p><strong>w1.py:</strong></p>
<pre><code>import kivy
from kivy.properties import StringProperty
from kivy.uix.widget import Widget
kivy.require('1.10.0')
class W1(Widget):
text = StringProperty('default')
def __init__(self, **kwargs):
super(W1, self).__init__(**kwargs)
</code></pre>
<p><strong>w1.kv:</strong></p>
<pre><code>#:kivy 1.10.0
<W1>:
text:
Label:
text: root.text
</code></pre>
<p><strong>w2.py:</strong></p>
<pre><code>import kivy from kivy.uix.boxlayout import BoxLayout
# from w1 import W1 # added this to get a working, but the incorrect layout
kivy.require('1.10.0')
class W2(BoxLayout):
def __init__(self, **kwargs):
super(W2, self).__init__(**kwargs)
</code></pre>
<p><strong>w2.kv:</strong></p>
<pre><code>#:kivy 1.10.0
#:include w1.kv
<W2>:
orientation: 'vertical'
W1:
text: 'w1.1'
W1:
text: 'w1.2'
</code></pre>
<p><strong>main.py:</strong></p>
<pre><code>import kivy
from w2 import W2
from kivy.app import App
kivy.require('1.10.0')
class mainApp(App):
def build(self):
pass
if __name__ == '__main__':
mainApp().run()
</code></pre>
<p><strong>main.kv:</strong></p>
<pre><code>#:kivy 1.10.0
#:include w2.kv
W2:
</code></pre>
<p><strong>EDIT</strong>
The overlapping has been resolved, though maybe not correctly. I had W1 inherit from BoxLayout rather than Widget, with the thought that maybe there was a minimum height/width property missing in the base Widget class.</p>
<p>I'm still not certain what the "correct" way to handle importing a widget which has a paired .kv file is, or exactly why I'm getting overlapping widgets when I inherit from Widget; only speculation.
<a href="https://i.stack.imgur.com/lxaPe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lxaPe.png" alt="enter image description here"></a></p> | <p>why are you using two different kv files for this?
I would say the proper way would be similar to what i have with my kv file. because you are spliting up things that can be done on a single page and if you need different pages you use the <code>ScreenManager</code> import stuff</p>
<p><strong>main.py</strong>:</p>
<pre><code>`
import kivy
from kivy.app import App
from kivy.uix.widgets import Widget
from kivy.uix.label import Label
from kivy.uix.gridlayut import GridLayout
class MyGrid(Widget):
pass
class MyApp(App):
def build(self):
# this calls what we want to show in the kv file
return MyGrid()
if __name__ == "__main__":
MyApp().run()
`
</code></pre>
<h1>file is written like this because the App falls off and in order to link the 2 it must have the same name</h1>
<p><strong>my.kv</strong>:
# "<>" Basically links <code>MyGrid</code> from the .py file and then displays the
# gridlayout and such
GridLayout:
rows: 2</p>
<pre><code> Label:
text: "whatever"
Label:
text: "whatever 2"
</code></pre> | python-3.x|kivy|kivy-language | 0 |
8 | 53,456,874 | ImportError: cannot import name 'convert_kernel' | <p>When i try to use tensorflow to train model, i get this error message. </p>
<p>File "/Users/ABC/anaconda3/lib/python3.6/site-packages/keras/utils/layer_utils.py", line 7, in
from .conv_utils import convert_kernel</p>
<p>ImportError: cannot import name 'convert_kernel'</p>
<p>i have already install Keras</p> | <p>I got the same issue. The filename of my python code was "tensorflow.py". After I changed the name to "test.py". The issue was resolved.</p>
<p>I guess there is already a "tensorflow.py" in the tensorflow package. If anyone uses the same name, it may lead to the conflict.</p>
<p>If your python code is also called "tensorflow.py", you can try to use other names and see if it helps.</p> | python|tensorflow | 1 |
9 | 53,467,807 | Python function that identifies if the numbers in a list or array are closer to 0 or 1 | <p>I have a <code>numpy</code> array of numbers. Below is an example:</p>
<pre><code>[[-2.10044520e-04 1.72314372e-04 1.77235336e-04 -1.06613465e-04
6.76617611e-07 2.71623057e-03 -3.32789944e-05 1.44899758e-05
5.79249863e-05 4.06502549e-04 -1.35823707e-05 -4.13955189e-04
5.29862793e-05 -1.98286005e-04 -2.22829175e-04 -8.88758230e-04
5.62228710e-05 1.36249752e-05 -2.00474996e-05 -2.10090068e-05
1.00007518e+00 1.00007569e+00 -4.44597417e-05 -2.93724453e-04
1.00007513e+00 1.00007496e+00 1.00007532e+00 -1.22357142e-03
3.27903892e-06 1.00007592e+00 1.00007468e+00 1.00007558e+00
2.09869172e-05 -1.97610235e-05 1.00007529e+00 1.00007530e+00
1.00007503e+00 -2.68725642e-05 -3.00372853e-03 1.00007386e+00
1.00007443e+00 1.00007388e+00 5.86993822e-05 -8.69989983e-06
1.00007590e+00 1.00007488e+00 1.00007515e+00 8.81850779e-04
2.03875532e-05 1.00007480e+00 1.00007425e+00 1.00007517e+00
-2.44678912e-05 -4.36556267e-08 1.00007436e+00 1.00007558e+00
1.00007571e+00 -5.42990711e-04 1.45517859e-04 1.00007522e+00
1.00007469e+00 1.00007575e+00 -2.52271817e-05 -7.46339417e-05
1.00007427e+00]]
</code></pre>
<p>I want to know if each of the numbers is closer to 0 or 1. Is there a function in Python that could do it or do I have to do it manually?</p> | <p>A straightforward way:</p>
<pre><code>lst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
closerTo1 = [x >= 0.5 for x in lst]
</code></pre>
<p>Or you can use np:</p>
<pre><code>import numpy as np
lst=[0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9]
arr = np.array(lst)
closerTo1 = arr >= 0.5
</code></pre>
<p>Note that <code>>= 0.5</code> can be changed to <code>> 0.5</code>, however you choose to treat it.</p> | python|arrays|list|function|numpy | 22 |
10 | 53,424,798 | Python pandas: map and return Nan | <p>I have two data frame, the first one is:</p>
<pre><code>id code
1 2
2 3
3 3
4 1
</code></pre>
<p>and the second one is:</p>
<pre><code>id code name
1 1 Mary
2 2 Ben
3 3 John
</code></pre>
<p>I would like to map the data frame 1 so that it looks like:</p>
<pre><code>id code name
1 2 Ben
2 3 John
3 3 John
4 1 Mary
</code></pre>
<p>I try to use this code:</p>
<pre><code>mapping = dict(df2[['code','name']].values)
df1['name'] = df1['code'].map(mapping)
</code></pre>
<p>My mapping is correct, but the mapping value are all NAN:</p>
<pre><code>mapping = {1:"Mary", 2:"Ben", 3:"John"}
id code name
1 2 NaN
2 3 NaN
3 3 NaN
4 1 NaN
</code></pre>
<p>Can anyone know why an how to solve? </p> | <p>Problem is different type of values in column <code>code</code> so necessary converting to integers or strings by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.astype.html" rel="noreferrer"><code>astype</code></a> for same types in both:</p>
<pre><code>print (df1['code'].dtype)
object
print (df2['code'].dtype)
int64
</code></pre>
<pre><code>print (type(df1.loc[0, 'code']))
<class 'str'>
print (type(df2.loc[0, 'code']))
<class 'numpy.int64'>
</code></pre>
<hr>
<pre><code>mapping = dict(df2[['code','name']].values)
#same dtypes - integers
df1['name'] = df1['code'].astype(int).map(mapping)
</code></pre>
<pre><code>#same dtypes - object (obviously strings)
df2['code'] = df2['code'].astype(str)
mapping = dict(df2[['code','name']].values)
df1['name'] = df1['code'].map(mapping)
</code></pre>
<hr>
<pre><code>print (df1)
id code name
0 1 2 Ben
1 2 3 John
2 3 3 John
3 4 1 Mary
</code></pre> | python|pandas|dataframe | 6 |
11 | 54,843,657 | How to select a specific range of cells in an Excel worksheet with Python library tools | <p>I would like to select a specific range of cells in a workbook worksheet. I am currently able to set a variable to a workbook worksheet with the line below.</p>
<pre><code> import pandas as pd
sheet1 = pd.read_excel('workbookname1.xlsx', sheet_name = ['sheet1'])
</code></pre>
<p>I would like to go one step further and have the ability to select a range of cells in the worksheet so that I can practice dataframe functionality with the defined range. Some of my ranges are with row values greater than 1000. How am I able to select a variable length row value for the desired excel range?</p> | <p>You can utilize <code>OpenPyXl</code> module.</p>
<pre><code>from openpyxl import Workbook, load_workbook
wb = load_workbook("workbookname1.xlsx")
ws = wb.active
cell_range = ws['A1':'C2']
</code></pre>
<p>You can also use <code>iter_rows()</code> or <code>iter_columns()</code> methods.</p>
<p>For additional information, you can refer to <a href="https://media.readthedocs.org/pdf/openpyxl/latest/openpyxl.pdf" rel="nofollow noreferrer">OpenPyXL documentation</a>.</p> | python|pandas|series | 2 |
12 | 33,204,160 | Listing all class members with Python `inspect` module | <p>What is the "optimal" way to list all class methods of a given class using <code>inspect</code>? It works if I use the <code>inspect.isfunction</code> as predicate in <code>getmembers</code> like so</p>
<pre><code>class MyClass(object):
def __init(self, a=1):
pass
def somemethod(self, b=1):
pass
inspect.getmembers(MyClass, predicate=inspect.isfunction)
</code></pre>
<p>returns</p>
<pre><code>[('_MyClass__init', <function __main__.MyClass.__init>),
('somemethod', <function __main__.MyClass.somemethod>)]
</code></pre>
<p>But isn't it supposed to work via <code>ismethod</code>?</p>
<pre><code> inspect.getmembers(MyClass, predicate=inspect.ismethod)
</code></pre>
<p>which returns an empty list in this case. Would be nice if someone could clarify what's going on. I was running this in Python 3.5.</p> | <p>As described in the documentation, <a href="https://docs.python.org/3/library/inspect.html#inspect.ismethod" rel="noreferrer"><code>inspect.ismethod</code></a> will show bound methods. This means you have to create an instance of the class if you want to inspect its methods. Since you are trying to inspect methods on the un-instantiated class you are getting an empty list.</p>
<p>If you do:</p>
<pre><code>x = MyClass()
inspect.getmembers(x, predicate=inspect.ismethod)
</code></pre>
<p>you would get the methods.</p> | python|class|inspect | 10 |
13 | 33,425,495 | Groupby in pandas multiplication | <p>I have a data frame called <code>bf</code>. The commas are mine, it was imported from a csv file.</p>
<pre><code>val,ben
a,123
b,234
c,123
</code></pre>
<p>I have another larger data frame <code>df</code></p>
<pre><code> bla,val, blablab, blablaa
1,a,123,333
2,b,333,222
3,c,12,33
1,a,123,333
.....
</code></pre>
<p>I would like to create a new data frame which multiplies all rows of <code>df</code> with the specific value corresponding to <code>ben</code> for it, taken from <code>bf</code>. For exaple the first row of this new data frame will be <code>1,a,123*123,333*123</code> How do we do that using pandas and groupby?</p>
<p>EDIT: Note that <code>bf</code> and <code>df</code> have different lengths.</p> | <p>Probably you want to use a merge to bring in the column <code>ben</code> into your dataframe:</p>
<pre><code>df_merged = pd.merge(df, bf, on='val')
</code></pre>
<p>Then you can calculate your product however you like, for example:</p>
<pre><code>df_prod = df_merged * df_merged.ben
</code></pre> | python|pandas|group-by | 1 |
14 | 13,055,309 | Why doesn't this python function with a dictionary named parameter and a default value apply the default value each time it's called? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument">βLeast Astonishmentβ in Python: The Mutable Default Argument</a> </p>
</blockquote>
<p>The following code illustrates the issue:</p>
<pre><code>def fn(param, named_param={}, another_named_param=1):
named_param[param] = str(another_named_param)
another_named_param += param
return named_param
for i in range(0, 2):
result = {}
result = fn(i)
print result
print
for i in range(0, 2):
result = fn(i, named_param={})
print result
print
result = fn(0)
print result
result = fn(1)
print result
</code></pre>
<p>Output:</p>
<pre><code>{0: '1'}
{0: '1', 1: '1'}
{0: '1'}
{1: '1'}
{0: '1', 1: '1'}
{0: '1', 1: '1'}
</code></pre>
<p>I expected the output of the 1st, 2nd loop and subsequent 2 single calls with param matching the values of the for loop would have the same textual output, but <code>fn</code> holds onto the value of <code>named_param</code> if not explicitly defaulted to an empty dictionary. Is functionality defined in the documentation?</p> | <p>The default value of <code>named_param</code> is evaluated once, when the function definition is executed. It is the same dictionary each time and its value is retained between calls to the function.</p>
<p>Do not use mutable objects as default values in functions unless you do not mutate them. Instead, use <code>None</code> or another sentinel value, and check for that value and replace it with a fresh object (e.g. empty dictionary). This way you get a fresh one each time your function is called.</p> | python | 1 |
15 | 12,921,260 | Importing a class to another class in python | <p>I am trying to learn python i tried to import a class in another class but it is not working</p>
<p><code>Application.py</code>:</p>
<pre><code>class Application:
def example(self):
return "i am from Application class"
</code></pre>
<p><code>Main.py</code></p>
<pre><code>class Main:
def main():
application = Application()
application.example()
if __name__ == "__main__":
Main.main()
</code></pre>
<p>This gives me :</p>
<pre><code>File "Main.py", line 11, in <module>
Main.main()
TypeError: unbound method main() must be called with Main instance as first argument (got nothing instead)
</code></pre> | <p>You should instantiate your Main class first. </p>
<pre><code>if __name__ == '__main__':
myMain = Main()
myMain.main()
</code></pre>
<p>But this will give you another error:</p>
<blockquote>
<p>TypeError: main() takes no arguments (1 given)</p>
</blockquote>
<p>There are two ways to fix this. Either make Main.main take one argument:</p>
<pre><code>class Main:
def main(self):
application = Application()
application.example()
</code></pre>
<p>or make Main.main a static method. In which case you don't have to instantiate your Main class:</p>
<pre><code>class Main:
@staticmethod
def main():
application = Application()
application.example()
if __name__ == "__main__":
Main.main()
</code></pre> | python | 0 |
16 | 21,924,444 | Jinja2 extensions - get the value of variable passed to extension | <p>So I have a Jinja2 extension. Basically follows the parser logic, except that I need to get a value from the parsed args being passed in.</p>
<p>For instance, if I have an extension called loadfile, and pass it a variable:</p>
<p><code>{% loadfile "file.txt" %}</code></p>
<p>when I grab the argument through <code>parser.parse_expression()</code> I get a <code>node.Const</code> variable that has a <code>.value</code> argument - and I can get the name <code>file.txt</code> no problem.</p>
<p>However...</p>
<pre><code>{% set filename = "file.txt" %}
{% loadfile filename %}
</code></pre>
<p>causes me issues. The parser gives me a <code>node.Name</code> expr node, which neither responds to <code>.value</code> or the <code>as_const(...)</code> call that all other nodes respond to.</p>
<p>I can't figure out how to evaluate the value of the <code>node.Name</code> node I'm getting from parsing the arguments, and thus cannot get the name <code>file.txt</code>.</p>
<p>Is there a good way to parse argument variables/values in an extension so that I can use them to execute the extention?</p>
<p>Thanks!</p> | <p>This works for me</p>
<pre><code>def parse(self, parser):
lineno = parser.stream.next().lineno
# args will contains filename
args = [parser.parse_expression()]
return nodes.Output([
nodes.MarkSafeIfAutoescape(self.call_method('handle', args))
]).set_lineno(lineno)
def handle(self, filename):
# bla-bla-bla
</code></pre> | python|jinja2 | 1 |
17 | 24,472,957 | Get relative links from html page | <p>I want to extract only relative urls from html page; somebody has suggest this :</p>
<pre><code>find_re = re.compile(r'\bhref\s*=\s*("[^"]*"|\'[^\']*\'|[^"\'<>=\s]+)', re.IGNORECASE)
</code></pre>
<p>but it return :</p>
<p>1/all absolute and relative urls from the page.</p>
<p>2/the url may be quated by <code>""</code> or <code>''</code> randomly .</p> | <p>Use <a href="https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags">the tool for the job</a>: an <code>HTML parser</code>, like <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="nofollow noreferrer"><code>BeautifulSoup</code></a>.</p>
<p>You can <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-function" rel="nofollow noreferrer">pass a function</a> as an attribute value to <a href="http://www.crummy.com/software/BeautifulSoup/bs4/doc/#find-all" rel="nofollow noreferrer"><code>find_all()</code></a> and check whether <code>href</code> starts with <code>http</code>:</p>
<pre><code>from bs4 import BeautifulSoup
data = """
<div>
<a href="http://google.com">test1</a>
<a href="test2">test2</a>
<a href="http://amazon.com">test3</a>
<a href="here/we/go">test4</a>
</div>
"""
soup = BeautifulSoup(data)
print soup.find_all('a', href=lambda x: not x.startswith('http'))
</code></pre>
<p>Or, using <a href="https://docs.python.org/2/library/urlparse.html" rel="nofollow noreferrer"><code>urlparse</code></a> and <a href="https://stackoverflow.com/a/8357518/771848">checking for network location part</a>:</p>
<pre><code>def is_relative(url):
return not bool(urlparse.urlparse(url).netloc)
print soup.find_all('a', href=is_relative)
</code></pre>
<p>Both solutions print:</p>
<pre><code>[<a href="test2">test2</a>,
<a href="here/we/go">test4</a>]
</code></pre> | python|html|regex|html-parsing | 4 |
18 | 24,665,403 | replace information in Json string based on a condition | <p>I have a very large json file with several nested keys. From whaat I've read so far, if you do:</p>
<pre><code>x = json.loads(data)
</code></pre>
<p>Python will interpret it as a dictionary (correct me if I'm wrong). The fourth level of nesting in the json file contains several elements named by an ID number and all of them contain an element called children, something like this:</p>
<pre><code>{"level1":
{"level2":
{"level3":
{"ID1":
{"children": [1,2,3,4,5]}
}
{"ID2":
{"children": []}
}
{"ID3":
{"children": [6,7,8,9,10]}
}
}
}
}
</code></pre>
<p>What I need to do is to replace all items in all the <code>"children"</code> elements with nothing, meaning <code>"children": []</code> if the ID number is in a list called <code>new_ids</code> and then convert it back to json. I've been reading on the subject for a few hours now but I haven't found anything similar to this to try to help myself.</p>
<p>I'm running Python 3.3.3. Any ideas are greatly appreciated!!</p>
<p>Thanks!!</p>
<p><strong>EDIT</strong></p>
<p>List:</p>
<pre><code>new_ids=["ID1","ID3"]
</code></pre>
<p>Expected result:</p>
<pre><code>{"level1":
{"level2":
{"level3":
{"ID1":
{"children": []}
}
{"ID2":
{"children": []}
}
{"ID3":
{"children": []}
}
}
}
}
</code></pre> | <p>First of all, your JSON is invalid. I assume you want this:</p>
<pre><code>{"level1":
{"level2":
{"level3":
{
"ID1":{"children": [1,2,3,4,5]},
"ID2":{"children": []},
"ID3":{"children": [6,7,8,9,10]}
}
}
}
}
</code></pre>
<p>Now, load your data as a dictionary:</p>
<pre><code>>>> with open('file', 'r') as f:
... x = json.load(f)
...
>>> x
{u'level1': {u'level2': {u'level3': {u'ID2': {u'children': []}, u'ID3': {u'children': [6, 7, 8, 9, 10]}, u'ID1': {u'children': [1, 2, 3, 4, 5]}}}}}
</code></pre>
<p>Now you can loop over the keys in <code>x['level1']['level2']['level3']</code> and check whether they are in your <code>new_ids</code>.</p>
<pre><code>>>> new_ids=["ID1","ID3"]
>>> for key in x['level1']['level2']['level3']:
... if key in new_ids:
... x['level1']['level2']['level3'][key]['children'] = []
...
>>> x
{u'level1': {u'level2': {u'level3': {u'ID2': {u'children': []}, u'ID3': {u'children': []}, u'ID1': {u'children': []}}}}}
</code></pre>
<p>You can now write <code>x</code> back to a file like this:</p>
<pre><code>with open('myfile', 'w') as f:
f.write(json.dumps(x))
</code></pre>
<p>If your <code>new_ids</code> list is large, consider making it a <code>set</code>.</p> | python|json|python-3.x | 1 |
19 | 38,326,387 | How to get percentiles on groupby column in python? | <p>I have a dataframe as below:</p>
<pre><code>df = pd.DataFrame({'state': ['CA', 'WA', 'CO', 'AZ'] * 3,
'office_id': list(range(1, 7)) * 2,
'sales': [np.random.randint(100000, 999999) for _ in range(12)]})
</code></pre>
<p>To get percentiles of sales,state wise,I have written below code:</p>
<pre><code>pct_list1 = []
pct_list2 = []
for i in df['state'].unique().tolist():
pct_list1.append(i)
for j in range(0,101,10):
pct_list1.append(np.percentile(df[df['state'] == i]['sales'],j))
pct_list2.append(pct_list1)
pct_list1 = []
colnm_list1 = []
for k in range(0,101,10):
colnm_list1.append('perct_'+str(k))
colnm_list2 = ['state'] + colnm_list1
df1 = pd.DataFrame(pct_list2)
df1.columns = colnm_list2
df1
</code></pre>
<p>Can we optimize this code?</p>
<p>I feel that,we can also use</p>
<pre><code>df1 = df[['state','sales']].groupby('state').quantile(0.1).reset_index(level=0)
df1.columns = ['state','perct_0']
for i in range(10,101,10):
df1.loc[:,('perct_'+str(i))] = df[['state','sales']].groupby('state').quantile(float(i/100.0)).reset_index(level=0)['sales']
</code></pre>
<p>If there are any other alternatives,please help.</p>
<p>Thanks.</p> | <p>How about this?</p>
<pre><code>quants = np.arange(.1,1,.1)
pd.concat([df.groupby('state')['sales'].quantile(x) for x in quants],axis=1,keys=[str(x) for x in quants])
</code></pre> | python|pandas | 1 |
20 | 38,490,748 | Isolating subquery from its parent | <p>I have a <code>column_property</code> on my model that is a count of the relationships on a secondary model.</p>
<pre><code>membership_total = column_property(
select([func.count(MembershipModel.id)]).where(
MembershipModel.account_id == id).correlate_except(None))
</code></pre>
<p>This works fine until I try to join the membership model.</p>
<pre><code>query = AccountModel.query.join(MembershipModel)
# ProgrammingError: subquery uses ungrouped column "membership.account_id" from outer query
</code></pre>
<p>I can fix this issue by appending:</p>
<pre><code>query = query.group_by(MembershipModel.account_id, AccountModel.id)
# resolves the issue
</code></pre>
<p>But I don't really want to do that. I want it to be its own island that ignores whatever the query is doing and just focuses on returning a count of memberships for that particular row's account ID.</p>
<p>What can I do to the column_property to make it more robust and less reliant on what the parent query is doing?</p> | <p>Pass <code>MembershipModel</code> to <code>correlate_except()</code> instead of <code>None</code>, as described <a href="http://docs.sqlalchemy.org/en/latest/orm/mapped_sql_expr.html#using-column-property" rel="nofollow">here</a> in the documentation. Your current method allows omitting everything from the subquery's FROM-clause, if it can be correlated to the enclosing query. When you join <code>MembershipModel</code> it becomes available in the enclosing query.</p>
<p>Here's a simplified example. Given 2 models <code>A</code> and <code>B</code>:</p>
<pre><code>In [2]: class A(Base):
...: __tablename__ = 'a'
...: id = Column(Integer, primary_key=True, autoincrement=True)
...:
In [3]: class B(Base):
...: __tablename__ = 'b'
...: id = Column(Integer, primary_key=True, autoincrement=True)
...: a_id = Column(Integer, ForeignKey('a.id'))
...: a = relationship('A', backref='bs')
</code></pre>
<p>and 2 <code>column_property</code> definitions on <code>A</code>:</p>
<pre><code>In [10]: A.b_count = column_property(
select([func.count(B.id)]).where(B.a_id == A.id).correlate_except(B))
In [11]: A.b_count_wrong = column_property(
select([func.count(B.id)]).where(B.a_id == A.id).correlate_except(None))
</code></pre>
<p>If we query just <code>A</code>, everything's fine:</p>
<pre><code>In [12]: print(session.query(A))
SELECT a.id AS a_id, (SELECT count(b.id) AS count_1
FROM b
WHERE b.a_id = a.id) AS anon_1, (SELECT count(b.id) AS count_2
FROM b
WHERE b.a_id = a.id) AS anon_2
FROM a
</code></pre>
<p>But if we join <code>B</code>, the second property incorrectly correlates <code>B</code> from the enclosing query and completely omits the FROM-clause:</p>
<pre><code>In [13]: print(session.query(A).join(B))
SELECT a.id AS a_id, (SELECT count(b.id) AS count_1
FROM b
WHERE b.a_id = a.id) AS anon_1, (SELECT count(b.id) AS count_2
WHERE b.a_id = a.id) AS anon_2
FROM a JOIN b ON a.id = b.a_id
</code></pre> | python|sqlalchemy | 2 |
21 | 31,154,238 | Clustering latitude longitude points in Python with fixed number of clusters | <p>kmeans does not work properly for geospatial coordinates - even when changing the distance function to haversine as stated <a href="https://datascience.stackexchange.com/a/848/10436">here</a>.</p>
<p>I had a look at <a href="http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html" rel="nofollow noreferrer">DBSCAN</a> which doesn
t let me set a fixed number of clusters.</p>
<ol>
<li>Is there any algorithm (in python if possible) that has the same input values as kmeans? or</li>
<li>Can I easily convert latitude, longitude to euclidean coordinates (x,y,z) as done <a href="https://stackoverflow.com/a/1185413/1252307">here</a> and do the calculation on my data?</li>
</ol>
<p>It does not have to perfectly accurate, but it would nice if it would.</p> | <p>Using just lat and longitude leads to problems when your geo data spans a large area. Especially since the distance between longitudes is less near the poles. To account for this it is good practice to first convert lon and lat to cartesian coordinates.</p>
<p>If your geo data spans the united states for example you could define an origin from which to calculate distance from as the center of the contiguous united states. I believe this is located at Latitude 39 degrees 50 minutes and Longitude 98 degrees 35 minute.</p>
<p>TO CONVERT lat lon to CARTESIAN coordinates- calculate the distance using haversine, from every location in your dataset to the defined origin. Again, I suggest Latitude 39 degrees 50 minutes and Longitude 98 degrees 35 minute. </p>
<p>You can use haversine in python to calculate these distances:</p>
<pre><code>from haversine import haversine
origin = (39.50, 98.35)
paris = (48.8567, 2.3508)
haversine(origin, paris, miles=True)
</code></pre>
<p>Now you can use k-means on this data to cluster, assuming the haversin model of the earth is adequate for your needs. If you are doing data analysis and not planning on launching a satellite I think this should be okay.</p> | python|gis|geospatial|latitude-longitude|k-means | 4 |
22 | 39,930,022 | How to make exceptions during the iteration of a for loop in python | <p>Sorry in advance for the certainly simple answer to this but I can't seem to figure out how to nest an <code>if ______ in ____:</code> block into an existing <code>for</code> block.</p>
<p>For example, how would I change this block to iterate through each instance of <code>i</code>, omitting odd numbers. </p>
<pre><code>odds = '1 3 5 7 9'.split()
for i in range(x):
if i in odds:
continue
print(i)
</code></pre>
<p>this code works for <code>if i == y</code> but I cannot get it to work with a specific set of "y"s</p> | <p>This has nothing to do with nesting. You are comparing apples to pears, or in this case, trying to find an <code>int</code> in a list of <code>str</code> objects.</p>
<p>So the <code>if</code> test never matches, because there is no <code>1</code> in the list <code>['1', '3', '5', '7', '9']</code>; there is no <code>3</code> or <code>5</code> or <code>7</code> or <code>9</code> either, because an integer is a different type of object from a string, even if that string contains digits that look, to you as a human, like digits.</p>
<p>Either convert your int to a string first, or convert your strings to integers:</p>
<pre><code>if str(i) in odds:
</code></pre>
<p>or</p>
<pre><code>odds = [int(i) for i in '1 3 5 7 9'.split()]
</code></pre>
<p>If you want to test for odd numbers, there is a much better test; check if the remainder of division by 2 is 1:</p>
<pre><code>if i % 2 == 1: # i is an odd number
</code></pre> | python|python-3.x|if-statement|for-loop|nested | 4 |
23 | 8,482,007 | Python 2.6.2: writing lines to file hard wrap at 192 characters | <p>I implemented a function to make a wrapper to write to files. This is the code:</p>
<pre><code>def writeStringToFile(thestring, thefile, mode='w'):
"""Write a string to filename `thefile' to the directory specified in `dir_out'."""
with open(os.path.join(dir_out, thefile), mode) as fh:
fh.write("{0}\n".format(thestring))
</code></pre>
<p>I found out that when I write any string over 192 characters, a newline is inserted at character 192, resulting in a hard wrap in my output file, which I don't want.</p>
<p>I looked at the docs for the <code>open</code> and <code>write</code> function/method, and I don't see anything that would specify a hard wrap at any line length.</p>
<p>Any insight into fixing this is appreciated.</p> | <p>My own stupidity -- I was writing strings that had the character sequence <code>\n</code> in them, and python was rightly interpreting them as newlines. I need to escape them in my string. I'd take this post down if it hadn't already been responded to.</p> | python | 1 |
24 | 59,013,654 | list of indices in 3D array | <p>I have an array that looks like this:</p>
<pre><code> [[[ -1., 1., -1., 1., -1., 1., 1., 1., 1., -1., 1., 1., 1., 1.]],
[[ 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0.]],
[[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]]
</code></pre>
<p>I have a list of 3 indices</p>
<pre><code>[2,3,4]
</code></pre>
<p>I would like to get only the "rows" where those indices are zero. So the mask would look like this:</p>
<pre><code>[False, True, True]
</code></pre>
<p>And the result I am looking for would just be the two "rows" which satisfy the condition:</p>
<pre><code> [[ 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0., 1., 0.]],
[[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]]
</code></pre>
<p>I put "rows" in quotes because I understand that there is an extra dimension in there - but it needs to stay.</p>
<p>======================EXTENDED EXAMPLE==================</p>
<pre><code>a = [[[0,1,0]], [[0,0,0]], [[1,1,1]], [[1,0,1]], [[0,0,1]], [[1,0,0]]]
b = [0, 1, 2, 2, 1, 0]
c = f(a,b)
For f(a,b)
the first element, [[0,1,0]] is skipped because it has a 0 in the 0th position
the second element, [[0,0,0]] is likewise omitted because because there is a 0 in the 1st position
The third element, [[1,1,1]] is included because it does not have a 0 in the 2nd index position
... and so on...
until the final result is...
c = [[[1, 1, 1]], [[1, 0, 1]], [[1, 0, 0]]
</code></pre>
<p>So I am looking for f()</p> | <p><strong>Solution 1:</strong></p>
<p><strong>The most pythonic way (my way to go).</strong></p>
<pre><code>c = [a[i] for i,j in enumerate(b) if a[i][0][j] == 1]
print(c)
[[[1, 1, 1]], [[1, 0, 1]], [[1, 0, 0]]]
</code></pre>
<hr>
<p><strong>Solution 2:</strong></p>
<pre><code>a = [[[0,1,0]], [[0,0,0]], [[1,1,1]], [[1,0,1]], [[0,0,1]], [[1,0,0]]]
b = [0, 1, 2, 2, 1, 0]
c=[]
for i,j in enumerate(b):
if a[i][0][j] == 1:
c.append(a[i])
print(c)
[[[1, 1, 1]], [[1, 0, 1]], [[1, 0, 0]]]
</code></pre> | python|numpy|numpy-ndarray | 1 |
25 | 51,953,821 | Close cmd while Tk object remains | <p>So I made a simple calculator in Python 3.7 and made a batch file to get it to run from the CMD. The thing is, after I run the batch file, I get a CMD window and then the Tk window, but the CMD window remains there and shuts my program down if I close it.
Is there a way to hide the CMD window or just omit its apperance at all?</p>
<p>Here is how it looks, in case my description is bad:<br>
<a href="https://i.stack.imgur.com/CXAsp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CXAsp.png" alt="Cmd window visible and active"></a></p>
<p>The BATCH FILE reads:</p>
<pre><code>Start "" "C:\Users\Username\AppData\Local\Programs\Python\Python37\draft.py"
</code></pre> | <p>You can use the <code>pythonw</code> executable, or rename your script to something<code>.pyw</code>.</p>
<p><code>.pyw</code> is a special extension for Python files on Windows which are associated with <code>pythonw</code>, the Python interpreter that does not pop up the console window at all.</p> | python|tkinter|cmd|visible | 4 |
26 | 62,205,131 | PyQt app won't run properly unless I open the whole folder | <p>So I'm trying to share my PyQt project. When I download the zip file and extract it, it looks like</p>
<p><a href="https://i.stack.imgur.com/ApGY4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ApGY4.png" alt="enter image description here"></a></p>
<p>If I run <code>app.py</code> from CMD, it will run the app, but without the icon file which is inside of that folder. Inside of the code I do need that file and point to it, so I'm not sure why it doesn't find it automatically. It seems that without it the app doesn't work properly. I was wondering if there's a work around for this issue.</p>
<p>Here is how the app looks when I "open folder" in my IDE:</p>
<p><a href="https://i.stack.imgur.com/Nrip3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nrip3.png" alt="enter image description here"></a></p>
<p>Here is how it looks when I simply open the <code>.py</code> file, in that same folder:</p>
<p><a href="https://i.stack.imgur.com/G7aGb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G7aGb.png" alt="enter image description here"></a></p>
<p>Anything related to the icons (basically all notifications) are not working when I run it like that.</p>
<p>I'm not sure what why it behaves like this, but I'd like to be able to share the code for anyone to use without them opening the whole folder.</p> | <p>Eventually, I ended up changing how I'm using the paths.</p>
<p>I added this</p>
<pre class="lang-py prettyprint-override"><code>dirname = os.path.dirname(__file__)
iconFile = os.path.join(dirname, 'icon/icon.png')
</code></pre>
<p>So now I'm using <code>iconFile</code> as my path. Seems to fix the issue</p> | python | 2 |
27 | 63,529,436 | Cannot connect VPS Server to MS SQL Server | <p>I'm trying to connect to MS SQL database using my VPS server IP, and login info. But I kept getting login failed error</p>
<blockquote>
<p>pyodbc.InterfaceError: ('28000', "[28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'root'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Login failed for user 'root'. (18456)")</p>
</blockquote>
<p>[enter image description here][1]
Products:
Vultr VPS Server
Version: Ubuntu 18.04
I already installed SQL Server 2017
In my python program, I got this</p>
<pre><code>server = '66.42.92.32'
username = 'root'
password = 'abc'
conn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};' +
f'Server={server};' +
'Database=KyInventory;' +
'UID=root;' +
'PWD=abc;'+
'Trusted_Connection=no;')
cursor = conn.cursor()
</code></pre>
<p>Please help me!</p> | <p>When you use IP address to connect to your server, you have to set SQL-Server port even it was default. like this:</p>
<pre><code>server = '66.42.92.32,1433'
</code></pre>
<p>for more information look at this Microsoft link:
<a href="https://docs.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-ver15" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/sql/connect/python/pyodbc/step-3-proof-of-concept-connecting-to-sql-using-pyodbc?view=sql-server-ver15</a></p> | python|sql-server|ubuntu|vps | -1 |
28 | 36,676,594 | Spark Sql: TypeError("StructType can not accept object in type %s" % type(obj)) | <p>I am currently pulling data from SQL Server using PyODBC and trying to insert into a table in Hive in a Near Real Time (NRT) manner. </p>
<p>I got a single row from source and converted into List[Strings] and creating schema programatically but while creating a DataFrame, Spark is throwing StructType error.</p>
<pre><code>>>> cnxn = pyodbc.connect(con_string)
>>> aj = cnxn.cursor()
>>>
>>> aj.execute("select * from tjob")
<pyodbc.Cursor object at 0x257b2d0>
>>> row = aj.fetchone()
>>> row
(1127, u'', u'8196660', u'', u'', 0, u'', u'', None, 35, None, 0, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, u'', 0, None, None)
>>> rowstr = map(str,row)
>>> rowstr
['1127', '', '8196660', '', '', '0', '', '', 'None', '35', 'None', '0', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', '', '0', 'None', 'None']
>>> schemaString = " ".join([row.column_name for row in aj.columns(table='tjob')])
>>> schemaString
u'ID ExternalID Name Description Notes Type Lot SubLot ParentJobID ProductID PlannedStartDateTime PlannedDurationSeconds Capture01 Capture02 Capture03 Capture04 Capture05 Capture06 Capture07 Capture08 Capture09 Capture10 Capture11 Capture12 Capture13 Capture14 Capture15 Capture16 Capture17 Capture18 Capture19 Capture20 User UserState ModifiedDateTime UploadedDateTime'
>>> fields = [StructField(field_name, StringType(), True) for field_name in schemaString.split()]
>>> schema = StructType(fields)
>>> [f.dataType for f in schema.fields]
[StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType, StringType]
>>> myrdd = sc.parallelize(rowstr)
>>> myrdd.collect()
['1127', '', '8196660', '', '', '0', '', '', 'None', '35', 'None', '0', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', 'None', '', '0', 'None', 'None']
>>> schemaPeople = sqlContext.createDataFrame(myrdd, schema)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/apps/opt/cloudera/parcels/CDH-5.5.2-1.cdh5.5.2.p0.4/lib/spark/python/pyspark/sql/context.py", line 404, in createDataFrame
rdd, schema = self._createFromRDD(data, schema, samplingRatio)
File "/apps/opt/cloudera/parcels/CDH-5.5.2-1.cdh5.5.2.p0.4/lib/spark/python/pyspark/sql/context.py", line 298, in _createFromRDD
_verify_type(row, schema)
File "/apps/opt/cloudera/parcels/CDH-5.5.2-1.cdh5.5.2.p0.4/lib/spark/python/pyspark/sql/types.py", line 1132, in _verify_type
raise TypeError("StructType can not accept object in type %s" % type(obj))
TypeError: StructType can not accept object in type <type 'str'>
</code></pre> | <p>here is the reason for error message:</p>
<pre><code>>>> rowstr
['1127', '', '8196660', '', '', '0', '', '', 'None' ... ]
#rowstr is a list of str
>>> myrdd = sc.parallelize(rowstr)
#myrdd is a rdd of str
>>> schema = StructType(fields)
#schema is StructType([StringType, StringType, ....])
>>> schemaPeople = sqlContext.createDataFrame(myrdd, schema)
#myrdd should have been RDD([StringType, StringType,...]) but is RDD(str)
</code></pre>
<p>to fix that, make the RDD of proper type:</p>
<pre><code>>>> myrdd = sc.parallelize([rowstr])
</code></pre> | python|apache-spark|apache-spark-sql | 27 |
29 | 36,393,643 | Encoder for a string - Python | <p>I've been playing around with encoding random sets of strings using a dictionary. I've gotten my code to replace the letters I want, but in some cases it will replace a character more than once, when I truly only want it to replace the letter in the string once. This is what I have:</p>
<pre><code>def encode(msg,code):
for i in msg:
for i in code:
msg = msg.replace(i, code[i])
return msg
</code></pre>
<p>for testing purposes I used the function calls:
initial:</p>
<pre><code>encode("blagh", {"a":"e","h":"r"})
</code></pre>
<p>and a more complex string:</p>
<pre><code>encode("once upon a time",{'a':'ae','e':'ei','i':'io','o':'ou','u':'ua'})
</code></pre>
<p>for the second one right above, I'm looking for the output of :
'ouncei uapoun ae tiomei'</p>
<p>but instead am finding myself with :</p>
<p>"ounceio uapoun aeio tiomeio"</p>
<p>How can I limit my loop to only replacing each character once?</p> | <p>Python 3's <a href="https://docs.python.org/3.3/library/stdtypes.html?highlight=translate#str.translate" rel="nofollow"><code>str.translate</code></a> function does what you want. Note that the translation dictionary must use Unicode ordinals for keys, so the function uses a dictionary comprehension to convert it to the right format:</p>
<pre><code>def encode(msg,code):
code = {ord(k):v for k,v in code.items()}
return msg.translate(code)
print(encode("blagh", {"a":"e","h":"r"}))
print(encode("once upon a time",{'a':'ae','e':'ei','i':'io','o':'ou','u':'ua'}))
</code></pre>
<p>Output:</p>
<pre><code>blegr
ouncei uapoun ae tiomei
</code></pre>
<p>It works in Python 2 as well if you use Unicode strings or add the following to the top of the file to make strings Unicode by default:</p>
<pre><code>from __future__ import unicode_literals
</code></pre> | python|string|loops|dictionary|encoding | 2 |
30 | 13,593,514 | assigning values in a numpy array | <p>I have a numpy array of zeros. For concreteness, suppose it's 2x3x4:</p>
<pre><code>x = np.zeros((2,3,4))
</code></pre>
<p>and suppose I have a 2x3 array of random integers from 0 to 3 (the index of the 3rd dimension of x).</p>
<pre><code>>>> y = sp.stats.distributions.randint.rvs(0, 4, size=(2,3))
>>> y
[[2 1 0]
[3 2 0]]
</code></pre>
<p>How do I do the following assignments efficiently (edit: something that doesn't use for loops and works for x with any number of dimensions and any number of elements in each dimension)? </p>
<pre><code>>>> x[0,0,y[0,0]]=1
>>> x[0,1,y[0,1]]=1
>>> x[0,2,y[0,2]]=1
>>> x[1,0,y[1,0]]=1
>>> x[1,1,y[1,1]]=1
>>> x[1,2,y[1,2]]=1
>>> x
array([[[ 0., 0., 1., 0.],
[ 0., 1., 0., 0.],
[ 1., 0., 0., 0.]],
[[ 0., 0., 0., 1.],
[ 0., 0., 1., 0.],
[ 1., 0., 0., 0.]]])
</code></pre>
<p>Thanks,
James</p> | <p>Use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html" rel="nofollow">numpy.meshgrid</a>() to make arrays of indexes that you can use to index into both your original array and the array of values for the third dimension.</p>
<pre><code>import numpy as np
import scipy as sp
import scipy.stats.distributions
a = np.zeros((2,3,4))
z = sp.stats.distributions.randint.rvs(0, 4, size=(2,3))
xx, yy = np.meshgrid( np.arange(2), np.arange(3) )
a[ xx, yy, z[xx, yy] ] = 1
print a
</code></pre>
<p>I've renamed your array from x to a, and the array of indexes from y to z, for clarity.</p>
<p><strong>EDIT:</strong> 4D example:</p>
<pre><code>a = np.zeros((2,3,4,5))
z = sp.stats.distributions.randint.rvs(0, 4, size=(2,3))
w = sp.stats.distributions.randint.rvs(0, 5, size=(2,3))
xx, yy = np.meshgrid( np.arange(2), np.arange(3) )
a[ xx, yy, z[xx, yy], w[xx, yy] ] = 1
</code></pre> | python|arrays|numpy|variable-assignment | 1 |
31 | 13,558,653 | How can I create a new folder with Google Drive API in Python? | <p>From <a href="https://developers.google.com/drive/v2/reference/files/insert" rel="noreferrer">this example</a>. Can I use MediafileUpload with creating folder? How can I get the parent_id from?</p>
<p>From <a href="https://developers.google.com/drive/folder" rel="noreferrer">https://developers.google.com/drive/folder</a></p>
<p>I just know that i should use mime = "application/vnd.google-apps.folder" but how do I implement this tutorial to programming in Python?</p>
<p>Thank you for your suggestions.</p> | <p>To create a folder on Drive, try:</p>
<pre><code> def createRemoteFolder(self, folderName, parentID = None):
# Create a folder on Drive, returns the newely created folders ID
body = {
'title': folderName,
'mimeType': "application/vnd.google-apps.folder"
}
if parentID:
body['parents'] = [{'id': parentID}]
root_folder = drive_service.files().insert(body = body).execute()
return root_folder['id']
</code></pre>
<p>You only need a parent ID here if you want to create folder within another folder, otherwise just don't pass any value for that. </p>
<p>If you want the parent ID, you'll need to write a method to search Drive for folders with that parent name in that location (do a list() call) and then get the ID of that folder.</p>
<hr>
<p><strong>Edit:</strong> Note that v3 of the API uses a list for the 'parents' field, instead of a dictionary. Also, the <code>'title'</code> field changed to <code>'name'</code>, and the <code>insert()</code> method changed to <code>create()</code>. The code from above would change to the following for v3:</p>
<pre><code> def createRemoteFolder(self, folderName, parentID = None):
# Create a folder on Drive, returns the newely created folders ID
body = {
'name': folderName,
'mimeType': "application/vnd.google-apps.folder"
}
if parentID:
body['parents'] = [parentID]
root_folder = drive_service.files().create(body = body).execute()
return root_folder['id']
</code></pre> | python|google-drive-api | 22 |
32 | 22,296,150 | Deadlock when creating index | <p>I try to create an index with a Cypher query using py2neo 1.6.2 and neo4j 2.0.1:</p>
<pre><code>graph_db = neo4j.GraphDatabaseService()
query = "CREATE INDEX ON :Label(prop)"
neo4j.CypherQuery(graph_db, query).run()
</code></pre>
<p>The query works fine in the neo4j web interface but throws a deadlock error in py2neo:
<hr>
py2neo.neo4j.DeadlockDetectedException: Don't panic.</p>
<p>A deadlock scenario has been detected and avoided. This means that two or more transactions, which were holding locks, were wanting to await locks held by one another, which would have resulted in a deadlock between these transactions. This exception was thrown instead of ending up in that deadlock.</p>
<p>See the deadlock section in the Neo4j manual for how to avoid this: <a href="http://docs.neo4j.org/chunked/stable/transactions-deadlocks.html" rel="nofollow">http://docs.neo4j.org/chunked/stable/transactions-deadlocks.html</a></p>
<p>Details: 'Transaction(15438, owner:"qtp1927594840-9525")[STATUS_ACTIVE,Resources=1] can't wait on resource RWLock[SchemaLock]since => Transaction(15438, owner:"qtp1927594840-9525")[STATUS_ACTIVE,Resources=1] <-[:HELD_BY]- RWLock[SchemaLock] <-[:WAITING_FOR]- Transaction(15233, owner:"qtp1927594840-9503")[STATUS_ACTIVE,Resources=1] <-[:HELD_BY]- RWLock[SchemaLock]'.</p>
<hr>
<p>It doesn't make a difference if the label exists or not, the request usually fails.</p> | <p>Judging from the deadlock graph in the details section, this looks like a bug in 2.0.1. Are you doing anything else to the database other than running this specific query, or is this just starting up a fresh database and running the code you provided?</p>
<p>In any case, since it works in the Neo4j Browser, I'd suggest swapping to use the transactional APIs, as that is what the browser uses. Py2neo supports this using the "Cypher Transactions" feature, documented here:</p>
<p><a href="http://book.py2neo.org/en/latest/cypher/#id2" rel="nofollow">http://book.py2neo.org/en/latest/cypher/#id2</a></p> | python|neo4j|cypher|py2neo | 1 |
33 | 43,838,895 | Data comes out misaligned when printing list | <p>I have a code that reads an inventory txt file that is suppose to display a menu for the user when it is run. However, when it runs the quantity and pice columns are misaligned:</p>
<pre><code>Select an item ID to purchase or return:
ID Item Quantity Price
244 Large Cake Pan 7.00 19.99
576 Assorted Sprinkles 3.00 12.89
212 Deluxe Icing Set 6.00 37.97
827 Yellow Cake Mix 3.00 1.99
194 Cupcake Display Board 2.00 27.99
285 Bakery Boxes 7.00 8.59
736 Mixer 5.00 136.94
Enter another item ID or 0 to stop
</code></pre>
<p>Here is my code:</p>
<pre><code>import InventoryFile
def readFile ():
#open the file and read the lines
inventoryFile = open ('Inventory.txt', 'r')
raw_data = inventoryFile.readlines ()
#remove the new line characters
clean_data = []
for item in raw_data:
clean_item = item.rstrip ('\n')
clean_data.append (clean_item)
#read lists into objects
all_objects = []
for i in range (0, len(clean_data), 4):
ID = clean_data [i]
item = clean_data [i+1]
qty = float (clean_data [i+2])
price = float (clean_data [i+3])
inventory_object = InventoryFile.Inventory (ID, item, qty, price)
all_objects.append (inventory_object)
return all_objects
def printMenu (all_data):
print ()
print ('Select an item ID to purchase or return: ')
print ()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
print (item)
print ()
print ('Enter another item ID or 0 to stop')
def main ():
all_items = readFile ()
printMenu (all_items)
main ()
</code></pre>
<p>How can I format the output so that the quantity and price columns are correctly aligned?</p>
<p>Here is the inventory class:</p>
<pre><code>class Inventory:
def __init__ (self, new_id, new_name, new_stock, new_price):
self.__id = new_id
self.__name = new_name
self.__stock = new_stock
self.__price = new_price
def get_id (self):
return self.__id
def get_name (self):
return self.__name
def get_stock (self):
return self.__stock
def get_price (self):
return self.__price
def restock (self, new_stock):
if new_stock < 0:
print ('ERROR')
return False
else:
self.__stock = self.__stock + new_stock
return True
def purchase (self, purch_qty):
if (new_stock - purch_qty < 0):
print ('ERROR')
return False
else:
self.__stock = self.__stock + purch_qty
return True
def __str__ (self):
return self.__id + '\t' + self.__name + '\t' + \
format (self.__stock, '7.2f') + format (self.__price, '7.2f')
</code></pre> | <p>Using your class <code>Inventory</code>'s getters you can make a list and just join the output.</p>
<pre><code>def printMenu (all_data):
print ()
print ('Select an item ID to purchase or return: ')
print ()
print ('ID\tItem\t\t Quantity\t Price')
for item in all_data:
product_id = item.get_id()
product_name = item.get_name()
product_stock = item.get_stock()
product_price = item.get_price()
output = [product_id, product_name, product_stock, product_price]
output = [str(item) for item in output]
print('{:<5}\t{:<5}\t{:<5}\t{:<5}'.format(output))
print ()
print ('Enter another item ID or 0 to stop')
</code></pre> | python|list | 0 |
34 | 71,384,054 | How to save a dictionary having multiple lists of values for each key in a csv file | <p>I have a dictionary in the format:</p>
<pre><code>cu = {'m':[['a1','a2'],['a3','a4'],['a5','a6']], 'n':[['b1','b2'], ['b3','b4']]}
</code></pre>
<p>#the code I used to save the dictionary in csv file was:</p>
<pre><code>#using numpy to make the csv file
import numpy as np
# using the savetxt
np.savetxt("cu_ck.csv", cu , delimiter ="," , fmt ='% s')
</code></pre>
<p>and it raised an error stating that:
<em>ValueError: Expected 1D or 2D array, got 0D array instead</em></p>
<p>Please help me write a code which can be used to save a dictionary of such type.
And it is to be noted that, this dictionary is only for example basis...the original dictionary has keys more than 12, wherein the length of values for each key may vary but are in the same format as stated in the cu dictionary.</p>
<p>The csv file should at least look like this:</p>
<pre><code>m a1 a2
m a3 a4
m a5 a6
n b1 b2
n b3 b4
</code></pre> | <p>The error is caused by <code>cu</code> being a dictionary type, which is not an array type.</p>
<p>However, simply converting to an array isn't going to work either, since what you want is fairly complicated. One way to perform this data transformation is to append the key to each subarray:</p>
<pre><code>([['m', a1, a2], ['m', a3, a4], ['m', a5, a6]], [['n', b1, b2], ['n', b3, b4]])
</code></pre>
<p>and then concatenate the outer lists:</p>
<pre><code>[['m', a1, a2], ['m', a3, a4], ['m', a5, a6], ['n', b1, b2], ['n', b3, b4]]
</code></pre>
<p>Admittedly, I don't know whether this is very Pythonic, but it does the trick:</p>
<pre class="lang-py prettyprint-override"><code>cu_arr2d = sum(([[key, *row] for row in cu[key]] for key in cu), [])
</code></pre>
<p>Here the</p>
<pre class="lang-py prettyprint-override"><code>([[key, *row] for row in cu[key]] for key in cu)
</code></pre>
<p>is iterating over all the keys and then iterating over all the rows of that key, and appending the key to the row. Its output is that tuple of 2d lists from the top of this post. Then the <code>sum</code> is concatenating everything.</p> | python|numpy|csv|dictionary | 0 |
35 | 39,063,571 | Binding command line arguments to the object methods calls in Python | <p>I am working on a command line utility with a few possible arguments. The argument parsing is done with argparse module. In the end, with some additional customization, I get a dictionary with one and only one element:</p>
<pre><code>{'add_account': ['example.com', 'example']}
</code></pre>
<p>Where the key is an option that should translate to a method call and the value is the arguments list.
I have all the planned objects method implemented.
I wonder what would be the best, most pythonic way to create method calls based on received dictionary.
I could obviously go through a predefined mapping like:</p>
<pre><code>if option == 'add_account':
object.add_account(
dictionary['add_account'][0],
dictionary['add_account'][1]
)
</code></pre>
<p>I feel that there's a much better way to do it, though. </p> | <p>You can use <code>getattr</code> to fetch a method object (<code>argparse.py</code> uses this approach several times).</p>
<p>You didn't give us a concrete example, but I'm guessing you have a class like this:</p>
<pre><code>In [387]: class MyClass(object):
...: def add_account(self,*args):
...: print(args)
...:
In [388]: obj=MyClass()
In [389]: obj.add_account(*['one','two'])
('one', 'two')
</code></pre>
<p>To do the same thing, starting with a string, I can use <code>getattr</code> to fetch the method object:</p>
<pre><code>In [390]: getattr(obj,'add_account')
Out[390]: <bound method MyClass.add_account of <__main__.MyClass object at 0x98ddaf2c>>
In [391]: getattr(obj,'add_account')('one')
('one',)
</code></pre>
<p>Now with your dictionary:</p>
<pre><code>In [392]: dd={'add_account': ['example.com', 'example']}
In [393]: key='add_account'
In [394]: getattr(obj, key)(*dd[key])
('example.com', 'example')
</code></pre> | python-3.x|argparse | 0 |
36 | 39,258,038 | The most efficient way to iterate over a list of elements. Python 2.7 | <p>I am trying to iterate over a list of elements, however the list can be massive and takes too long to execute. I am using newspaper api. The for loop I constructed is:</p>
<pre><code>for article in list_articles:
</code></pre>
<p>Each article in the list_articles are an object in the format of:</p>
<pre><code><newspaper.article.Article object at 0x1103e1250>
</code></pre>
<p>I checked that some recommended using xrange or range, however that did not work in my case, giving a type error:</p>
<pre><code>TypeError: 'int' object is not iterable
</code></pre>
<p>It would be awesome if anyone can point me to the right direction or give me some idea that can efficietly increase iterating over this list.</p> | <p>The best way is to use built in functions, when possible, such as functions to split strings, join strings, group things, etc...</p>
<p>The there is the list comprehension or <code>map</code> when possible. If you need to construct one list from another by manipulating each element, then this is it.</p>
<p>The thirst best way is the <code>for item in items</code> loop.</p>
<p><strong>ADDED</strong></p>
<p>One of the things that makes you a Python programmer, a better programmer, takes you to the next level of programming is the second thing I mentioned - list comprehension and map. Many times you iterate a list only to construct something that could be easily done with list comprehension. For example:</p>
<pre><code>new_items = []
for item in items:
if item > 3:
print(item * 10)
new_items.append(item * 10)
</code></pre>
<p>You could do this much better (shorter and faster and more robust) like this:</p>
<pre><code>new_items = [item * 10 for item in items if item > 3]
print(items)
</code></pre>
<p>Now, the printing is a bit different from the first example, but more often than not, it doesn't matter, and even better, and also can be transformed with one line of code to what you need.</p> | python|list|python-2.7|loops|cpython | 2 |
37 | 52,505,943 | SyntaxError: invalid syntax in URLpattern | <p>hi am getting a syntax error</p>
<p>url:</p>
<pre><code>url(r'^reset-password/$',
PasswordResetView.as_view(template_name='accounts/reset_password.html', 'post_reset_redirect': 'accounts:password_reset_done'), name='reset_password'),
</code></pre>
<p>What is the problem?</p>
<p>thanks</p> | <p>The problem is that you mix dictionary syntax with parameter syntax:</p>
<pre><code>url(
r'^reset-password/$',
PasswordResetView.as_view(
template_name='accounts/reset_password.html',
<s><b>'post_reset_redirect': 'accounts:password_reset_done'</b></s>
),
name='reset_password'
)</code></pre>
<p>This syntax with a colon, is used for dictionaries. For parameters, it is <code>identifier=expression</code>, so:</p>
<pre><code>from django.urls import <b>reverse_lazy</b>
url(
r'^reset-password/$',
PasswordResetView.as_view(
template_name='accounts/reset_password.html',
<b>success_url=reverse_lazy('accounts:password_reset_done')</b>
),
name='reset_password'
)</code></pre>
<p>The <code>post_reset_redirect</code> has been removed as parameter, but the <code>success_url</code> performs the same functionality: it is the URL to which a redirect is done, after the POST request has been handled successfully.</p>
<p>The wrong syntax probably originates from the fact that when you used a <em>function-based view</em>, you passed parameters through the <code>kwargs</code> paramter, which accepted a dictionary.</p>
<p>The class-based view however, obtains these parameter through the <code>.as_view(..)</code> call. Furthermore class-based views typically aim to generalize the process, and there the <code>success_url</code>, is used for <code>FormView</code>s.</p> | python|django|syntax | 3 |
38 | 52,831,640 | Converting hex to binary in array | <p>I'm working on Visual Studio about python Project and The user input like that <code>010203</code> and
I use this code for saparating the input:</p>
<pre><code>dynamic_array = [ ]
hexdec = input("Enter the hex number to binary ");
strArray = [hexdec[idx:idx+2] for idx in range(len(hexdec)) if idx%2 == 0]
dynamic_array = strArray
print(dynamic_array[0] + " IAM" )
print(dynamic_array[1] + " NOA" )
print(dynamic_array[2] + " FCI" )
</code></pre>
<p>So, the output is:</p>
<pre><code>01 IAM
02 NOA
03 FCI
</code></pre>
<p>However my expected output converting this hex numbers to binary numbers look like this:</p>
<pre><code>00000001 IAM
00000010 NOA
00000011 FCI
</code></pre>
<p>Is there any way to do this?</p> | <p>It's a lot easier if you thnk of hex as a integer (number).<br>
There's a lot of tips on how to convert integers to different outcomes, but one useful string representation tool is <code>.format()</code> which can format a integer (and others) to various outputs.</p>
<p>This is a combination of:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python">Convert hex string to int in Python</a></li>
<li><a href="https://stackoverflow.com/questions/699866/python-int-to-binary">Python int to binary?</a></li>
</ul>
<p>The solutions would be:</p>
<pre><code>binary = '{:08b}'.format(int(hex_val, 16))
</code></pre>
<p>And the end result code would look something like this:</p>
<pre><code>def toBin(hex_val):
return '{:08b}'.format(int(hex_val, 16)).zfill(8)
hexdec = input("Enter the hex number to binary ");
dynamic_array = [toBin(hexdec[idx:idx+2]) for idx in range(len(hexdec)) if idx%2 == 0]
print(dynamic_array[0] + " IAM" )
print(dynamic_array[1] + " NOA" )
print(dynamic_array[2] + " FCI" )
</code></pre>
<p>Rohit also proposed a pretty good solution, but I'd suggest you swap the contents of <code>toBin()</code> with <code>bin(int())</code> rather than doing it per print statement.</p>
<p>I also restructured the code a bit, because I saw no point in initializing <code>dynamic_array</code> with a empty list. Python doesn't need you to set up variables before assigning values to them. There was also no point in creating <code>strArray</code> just to replace the empty <code>dynamic_array</code> with it, so concatenated three lines into one.</p>
<p>machnic also points out a good programming tip, the use of <code>format()</code> on your entire string. Makes for a very readable code :) </p>
<p>Hope this helps and that my tips makes sense. </p> | python|python-3.x | 3 |
39 | 52,626,708 | Why is my program shifting s and c by the wrong amount if I enter 5 into my program but not with any other letters or number? | <p>This program is meant to ask you for a sentence and a number then it shifts the letters down the alphabet all by the inputted number and then lets you undo it by shift it by minus what you enter. For some reason when you enter <code>5</code> as your shift the letter s shift to different random letters and does not give you the correct word when you try and shift back and I have no idea why.</p>
<pre><code>import sys
import time
letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
"n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
(a, b, c, d, e, f, g, h, i, j, k, l, m,
n, o, p, q, r, s, t, u, v, w, x, y, z) = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26)
def program():
def encryption():
def encryption1():
global message
global shift
message = list ((input ("Please enter the sentence you would like to be %s\n>" % (EnDe1))).lower())
print ("To %s your message please %s your private key number (from 1 - 10)" % (EnDe2, EnDe3))
shift = int (input (">"))
if EnDe == "b":
shift = - (shift)
if shift < 11 or shift > 0:
for x in range(len(message)):
if message[x] != " ":
if eval(message[x]) > 26 - shift:
message[x] = letters[eval(message[x]) + shift - 27]
else:
message[x] = letters[eval(message[x]) + shift - 1]
else:
shift = int (input ("only numbers from 1 to 10 are accepted, try again\n>"))
encryption1()
def choice():
global EnDe
global EnDe1
global EnDe2
global EnDe3
EnDe = (input ("would you like to A)encrypt or B)decrypt\n>")).lower()
if EnDe == "a":
EnDe1 = "encrypted"
EnDe2 = "encrypt"
EnDe3 = "pick"
encryption1()
elif EnDe == "b":
EnDe1 = "decrypted"
EnDe2 = "decrypt"
EnDe3 = "enter"
encryption1()
else:
print ("please pick either 'A' or 'B' , ONLY!")
time.sleep(2)
choice()
choice()
output = ''.join(message)
print (output)
retry = input ("would you like to Decrypt/Encrypt another message? (Y/N)\n>")
retry = retry.lower()
while retry != ("y" or "n"):
retry = input ("please select either y or n\n>")
retry = retry.lower()
while retry == "y":
program()
else:
sys.exit()
encryption()
</code></pre> | <p>The problem is that you define a global <code>x</code> variable, and also a local one. The local one shadows the global one and so the result of <code>eval("x")</code> is not anymore what you expected to have. </p>
<p>Solution: use a different variable for the <code>for</code> loop.</p>
<p>There is much that can be improved in your code. You can take advantage of the modulo operator and the <code>ord</code> function, avoiding the need for all those 26 letter names.</p>
<p>Here is how that <code>for</code> loop could look without all that:</p>
<pre><code>if 0 < shift < 11:
for i, ch in enumerate(message):
if ch != " ":
message[i] = chr((ord(ch)-ord('a')+shift)%26+ord('a'))
</code></pre>
<p>Unrelated: note that <code>retry != ("y" or "n")</code> does not work like that. You should do <code>retry not in "yn"</code> </p> | python|arrays|loops|eval | 0 |
40 | 47,735,224 | Receiving service messages in a group chat using Telegram Bot | <p>I am trying to create a bot in my group to help me track the group users who have invited other users into the group.</p>
<p>I have disabled the privacy mode so the bot can receive all messages in a group chat. However, it seems to be that <code>update.message</code> only gets messages supplied by other users but not service messages like <code>Alice has added Bob into the group</code></p>
<p>Is there any way that I can get these service messages as well?</p>
<p>Thanks for helping!</p> | <p>I suppose you are using <code>python-telegram-bot</code> library.</p>
<p>You can add a handler with a specific filter to listen to service messages:</p>
<pre><code>from telegram.ext import MessageHandler, Filters
def callback_func(bot, update):
# here you receive a list of new members (User Objects) in a single service message
new_members = update.message.new_chat_members
# do your stuff here:
for member in new_members:
print(member.username)
def main():
...
dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, callback_func)
</code></pre>
<p>There are several more service message types your bot may receive using the <code>Filters</code> module, check them out <a href="http://python-telegram-bot.readthedocs.io/en/stable/telegram.ext.filters.html#telegram.ext.filters.Filters.status_update" rel="nofollow noreferrer">here</a>.</p> | python|python-3.x|telegram-bot|python-telegram-bot | 1 |
41 | 47,930,647 | Pandas division with 2 dfs | <p>I want to divide 2 dfs by matching their names. For example,</p>
<p><code>df1 = pd.DataFrame({'Name':['xy-yz','xa-ab','yz-ijk','zb-ijk'],1:[1,2,3,4],2:[1,2,1,2],3:[2,2,2,2]} )</code></p>
<p><code>df2 = pd.DataFrame({'Name2':['x','y','z','a'],1:[0,1,2,3],2:[1,2,3,4],3:[5,5,5,6]})</code></p>
<p>df1:</p>
<pre><code>Name1 1 2 3
xy-yz 1 1 2
xa-ab 2 2 2
yz-ijk 3 1 2
zb-ijk 4 2 2
</code></pre>
<p>df2:</p>
<pre><code>Name2 1 2 3
x 0 1 5
y 1 2 5
z 2 3 5
a 3 4 6
</code></pre>
<p>The result would be df3: </p>
<pre><code>Name1 1 2 3
xy-yz 1 1 2
x 0 1 5
xy-yz 1 .4 <---(xy-yz)/x
xa-ab 2 2 2
x 0 1 5
xa-ab 2 .4 <---(xa-ab)/x
yz-ijk 3 1 2
y 1 2 5
yz-ijk 3 .5 .4 <---(yz-ijk)/y
zb-ijk 4 2 2
z 2 3 5
zb-ijk 2 .67 .4 <---(zb-ijk)/z
</code></pre>
<p>I would use concat but I'm not not sure how to do the division by mapping the Name2 to the first letter in Name1 here. </p>
<p>Thank you!</p> | <p>I do not know why you need it , but this give back what you need </p>
<pre><code>df2=df2.set_index('Name2')
dfNew=df2.reindex(df1.Name1.str.split('-',expand=True)[0])
df1=df1.set_index('Name1')
pd.concat([df1.reset_index(),dfNew.reset_index().rename(columns={0:'Name1'}),pd.DataFrame(df1.values/dfNew.values,columns=df1.columns).assign(Name1=df1.index)]).sort_index()
Out[897]:
1 2 3 Name1
0 1.000000 1.000000 2.0 x-yz
0 0.000000 1.000000 5.0 x
0 inf 1.000000 0.4 x-yz
1 2.000000 2.000000 2.0 x-ab
1 0.000000 1.000000 5.0 x
1 inf 2.000000 0.4 x-ab
2 3.000000 1.000000 2.0 y-ijk
2 1.000000 2.000000 5.0 y
2 3.000000 0.500000 0.4 y-ijk
3 4.000000 2.000000 2.0 z-ijk
3 2.000000 3.000000 5.0 z
3 2.000000 0.666667 0.4 z-ijk
</code></pre> | python|pandas|dataframe|division | 3 |
42 | 34,316,747 | Django logout() returns none | <p>Morning everyone</p>
<p>Im using django logout() to end my sessions just like django docs says :</p>
<p><strong>views.py</strong></p>
<pre><code>class Logout(View):
def logout_view(request):
logout(request)
return HttpResponseRedirect(reverse('cost_control_app:login'))
</code></pre>
<p>and im calling it from this url :</p>
<p>urls.py</p>
<pre><code>url(r'^logout/$', views.Logout.as_view(), name = "logout"),
</code></pre>
<p>Buttttttt it's not working, when i do a trace i find that the function :</p>
<pre><code> def logout_view(request):
</code></pre>
<p>it's returning "none" and it's nos entering to execute the code inside...</p>
<p>Please help me !</p> | <p>I'm curious, why do you have the method named <code>logout_view()</code>? By default, nothing is going to call that method. You need to change the name to match the HTTP verb which will be used to call the page. For instance, if it's going to be a <code>GET</code> request, you would change it to:</p>
<pre><code>def get(self, request):
</code></pre>
<p>If you want it to be a POST request, you would change it to:</p>
<pre><code>def post(self, request):
</code></pre>
<p>This is the standard way that class-based views work in Django. Also, you may want to look at the <a href="https://docs.djangoproject.com/en/1.9/topics/class-based-views/" rel="nofollow">documentation for class-based views</a>, as this may give you a better idea of their workings and what they can provide to you. (Hint: There is a built-in <a href="https://docs.djangoproject.com/en/1.9/ref/class-based-views/base/#redirectview" rel="nofollow">RedirectView</a>)</p> | python|django|logout | 2 |
43 | 72,769,527 | Def and Return Function in python | <p>I'm having some problems with the def and return function in Python.
On the top of my program I've defined:</p>
<pre><code>from subprogram import subprogram
</code></pre>
<p>then I've defined the def in which I've included the values I wanted to be returned:</p>
<pre><code>def subprogram(ssh, x_off, y_off, data_array, i, j):
if j==1:
print('shutdonw X')
# Run command.
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(x_off)
var_colonna_1 = data_array[i][j]
return var_colonna_1
print(var_colonna_1)
if j==2:
print('shutdown Y')
# Run command.
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(y_off)
var_colonna_2 = data_array[i][j]
return var_colonna_2
</code></pre>
<p>this is then called in the main program as:</p>
<pre><code>for j in range(5, lunghezza_colonna):
if data_array[i][j] == 'V':
subprogram(ssh, x_off, y_off, data_array, i, j)
print(var_colonna_1)
</code></pre>
<p>I was expecting that every time the <code>subprogram</code> is called, it returns the <code>var_colonna_1</code> or <code>var_colonna_2</code>, but the values I see when I print <code>var_colonna_1</code> is always 0 even if, internally the other commands are execute (so X and Y are set in shut down).
Can you help me? I don't see my coding mistake.</p> | <p>The function doesn't return the variable, only the value on it.</p>
<p>If you want to get the returned value on var_colonna_1, you should asign it, as Sayse said, you should do:</p>
<pre><code>var_colonna_1 = subprogram(ssh, x_off, y_off, data_array, i, j)
</code></pre> | python | 1 |
44 | 16,380,528 | Faster alternatives to Popen for CAN bus access? | <p>I'm currently using Popen to send instructions to a utility (<code>canutils</code>... the <code>cansend</code> function in particular) via the command line.</p>
<p>The entire function looks like this.</p>
<pre><code>def _CANSend(self, register, value, readWrite = 'write'):
"""send a CAN frame"""
queue=self.CANbus.queue
cobID = hex(0x600 + self.nodeID) #assign nodeID
indexByteLow,indexByteHigh,indexByteHigher,indexByteHighest = _bytes(register['index'], register['objectDataType'])
subIndex = hex(register['subindex'])
valueByteLow,valueByteHigh,valueByteHigher,valueByteHighest = _bytes(value, register['objectDataType'])
io = hex(COMMAND_SPECIFIER[readWrite])
frame = ["cansend", self.formattedCANBus, "-i", cobID, io, indexByteLow, indexByteHigh, subIndex, valueByteLow, valueByteHigh, valueByteHigher, valueByteHighest, "0x00"]
Popen(frame,stdout=PIPE)
a=queue.get()
queue.task_done()
return a
</code></pre>
<p>I was running into some issues as I was trying to send frames (the <code>Popen</code> frame actually executes the command that sends the frame) in rapid succession, but found that the Popen line was taking somewhere on the order of 35 ms to execute... every other line was less than 2 us.</p>
<p>So... what might be a better way to invoke the <code>cansend</code> function (which, again, is part of the <code>canutils</code> utility...<code>_CANSend</code> is the python function above that calls ) more rapidly?</p> | <p>I suspect that most of that time is due to the overhead of forking every time you run cansend. To get rid of it, you'll want an approach that doesn't have to create a new process for each send.</p>
<p>According to <a href="http://libbits.wordpress.com/2012/05/22/socketcan-support-in-python/" rel="nofollow">this blog post</a>, <a href="https://en.wikipedia.org/wiki/SocketCAN" rel="nofollow">SocketCAN</a> is supported by python 3.3. It should let your program create and use CAN sockets directly. That's probably the direction you'll want to go.</p> | python|linux|popen|can-bus|socketcan | 4 |
45 | 38,892,509 | how to install wordcloud package in python? | <pre><code>pip install wordcloud
File "<ipython-input-130-12ee30540bab>", line 1
pip install wordcloud
^
SyntaxError: invalid syntax
</code></pre>
<p>This is the problem I am facing while using <code>pip install wordcloud</code>.</p> | <p><code>pip</code> is a tool used for installing python packages. You should not use this command inside the python interactive shell. </p>
<p>Instead, exit out of it and write <code>pip install wordcloud</code> on the main shell.</p> | python|word-cloud | 5 |
46 | 38,810,696 | Python -- sizing frames with weights | <p>In the minimum example code below, you can change the last range(), currently at 3, to 6 and notice that the frames with buttons all get smaller than if you run it with 3. I have configured 6 columns of "lower_frame" to all be weight 1. The expected result is that there are 6 empty columns of the same width no matter how many buttons I put in there. If I put 3 buttons in there, as the example below has by default, the buttons are quite large and leave only room for about 1 more button. If I put 6 buttons in, they fill the space and each gets smaller.</p>
<p>How do I achieve the expected result of having equal width columns no matter how many widgets I actually put in the cells? The goal here is a standard size to these buttons that is based on proportion of the screen, not a pixel size, and have it always be the same no matter the number of buttons. I realize I could do a bunch of math with bounding boxes and programatically set the sizes at runtime, but that seems like overkill and lacking elegance.</p>
<p>Minimum example:</p>
<pre><code>import Tkinter as tk
import ttk
mods = {}
modBtns = {}
root = tk.Tk()
upper_frame = ttk.Frame(master=root)
lower_frame = ttk.Frame(master=root)
right_frame = ttk.Frame(master=root)
root.columnconfigure(0, weight=3)
root.columnconfigure(1, weight=1)
root.rowconfigure(0, weight=1)
root.rowconfigure(1, weight=5)
for i in range(6):
lower_frame.columnconfigure(i, weight=1)
for i in range(5):
lower_frame.rowconfigure(i, weight=1)
upper_frame.grid(column=0, row=0, sticky=tk.N + tk.S + tk.E + tk.W)
lower_frame.grid(column=0, row=1, sticky=tk.N + tk.S + tk.E + tk.W)
right_frame.grid(column=1, row=0, sticky=tk.N + tk.S + tk.E + tk.W)
for i in range(3):
mods[i] = ttk.Frame(master=lower_frame)
mods[i].columnconfigure(0, weight=1)
mods[i].rowconfigure(0, weight=1)
modBtns[i] = ttk.Button(master=mods[i], text="mod{0}".format(i))
modBtns[i].grid(column=0, row=0, sticky=tk.N + tk.S + tk.E + tk.W)
mods[i].grid(column=i, row=0, sticky=tk.N + tk.S + tk.E + tk.W)
root.geometry("700x700+0+0")
root.mainloop()
</code></pre> | <p>If you want all of the rows and all of the columns to have the same width/height, you can set the <code>uniform</code> attribute of each row and column. All columns with the same <code>uniform</code> value will be the same width, and all rows with the same <code>uniform</code> value will be the same height.</p>
<p>Note: the actual value to the <code>uniform</code> attribute is irrelevant, as long as it is consistent.</p>
<pre><code>for i in range(6):
lower_frame.columnconfigure(i, weight=1, uniform='whatever')
for i in range(5):
lower_frame.rowconfigure(i, weight=1, uniform='whatever')
</code></pre> | python|python-2.7|user-interface|tkinter|tk | 1 |
47 | 40,621,144 | Can't get stored python integer back in java in habase google cloud | <p>I'm using hbase over google cloud bigtable to store my bigdata. I have 2 programs. first, store data using python into hbase and the second, read those info back from java by connecting to the same endpoint.</p>
<p>so from python interactive shell I can read byte arrays back into an integer (command 15)</p>
<pre><code>In [13]: row.cells['stat']['viewability'][0].value
Out[13]: '\x00\x00\x00\x00\x00\x00\x00A'
In [14]: len(row.cells['stat']['viewability'][0].value)
Out[14]: 8
In [15]: struct.unpack('>Q', row.cells['stat']['viewability'][0].value)
Out[15]: (65,)
</code></pre>
<p>but I can't read back the same byte array into java Integer data type<br/>
I'm using the following in java</p>
<pre><code>byte[] columnFamilyBytes = Bytes.toBytes("stat");
byte[] viewabilityColumnBytes = Bytes.toBytes("viewability");
Integer viewability = Bytes.toInt(c1.getValue(columnFamilyBytes, viewabilityColumnBytes));
</code></pre>
<p>and I'm getting NULL in response.</p> | <p>I found the problem<br/>
the column stored as long value so I had to first read it as long in java and then convert it to int</p> | java|python|hbase|google-cloud-dataproc | 0 |
48 | 1,504,804 | Using IronPython to learn the .NET framework, is this bad? | <p>Because I'm a Python fan, I'd like to learn the .NET framework using IronPython. Would I be missing out on something? Is this in some way not recommended?</p>
<p>EDIT:
I'm pretty knowledgeable of Java ( so learning/using a new language is not a problem for me ). If needed, will I be able to use everything I learned in IronPython ( excluding language featurs ) to write C# code?</p> | <p>No, sounds like a good way to learn to me. You get to stick with a language and syntax that you are familiar with, and learn about the huge range of classes available in the framework, and how the CLR supports your code.</p>
<p>Once you've got to grips with some of the framework and the CLR services you could always pick up C# in the future. By that point it will just be a minor syntax change from what you already know.</p>
<p>Bare in mind that if you are thinking with respect to a career, you won't find many iron python jobs, but like I say, this could be a good way to learn about the framework first, then build on that with C# in a month or twos time.</p> | c#|.net|ironpython | 11 |
49 | 32,230,578 | Django: handle migrations for an imported database? | <p>I'm working in Django 1.8 and trying to set up an existing project. I've inherited a database dump, plus a codebase. </p>
<p>I've imported the database dump successfully. </p>
<p>The problem is that if I try to run <code>migrate</code> against the imported database I then get errors about columns already existing, because the database is already at the end state of all the migrations:</p>
<pre><code> django.db.utils.ProgrammingError: column "managing_group_id"
of relation "frontend_pct" already exists
</code></pre>
<p>How can I resolve this? </p>
<p>I would like to be able to add new migrations from this point, and I would also prefer not to delete all the existing migrations. </p>
<p>Basically I need a way to say "skip straight to migration 36, and continue from there". </p> | <p>I think your migrations problem solved by the previous Answer. Therefore I'm adding a link below...</p>
<p>If you just started django 1.7 and above then</p>
<p>Here I'ld like to add a link <a href="https://markusholtermann.eu/2014/09/django-17-database-migrations-done-right/" rel="nofollow">Django Migration How works </a></p>
<p>That will useful where I think.</p> | python|django|django-migrations|django-database | 1 |
50 | 32,399,565 | convert python integer to its signed binary representation | <p>Given a positive integer such as 171 and a "register" size, e.g. 8.</p>
<p>I want the integer which is represented by the binary representation of 171, i.e. '0b10101011' interpreted as twos complement.</p>
<p>In the present case, the 171 should become -85.
It is negative because given the "register" size 8, the MSB is 1.</p>
<p>I hope I managed to explain my problem.
How can I do this conversion?</p>
<p>What I tried:</p>
<pre><code>size = 8
value = 171
b = bin(value)
if b[len(b)-size] == '1':
print "signed"
# What to do next?
</code></pre> | <p>You don't need binary conversion to achieve that:</p>
<pre><code>>>> size = 8
>>> value = 171
>>> unsigned = value % 2**size
>>> signed = unsigned - 2**size if unsigned >= 2**(size-1) else unsigned
>>> signed
-85
</code></pre> | python|binary|integer|twos-complement | 3 |
51 | 43,992,609 | Unable to uninstall anaconda from Ubuntu 16.04 | <p>I am trying to uninstall Ananconda from my Ubuntu 16.04 LTS machine.</p>
<p>I ran the following commands</p>
<pre><code>conda install anaconda-clean
anaconda-clean
rm -rf ~/anaconda
</code></pre>
<p>Everything is getting exceuted without any error/warning. If fact, when I run <code>anaconda-clean</code> it is saying so and so packages have been uninstalled. However, I can still open up anaconda navigator and everything seems to be working just fine. What am I missing?</p> | <pre><code>conda install anaconda-clean
anaconda-clean --yes
rm -rf ~/anaconda3
</code></pre>
<p>Replace <em>anaconda3</em> with your version of anaconda</p>
<p>This will uninstall anaconda</p> | python|ubuntu|anaconda|ubuntu-16.04|uninstallation | 4 |
52 | 34,612,214 | if loop repeating first if statement | <p>I'm trying to create a continuous question loop to process all my calculations for my nmea sentences in my project. For some reason only the first <code>if</code> statement is executed. What am I doing wrong? I'm still fairly new to python</p>
<pre><code> if command_type == "$GPGGA" or "GPGGA" or "GGA":
#define the classes
gps = GPS()
createworkbook = CreateWorkbook()
convertfile = ConvertFile()
print_gps = PrintGPS()
#do the deeds
createworkbook.openworkbook(data)
print_gps.process_gpgga_data(data)
createworkbook.closeworkbook_gpgga(data)
convertfile.convert2csv(data)
convertfile.convert2kml(data)
if command_type == "$GPRMC" or "GPRMC" or "RMC":
#define the classes
gps = GPS()
createworkbook = CreateWorkbook()
convertfile = ConvertFile()
print_gps = PrintGPS()
#do the deeds
createworkbook.openworkbook(data)
print_gps.process_gprmc_data(data)
createworkbook.closeworkbook_gprmc(data)
convertfile.convert2csv(data)
convertfile.convert2kml(data)
if command_type == "$GPGLL" or "GPGLL" or "GLL":
#define the classes
gps = GPS()
createworkbook = CreateWorkbook()
convertfile = ConvertFile()
print_gps = PrintGPS()
#do the deeds
createworkbook.openworkbook(data)
print_gps.process_gpgll_data(data)
createworkbook.closeworkbook_gpgll(data)
convertfile.convert2csv(data)
convertfile.convert2kml(data)
if command_type == "$GPGSA" or "GPGSA" or "GSA":
#define the classes
gps = GPS()
createworkbook = CreateWorkbook()
convertfile = ConvertFile()
print_gps = PrintGPS()
#do the deeds
createworkbook.openworkbook(data)
print_gps.process_gpgsa_data(data)
createworkbook.closeworkbook_gpgsa(data)
convertfile.convert2csv(data)
if command_type == "$GPVTG" or "GPVTG" or "VTG":
print('Better check $GPRMC')
else:
print("Invalid type:", command_type)
list_gps_commands(data)
wannalook = input('Want to look at another message or no?')
if not wannalook.startswith('y'):
keep_asking = False
print('********************')
print('**mischief managed**')
print('********************')
</code></pre> | <pre><code>if command_type == "$GPGGA" or "GPGGA" or "GGA":
</code></pre>
<p>As you can see, here you are not trying to check if <em>command_type</em> is valued "$GPGGA" or "GPGGA" or "GGA". But if <em>command_type == "$GPGGA"</em> is true <strong>or</strong> <em>"GPGGA"</em> is true <strong>or</strong> <em>"GGA"</em> is true.</p>
<p>And a non-empty string in python is always true : your first condition will be evaluated true.</p>
<p>So you have to do : </p>
<pre><code>if command_type == "$GPGGA" or command_type == "GPGGA" or command_type == "GGA"
</code></pre> | python|loops|python-3.x|if-statement | 2 |
53 | 789,598 | What is the easiest way to build Python26.zip for embedded distribution? | <p>I am using Python as a plug-in scripting language for an existing C++ application. I am able to embed the python interpreter as stated in the Python documentation. Everything works successfully with the initialization and de-initialization of the interpreter. I am, however, having trouble loading modules because I have not been able to zip up the standard library in to a zip file (normally PythonXX.zip, corresponding to the version number of the python dll). </p>
<p>What is the simplest way to zip up all of the standard library after optimized bytecode compiling? I'm looking for a simple script or command to do so for me, as I really don't want to do this by hand. </p>
<p>Any ideas? </p>
<p>Thanks!</p> | <p>I would probably use <a href="http://peak.telecommunity.com/DevCenter/setuptools" rel="nofollow noreferrer">setuptools</a> to create an egg (basically a java jar for python). The setup.py would probably look something like this:</p>
<pre><code>from setuptools import setup, find_packages
setup(
name='python26_stdlib',
package_dir = {'' : '/path/to/python/lib/directory'},
packages = find_packages(),
#any other metadata
)
</code></pre>
<p>You could run this using <code>python setup.py bdist_egg</code>. Once you have the egg, you can either add it to the python path or you can install it using setuptools. I believe this should also handle the generation of pycs for you as well.</p>
<p><strong>NOTE</strong>: I wouldn't use this on my system python directory. You might want to set up a <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow noreferrer">virtualenv</a> for this.</p> | c++|python|distribution|embedded-language | 2 |
54 | 1,053,344 | Modeling a complex relationship in Django | <p>I'm working on a Web service in Django, and I need to model a very specific, complex relationship which I just can't be able to solve.</p>
<p>Imagine three general models, let's call them Site, Category and Item. Each Site contains one or several Categories, but it can relate to them in one of two possible ways: one are "common" categories, which are in a many-to-many relationship: they are predefined, and each Site can relate to zero or more of the Categories, and vice versa. The other type of categories are individually defined for each site, and one such category "belongs" only to that site and none other; i.e. they are in a many-to-one relationship, as each Site may have a number of those Categories.</p>
<p>Internally, those two type of Categories are completely identical, they only differ in the way they are related to the Sites. It could, however, separate them in two different models (with a common parent model probably), but that solves only half of my problem: the Item model is in a many-to-one relationship with the Categories, i.e. each Item belongs to only one Category, and ideally it shouldn't care how it is related to a Site.</p>
<p>Another solution would be to allow the two separate types of Site-Category relations to coexist (i.e. to have both a ForeignKey and a ManyToMany field on the same Category model), but this solution feels like opening a whole other can of worms.</p>
<p>Does anyone have an idea if there is a third, better solution to this dead end?</p> | <p>Why not just have both types of category in one model, so you just have 3 models?</p>
<pre><code>Site
Category
Sites = models.ManyToManyField(Site)
IsCommon = models.BooleanField()
Item
Category = models.ForeignKey(Category)
</code></pre>
<p>You say "Internally, those two type of Categories are completely identical". So in sounds like this is possible. Note it is perfectly valid for a ManyToManyField to have only one value, so you don't need "ForeignKey and a ManyToMany field on the same Category model" which just sounds like a hassle. Just put only one value in the ManyToMany field</p> | python|django|django-models|entity-relationship | 4 |
55 | 815,530 | How to use subversion Ctypes Python Bindings? | <p>Subversion 1.6 introduce something that is called 'Ctypes Python Binding', but it is not documented. Is it any information available what this bindings are and how to use it? For example, i have a fresh windows XP and want to control SVN repository using subversiion 1.6 and this mysterious python bindings. What exactly i need to download/install/compile in order to do something like</p>
<pre><code>import svn from almighty_ctype_subversion_bindings
svn.get( "\\rep\\project" )
</code></pre>
<p>And how is this connected to pysvn project? Is this a same technology, or different technologies?</p> | <p>You need the Subversion source distribution, Python (>= 2.5), and <a href="http://code.google.com/p/ctypesgen/" rel="nofollow noreferrer">ctypesgen</a>.</p>
<p>Instructions for building the ctypes bindings are <a href="http://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/ctypes-python/README" rel="nofollow noreferrer">here</a>.</p>
<p>You will end up with a package called <code>csvn</code>, examples of it's use are <a href="http://svn.apache.org/repos/asf/subversion/trunk/subversion/bindings/ctypes-python/examples/" rel="nofollow noreferrer">here</a>.</p> | python|svn | 1 |
56 | 47,413,755 | Installing Python's Cryptography on Windows | <p>I've created a script on windows to connect to Remote SSH server. I have successfully installed <code>cryptography</code>, <code>pynacl</code> and finally <code>paramiko</code>(Took me an entire day to figure out how to successfully install them on windows).</p>
<p>Now that I run the script, it pops an error saying that the DLL loading has failed. The error seems to be related to <code>libsodium</code> but I cannot figure out exactly which DLL is to trying to load and from where. Just to be on the safer side I also installed <code>pysodium</code>.</p>
<p>Here's the script:</p>
<blockquote>
<p>automate.py</p>
</blockquote>
<pre><code>import SSH
connection = ssh("10.10.65.100", "gerrit2", "gerrit@123")
print("Calling OpenShell")
connection.openShell()
print("Calling sendShell")
connection.sendShell("ls -l")
print("Calling process")
connection.process()
print("Calling closeConnection")
connection.closeConnection()
</code></pre>
<blockquote>
<p>SSH.py</p>
</blockquote>
<pre><code>import threading, paramiko
class ssh:
shell = None
client = None
transport = None
def __init__(self, address, username, password):
print("Connecting to server on ip", str(address) + ".")
self.client = paramiko.client.SSHClient()
self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
self.client.connect(address, username=username, password=password, look_for_keys=False)
self.transport = paramiko.Transport((address, 22))
self.transport.connect(username=username, password=password)
thread = threading.Thread(target=self.process)
thread.daemon = True
thread.start()
def closeConnection(self):
if(self.client != None):
self.client.close()
self.transport.close()
def openShell(self):
self.shell = self.client.invoke_shell()
def sendShell(self, command):
if(self.shell):
self.shell.send(command + "\n")
else:
print("Shell not opened.")
def process(self):
global connection
while True:
# Print data when available
if self.shell != None and self.shell.recv_ready():
alldata = self.shell.recv(1024)
while self.shell.recv_ready():
alldata += self.shell.recv(1024)
strdata = str(alldata, "utf8")
strdata.replace('\r', '')
print(strdata, end = "")
if(strdata.endswith("$ ")):
print("\n$ ", end = "")
</code></pre>
<p>And here's the error:</p>
<pre><code>> python automate.py
Traceback (most recent call last):
File "automate.py", line 1, in <module>
import SSH
File "D:\Automate\SSH_Paramiko\SSH.py", line 1, in <module>
import threading, paramiko
File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\paramiko-2.4.0-py3.7.egg\paramiko\__init__.py", line 22, in <module>
File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\paramiko-2.4.0-py3.7.egg\paramiko\transport.py", line 57, in <module>
File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\paramiko-2.4.0-py3.7.egg\paramiko\ed25519key.py", line 22, in <module>
File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\nacl\signing.py", line 19, in <module>
import nacl.bindings
File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\nacl\bindings\__init__.py", line 17, in <module>
from nacl.bindings.crypto_box import (
File "D:\Users\prashant-gu\AppData\Local\Programs\Python\Python37\lib\site-packages\nacl\bindings\crypto_box.py", line 18, in <module>
from nacl._sodium import ffi, lib
ImportError: DLL load failed: The specified module could not be found.
</code></pre> | <p>After a lot of googling, I finally stumbled upon <a href="https://github.com/pyca/pynacl/issues/281" rel="nofollow noreferrer">this</a>. As mentioned in the conversation I uninstalled my previous pynacl installation, downloaded the zipped source from <a href="https://github.com/lmctv/pynacl/archive/v1.2.a0.reorder.zip" rel="nofollow noreferrer">https://github.com/lmctv/pynacl/archive/v1.2.a0.reorder.zip</a>, downloaded libsodium from <a href="https://github.com/jedisct1/libsodium/releases/download/1.0.15/libsodium-1.0.15.tar.gz" rel="nofollow noreferrer">https://github.com/jedisct1/libsodium/releases/download/1.0.15/libsodium-1.0.15.tar.gz</a>, set <code>LIB</code> environment variable to <code>D:\Users\prashant-gu\Downloads\libsodium-1.0.15\bin\x64\Release\v140\dynamic</code>, and finally installed pynacl form this downloaded source using </p>
<p><code>pip install .</code></p>
<p>Now it works fine.</p>
<p>During the installation of <code>paramiko</code>, I also happen to download OpenSSL from <a href="https://ci.cryptography.io/job/cryptography-support-jobs/job/openssl-release-1.1/" rel="nofollow noreferrer">https://ci.cryptography.io/job/cryptography-support-jobs/job/openssl-release-1.1/</a>, and set INCLUDE environment variable to <code>D:\Users\prashant-gu\Downloads\openssl-1.1.0g-2015-x86_64\openssl-win64-2015\include</code> in order to successfully install the <code>cryptography</code> package which happens to be a dependency for <code>paramiko</code>.</p> | python|windows|ssh | 0 |
57 | 47,206,902 | OpenCV Python Assertion Failed | <p>I am trying to run opencv-python==3.3.0.10 on a macOS 10.12.6 to read from a file and show the video in a window. I have exactly copied the code from here <a href="http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html" rel="nofollow noreferrer">http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html</a>, section 'Playing' video from file.</p>
<p>The code runs correctly and shows the video, however after termination of the video it breaks the program, giving the following error:</p>
<blockquote>
<p>Assertion failed: (ec == 0), function unlock, file /BuildRoot/Library/Caches/com.apple.xbs/Sources/libcxx/libcxx-307.5/src/mutex.cpp, line 48.</p>
</blockquote>
<p>Does anyone have any idea of what might cause this?</p>
<hr>
<p>Code snippet for your convenience (edited to include some suggestions in the comment)</p>
<pre><code>cap = cv2.VideoCapture('vtest.avi')
while(True):
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.destroyAllWindows()
</code></pre> | <p>It's not clear from your question, but it looks like you're specifically running into a situation where the video completes playing without being interrupted. I <em>think</em> the issue is that the VideoCapture object is already closed by the time you get to <code>cap.release()</code>. I'd recommend putting the call to <code>release</code> inside of the <code>if</code> statement by the break.</p>
<p>I've not had time to experiment, but I normally follow this pattern:</p>
<pre><code>reader = cv2.VideoCapture(<stuff>)
while True:
success, frame = reader.read()
if not success:
break
</code></pre>
<p>I'd not had to call <code>release</code> explicitly in those contexts.</p> | python|opencv|opencv3.0|opencv-python | 1 |
58 | 57,332,622 | reference to invalid character number: (Python ElementTree parse) | <p>I have xml file which has following content:</p>
<pre><code> <word>vegetation</word>
<word>cover</word>
<word>(&#x2;31%</word>
<word>split_identifier ;</word>
<word>Still</word>
<word>and</word>
</code></pre>
<p>When I read the file using ElmentTree parse, it gives me error : </p>
<blockquote>
<p>xml.etree.ElementTree.ParseError: reference to invalid character
number </p>
</blockquote>
<p>Its becuase of (&#x2 which is "~").</p>
<p>How can I take care of such issues. I am not sure how many other symbols i would get in future.</p> | <p>If you want to get rid of those special characters, you can by scrubbing the input XML as a string:</p>
<pre><code>respXML = response.content.decode("utf-16")
scrubbedXML = re.sub('&.+[0-9]+;', '', respXML)
respRoot = ET.fromstring(scrubbedXML)
</code></pre>
<p>If you prefer to keep the special characters you may parse them beforehand. In your case it looks like html, therefore you may use the python html module:</p>
<pre><code>import html
respRoot = ET.fromstring(html.unescape(response.content.decode("utf-16"))
</code></pre> | python|elementtree | 1 |
59 | 57,447,687 | Can I save results anyway even when Keyboardinterrupt? | <p>I have a very long code which is taking forever to run. I was wondering if there is a way to save the results even if I use the keyboard to interrupt the code from running? All the examples I found were using except with Keyboardinterrupt, so I don't know if this is the right code to use.</p>
<p>More concretely: I have a code which ends with saving results in a list, and returning the list. In this case, is there a way to return the list despite keyboardinterrupt? Can I use <code>if keyboardinterrupt</code> statement?</p>
<p>My code:</p>
<pre><code># removed is a very long list
for a, b in itertools.combinations(removed, 2):
temp = [a,b]
Token_Set_Ratio = fuzz.token_set_ratio(temp[0],temp[1])
if Token_Set_Ratio > k:
c = random.choice(temp)
if c in removed:
removed.remove(c)
else:
pass
else:
pass
return removed
</code></pre>
<p>Where can I add the part for python to retain removed even if keyboard interrupt occurs?</p> | <p>You could use a <code>try</code>-<code>except</code> with <code>KeyboardInterrupt</code>:</p>
<pre><code>def your_function():
removed = [...]
try:
# Code that takes long time
for a, b in itertools.combinations(removed, 2):
...
return removed
except KeyboardInterrupt:
return removed
</code></pre>
<p>A small example:</p>
<pre><code>import time
def foo():
result = []
try:
# Long running code
for i in range(10000):
result.append(i)
time.sleep(0.1)
return result
except KeyboardInterrupt:
# Code to "save"
return result
print(foo())
</code></pre>
<p>When you Ctrl-C before the end of execution, a partial list is printed.</p> | python|python-3.x|keyboardinterrupt | 2 |
60 | 71,057,396 | How can i replace a value in a specific row and column in a csv file | <p>I need to replace a value in correspondence of an ID in a .csv file:</p>
<pre><code>ChatId,Color
805525230,black
</code></pre>
<p>So if the ID in input is equal to the one in the file my program will replace the Color "black" with the new one. I tried this:</p>
<pre class="lang-py prettyprint-override"><code>for idx, row in enumerate(df.ChatId):
if str(row) == str(CHAT_ID):
df.loc[1,idx] = BGc
df.to_csv("path")
</code></pre> | <p>Assuming you loaded the csv on a dataframe, you could you use some of its functions.</p>
<p>For example: <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html" rel="nofollow noreferrer">https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.replace.html</a></p>
<p>Alternatively, you could use the loc function:</p>
<pre><code>df.loc[df['ChatId'=='SomeId'], 'Color'] = 'ValueToReplace'
</code></pre>
<p>If you need to apply it to a different column, you can 'Color' with the appropriate name. <br>
I think you could even include a list of column names, though I haven't tested it</p> | python|pandas|csv | 0 |
61 | 11,737,817 | What is the simplest language which support template&context mechanism? | <p>I need to find the easiest way to automatically build ebooks from downloaded articles.</p>
<p>I want to automatically generate TOC, which will be based on HTML template.</p>
<p>I know that python django has template & context mechanism, however django is a little to complicated for people to which I am preparing this whole mechanism. I don't need all web-related features.</p> | <p>IMHO, if you are familiar with Django:</p>
<ul>
<li>if you want to build a command line application or a abstract library, look at <a href="http://jinja.pocoo.org/docs/" rel="nofollow">Jinja2</a> template engine.</li>
<li>if you are looking for a web framework simpler than Django, look at <a href="http://flask.pocoo.org/docs/" rel="nofollow">Flask</a> (Flask uses Jinja2 as the default template engine).</li>
</ul> | python|django|templates|programming-languages|django-context | 3 |
62 | 46,815,043 | python managing tasks in threads when using priority queue | <p>I'm trying to write a program which starts new tasks in new threads.
Data is passed from task threads to a single worker/processing thread via a priority queue (so more important jobs are processes first).
The worker/processing thread gets higher priority data from the queue and limits calls to a REST API </p>
<p>How can I passed the data back to it's origionating task thread, while tracking that all that particular task threads data has been processed?</p>
<p>Thanks</p> | <p>In your request queue entry include a response queue. When finished place a response on the response queue.</p>
<p>The requesting thread waits on the response queue.</p>
<p>A callback method could alternately be used.</p> | python|queue | 0 |
63 | 46,730,360 | Wrong datetimes picked up by pandas | <p>Data Scraped</p>
<p><a href="https://i.stack.imgur.com/lULod.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lULod.png" alt="enter image description here"></a></p>
<p>So I've scraped data from a website with a timestamp of when it was scraped. As you can see I have no date between 2017-09-14 13:56:28 and 2017-09-16 14:43:05, however when I scrape it using the following code:</p>
<pre><code>path ='law_scraped'
files = glob.glob(path + "/*.csv")
frame = pd.DataFrame()
for f in files:
df = pd.read_csv(f)
df['dtScraped'] = df['dtScraped'].str.replace("|", " ")
try:
df['dtScraped'] = pd.to_datetime(df['dtScraped'], format = "%Y/%m/%d %H:%M:%S")
except Exception as e:
df['dtScraped'] = pd.to_datetime(df['dtScraped'])
frame = pd.concat([frame, df], ignore_index=True)
</code></pre>
<p>I get datetimes that don't match the data as you can see below:</p>
<pre><code>+-----------+---------------------+-------+-------------------+
| | dtScraped | odds | team |
+-----------+---------------------+-------+-------------------+
| 15117 | 2017-09-14 14:00:00 | 7.75 | Feyenoord |
| 15118 | 2017-09-14 14:00:00 | 1.446 | Manchester City |
| 15119 | 2017-09-14 14:00:00 | 5.01 | Draw |
| 15120 | 2017-09-14 14:00:00 | 4.73 | NK Maribor |
| 15121 | 2017-09-14 14:00:00 | 1.869 | Spartak Moscow |
| 15122 | 2017-09-14 14:00:00 | 3.65 | Draw |
| 15123 | 2017-09-14 14:00:00 | 1.694 | Liverpool |
| 15124 | 2017-09-14 14:00:00 | 5.16 | Sevilla |
| 15125 | 2017-09-14 14:00:00 | 4.25 | Draw |
| 15126 | 2017-09-14 14:00:00 | 3.53 | Shakhtar Donetsk |
| 15127 | 2017-09-14 14:00:00 | 2.19 | Napoli |
| 15128 | 2017-09-14 14:00:00 | 3.58 | Draw |
| 15129 | 2017-09-14 14:00:00 | 2.15 | RB Leipzig |
| 15130 | 2017-09-14 14:00:00 | 3.5 | AS Monaco |
| 15131 | 2017-09-14 14:00:00 | 3.73 | Draw |
| 15132 | 2017-09-14 14:00:00 | 1.044 | Real Madrid |
| 15133 | 2017-09-14 14:00:00 | 34.68 | APOEL Nicosia |
| 15134 | 2017-09-14 14:00:00 | 23.04 | Draw |
| 15135 | 2017-09-14 14:00:00 | 2.33 | Tottenham Hotspur |
| 15136 | 2017-09-14 14:00:00 | 3.12 | Borussia Dortmund |
| 15137 | 2017-09-14 14:00:00 | 3.69 | Draw |
| 15138 | 2017-09-14 14:00:00 | 1.52 | FC Porto |
| 15139 | 2017-09-14 14:00:00 | 7.63 | Besiktas JK |
| 15140 | 2017-09-14 14:00:00 | 4.32 | Draw |
| 144009 | 2017-09-14 14:00:00 | 7.75 | Feyenoord |
| 144010 | 2017-09-14 14:00:00 | 1.446 | Manchester City |
| 144011 | 2017-09-14 14:00:00 | 5.01 | Draw |
| 144012 | 2017-09-14 14:00:00 | 4.609 | NK Maribor |
| 144013 | 2017-09-14 14:00:00 | 1.892 | Spartak Moscow |
| 144014 | 2017-09-14 14:00:00 | 3.64 | Draw |
| 144015 | 2017-09-14 14:00:00 | 1.694 | Liverpool |
| 144016 | 2017-09-14 14:00:00 | 5.16 | Sevilla |
| 144017 | 2017-09-14 14:00:00 | 4.25 | Draw |
| 144018 | 2017-09-14 14:00:00 | 3.53 | Shakhtar Donetsk |
| 144019 | 2017-09-14 14:00:00 | 2.19 | Napoli |
| 144020 | 2017-09-14 14:00:00 | 3.58 | Draw |
| 144021 | 2017-09-14 14:00:00 | 2.15 | RB Leipzig |
| 144022 | 2017-09-14 14:00:00 | 3.5 | AS Monaco |
| 144023 | 2017-09-14 14:00:00 | 3.73 | Draw |
| 144024 | 2017-09-14 14:00:00 | 1.044 | Real Madrid |
| 144025 | 2017-09-14 14:00:00 | 34.68 | APOEL Nicosia |
| 144026 | 2017-09-14 14:00:00 | 23.04 | Draw |
| 144027 | 2017-09-14 14:00:00 | 2.33 | Tottenham Hotspur |
| 144028 | 2017-09-14 14:00:00 | 3.12 | Borussia Dortmund |
| 144029 | 2017-09-14 14:00:00 | 3.69 | Draw |
| 144030 | 2017-09-14 14:00:00 | 1.52 | FC Porto |
| 144031 | 2017-09-14 14:00:00 | 7.63 | Besiktas JK |
| 144032 | 2017-09-14 14:00:00 | 4.32 | Draw |
+-----------+---------------------+-------+-------------------+
</code></pre> | <p>Assuming your timestamps have the same format as the filenames in your screenshot, this should work (after the replacement of <code>"|"</code> by <code>" "</code>):</p>
<pre><code>df['dtScraped'] = pd.to_datetime(df['dtScraped'], format="%Y-%m-%d %H-%M-%S")
</code></pre> | python-3.x|pandas | 0 |
64 | 37,619,363 | Plot wind speed and direction from u, v components | <p>I'm trying to plot the wind speed and direction, but there is an error code that keeps telling me that "sequence too large; cannot be greater than 32." Here is the code that I am using:</p>
<pre><code>N = 500
ws = np.array(u)
wd = np.array(v)
df = pd.DataFrame({'direction': [ws], 'speed': [wd]})
df
direction speed
0 [[-7.87291, -8.19969, -8.41213, -8.42775, -8.4... [[-3.68055, -4.07912, -4.07992, -3.55594, -3.2...
from windrose import plot_windrose
N = 500
ws = np.random.random(u) * 6
wd = np.random.random(v) * 360
df = pd.DataFrame({'speed': ws, 'direction': wd})
plot_windrose(df, kind='contour', bins=np.arange(0.01,8,1), cmap=cm.hot, lw=3)
ValueError Traceback (most recent call last)
<ipython-input-78-dfb188ec377a> in <module>()
1 from windrose import plot_windrose
2 N = 500
3 ws = np.random.random(u) * 6
4 wd = np.random.random(v) * 360
5 df = pd.DataFrame({'speed': ws, 'direction': wd})
mtrand.pyx in mtrand.RandomState.random_sample (numpy\random\mtrand\mtrand.c:10396)()
mtrand.pyx in mtrand.cont0_array (numpy\random\mtrand\mtrand.c:1865)()
ValueError: sequence too large; cannot be greater than 32
</code></pre>
<p>How do I fix this and plot the U and V? Thank you.</p> | <p>To plot wind U, V use <code>barbs</code> and <code>quiver</code>. Look at the code below:</p>
<pre><code>import matplotlib.pylab as plt
import numpy as np
x = np.linspace(-5, 5, 5)
X, Y = np.meshgrid(x, x)
d = np.arctan(Y ** 2. - .25 * Y - X)
U, V = 5 * np.cos(d), np.sin(d)
# barbs plot
ax1 = plt.subplot(1, 2, 1)
ax1.barbs(X, Y, U, V)
#quiver plot
ax2 = plt.subplot(1, 2, 2)
qui = ax2.quiver(X, Y, U, V)
plt.quiverkey(qui, 0.9, 1.05, 1, '1 m/s',labelpos='E',fontproperties={'weight': 'bold'})
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/WhRt0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WhRt0.png" alt="enter image description here"></a></p> | python|pandas|matplotlib|jupyter-notebook | 1 |
65 | 37,934,099 | Python 2.7.3 urllib2 Error | <p>When I try to run my python script this error happens. How can I solve this problem ?</p>
<pre><code>['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'urllib2']
Traceback (most recent call last):
File "m.py", line 3, in <module>
import requests
File "/usr/local/lib/python2.7/dist-packages/requests-2.9.1-py2.7.egg/requests/__init__.py", line 58, in <module>
from . import utils
File "/usr/local/lib/python2.7/dist-packages/requests-2.9.1-py2.7.egg/requests/utils.py", line 26, in <module>
from .compat import parse_http_list as _parse_list_header
File "/usr/local/lib/python2.7/dist-packages/requests-2.9.1-py2.7.egg/requests/compat.py", line 38, in <module>
from urllib2 import parse_http_list
ImportError: cannot import name parse_http_list
</code></pre> | <p>you need to upgrade <a href="https://pypi.python.org/pypi/requests/" rel="nofollow">requests</a> </p>
<pre><code>pip install --upgrade requests
</code></pre> | python | 2 |
66 | 67,669,925 | "The request's session was deleted before the request completed. The user may have logged out in a concurrent request" | <p>"The request's session was deleted before the request completed. The user may have logged out in a concurrent request" I am facing this error when trying to use 2 request.session().</p>
<p>In my code my using two request.session() to store variables.After one request successfully completed,its going to another request and throwing this error.</p>
<pre><code>request.session['dataset1'] = dataset1.to_json()
request.session['total_cols'] = total_cols // getting error here
</code></pre>
<p>Please help to resolve the same.</p> | <p>Since my dataset has 8000 rows, It was not a good idea to store in session variables. I have written some rest calls and that solved my problem.</p> | python|django | 0 |
67 | 30,036,305 | Shelves an multiple items | <p>I've been trying to make a quote input that puts multiple quotes inside a file (coupled with the authors name). I have tried with pickle, but I could not get more than 2 pickled items inside a file and finally I decided to use shelf.</p>
<p>However, I am having some trouble with shelves as well.</p>
<p>I dont really know how to put multiple items inside a file, even if I can shelf one.</p>
<pre><code>import pickle
import shelve
quote = []
author = []
def givequote():
f = shelve.open('quotation')
## open the shelve so that i can write stuff in it
f["quote"] = raw_input("What quote has its place in the quote book? \n to quit press Q\n\n")
## ask for input so that i can put stuff into quote,
##quote is a random value so its a problem, i might have to make a key/value first.
if quote != "Q":
f['author'] = raw_input("what author said that? \n to quit press Q \n\n")
if author == "Q":
print "goodbye"
elif quote == "Q":
print "goodbye"
f.close()
def readquote():
f = shelve.open('quotation')
print "%3s\n - %s" % (f["quote"], f['author'])
</code></pre>
<p>thank you.</p>
<p>After finding out how it works I plan to try to make the same program using classes ( was thinking of nested ones) and methods, just to practice figuring out my inner programmer.</p> | <p>You can do this with pickle. As this <a href="https://stackoverflow.com/questions/12761991/how-to-use-append-with-pickle-in-python">answer</a> describes, you can append a pickled object to a binary file using open with append in binary mode. </p>
<p>To read the multiple pickled objects out of the file, just call <code>pickle.load</code> on the file handle until you get an EOF error.</p>
<blockquote>
<p>so your unpickle code might look like</p>
<pre><code>import pickle
objs = []
while 1:
try:
objs.append(pickle.load(f))
except EOFError:
break
</code></pre>
</blockquote> | python | 0 |
68 | 57,028,126 | "chalice deploy" call ends up with "Unknown parameter in input: "Layers"" | <p>I create the most basic chalice app </p>
<pre><code>from chalice import Chalice
app = Chalice(app_name='testApp')
@app.route('/')
def index():
return {'hello': 'world'}
</code></pre>
<p>with empty requirements.txt and config that looks like this:</p>
<pre><code>{
"version": "2.0",
"app_name": "testApp",
"stages": {
"dev": {
"api_gateway_stage": "api"
}
}
}
</code></pre>
<p>Error fires right after the first deploy</p>
<p>This is the error i receive:</p>
<p>Creating deployment package.
Updating policy for IAM role: testApp-dev
Updating lambda function: testApp-dev
Traceback (most recent call last):
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\cli__init__.py", line 466, in main
return cli(obj={})
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 722, in <strong>call</strong>
return self.main(*args, **kwargs)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 697, in main
rv = self.invoke(ctx)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 1066, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 895, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\core.py", line 535, in invoke
return callback(*args, **kwargs)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\click\decorators.py", line 17, in new_func
return f(get_current_context(), *args, **kwargs)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\cli__init__.py", line 202, in deploy
deployed_values = d.deploy(config, chalice_stage_name=stage)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\deploy\deployer.py", line 342, in deploy
return self._deploy(config, chalice_stage_name)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\deploy\deployer.py", line 355, in _deploy
self._executor.execute(plan)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\deploy\executor.py", line 31, in execute
self._default_handler)(instruction)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\deploy\executor.py", line 43, in _do_apicall
result = method(**final_kwargs)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\awsclient.py", line 283, in update_function
layers=layers
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\awsclient.py", line 352, in _update_function_config
max_attempts=self.LAMBDA_CREATE_ATTEMPTS
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\chalice\awsclient.py", line 1009, in _call_client_method_with_retries
response = method(**kwargs)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\botocore\client.py", line 314, in _api_call
return self._make_api_call(operation_name, kwargs)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\botocore\client.py", line 586, in _make_api_call
api_params, operation_model, context=request_context)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\botocore\client.py", line 621, in _convert_to_request_dict
api_params, operation_model)
File "c:\users\vic\appdata\local\programs\python\python37-32\lib\site-packages\botocore\validate.py", line 291, in serialize_to_request
raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:</p>
<p>Unknown parameter in input: "Layers", must be one of: FunctionName, Role, Handler, Description, Timeout, MemorySize, VpcConfig, Environment, Runtime, DeadLetterConfig, KMSKeyArn, TracingConfig, RevisionId</p> | <p>After troubleshooting found some issues with my local configurations. What helped was running the chalice in virtualenv (<a href="https://virtualenv.pypa.io/en/latest/" rel="nofollow noreferrer">https://virtualenv.pypa.io/en/latest/</a>)</p> | python|amazon-web-services|deployment|aws-lambda|chalice | 0 |
69 | 65,540,231 | Import and insert word in sequence in Python | <p>I want to <strong>import</strong> and <strong>insert</strong> word in <strong>sequence</strong> and <strong>NOT RANDOMLY</strong>, each registration attempt uses a <strong>single</strong> username and <strong>stop</strong> until the registration is <strong>completed</strong>. Then logout and begin a <strong>new</strong> registration with the <strong>next</strong> username in the list if the <strong>REGISTRATION is FAILED</strong>, and <strong>skip</strong> if the <strong>REGISTRATION is SUCCEDED</strong>.</p>
<p>I'm really confused because I have no clue. I've tried this <strong>code</strong> but it chooses randomly and I have <strong>no</strong> idea how to use the "<strong>for loop</strong>"</p>
<pre><code>import random
Copy = driver.find_element_by_xpath('XPATH')
Copy.click()
names = [
"Noah" ,"Liam" ,"William" ,"Anthony"
]
idx = random.randint(0, len(names) - 1)
print(f"Picked name: {names[idx]}")
Copy.send_keys(names[idx])
</code></pre>
<p>How can I make it choose the next word in sequence and <strong>NOT RANDOMLY</strong>
Any Help Please</p> | <p>I am going to assume that you are happy with what the code does, with exception that the names it picks are random. This narrows everything down to one line, and namely the one that picks names randomly:</p>
<pre><code>idx = random.randint(0, len(names) - 1)
</code></pre>
<p>Simple enough, you want "the next word in sequence and NOT RANDOMLY":
<a href="https://docs.python.org/3/tutorial/datastructures.html#more-on-lists" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/datastructures.html#more-on-lists</a></p>
<p>If you take a look at the link I've provided, you can see that lists have a <em><strong>pop()</strong></em> method, returning and removing some element from the list. We want the first one so we will provide 0 as the argument for the pop method.</p>
<p>We modify the line to look something like this</p>
<pre><code>name = names.pop(0)
</code></pre>
<p>Now you still want to have the for-loop that will loop over all of the actions including name picking so you encapsulate all of the code in a for-loop:</p>
<pre><code>names = [
"Noah" ,"Liam" ,"William" ,"Anthony"
]
for i in range(len(names)):
# ...
Copy = driver.find_element_by_xpath('XPATH')
Copy.click()
name = names.pop(0)
print(f"Picked name: {name}")
Copy.send_keys(name)
# ...
</code></pre>
<p>You might notice that the names list is <strong>not</strong> inside the for-loop. That is because we don't want to reassign the list every time we try to use a new name.</p>
<p>If you're completely unsure how for-loops work or how to implement one yourself, you should probably start by reading about how they work.</p>
<p><a href="https://docs.python.org/3/tutorial/controlflow.html?highlight=loop#for-statements" rel="nofollow noreferrer">https://docs.python.org/3/tutorial/controlflow.html?highlight=loop#for-statements</a></p>
<p>Last but not least you can see some <code># ...</code> comments in my example indicating where the logic will probably go for the other part of your question: <em>"Then logout and begin a new registration with the next username in the list if the REGISTRATION is FAILED, and skip if the REGISTRATION is SUCCEDED."</em> I don't think we I can help you with that since there is simply not enough context or examples in your question.</p>
<p>Refer to <a href="https://stackoverflow.com/help/how-to-ask">this guide</a> explaining how to ask a well formulated question so we can help you more next time.</p> | python|import|webforms | 0 |
70 | 65,903,633 | Load a text file paragraph into a string without libraries | <p>sorry if this question may look a bit dumb for some of you but i'm totally a beginner at programming in Python so i'm quite bad and got a still got a lot to learn.
So basically I have this long text file separated by paragraphs, sometimes the newline can be double or triple to make the task more hard for us so i added a little check and looks like it's working fine so i have a variable called "paragraph" that tells me in which paragraph i am currently.
Now basically i need to scan this text file and search for some sequences of words in it but the newline character is the worst enemy here, for example if i have the string = "dummy text" and i'm looking into this:</p>
<pre><code>"random questions about files with a dummy
text and strings
hey look a new paragraph here"
</code></pre>
<p>As you can see there is a newline between dummy and text so reading the file line by line doesn't work. So i was wondering to load directly the entire paragraph to a string so this way i can even remove punctuation and stuff more easly and check directly if those sequences of words are contained in it.
All this must be done without libraries.
However my piece of code of paragraph counter works while the file is being read, so if uploading a whole paragraph in a string is possible i should basically use something like "".join until the paragraph increases by 1 because we're on the next paragraph? Any idea?</p> | <p>This should do the trick. It is very short and elegant:</p>
<pre><code>with open('dummy text.txt') as file:
data = file.read().replace('\n', '')
print(data)#prints out the file
</code></pre>
<p>The output is:</p>
<pre><code>"random questions about files with a dummy text and strings hey look a new paragraph here"
</code></pre> | python|string|file|txt | 1 |
71 | 43,439,172 | Python/Kivy Assertion Error | <p>I obtained an Assertion error while attempting to learn BoxLayout in kivy. I cannot figure out what has went wrong.</p>
<pre><code> from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
class BoxLayoutApp(App):
def build(self):
return BoxLayout()
if __name__=="__main__":
BoxLayoutApp().run()
</code></pre>
<p>And for the kv code:</p>
<pre><code><BoxLayout>:
BoxLayout:
Button:
text: "test"
Button:
text: "test"
Button:
text: "test"
BoxLayout:
Button:
text: "test"
Button:
text: "test"
Button:
text: "test"
</code></pre>
<p>Edit: I tried to subclass BoxLayout as suggested however, I still face an AssertionError. The full (original) error message I reproduce here:</p>
<pre><code> Traceback (most recent call last):
File "boxlayout.py", line 12, in <module>
BoxLayoutApp().run()
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\app.py", line 802, in run
root = self.build()
File "boxlayout.py", line 8, in build
return BoxLayout()
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\boxlayout.py", line 131, in
__init__
super(BoxLayout, self).__init__(**kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\layout.py", line 76, in __in
it__
super(Layout, self).__init__(**kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\widget.py", line 345, in __i
nit__
Builder.apply(self, ignored_consts=self._kwargs_applied_init)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 451, in a
pply
self._apply_rule(widget, rule, rule, ignored_consts=ignored_consts)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 566, in _
apply_rule
self.apply(child)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 451, in a
pply
self._apply_rule(widget, rule, rule, ignored_consts=ignored_consts)
File "C:\Users\user\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 464, in _
apply_rule
assert(rule not in self.rulectx)
AssertionError
</code></pre> | <p>Try subclassing boxlayout instead:</p>
<pre><code>from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
class MyBoxLayout(BoxLayout):
pass
Builder.load_string('''
<MyBoxLayout>:
BoxLayout:
Button:
text: "test"
Button:
text: "test"
Button:
text: "test"
BoxLayout:
Button:
text: "test"
Button:
text: "test"
Button:
text: "test"
''')
class BoxLayoutApp(App):
def build(self):
return MyBoxLayout()
if __name__=="__main__":
BoxLayoutApp().run()
</code></pre>
<p>The <code>AssertionError</code> is being thrown because you try to apply rules to the same class you are nesting.<br>
In other words you apply a rule to a class, that it shall contain itself.<br>
That causes issues.<br>
Following will throw the same error.</p>
<pre><code><MyBoxLayout>:
MyBoxLayout:
</code></pre> | python|kivy | 5 |
72 | 36,966,316 | How to get the dimensions of a tensor (in TensorFlow) at graph construction time? | <p>I am trying an Op that is not behaving as expected.</p>
<pre><code>graph = tf.Graph()
with graph.as_default():
train_dataset = tf.placeholder(tf.int32, shape=[128, 2])
embeddings = tf.Variable(
tf.random_uniform([50000, 64], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
embed = tf.reduce_sum(embed, reduction_indices=0)
</code></pre>
<p>So I need to know the dimensions of the Tensor <code>embed</code>. I know that it can be done at the run time but it's too much work for such a simple operation. What's the easier way to do it?</p> | <p>I see most people confused about <code>tf.shape(tensor)</code> and <code>tensor.get_shape()</code>
Let's make it clear:</p>
<ol>
<li><code>tf.shape</code></li>
</ol>
<p><code>tf.shape</code> is used for dynamic shape. If your tensor's shape is <strong>changable</strong>, use it.
An example: a input is an image with changable width and height, we want resize it to half of its size, then we can write something like:<br>
<code>new_height = tf.shape(image)[0] / 2</code></p>
<ol start="2">
<li><code>tensor.get_shape</code></li>
</ol>
<p><code>tensor.get_shape</code> is used for fixed shapes, which means the tensor's <strong>shape can be deduced</strong> in the graph. </p>
<p>Conclusion:
<code>tf.shape</code> can be used almost anywhere, but <code>t.get_shape</code> only for shapes can be deduced from graph. </p> | python|tensorflow|deep-learning|tensor | 62 |
73 | 36,993,569 | /usr/bin/python: No module named pip | <p>I am having a bit of trouble getting everything to work on my Mac running El Capitan. I am running 3.5.1. I am under the impression that Pip is included with an install of the above, however when I try to use it to install sympy using the syntax in terminal: <code>python -m pip install SomePackage</code>, I get the error mentioned in the title. I tried running <code>import pip</code> in IDLE, and got no error, so I am quite confused. If I type pip into IDLE, I get:</p>
<pre><code><module 'pip' from '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip/__init__.py'>
</code></pre>
<p>Does anybody know what the problem is? Do I need to navigate to a certain directory in Terminal when I run the command?</p> | <p>I believe that you can run it by calling <code>pip</code> in the terminal. If you have it already installed.</p>
<p><code>pip install sympy</code></p> | python|python-3.x|pip | 2 |
74 | 36,897,802 | Get params validation on viewsets.ModelViewSet | <p>I am new to django and building a REST API using <code>django-rest-framework</code>.
I have written some code to check whether the user has supplied some parameters or not.But that is very ugly with lot of <code>if conditions</code>, so i want to refactor it.Below is the code that i have written please suggest how to refactor it.</p>
<p>I am looking for some django based validations.</p>
<pre><code>class AssetsViewSet(viewsets.ModelViewSet):
queryset = Assets.objects.using("gpr").all()
def create(self, request):
assets = []
farming_details = {}
bluenumberid = request.data.get('bluenumberid', None)
if not bluenumberid:
return Response({'error': 'BlueNumber is required.'})
actorid = request.data.get('actorid', None)
if not actorid:
return Response({'error': 'Actorid is required.'})
asset_details = request.data.get('asset_details', None)
if not asset_details:
return Response({'error': 'AssetDetails is required.'})
for asset_detail in asset_details:
location = asset_detail.get('location', None)
if not location:
return Response({'error': 'location details is required.'})
assettype = asset_detail.get('type', None)
if not assettype:
return Response({'error': 'assettype is required.'})
asset_relationship = asset_detail.get('asset_relationship', None)
if not asset_relationship:
return Response({'error': 'asset_relationship is required.'})
subdivision_code = location.get('subdivision_code', None)
if not subdivision_code:
return Response({'error': 'subdivision_code is required.'})
country_code = location.get('country_code', None)
if not country_code:
return Response({'error': 'country_code is required.'})
locationtype = location.get('locationtype', None)
if not locationtype:
return Response({'error': 'locationtype is required.'})
latitude = location.get('latitude', None)
if not latitude:
return Response({'error': 'latitude is required.'})
longitude = location.get('longitude', None)
if not longitude:
return Response({'error': 'longitude is required.'})
try:
country_instance = Countries.objects.using('gpr').get(countrycode=country_code)
except:
return Response({'error': 'Unable to find country with countrycode ' + str(country_code)})
try:
subdivision_instance = NationalSubdivisions.objects.using('gpr').get(subdivisioncode=subdivision_code, countrycode=country_code)
except:
return Response({'error': 'Unable to find subdivision with countrycode ' + str(country_code) + ' and' + ' subdivisioncode ' + str(subdivision_code)})
kwargs = {}
kwargs['pobox'] = location.get('pobox', '')
kwargs['sublocation'] = location.get('sublocation', '')
kwargs['streetaddressone'] = location.get('streetaddressone', '')
kwargs['streetaddresstwo'] = location.get('streetaddresstwo', '')
kwargs['streetaddressthree'] = location.get('streetaddressthree', '')
kwargs['city'] = location.get('city', '')
kwargs['postalcode'] = location.get('postalcode', '')
cursor = connections['gpr'].cursor()
cursor.execute("Select uuid() as uuid")
u = cursor.fetchall()
uuid = u[0][0].replace("-", "")
kwargs['locationid'] = uuid
# l.refresh_from_db()
try:
Locations.objects.using('gpr').create_location(locationtype=locationtype, latitude=latitude, longitude=longitude, countrycode=country_instance, subdivisioncode = subdivision_instance, **kwargs)
except (TypeError, ValueError):
return Response({'error': 'Error while saving location'})
try:
location_entry = Locations.objects.using('gpr').get(locationid=uuid)
except:
return Response({'error': 'Unable to find location with locationid ' + str(uuid)})
asset_entry = Assets.objects.using('gpr').create(locationid=location_entry, assettype=assettype)
asset_entry = Assets.objects.using('gpr').filter(locationid=location_entry, assettype=assettype).latest('assetinserted')
farming_details[asset_entry.assetid] = []
try:
actor = Actors.objects.using('gpr').get(actorid = actorid)
except:
return Response({'error': 'Unable to find actor with actorid ' + str(actorid)})
assetrelationship = AssetRelationships.objects.using('gpr').create(assetid= asset_entry, actorid= actor,assetrelationship=asset_relationship)
assets.append(asset_entry)
if assettype=="Farm or pasture land":
hectares = asset_detail.get('hectares', None)
if hectares is None:
return Response({'error': 'hectares must be a decimal number'})
try:
farmingasset = FarmingAssets.objects.using('gpr').create(assetid=asset_entry, hectares=hectares)
except ValidationError:
return Response({'error': 'hectares must be decimal value.'})
farmingasset = FarmingAssets.objects.using('gpr').filter(assetid=asset_entry, hectares=hectares).last()
for type_detail in asset_detail.get('type_details', []):
crop = type_detail.get('crop', '')
hectare = type_detail.get('hectare', '')
if crop != '' and hectare != '':
try:
h3code = ProductCodes.objects.using('gpr').get(h3code=crop)
except:
return Response({'error': 'Unable to find ProductCode with h3code' + str(crop)})
try:
farming = Farming.objects.using('gpr').create(assetid=farmingasset, h3code=h3code, annualyield=hectare)
farming_details[asset_entry.assetid].append(farming.farmingid)
except Exception as e:
return Response({'error': e})
else:
return Response({'error': 'crop with hectare is required.'})
i = 0
data = {}
for asset in assets:
if farming_details[asset.assetid]:
data[i] = {"assetid": asset.assetid, "assetbluenumber": asset.assetuniversalid, "farming_ids": farming_details[asset.assetid]}
else:
data[i] = {"assetid": asset.assetid, "assetbluenumber": asset.assetuniversalid}
i+=1
return Response(data)
</code></pre>
<p>Asset Model</p>
<pre><code>class Assets(models.Model):
assetid = models.CharField(db_column='AssetID', primary_key=True, max_length=255) # Field name made lowercase.
assetname = models.CharField(db_column='AssetName', max_length=255, blank=True, null=True) # Field name made lowercase.
locationid = models.ForeignKey('Locations', models.DO_NOTHING, db_column='LocationID') # Field name made lowercase.
assetuniversalid = models.CharField(db_column='AssetBluenumber', unique=True, blank=True, null=True, max_length=255) # Field name made lowercase.
assettype = models.CharField(db_column='AssetType', max_length=45, blank=True, null=True) # Field name made lowercase.
assetinserted = models.DateTimeField(db_column='AssetInserted', blank=True, null=True, auto_now_add=True) # Field name made lowercase.
assetupdated = models.DateTimeField(db_column='AssetUpdated', blank=True, null=True, auto_now=True) # Field name made lowercase.
</code></pre> | <p>You can make <a href="http://www.django-rest-framework.org/api-guide/serializers/#modelserializer" rel="noreferrer">serializers</a>, they have a very easy way to validate your data. As in your case all the fields seem to be required it becomes even easier.</p>
<p>Create a file on you api app like:</p>
<h3>serializers.py</h3>
<pre><code>#Import Serializers lib
from rest_framework import serializers
#Import your models here (You can put more than one serializer in one file)
from assets.model import Assets
#Now make you serializer class
class AssetsSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = '__all__'
#This last line will put all the fields on you serializer
#but you can also especify only some fields like:
#fields = ('assetid', 'assetname')
</code></pre>
<p>On you view you can use your serializer(s) class to validate you data.</p>
<h3>views.py</h3>
<pre><code>#Serializers
from assets.serializers import AssetsSerializer
#Libraries you can use
from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
class AssetsViewSet(viewsets.ModelViewSet):
queryset = Assets.objects.using("gpr").all()
def create(self, request):
assets = []
farming_details = {}
#Set your serializer
serializer = AssetsSerializer(data=request.data)
if serializer.is_valid(): #MAGIC HAPPENS HERE
#... Here you do the routine you do when the data is valid
#You can use the serializer as an object of you Assets Model
#Save it
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code></pre>
<p>i took this all from the documentation. You can learn a lot doing the <a href="http://www.django-rest-framework.org/tutorial/1-serialization/" rel="noreferrer">tutorial</a> from the official site. I hope it helps.</p> | python|django|django-views|django-rest-framework | 8 |
75 | 48,687,009 | Python - Error in two-layer neural network | <p>I am trying to implement a 2-layer neural network from scratch. But there is something wrong. After some iterations, my loss becomes <code>nan</code>.</p>
<pre><code>'''
We are implementing a two layer neural network.
'''
import numpy as np
x,y = np.random.rand(64,1000),np.random.randn(64,10)
w1,w2 = np.random.rand(1000,100),np.random.rand(100,10)
learning_rate = 1e-4
x -= np.mean(x,axis=0) #Normalizing the Training Data Set
for t in range(2000):
h = np.maximum(0,x.dot(w1)) # Applying Relu Non linearity
ypred = h.dot(w2) #Output of Hidden layer
loss = np.square(ypred - y).sum()
print('Step',t,'\tLoss:- ',loss)
#Gradient Descent
grad_ypred = 2.0 * (ypred - y)
gradw2 = (h.transpose()).dot(grad_ypred)
grad_h = grad_ypred.dot(w2.transpose())
gradw1 = (x.transpose()).dot(grad_h*h*(1-h))
w1 -= learning_rate*gradw1
w2 -= learning_rate*gradw2
</code></pre>
<p>I also implemented Linear Regression using a Softmax classifier and multi-class SVM loss. Same problem happens. Please tell me how to resolve this.</p>
<p>Output:</p>
<pre><code>D:\Study Material\Python 3 Tutorial\PythonScripts\Machine Learning>python TwoLayerNeuralNet.py
Step 0 Loss:- 19436393.79233052
Step 1 Loss:- 236820315509427.38
Step 2 Loss:- 1.3887002186558748e+47
Step 3 Loss:- 1.868219503527502e+189
Step 4 Loss:- inf
TwoLayerNeuralNet.py:23: RuntimeWarning: invalid value encountered in multiply
gradw1 = (x.transpose()).dot(grad_h*h*(1-h))
TwoLayerNeuralNet.py:12: RuntimeWarning: invalid value encountered in maximum
h = np.maximum(0,x.dot(w1)) # Applying Relu Non linearity
Step 5 Loss:- nan
Step 6 Loss:- nan
Step 7 Loss:- nan
Step 8 Loss:- nan
Step 9 Loss:- nan
Step 10 Loss:- nan
Step 11 Loss:- nan
Step 12 Loss:- nan
Step 13 Loss:- nan
Step 14 Loss:- nan
Step 15 Loss:- nan
Step 16 Loss:- nan
Step 17 Loss:- nan
Step 18 Loss:- nan
Step 19 Loss:- nan
Step 20 Loss:- nan
</code></pre> | <p>Its because your loss is becoming too high<br>
try this </p>
<pre><code>loss = np.square(ypred - y).mean()
</code></pre>
<p>and if still doesn't work try reducing the learning rate to something like <code>1e-8</code>.<br>
and observe if the loss is going up or down, if loss is reducing thats good, if the loss is increasing thats a bad sign, you might want to consider using a better dataset and check the weights updation.</p> | python|neural-network | 0 |
76 | 19,919,498 | How to implement n times nested loops in python? | <p>I want to do nested loops with n times, this n is an variable and can be provided by function or input methods. In order to do this, I have to write lots of if..elif blocks depend on size of n, does anybody have good strategies to handle this task? The codes (for combination of 4 letters problem) I used are as follows:</p>
<pre><code>def charCombination(n):
patList = []
s = 'ATCG'
if n == 1:
for i in s:
patList.append(i)
elif n == 2:
for i in s:
for j in s:
patList.append(i+j)
elif n == 3:
for i in s:
for j in s:
for k in s:
patList.append(i+j+k)
...
return patList
</code></pre> | <p>You can use <a href="http://docs.python.org/2/library/itertools.html#itertools.product" rel="noreferrer">itertools.product</a> with <code>repeat</code> parameter</p>
<pre><code>import itertools
def charCombination(n):
return ["".join(item) for item in itertools.product("ATCG", repeat=n)]
print charCombination(1)
print charCombination(2)
print charCombination(3)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>['A', 'T', 'C', 'G']
['AA', 'AT', 'AC', 'AG', 'TA', 'TT', 'TC', 'TG', 'CA', 'CT', 'CC', 'CG', 'GA', 'GT', 'GC', 'GG']
['AAA', 'AAT', 'AAC', 'AAG', 'ATA', 'ATT', 'ATC', 'ATG', 'ACA', 'ACT', 'ACC', 'ACG', 'AGA', 'AGT', 'AGC', 'AGG', 'TAA', 'TAT', 'TAC', 'TAG', 'TTA', 'TTT', 'TTC', 'TTG', 'TCA', 'TCT', 'TCC', 'TCG', 'TGA', 'TGT', 'TGC', 'TGG', 'CAA', 'CAT', 'CAC', 'CAG', 'CTA', 'CTT', 'CTC', 'CTG', 'CCA', 'CCT', 'CCC', 'CCG', 'CGA', 'CGT', 'CGC', 'CGG', 'GAA', 'GAT', 'GAC', 'GAG', 'GTA', 'GTT', 'GTC', 'GTG', 'GCA', 'GCT', 'GCC', 'GCG', 'GGA', 'GGT', 'GGC', 'GGG']
</code></pre> | python | 5 |
77 | 66,959,167 | Timer for variable time delay | <p>I would like a timer (Using Python 3.8 currently) that first checks the system time or Naval Observatory clock, so it can be started at any time and synch with the 00 seconds.</p>
<p>I'm only interested in the number of seconds on the system clock or Naval Observatory. At the top of every minute, i.e when the seconds = 00 I need to write data to a DataFrame or database, then sleep again for another 60 seconds.</p>
<p>I first checked the system time, determined how long it is from the 00 seconds, and placed the first delay for that amount. After that it should delay or sleep for 60 seconds, then run again. Data is constantly changing but at this point I only need to write the data every 60 seconds, would like to also have it have the capability of using other time frames like 5 minutes, 15 minutes etc, but once the first is done the other time frames will be easy.</p>
<p>Here is my lame attempt, it runs a few iterations then quits, and I'm sure it's not very efficient</p>
<pre class="lang-py prettyprint-override"><code>def time_delay():
sec = int(time.strftime('%S'))
if sec != 0:
wait_time = 60 - sec
time.sleep(wait_time)
sec = int(time.strftime('%S'))
wait_time = 60 - sec
elif time.sleep(60):
time_delay()
</code></pre> | <p>This will call a function when the seconds are 0:</p>
<pre><code>def time_loop(job):
while True:
if int(time.time()) % 60 == 0:
job()
time.sleep( 1 )
</code></pre> | python|variables|time|timer|delay | 1 |
78 | 48,054,298 | Finding nearest timeindex for many categories | <p>I am trying to obtain the data points nearest to the query timestamp for multiple independent categories like this (<a href="https://gist.github.com/talesa/babe9955b891c8f75611eaf8e4f48974" rel="nofollow noreferrer">example in more detail in the gist</a>):</p>
<pre><code>dt = pd.to_datetime(dt)
df_output = list()
for category in df.category.unique():
df_temp = df[df.category == category]
i = df_temp.index.get_loc(dt, method='nearest')
latest = df_temp.iloc[i]
df_output.append(latest)
pd.DataFrame(df_output)
</code></pre>
<p>The issue with this approach is that it is very slow (and obviously feels very blunt). Profiling suggests the bottleneck is <code>iloc</code>, which seems odd.</p>
<p>What is a faster/more correct way to go about it? Is there a way to obtain the result for all of the categories at once? (I'm thinking of some <code>groupby</code> magic) </p>
<p>Is <code>pandas</code> capable of doing it or should I switch to some other timeseries storage method?</p> | <p>Pandas was made for time-series data so this is it's bread and butter. Try this for performance:</p>
<pre><code>dt = '2017-12-23 01:49:13'
df["timedelta"] = abs(df.index - pd.Timestamp(dt))
df.loc[df.groupby(by="category")["timedelta"].idxmin()].drop("timedelta", axis=1)
</code></pre>
<p>This is creating a new column called timedelta, named after <code>pandas.Timedelta</code> class, and then using <code>groupby</code> to combine all the categories, find the smallest timedelta in each and return their index into <code>.loc</code>. Lastly I dropped the column.</p> | python|pandas|time-series | 1 |
79 | 48,082,038 | Cassandra Pagination CPU Utilization Issue | <p>I had developed a python script for pulling the data but it is using only single cpu core and when I do top cassandra is using more than 200% cpu. Going into Idle state since in between GC coming into picture Unable understand how can I convert the code to utilize multiple cores and parallel processing.</p>
<pre><code>class PagedResultHandler(object):
def __init__(self, future):
self.error = None
self.finished_event = multiprocessing.Event()
self.future = future
self.future.add_callbacks(
callback=self.handle_page,
errback=self.handle_error)
self.rows = []
def handle_page(self, rows):
self.rows += rows
if self.future.has_more_pages:
self.future.start_fetching_next_page()
else:
self.finished_event.set()
def handle_error(self, exc):
self.error = exc
self.finished_event.set()
start_time = time.time()
cluster = Cluster(contact_points=['127.0.0.1'],protocol_version=4)
session = cluster.connect('unit_test')
query = "select * from "+table_name+" where runseq=0"
print("--Fired Query--->> ", query)
future = session.execute_async(query)
handler = PagedResultHandler(future)
handler.finished_event.wait()
data = pd.DataFrame(handler.rows)
print("--- %s seconds ---" % (time.time() - start_time))
if handler.error:
raise handler.error
cluster.shutdown()
</code></pre>
<p>Each table I pull contains more than 3million rows and has lot performance issue. Can I help me how I can Make cpu cores and improve performance </p> | <p>You wont get blazing performance out of python driver, but you can look at cqlsh's copy functions (<a href="https://github.com/apache/cassandra/blob/trunk/pylib/cqlshlib/copyutil.py#L229" rel="nofollow noreferrer">https://github.com/apache/cassandra/blob/trunk/pylib/cqlshlib/copyutil.py#L229</a>) if you really want to see a fast implementation that can use multiple cores.</p>
<p>On C* side make sure you have enough nodes with adequate hardware (ssds, multiple cores, >16gb of ram). If using sub 8gb heaps etc don't expect much out of it. Cassandra/JVM (with default settings) are designed to fully utilize the server as much as it can, not share resources so expect high CPU.</p> | python-3.x|cassandra | 1 |
80 | 48,376,460 | finding just full words in a python string | <p>Basically it all comes down to finding just the fullword, not matching also a substring thereof.</p>
<p>I have phrases like: </p>
<p>texto = "hello today is the first day of working week" and what I wanted to do is to split that phrase into words to see if any matched fullwords that I have obtained from a sql query, like this:</p>
<pre><code>sql = "select keyword from keywords"
try:
cursor.execute(sql)
# Fetch all the rows in a list of lists.
results = cursor.fetchall()
for result in results:
keywords.append(result)
</code></pre>
<p>so there I have a tuple of keywords.</p>
<p>So, yes, of course, you would split the phrase like this:</p>
<pre><code>for word in texto.split():
if word in keywords.__str__():
print ("keyword %s detected in texto" % (word))
</code></pre>
<p>but while that does indeed find me words, it also "finds" me things that I would have not wanted or expected (a substring of a word):</p>
<p>I know that in PHP you would do something like this:</p>
<pre><code>if (preg_match("/\b$search\b/", texto)):
{print "word found"}
</code></pre>
<p>and I ve read quite a few discussions on this at SO. Some people say that you just do split, (but that is what I have done), others say use this:</p>
<p>in isn't how it's done.</p>
<pre><code>>>> re.search(r'\babc\b', 'abc123')
>>> re.search(r'\babc\b', 'abc 123')
<_sre.SRE_Match object at 0x1146780>
</code></pre>
<p>is this latest example the way to do it? according to the shell interpreter it would match the second row.</p> | <p>I dont't see why split() should not work. The issue is the <code>.__str__()</code> (which I don't see any need for). It creates one single string in which the keywords are searched - and then it will find substrings as well. </p>
<p>The following is working for me:</p>
<pre><code>texto = "hello today is the first day of working week"
keywords = ["is", "day", "week", "work", "sun"]
for keyword in keywords:
print("keyword", keyword, end=" ")
if keyword in texto.split():
print("found.")
else:
print("not found")
</code></pre>
<p><code>work</code> and <code>sun</code> should not match, <code>work</code> is a substring in the text, <code>sun</code> is not in the text.</p>
<p>Output is </p>
<pre><code>keyword is found.
keyword day found.
keyword week found.
keyword work not found
keyword sun not found
</code></pre> | python | 0 |
81 | 73,682,019 | How to solve a Dataset problem in python? | <p>i have a dataset with different programming language in a column titled and i want to get the 10 most used programming language in my dataset python</p>
<p>Dataset: <a href="https://drive.google.com/file/d/1nJLDFSdIbkNxcqY7NBtJZfcgLW1wpsUZ/view?usp=sharing" rel="nofollow noreferrer">https://drive.google.com/file/d/1nJLDFSdIbkNxcqY7NBtJZfcgLW1wpsUZ/view?usp=sharing</a></p> | <p>On StackOverflow, you should not link to outside sources, but include relevant data in your question. You should also pare down the data - if it is long, make it as short as possible and still illustrate your question.</p>
<p>Finally, on StackOverflow, we don't ask bare questions like "how to do x". You must first make an effort yourself to solve your problem, and then, if you don't understand why your code does not work, then you post the smallest possible example, and we will tell you where the bug is. You must show the effort first and then we help you fix it. The purpose of it is so that you learn to code yourself, and not just copy a ready solution.</p>
<p>Since you did not show any effort, I will not give you a complete solution, but I will give you some start to point you in the right direction. You should first analyze my code so that you understand how it works and then you can finish it.</p>
<p>When you run this code, it will print for you the relevant words. You should probably further process them, to remove irrelevant characters that people put in, and also to use proper case of letters, and then you can count the occurrences of words.</p>
<pre><code>#!/usr/bin/python3
LANGUAGE_COLUMN_INDEX = 8
with open('Salary.csv') as fp:
#skip over first line
fp.readline()
for line in fp:
for word in line.split(',')[LANGUAGE_COLUMN_INDEX].split('/'):
print(word.strip())
</code></pre> | python | 0 |
82 | 17,505,091 | Python/Django - Having trouble giving an object a foreignkey that was just created | <p>I am expanding on the basic django Poll site tutorial, and I have made a view that allows users to add their own polls. Adding a poll works, adding choices does not. Apparently this is because the poll does not "exist" yet, and the p.id cannot be used. However, the p.id works when redirecting the browser at the bottom. Anyy ideas? </p>
<pre><code>def save(request):
p = Poll(question=request.POST['question'], pub_date=timezone.now())
p.save()
c1 = Choice(poll=p.id, choice_text=request.POST['c1'], votes=0)
c2 = Choice(poll=p.id, choice_text=request.POST['c2'], votes=0)
c3 = Choice(poll=p.id, choice_text=request.POST['c3'], votes=0)
c4 = Choice(poll=p.id, choice_text=request.POST['c4'], votes=0)
c1.save()
c2.save()
c3.save()
c4.save()
return HttpResponseRedirect(reverse('detail', args=(p.id,)))
</code></pre> | <p>Nevermind, I figured it out. The choice doent need an id, rather, it needs the object.
FIxed by changing:</p>
<pre><code>c1 = Choice(poll=p.id, choice_text=request.POST['c1'], votes=0)
</code></pre>
<p>to</p>
<pre><code>c1 = Choice(poll=p, choice_text=request.POST['c1'], votes=0)
</code></pre> | python|django | 1 |
83 | 17,265,845 | No such file or directory: ...build/sip/setup.py | <p>I'm trying to install PyQt on Ubuntu. The list of obstacles I'm dealing with is far too long to include here. The obstacle I'm currently trying to get past is this:</p>
<pre><code>(myvenv)% cd ~/.virtualenvs/myvenv/build/pyqt
(myvenv)% python ./configure.py
Traceback (most recent call last):
File "./configure.py", line 32, in <module>
import sipconfig
</code></pre>
<p>OK, so let's install <code>sipconfig</code>...</p>
<pre><code>(myvenv)% pip install SIP
Downloading/unpacking SIP
Downloading sip-4.14.8-snapshot-02bdf6cc32c1.zip (848Kb): 848Kb downloaded
Running setup.py egg_info for package SIP
Traceback (most recent call last):
File "<string>", line 14, in <module>
IOError: [Errno 2] No such file or directory: '/home/yt/.virtualenvs/myvenv/build/SIP/setup.py'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 14, in <module>
IOError: [Errno 2] No such file or directory: '/home/yt/.virtualenvs/myvenv/build/SIP/setup.py'
----------------------------------------
Command python setup.py egg_info failed with error code 1 in /home/yt/.virtualenvs/myvenv/build/SIP
Storing complete log in /home/yt/.pip/pip.log
</code></pre>
<p>The only recipe I've found so far installing SIP is this</p>
<pre><code>python configure.py
make
sudo make install
</code></pre>
<p>But, on Ubuntu I try to do every installation through <code>apt-get</code>, so I'm reluctant to follow the recipe above.</p>
<p>How else can I install SIP?</p> | <p>allready answer <a href="https://stackoverflow.com/questions/7942887/how-to-configure-pyqt4-for-python-3-in-ubuntu">here</a></p>
<p>start all from the beginning and make sure that all dependencies are satisfied.</p> | python|qt | 0 |
84 | 17,314,150 | parallel installion of Python 2.7 and 3.3 via Homebrew - pip3 fails | <p>I would like to make the jump and get acquainted with Python 3.
I followed the instructions found <a href="https://github.com/mxcl/homebrew/wiki/Homebrew-and-Python#python-2x-or-python-3x" rel="nofollow noreferrer">here</a> with the installation working flawlessly.</p>
<p>I'm also able to use the provided virtualenv to create enviroments for Python 2 and Python 3 (Followed the instuctions <a href="https://stackoverflow.com/questions/12566064/virtualenv-with-python2-and-python3-via-homebrew">here</a>.). Unfortunalty pip3 fails when no virtualenv is activated. I need to use it to install global modules for python3.</p>
<p>This is the error message:</p>
<pre><code>Β± |master β| β pip3
Traceback (most recent call last):
File "/usr/local/bin/pip3", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/local/lib/python2.7/site-packages/distribute-0.6.45-py2.7.egg/pkg_resources.py", line 51
def _bypass_ensure_directory(name, mode=0777):
^
SyntaxError: invalid token
</code></pre>
<p>It looks like pip3 is trying to access distribute of python2. Is there any workaround for this?</p> | <p>I was having the same problem as you were and I had </p>
<pre><code>export PYTHONPATH="/usr/local/lib/python2.7/site-packages:$PYTHONPATH"
</code></pre>
<p>in my ~/.bash_profile. Removing that line solved the problem for me. If you have that or something like it in your ~/.bashrc or ~/.bash_profile, try removing it.</p> | python|macos|python-3.x|pip|homebrew | 2 |
85 | 64,426,691 | graph theory - connect point in 3D space with other three nearest points (distance based) | <p>I want to connect nodes (Atoms) with the three nearest nodes(atoms).</p>
<p>I am doing</p>
<pre><code>ad1 = np.zeros((31,31))
for i in range(31):
dist_i = dist_mat[i]
cut_off = sorted(dist_i)[3]
ad1[i, np.where((dist_i<=cut_off) & (dist_i!=0.0))] = 1
np.sum(ad1, axis=1) #[3,3,3,3........3]
np.sum(ad1, axis=0)
#array([3., 3., 2., 2., 2., 4., 2., 5., 2., 3., 2., 3., 3., 2., 3., 6., 3.,
5., 3., 4., 2., 3., 2., 4., 3., 3., 2., 4., 3., 2., 3.])
</code></pre>
<p>I want <code>np.sum(ad1, axis=0)</code> to be all 3. That would mean all node (atoms) are connected to exactly 3 nearest nodes. As we can see node/atom 5 is connected to 4 other nodes/atoms which is wrong, I want it to be connected to exactly 3 nearest nodes. How do I do it.</p>
<p>Below is the distance matrix of 31 atoms (31 X 31).</p>
<pre><code>0.0000,6.8223,7.5588,4.8966,7.2452,2.7778,3.7082,2.7345,7.1540,6.8273,3.6995,7.4136,4.6132,5.8456,2.8037,5.4881,8.1769,2.7361,8.3034,4.9450,4.8225,4.6152,4.8243,9.4876,7.2391,2.9941,7.4180,5.8523,7.6310,5.5996,8.1761
6.8223,0.0000,3.0097,2.8567,2.6647,5.0092,5.8451,6.8037,6.7031,4.8983,7.5806,5.2873,5.5000,7.0038,4.9530,3.9763,7.0263,4.8941,4.7416,6.8450,2.8166,2.9221,5.5502,7.0328,5.5148,7.6318,2.7456,5.1150,2.9654,4.2863,5.3168
7.5588,3.0097,0.0000,2.8679,2.9242,5.1443,6.8372,6.5621,5.5169,3.0135,6.8412,4.6886,4.2507,5.4276,5.8673,4.8804,4.7149,6.5707,2.5568,6.3820,5.0625,4.2533,5.0600,5.2125,2.9262,7.8126,4.6864,5.4224,2.6001,3.2330,4.7116
4.8966,2.8567,2.8679,0.0000,3.8064,3.0221,5.1335,4.1131,5.8284,2.8610,5.1354,3.8488,2.8086,4.9618,3.0028,2.7539,5.7401,4.1214,4.5830,5.4268,2.9346,2.8122,2.9319,6.8084,3.8015,5.8992,3.8516,4.9611,2.9212,3.0441,5.7392
7.2452,2.6647,2.9242,3.8064,0.0000,4.7907,5.1676,7.2899,4.5138,5.5206,7.0249,6.9978,5.3888,5.7435,6.2424,6.0645,5.2615,5.6079,2.8907,5.3589,4.7384,2.8152,6.6866,4.6140,4.7660,6.9472,5.3921,3.2734,4.7050,2.9157,2.6684
2.7778,5.0092,5.1443,3.0221,4.7907,0.0000,2.8352,3.0025,4.6425,5.0210,2.8371,6.4170,2.6958,3.6516,3.1115,4.9489,5.5823,3.0042,5.5496,3.0193,4.1730,2.6916,4.1796,6.7613,4.7913,2.8772,6.4156,3.6500,5.9378,2.8228,5.5754
3.7082,5.8451,6.8372,5.1335,5.1676,2.8352,0.0000,5.4535,5.0179,7.5889,4.7500,8.8240,5.4549,5.4488,4.9281,6.8616,7.0789,2.8247,6.7504,3.1734,4.9441,2.9387,6.8368,7.3498,7.0263,2.7571,7.6165,2.7391,7.8184,4.2915,5.4352
2.7345,6.8037,6.5621,4.1131,7.2899,3.0025,5.4535,0.0000,6.9646,4.8923,2.8238,5.6867,2.8002,4.7436,2.7895,4.7319,7.0025,4.5800,7.4954,5.2983,5.3961,5.3071,2.7803,8.9227,5.5914,4.2758,7.1749,6.6267,6.5470,5.1104,8.2905
7.1540,6.7031,5.5169,5.8284,4.5138,4.6425,5.0179,6.9646,0.0000,6.7047,5.0056,9.1250,4.9769,2.9634,7.5819,8.5546,2.8061,6.9800,3.6751,2.5834,7.6541,4.9881,7.6494,2.7948,4.5088,5.2110,9.1264,2.9761,7.8062,2.7941,2.8038
6.8273,4.8983,3.0135,2.8610,5.5206,5.0210,7.5889,4.8923,6.7047,0.0000,5.8617,2.7465,2.9301,5.1272,4.9558,3.9808,5.3162,6.8165,4.7404,6.8576,5.5561,5.5098,2.8152,7.0330,2.6644,7.6461,5.2912,7.0096,2.9674,4.2945,7.0258
3.6995,7.5806,6.8412,5.1354,7.0249,2.8371,4.7500,2.8238,5.0056,5.8617,0.0000,7.6266,2.9474,2.7359,4.9270,6.8677,5.4363,5.4517,6.7478,3.1721,6.8329,5.4529,4.9555,7.3438,5.1708,2.7597,8.8287,5.4452,7.8249,4.2909,7.0646
7.4136,5.2873,4.6886,3.8488,6.9978,6.4170,8.8240,5.6867,9.1250,2.7465,7.6266,0.0000,4.9529,7.5866,4.8602,2.7541,8.0299,7.1729,7.0207,8.9107,5.2910,6.5588,2.9146,9.5249,5.3922,9.1160,4.1719,8.7725,2.7497,6.4529,9.0793
4.6132,5.5000,4.2507,2.8086,5.3888,2.6958,5.4549,2.8002,4.9769,2.9301,2.9474,4.9529,0.0000,2.8097,3.9433,4.7505,4.4056,5.3122,4.8719,4.3293,5.3691,4.4387,2.8442,6.4077,2.8070,4.8696,6.5606,5.3482,5.0545,2.9281,6.2031
5.8456,7.0038,5.4276,4.9618,5.7435,3.6516,5.4488,4.7436,2.9634,5.1272,2.7359,7.5866,2.8097,0.0000,6.2398,7.3805,2.7234,6.6316,4.5653,2.8038,7.3250,5.3513,5.6427,4.8167,3.2793,4.4545,8.7753,4.6687,7.1729,2.8747,5.2395
2.8037,4.9530,5.8673,3.0028,6.2424,3.1115,4.9281,2.7895,7.5819,4.9558,4.9270,4.8602,3.9433,6.2398,0.0000,2.6964,7.9654,2.7924,7.3935,6.1211,2.8429,3.9452,2.8424,9.2720,6.2355,5.1988,4.8668,6.2430,5.2004,5.1737,7.9659
5.4881,3.9763,4.8804,2.7539,6.0645,4.9489,6.8616,4.7319,8.5546,3.9808,6.8677,2.7541,4.7505,7.3805,2.6964,0.0000,8.3401,4.7306,7.1148,7.8221,2.7718,4.7476,2.7753,9.5030,6.0617,7.5711,2.7577,7.3777,3.1397,5.7882,8.3392
8.1769,7.0263,4.7149,5.7401,5.2615,5.5823,7.0789,7.0025,2.8061,5.3162,5.4363,8.0299,4.4056,2.7234,7.9654,8.3401,0.0000,8.3066,2.9172,4.5762,8.3187,6.2166,6.9974,2.6988,2.6667,6.8504,9.0816,5.2518,7.0366,3.3010,4.3079
2.7361,4.8941,6.5707,4.1214,5.6079,3.0042,2.8247,4.5800,6.9800,6.8165,5.4517,7.1729,5.3122,6.6316,2.7924,4.7306,8.3066,0.0000,7.5094,5.3015,2.7788,2.8080,5.4012,8.9373,7.2956,4.2691,5.6901,4.7565,6.5515,5.1204,7.0169
8.3034,4.7416,2.5568,4.5830,2.8907,5.5496,6.7504,7.4954,3.6751,4.7404,6.7478,7.0207,4.8719,4.5653,7.3935,7.1148,2.9172,7.5094,0.0000,5.4477,6.7736,4.8812,6.7675,2.6661,2.8871,7.5857,7.0211,4.5660,5.1569,2.7695,2.9165
4.9450,6.8450,6.3820,5.4268,5.3589,3.0193,3.1734,5.2983,2.5834,6.8576,3.1721,8.9107,4.3293,2.8038,6.1211,7.8221,4.5762,5.3015,5.4477,0.0000,6.7806,4.3263,6.7865,5.3395,5.3642,2.6393,8.9072,2.7997,8.0722,3.1518,4.5623
4.8225,2.8166,5.0625,2.9346,4.7384,4.1730,4.9441,5.3961,7.6541,5.5561,6.8329,5.2910,5.3691,7.3250,2.8429,2.7718,8.3187,2.7788,6.7736,6.7806,0.0000,2.8411,4.6768,8.8466,6.6849,6.5259,2.9190,5.6409,4.2802,5.1556,7.0036
4.6152,2.9221,4.2533,2.8122,2.8152,2.6916,2.9387,5.3071,4.9881,5.5098,5.4529,6.5588,4.4387,5.3513,3.9452,4.7476,6.2166,2.8080,4.8812,4.3263,2.8411,0.0000,5.3713,6.4170,5.3921,4.8619,4.9490,2.8105,5.0539,2.9321,4.4129
4.8243,5.5502,5.0600,2.9319,6.6866,4.1796,6.8368,2.7803,7.6494,2.8152,4.9555,2.9146,2.8442,5.6427,2.8424,2.7753,6.9974,5.4012,6.7675,6.7865,4.6768,5.3713,0.0000,8.8413,4.7294,6.5361,5.2956,7.3262,4.2788,5.1556,8.3129
9.4876,7.0328,5.2125,6.8084,4.6140,6.7613,7.3498,8.9227,2.7948,7.0330,7.3438,9.5249,6.4077,4.8167,9.2720,9.5030,2.6988,8.9373,2.6661,5.3395,8.8466,6.4170,8.8413,0.0000,4.6127,7.9200,9.5247,4.8201,7.8081,4.1075,2.6956
7.2391,5.5148,2.9262,3.8015,4.7660,4.7913,7.0263,5.5914,4.5088,2.6644,5.1708,5.3922,2.8070,3.2793,6.2355,6.0617,2.6667,7.2956,2.8871,5.3642,6.6849,5.3921,4.7294,4.6127,0.0000,6.9513,6.9963,5.7431,4.7049,2.9171,5.2546
2.9941,7.6318,7.8126,5.8992,6.9472,2.8772,2.7571,4.2758,5.2110,7.6461,2.7597,9.1160,4.8696,4.4545,5.1988,7.5711,6.8504,4.2691,7.5857,2.6393,6.5259,4.8619,6.5361,7.9200,6.9513,0.0000,9.1125,4.4513,8.8145,4.8939,6.8395
7.4180,2.7456,4.6864,3.8516,5.3921,6.4156,7.6165,7.1749,9.1264,5.2912,8.8287,4.1719,6.5606,8.7753,4.8668,2.7577,9.0816,5.6901,7.0211,8.9072,2.9190,4.9490,5.2956,9.5247,6.9963,9.1125,0.0000,7.5797,2.7482,6.4514,8.0302
5.8523,5.1150,5.4224,4.9611,3.2734,3.6500,2.7391,6.6267,2.9761,7.0096,5.4452,8.7725,5.3482,4.6687,6.2430,7.3777,5.2518,4.7565,4.5660,2.7997,5.6409,2.8105,7.3262,4.8201,5.7431,4.4513,7.5797,0.0000,7.1676,2.8724,2.7190
7.6310,2.9654,2.6001,2.9212,4.7050,5.9378,7.8184,6.5470,7.8062,2.9674,7.8249,2.7497,5.0545,7.1729,5.2004,3.1397,7.0366,6.5515,5.1569,8.0722,4.2802,5.0539,4.2788,7.8081,4.7049,8.8145,2.7482,7.1676,0.0000,5.1559,7.0354
5.5996,4.2863,3.2330,3.0441,2.9157,2.8228,4.2915,5.1104,2.7941,4.2945,4.2909,6.4529,2.9281,2.8747,5.1737,5.7882,3.3010,5.1204,2.7695,3.1518,5.1556,2.9321,5.1556,4.1075,2.9171,4.8939,6.4514,2.8724,5.1559,0.0000,3.2927
8.1761,5.3168,4.7116,5.7392,2.6684,5.5754,5.4352,8.2905,2.8038,7.0258,7.0646,9.0793,6.2031,5.2395,7.9659,8.3392,4.3079,7.0169,2.9165,4.5623,7.0036,4.4129,8.3129,2.6956,5.2546,6.8395,8.0302,2.7190,7.0354,3.2927,0.0000
</code></pre>
<p><strong>Edit 1</strong></p>
<p>Thank-you, @yatu, and @mathfux but Kdtree does not produce what I want.</p>
<p>so from @mathfux answer if the nearest list of 3 is 0,1,2 and 0 has the nearest list of 1,4,2 then the algorithm should give more importance to distances and break the connections of 3 and 0. 3 should find other points nearest to it, instead of joining with 0. if 3 cannot find other points nearest to it then 0 has to exclude either 1 or 2 based on the distance and include 3 because 3 could not find 3 nearest points other than 0,1,2.</p>
<p>Also one can see 0 is connected to 25 but 25 is not connected to 0 which is wrong. if 0 is connected to 25 then 25 should also be connected to 0.</p>
<pre><code>[ 0, 17, 7, 25]
[ 5, 21, 12, 6]
[ 6, 25, 27, 17]
[10, 25, 13, 7]
[12, 5, 3, 24]
[21, 5, 3, 4]
[25, 6, 10, 19]
[29, 4, 12, 24]
</code></pre> | <p>A <a href="https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KDTree.html" rel="nofollow noreferrer"><code>KDTree</code></a> would be more appropriate for what you're trying to do. Once you've built the tree, you can search for the <code>3</code> nearest points to all points in the tree:</p>
<pre><code>from sklearn.neighbors import KDTree
tree = KDTree(X, leaf_size=2)
dist, ind = tree.query(X, k=3)
</code></pre>
<p>To check the result, we can verify that the three smallest values in the first row, match the three smallest distances returned by the <code>query</code> indexing on the first row <code>ind[0]</code>:</p>
<pre><code>np.sort(X[0])[:3]
#array([0. , 2.7345, 2.7361])
X[0,ind[0]]
# array([0. , 2.7361, 2.7345])
</code></pre> | python|python-3.x|graph-theory|chemistry|rdkit | 3 |
86 | 70,541,291 | How to change the field of username to user_name in to django custom user model? | <p>I have created custom user model. now I want to use <code>user_name</code> as username field instead of <code>username</code>. like shown in below code snippet.</p>
<pre><code>class CustomUser(AbstractBaseUser):
username_validator = UnicodeUsernameValidator()
user_name = models.CharField(
_('username'),
max_length=100,
unique=True,
help_text=_('Required. 100 characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[username_validator],
error_messages={
'unique': _("A user with that username already exists."),
},
)
USERNAME_FIELD = 'user_name'
</code></pre>
<p>i'm unable to do that. i'm getting below error:</p>
<pre><code>SystemCheckError: System check identified some issues:
ERRORS:
<class 'accounts.admin.CustomUserAdmin'>: (admin.E033) The value of 'ordering[0]' refers to 'username', which is not an attribute of 'accounts.CustomUser'.
<class 'accounts.admin.CustomUserAdmin'>: (admin.E108) The value of 'list_display[0]' refers to 'username', which is not a callable, an attribute of 'CustomUserAdmin', or an attribute or method on 'accounts.CustomUser'
</code></pre>
<p>the reason of using this, is because all the project's database tables convention is like this. It would be more better if i could define field name is database just as we do for tables in Meta class like below. where i'm calling my customuser model as user model in db.</p>
<pre><code>class Meta:
db_table = "user"
</code></pre>
<p>is there anyway to call table field like this way ?</p>
<pre><code>class Meta:
db_table_user_name = "username"
</code></pre>
<p>if it possible then we dont need to change <code>username</code> to <code>user_name</code>. we can directly call username field is equal to user_name in database. if and only if it is possible with django models.</p> | <p>in admin.py where you are registering your User model. you are registering it with ModelAdmin and in that ModelAdmion you have named field incorrectly. change it to user_name their too.</p> | python|django|django-models|abstract-class|django-users | 1 |
87 | 49,806,443 | Video Intelligence API - Label Segment time | <p>I am following <a href="https://cloud.google.com/video-intelligence/docs/label-tutorial" rel="nofollow noreferrer">this</a> <strong>LABEL DETECTION TUTORIAL</strong>.</p>
<p>The code below does the following(after getting the response back)</p>
<blockquote>
<p>Our response will contain result within an AnnotateVideoResponse,
which consists of a list of annotationResults, one for each video sent
in the request. Because we sent only one video in the request, we take
the first segmentLabelAnnotations of the results. We then loop through
all the labels in segmentLabelAnnotations. For the purpose of this
tutorial, we only display video-level annotations. To identify
video-level annotations, we pull segment_label_annotations data from
the results. Each segment label annotation includes a description
(segment_label.description), a list of entity categories
(category_entity.description) and where they occur in segments by
start and end time offsets from the beginning of the video.</p>
</blockquote>
<pre><code>segment_labels = result.annotation_results[0].segment_label_annotations
for i, segment_label in enumerate(segment_labels):
print('Video label description: {}'.format(
segment_label.entity.description))
for category_entity in segment_label.category_entities:
print('\tLabel category description: {}'.format(
category_entity.description))
for i, segment in enumerate(segment_label.segments):
start_time = (segment.segment.start_time_offset.seconds +
segment.segment.start_time_offset.nanos / 1e9)
end_time = (segment.segment.end_time_offset.seconds +
segment.segment.end_time_offset.nanos / 1e9)
positions = '{}s to {}s'.format(start_time, end_time)
confidence = segment.confidence
print('\tSegment {}: {}'.format(i, positions))
print('\tConfidence: {}'.format(confidence))
print('\n')
</code></pre>
<p>So, it says "Each segment label annotation includes a description (segment_label.description), a list of entity categories (category_entity.description) and <strong><em>where they occur in segments by start and end time offsets from the beginning of the video</em></strong>."</p>
<p>But, in the output, all the labels <code>urban area</code>, <code>traffic</code>, <code>vehicle</code>.. have the same <code>start and end time offsets</code> which are basically the start and the end of the video.</p>
<pre><code>$ python label_det.py gs://cloud-ml-sandbox/video/chicago.mp4
Operation us-west1.4757250774497581229 started: 2017-01-30T01:46:30.158989Z
Operation processing ...
The video has been successfully processed.
Video label description: urban area
Label category description: city
Segment 0: 0.0s to 38.752016s
Confidence: 0.946980476379
Video label description: traffic
Segment 0: 0.0s to 38.752016s
Confidence: 0.94105899334
Video label description: vehicle
Segment 0: 0.0s to 38.752016s
Confidence: 0.919958174229
...
</code></pre>
<ul>
<li><p>Why is this happening?</p></li>
<li><p>Why is the API returning these offsets for all the labels and not the
start and end time offsets of the segment where that particular label
(entity) appears?(I feel like it has something to do with the
<strong>video-level annotation</strong> but I am not sure)</p></li>
<li>How can I get the start and end time offsets of the segment where
they actually appear?</li>
</ul> | <p>I see that the part of the tutorial that you are following uses the <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/video/cloud-client/labels/labels.py" rel="nofollow noreferrer">simplest examples available</a>, while the list of samples provides a <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/video/cloud-client/analyze/analyze.py" rel="nofollow noreferrer">more complete example</a> where more features of the Video Intelligence API are used.</p>
<p>In order to achieve the objective you want (have a more detailed information about the time instants when each annotation is identified), there are two possibilities that you can explore:</p>
<ul>
<li><strong><em>Option 1</em></strong></li>
</ul>
<p>The key point here is the fact that the video-level annotations only work over <a href="https://cloud.google.com/video-intelligence/docs/reference/rest/v1/videos/annotate#videocontext" rel="nofollow noreferrer">segments</a>. As explained in this documentation page I linked, if segments in a video are not specified, the API will treat the video as a single segment. Therefore, if you want that the API returns more "specific" results about when each annotation is identified, you should split the video in segments yourself, by splitting it into different segments (which can overlap and may not need the complete video), and passing those arguments as part of the <code>videoContext</code> field in the <a href="https://cloud.google.com/video-intelligence/docs/reference/rest/v1/videos/annotate" rel="nofollow noreferrer">annotate request</a>.</p>
<p>If you do these through the API request, you may do a request such as the following one, defining as many segments as you want, by specifying the start and end TimeOffsets:</p>
<pre><code>{
"inputUri": "gs://cloud-ml-sandbox/video/chicago.mp4",
"features": [
"LABEL_DETECTION"
],
"videoContext": {
"segments": [
{
"startTimeOffset": "TO_DO",
"endTimeOffset": "TO_DO"
}
{
"startTimeOffset": "TO_DO",
"endTimeOffset": "TO_DO"
}
]
}
}
</code></pre>
<p>If, instead, you are willing to use the Python Client Library, you can instead use the <code>video_context</code> parameter as in the code below:</p>
<pre><code>video_client = videointelligence.VideoIntelligenceServiceClient()
features = [videointelligence.enums.Feature.LABEL_DETECTION]
mode = videointelligence.enums.LabelDetectionMode.SHOT_AND_FRAME_MODE
config = videointelligence.types.LabelDetectionConfig(label_detection_mode=mode)
context = videointelligence.types.VideoContext(label_detection_config=config)
operation = video_client.annotate_video("gs://cloud-ml-sandbox/video/chicago.mp4", features=features, video_context=context)
</code></pre>
<ul>
<li><strong><em>Option 2</em></strong></li>
</ul>
<p>The second option that I propose for your use case is using a different Label Detection Mode. The list of available Label Detection Modes is available in <a href="https://cloud.google.com/video-intelligence/docs/reference/rest/v1/videos/annotate#LabelDetectionMode" rel="nofollow noreferrer">this documentation link</a>. By default, the <code>SHOT_MODE</code> is used, and it will only provide video-level and shot-level annotations, which require that you work with segments as explained in <strong><em>Option 1</em></strong>. If, instead, you use <code>FRAME_MODE</code>, frame-level annotations will be processed. This is a costly option, as it analyses all the frames in the video and annotates each of them, but it may be a suitable option depending on your specific use case. This mode (well, actually the <code>SHOT_AND_FRAME_MODE</code> one, which is a combination of the two previous) is used in the more complete example that I mentioned at the beginning of my answer. The <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/video/cloud-client/analyze/analyze.py#L57" rel="nofollow noreferrer"><code>analyze_labels()</code> function in that code</a> provides a really complete example on how to perform video/shot/frame-level annotations, and specifically for <a href="https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/video/cloud-client/analyze/analyze.py#L115" rel="nofollow noreferrer">frame-level annotation</a> there is an explanation on how to obtain information about the frames were the annotations happen.</p>
<p>Note that this option is really costly, as I explained earlier, and for example, I have run it for the "chicago.mp4" video provided as a sample in the tutorial, and it took around 30 minutes to complete. However, the level of detail achieved is really high (again, each frame is analyzed, and then annotations are grouped by element), and this is the kind of response that you can expect to obtain:</p>
<pre><code>"frameLabelAnnotations": [
{
"entity": {
"entityId": "/m/088l6h",
"description": "family car",
"languageCode": "en-US"
},
"categoryEntities": [
{
"entityId": "/m/0k4j",
"description": "car",
"languageCode": "en-US"
}
],
"frames": [
{
"timeOffset": "0.570808s",
"confidence": 0.76606256
},
{
"timeOffset": "1.381775s",
"confidence": 0.74966145
},
{
"timeOffset": "2.468091s",
"confidence": 0.85502887
},
{
"timeOffset": "3.426006s",
"confidence": 0.78749716
},
]
},
</code></pre>
<p><strong><em>TL;DR:</em></strong></p>
<p>The results returned by the type of call you are making following the simple example in the tutorial is expected. If there is no specific configuration, a video will be considered as a single segment, reason why the response you are getting identifies annotations in the whole video.</p>
<p>If you want to get more details about when are the elements identified, you will need to follow one of the two following approaches: <strong>(1)</strong> define segments in your video (which requires that you manually specify the segments in which you want to split the video), or <strong>(2)</strong> use <code>FRAME_MODE</code> (which is way more costly and precise).</p> | python|google-cloud-platform|video-intelligence-api | 2 |
88 | 66,362,963 | Is there a way to extend a PyTables EArray in the second dimension? | <p>I have a 2D array that can grow to larger sizes than I'm able to fit on memory, so I'm trying to store it in a h5 file using Pytables. The number of rows is known beforehand but the length of each row is not known and is variable between rows. After some research, I thought something along these lines would work, where I can set the extendable dimension as the second dimension.</p>
<pre><code>filename = os.path.join(tempfile.mkdtemp(), 'example.h5')
h5_file = open_file(filename, mode="w", title="Example Extendable Array")
h5_group = h5_file.create_group("/", "example_on_dim_2")
e_array = h5_file.create_earray(h5_group, "example", Int32Atom(shape=()), (100, 0)) # Assume num of rows is 100
# Add some item to index 2
print(e_array[2]) # should print an empty array
e_array[2] = np.append(e_array[2], 5) # add the value 5 to row 2
print(e_array[2]) # should print [5], currently printing empty array
</code></pre>
<p>I'm not sure if it's possible to add elements in this way (I might have misunderstood the way earrays work), but any help would be greatly appreciated!</p> | <p>Here is an example showing how to create a <strong>VLArray</strong> (Variable Length). It is similar to the EArray example above, and follows the example from the Pytables doc (link in comment above). <em>However, although a VLArray supports variable length rows, <strong>it does not have a mechanism to add items to an existing row</strong> (AFAIK).</em></p>
<pre><code>import tables as tb
import numpy as np
filename = 'example_vlarray.h5'
with tb.File(filename, mode="w", title="Example Variable Length Array") as h5_file :
h5_group = h5_file.create_group("/", "vl_example")
vlarray = h5_file.create_vlarray(h5_group, "example", tb.IntAtom(), "ragged array of ints",)
# Append some (variable length) rows:
vlarray.append(np.array([0]))
vlarray.append(np.array([1, 2]))
vlarray.append([3, 4, 5])
vlarray.append([6, 7, 8, 9])
# Now, read it through an iterator:
print('-->', vlarray.title)
for x in vlarray:
print('%s[%d]--> %s' % (vlarray.name, vlarray.nrow, x))
</code></pre> | python|python-3.x|pytables | 0 |
89 | 53,122,592 | Legend with vertical line in matplotlib | <p>I need to show a vertical line in a matplotlib legend for a specific reason. I am trying to make matplotlib understand that I want a vertical line with the lines.Line2D(x,y) but this is clearly not working.</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib import lines
fig, ax = plt.subplots()
ax.plot([0,0],[0,3])
lgd = []
lgd.append(lines.Line2D([0,0],[0,1], color = 'blue', label = 'Vertical line'))
plt.legend(handles = lgd)
</code></pre>
<p><a href="https://i.stack.imgur.com/cJrPX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/cJrPX.png" alt="enter image description here"></a></p>
<p>I need the line to appear vertical, not the legend. Can anyone help?</p> | <p>You can use the vertical line marker when making your line2D object. A list of valid markers can be found <a href="https://matplotlib.org/api/markers_api.html" rel="noreferrer">here</a>.</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib import lines
fig, ax = plt.subplots()
ax.plot([0,0],[0,3])
vertical_line = lines.Line2D([], [], color='#1f77b4', marker='|', linestyle='None',
markersize=10, markeredgewidth=1.5, label='Vertical line')
plt.legend(handles = [vertical_line])
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/xyKij.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xyKij.png" alt="enter image description here"></a></p> | python|matplotlib|legend | 10 |
90 | 53,063,221 | count the occurrences of alphabet of string in python | <p>String containing both upper and lower case alphabets. </p>
<p>We need to count the number of occurrences of each alphabet(case insensitive) and display the same.</p>
<p>Below is the program,but does not led to desired output</p>
<p>output should be-
2A 3B 2C 1G</p>
<p>my output is -
A 2
B 3
A 2
B 3
C 2
B 3
G 1
C 2</p>
<pre><code>String="ABaBCbGc"
String1=String.upper()
for i in String1:
print(i,String1.count(i))
</code></pre> | <p>Use <a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow noreferrer">Counter</a>:</p>
<pre><code>from collections import Counter
String = "ABaBCbGc"
counts = Counter(String.lower())
print(counts)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>Counter({'b': 3, 'c': 2, 'a': 2, 'g': 1})
</code></pre>
<p>If you prefer upper case, just change <code>str.lower</code> to <code>str.upper</code>. Or use a dictionary to keep track of the counts:</p>
<pre><code>string = "ABaBCbGc"
counts = {}
for c in string.upper():
counts[c] = counts.get(c, 0) + 1
print(counts)
</code></pre>
<p><strong>Output</strong></p>
<pre><code>{'C': 2, 'B': 3, 'A': 2, 'G': 1}
</code></pre> | python|count | 5 |
91 | 65,254,860 | How do I insert something into multiple strings? | <p>I have 12 different strings that I want in a tuple format because I will use the strings later in a graph.
How do I add the same string into the array of strings?</p>
<p>I have these months:
January, February etc. and I want to insert into each string "January LSDS", "February LSDS", etc.</p>
<p>I tried this but I get an error:</p>
<pre><code>insert = 'LSDS'
month_names = ('January {}', 'February {}','March {}','April {}', 'May {}', 'June {}', 'July {}', 'August {}', 'September {}', 'October {}', 'November {}', 'December {}').format(insert)
print(month_names)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-167-c79c038f3ebc> in <module>
3 insert = 'LSDS'
4
----> 5 month_names = ('January {}', 'February {}','March {}','April {}', 'May {}', 'June {}', 'July {}', 'August {}', 'September {}', 'October {}', 'November {}', 'December {}').format(insert)
6
7 print(month_names)
AttributeError: 'tuple' object has no attribute 'format'
</code></pre> | <pre><code>inserted = [month.format(insert) for month in month_names]
</code></pre> | python|string|numpy|jupyter | 1 |
92 | 67,523,374 | Pandas: Reshaping Long Data to Wide with duplicated columns | <p>I need to pivot long pandas dataframe to wide. The issue is that for some id there are multiple values for the same parameter. Some parameters present only in a few ids.</p>
<pre><code>df = pd.DataFrame({'indx':[11,11,11,11,12,12,12,13,13,13,13],'param':['a','b','b','c','a','b','d','a','b','c','c'],'value':[100,54,65,65,789,24,98,24,27,75,35]})
</code></pre>
<pre><code>indx param value
11 a 100
11 b 54
11 b 65
11 c 65
12 a 789
12 b 24
12 d 98
13 a 24
13 b 27
13 c 75
13 c 35
</code></pre>
<p>Want to receive something like this:</p>
<pre><code>indx a b c d
11 100 `54,65` 65 None
12 789 None 98 24
13 24 27 `75,35` None
</code></pre>
<p>or</p>
<pre><code>indx a b b1 c c1 d
11 100 54 65 65 None None
12 789 None None 98 None 24
13 24 27 None 75 35 None
</code></pre>
<p>So, obviously direct <code>df.pivot()</code> not a solution.<br />
Thanks for any help.</p> | <h2>Option 1:</h2>
<pre><code>df.astype(str).groupby(['indx', 'param'])['value'].agg(','.join).unstack()
</code></pre>
<p>Output:</p>
<pre><code>param a b c d
indx
11 100 54,65 65 NaN
12 789 24 NaN 98
13 24 27 75,35 NaN
</code></pre>
<h2>Option 2</h2>
<pre><code>df_out = df.set_index(['indx', 'param', df.groupby(['indx','param']).cumcount()])['value'].unstack([1,2])
df_out.columns = [f'{i}_{j}' if j != 0 else f'{i}' for i, j in df_out.columns]
df_out.reset_index()
</code></pre>
<p>Output:</p>
<pre><code> indx a b b_1 c d c_1
0 11 100.0 54.0 65.0 65.0 NaN NaN
1 12 789.0 24.0 NaN NaN 98.0 NaN
2 13 24.0 27.0 NaN 75.0 NaN 35.0
</code></pre> | python|pandas|dataframe|pivot | 3 |
93 | 63,553,935 | Using Pygame and Pymunk Circle will not spawn in space | <p>So, I'm trying to make a function <code>create_particle</code> then make the function draw a partial with <code>draw_circle</code>. However, whenever I open the window, I get my grey window but no particle is shown. I'm extremely new to both pygame and pymunk so any help is appreciated.</p>
<pre><code>import sys, pygame, random, pymunk
BG = (94, 93, 93)
S_width = 800
S_height = 800
pygame.init()
Window = pygame.display.set_mode((S_width,S_height))
clock = pygame.time.Clock()
pygame.display.set_caption("H20 Particle simulation")
Window.fill(BG)
space = pymunk.Space()
space.gravity = (0,100)
def create_particle(space):
body = pymunk.Body(1, 100, body_type = pymunk.Body.DYNAMIC)
body.position = (400, 400)
shape = pymunk.Circle(body,80)
space.add(body, shape)
return shape
def draw_circle(circle):
for circle in circles:
pos_x = int(circle.body.position.x)
pos_y = int(circle.body.position.y)
pygame.draw.circle(screen,(0,0,0),circle.body.position20)
circles = []
circles.append(create_particle(space))
while True:
Window.fill((217,217,217))
clock.tick(120)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
</code></pre> | <p>A few changes are needed:</p>
<ul>
<li><code>draw_circle()</code> does not require a parameter</li>
<li>When you draw the circle, you need to specify the coordinates and radius</li>
<li>In the main loop, call <code>draw_circle()</code> and <code>space.step(0.02)</code></li>
</ul>
<p>Here is the updated code:</p>
<pre><code>def draw_circle():
for circle in circles:
pos_x = int(circle.body.position.x)
pos_y = int(circle.body.position.y)
pygame.draw.circle(Window,(0,200,0), (pos_x, pos_y), 20)
circles = []
circles.append(create_particle(space))
while True:
Window.fill((217,217,217))
draw_circle()
space.step(0.02)
clock.tick(120)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
</code></pre> | python|python-3.x|pygame|pymunk | 3 |
94 | 56,534,514 | Add a new column to a dataframe based on an existing column value using pandas | <p>I am working with a dataframe created by importing a .csv file I created. I want to (1) create a new column in the dataframe and (2) use values from an existing column to assign a value to the new column. This is an example of what I'm working with:</p>
<pre><code> date id height gender
dd/mm/yyyy 1A 6 M
dd/mm/yyyy 2A 4 F
dd/mm/yyyy 1B 1 M
dd/mm/yyyy 2B 7 F
</code></pre>
<p>So I want to make a new column "side" and make that side have the value "A" or "B" based on the existing "id" column value:</p>
<pre><code> date id height gender side
dd/mm/yyyy 1A 6 M A
dd/mm/yyyy 2A 4 F A
dd/mm/yyyy 1B 1 M B
dd/mm/yyyy 2B 7 F B
</code></pre>
<p>I have gotten to a point where I have been able to make the new column and assign a new value but when I attempt to use the <code>.groupby</code> method on the "side" column it doesn't work as expected. </p>
<pre><code>df = pd.read_csv("clean.csv")
df = df.drop(["Unnamed: 0"], axis=1)
df["side"] = ""
df.columns = ["date", "id", "height", "gender", "side"]
for i, row in df.iterrows():
if "A" in row["id"]:
df.at[i, row["side"]] = "A"
else:
df.at[i, row["side"]] = "B"
df["side"]
</code></pre>
<p>calling <code>df["side"]</code> results in blank output, but calling <code>df</code> by itself produces this:
<a href="https://i.stack.imgur.com/PTpZ4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PTpZ4.png" alt="df shows a value in the side column"></a></p>
<p>So there is a value in the dataframe, but using the .groupby method treats the values in the side column as not existing. This is a real headscratcher. I'm new to Python and would appreciate if someone could explain to me what I'm doing wrong.</p> | <p>Just use <code>str[]</code>. I could not see the image. If your <code>id</code> has more than 2 chars, you need this to get the last char</p>
<pre><code>df['side'] = df.id.str[-1]
Out[582]:
date id height gender side
0 dd/mm/yyyy 1A 6 M A
1 dd/mm/yyyy 2A 4 F A
2 dd/mm/yyyy 1B 1 M B
3 dd/mm/yyyy 2B 7 F B
</code></pre> | python|pandas|dataframe | 3 |
95 | 56,698,504 | How can I load my homemade 32bit cpp DLL into my canopy 3.5 32bit python? | <p>I am trying to load my DLL (32bit) file containing CPP functions into python. It works on python 3.7 (32bit) but it gives an error when using canopy 3.5 (32bit). </p>
<p>the code I use to load my dll:</p>
<pre class="lang-py prettyprint-override"><code>import os
import ctypes
os.chdir(r"G:\DLLdirectory")
mydll = ctypes.cdll.LoadLibrary('MyDLL.dll')
</code></pre>
<p>If I run it on pyton 3.7 it works, if I run it with canopy 3.5 I get:</p>
<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
File "DIR/PythonFile.py", line 26, in <module>
mydll = ctypes.cdll.LoadLibrary('MyDLL.dll')
File "DIR\Canopy32\edm\envs\User\lib\ctypes\__init__.py", line 425, in LoadLibrary
return self._dlltype(name)
File "DIR\Canopy32\edm\envs\User\lib\ctypes\__init__.py", line 347, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 126] The specified module could not be found
</code></pre>
<p>If you change os.chdir() to sys.path.append() in canopy still the module is not found and in python 3.7 I get this error: </p>
<pre class="lang-py prettyprint-override"><code>Traceback (most recent call last):
File "DIR/PythonFile.py", line 26, in <module>
mydll = ctypes.cdll.LoadLibrary('MyDLL.dll')
File "DIR\Python\Python37-32\lib\ctypes\__init__.py", line 434, in LoadLibrary
return self._dlltype(name)
File "DIR\Python37-32\lib\ctypes\__init__.py", line 356, in __init__
self._handle = _dlopen(self._name, mode)
OSError: [WinError 193] %1 is not a valid Win32 application
</code></pre> | <p>It turned out that the DLL was dependent on another DLL and this DLL was found in python automatically. However, in Canopy the second DLL needed to be loaded separately.</p> | python|dll|canopy | 0 |
96 | 66,127,086 | Django - pass a list of results when querying using filter | <p>In my FollowingPageView function, I'm trying to filter posts based on the logged in user's list of user's he/she is following.</p>
<p>You'll see the Profile model has a "following" field that captures the names of users the Profile owner is following. What I'm trying to do in my view is capture these names of the users in "following" then pass them to Post.objects.filter(created_by=user_list), but I will only get the last user in that list in this case. How can I iterate over the "user_list" Queryset and pass that to Post.objects.filter in order to return the posts from each user in that list? In this case, I should have two users in the Queryset [<User: winter>, <User: daisy>].</p>
<p>models.py</p>
<pre><code>class Profile(models.Model):
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
bio = models.TextField(null=True, blank=True)
website = models.CharField(max_length=225, null=True, blank=True)
follower = models.ManyToManyField(User, blank=True, related_name="followed_user") # user following this profile
following = models.ManyToManyField(User, blank=True, related_name="following_user") # profile user that follows this profile
def __str__(self):
return f"{self.user}'s' profile id is {self.id}"
def following_users(self):
for username in self.following:
return username
def get_absolute_url(self):
return reverse("network:profile-detail", args=[str(self.id)])
class Post(models.Model):
created_by = models.ForeignKey(User, on_delete=models.CASCADE)
subject = models.CharField(max_length=50)
body = models.TextField(max_length=1000)
timestamp = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, blank=True, related_name="posts")
def __str__(self):
return f"{self.created_by} posted {self.body}"
</code></pre>
<p>views.py</p>
<pre><code># Following Users
def FollowingPageView(request, pk):
profile = get_object_or_404(Profile, id=pk)
user_list = []
for user in profile.following.all():
user_list.append(user)
posts = Post.objects.filter(created_by=user_list[0])
print(user_list)
paginator = Paginator(posts, 10)
page_number = request.GET.get("page")
page_obj = paginator.get_page(page_number)
try:
if request.method == "GET":
return render(request, "network/follow-posts.html", { "profile": profile, "page_obj": page_obj })
except ValueError:
return render(request, "network:index.html", {"error": ValueError})
</code></pre> | <p>One approach is to use an <a href="https://docs.djangoproject.com/en/3.1/ref/models/querysets/#in" rel="nofollow noreferrer"><code>__in</code></a> query. Here, because you're not using <code>user_list</code> for anything else, you'll probably get the best results from using an inner query:</p>
<pre><code>posts = Post.objects.filter(created_by__in=profile.following.all())
</code></pre>
<p>But note the performance advice in the linked docs - test it on your actual setup and see.</p>
<p>Possibly with a <code>distinct()</code> call required, I can't remember exactly what triggers the possibility of duplicate records with many-to-many fields.</p>
<p>There are other ways to express it using field references, something like:</p>
<pre><code>posts = Post.objects.filter(created_by__profile__followed_user=profile.user).distinct()
</code></pre>
<p>Backing databases tend to do that with a join rather than a subquery, so it can have different performance characteristics.</p> | python|django|django-models | 1 |
97 | 59,077,093 | Problem with training cifar10 data in Tensorflow-2 | <p>I got the following error in training cifar10 data in tensorflow-2. I used this <a href="https://www.tensorflow.org/tutorials/quickstart/advanced" rel="nofollow noreferrer">tutorial</a>. </p>
<blockquote>
<p>TypeError: Expected float32 passed to parameter 'y' of op 'Equal',
got 'collections' of type 'str' instead. Error: Expected float32, got
'collections' of type 'str' instead.</p>
</blockquote>
<p>My code looks like:</p>
<pre><code> class Mymodel(tf.keras.Model):
def __init__(self, class_size):
"""Initialize parameters and build model.
"""
super(Mymodel, self).__init__()
self.class_size =class_size
self.conv1 = tf.keras.layers.Conv2D(32, kernel_size =3, strides =2, activation='relu')
self.conv2 = tf.keras.layers.Conv2D(64, kernel_size =2, strides =2, activation='relu')
self.conv3 = tf.keras.layers.Conv2D(64, kernel_size =2, strides =1, activation='relu')
self.flat = tf.keras.layers.Flatten()
self.d1 = tf.keras.layers.Dense(512, activation='relu')
self.d2 = tf.keras.layers.Dense(128, activation='relu')
self.fd =tf.keras.layers.Dense(self.class_size, activation='softmax')
def call(self, inputs):
x = self.conv1(inputs)
x = self.conv2(x)
x = self.conv3(x)
x = self.flat(x)
x = self.d1(x)
x = self.d2(x)
return self.fd(x)
model = Mymodel(10)
train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()
train_images, test_images = train_images / 255.0, test_images / 255.0
train_ds = tf.data.Dataset.from_tensor_slices(
(train_images, train_labels)).shuffle(1000).batch(32)
test_ds = tf.data.Dataset.from_tensor_slices((test_images, test_labels)).batch(32)
# define the training and testing objects
loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam()
@tf.function
def train_step(images, labels):
with tf.GradientTape() as tape:
predictions = model(images)
loss = loss_object(labels, predictions)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
loss(loss)
accuracy(labels, predictions)
tf.function
def test_step(images, labels):
predictions = model(images)
t_loss = loss_object(labels, predictions)
loss(t_loss)
accuracy(labels, predictions)
def train():
EPOCHS = 5
for epoch in range(EPOCHS):
for images, labels in train_ds:
train_step(images, labels)
for test_images, test_labels in test_ds:
test_step(test_images, test_labels)
template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'
print(template.format(epoch+1,
train_loss.result(),
train_accuracy.result()*100,
test_loss.result(),
test_accuracy.result()*100))
# Reset the metrics for the next epoch
train_loss.reset_states()
train_accuracy.reset_states()
test_loss.reset_states()
test_accuracy.reset_states()
train()
</code></pre>
<p>It works when I replaced the compile and fit functions. </p>
<pre><code>model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, batch_size= 200, epochs=6, validation_data=(test_images, test_labels))
</code></pre>
<p>Highly appropriated for any help. </p> | <p>set from_logits=True in the loss function.</p>
<p>loss_object = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)</p>
<p>It solves the error!</p> | python|tensorflow|keras | 1 |
98 | 63,141,248 | Problem in creating delete button in django | <p>I am trying to build delete button and currently stuck. I am new to django and need help. Thank You</p>
<pre><code>This is my models.py:-
from django.db import models
from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse
# Create your models here.
class simpleList(models.Model):
title = models.CharField(max_length=250)
def __str__(self):
return self.title
</code></pre>
<p>This is my views.py:-</p>
<pre><code>from django.shortcuts import render, get_object_or_404
from .models import simpleList
from django.views.generic import ListView, DeleteView
from django.urls import reverse_lazy
from django.contrib.messages.views import SuccessMessageMixin
# Create your views here.
class ListListView(ListView):
model = simpleList
template_name = 'list_list.html'
class DeleteList(SuccessMessageMixin, DeleteView):
model = simpleList
success_url = '/'
success_message = "deleted..."
def delete(self, request, *args, **kwargs):
self.object = self.get_object()
name = self.object.title
# name will be change according to your need
request.session['title'] = title
message = request.session['title'] + ' deleted successfully'
messages.success(self.request, message)
return super(DeleteView, self).delete(request, *args, **kwargs)
</code></pre>
<p>This is my urls.py:-</p>
<pre><code>from django.urls import path
from .views import ListListView, DeleteList
from django.conf.urls import url
from . import views
urlpatterns = [
path('', ListListView.as_view(), name='list_list'),
path('<int:pk>/', DeleteList.as_view(), name='delete_view'),
]
</code></pre>
<p>This is my home.html:-</p>
<pre><code>{% extends 'base.html' %}
{% block title %}Home{% endblock title %}
{% block content %}
<div>
{% if user.is_authenticated %}
<button type="button" class="btn btn-info"><a style="color: white;" href="{% url 'list_list' %}">Continue to
slist</a></button>
{% endif %}
</div>
{% endblock content %}
</code></pre>
<p>and this is my list_list.html which is currently not complete:-</p>
<pre><code>{% extends 'base.html' %}
{% block title %}sList{% endblock title %}
{% block content %}
<h2>simpleList</h2>
{% for simpleList in object_list %}
<div>
<h3>{{ simpleList.title }}</h3>
<div>
<form action="{% url 'delete_view' pk=part.pk %}">{% csrf_token %}
X<input class="btn btn-default btn-danger" type="submit" value="Delete" />
</form>
</div>
</div>
{% endfor %}
{% endblock content %}
</code></pre>
<p>The error i am getting from django is this:-</p>
<p>NoReverseMatch at /list/
Reverse for 'delete_view' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['list/(?P[0-9]+)/$']</p>
<pre><code>10 <body>
11 <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
12 <a class="navbar-brand" href="{% url 'home' %}">simpleList</a>
13 <div class="collapse navbar-collapse" id="navbarColor01"></div>
14 {% if user.is_authenticated %}
15 <button type="button" class="btn btn-secondary">Hi, {{ user.username }}</button>
16 <button type="button" class="btn btn-info"><a style="color:white;" href="{% url 'logout' %}">Logout</a></button>
</code></pre> | <p>You need to make a POST request to delete the object. Furthermore the name of the object is <code>simpleList</code>, not <code>part</code>, so the form should be rewritten to:</p>
<pre><code><form <b>method="post"</b> action="{% url 'delete_view' pk=<b>simpleList.pk</b> %}">
{% csrf_token %}
<input class="btn btn-default btn-danger" type="submit" value="Delete" />
</form></code></pre>
<p>While it is not a problem to use <code><int:pk>/</code> as the path pattern. It might be better to use <code><int:pk>/delete</code>, for example, since <code><int:pk>/</code> is often used to show the <em>details</em> of the object with that primary key:</p>
<pre><code>urlpatterns = [
path('', ListListView.as_view(), name='list_list'),
path('<int:pk>/<b>delete/</b>', DeleteList.as_view(), name='delete_view'),
]</code></pre> | python|django | 2 |
99 | 59,011,724 | Counter inside for loop adding duplicates in output, remove duplicate entries in output in Python | <p>I want to remove duplicate entries from my function output. </p>
<p>I have a function which searches for relationships inside each paragraph of a text file. A sample of the
metadata.csv file which searches for relationship in paragraphs is as follows:</p>
<pre><code>Blister Base Web PVC/PVDC
Blister Foil Aluminium
Blister Base Web PVC/PVDC
Blister Foil Aluminium
Vial Glass Borosilicate Glass
Vial Stopper Bromobutyl Rubber
Vial Cap Aluminium
</code></pre>
<p>The sample text file is as follows:</p>
<pre><code>The tablets are filled into cylindrically shaped bottles made of white coloured
polyethylene. The volumes of the bottles depend on the tablet strength and amount of
tablets, ranging from 20 to 175 ml. The screw type cap is made of white coloured
polypropylene and is equipped with a tamper proof ring.
PVC/PVDC blister pack
Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tablet
is filled into a separate blister and a lidding foil of aluminium is welded on. The blisters
are opened by pressing the tablets through the lidding foil. PVDC foil is in contact with
the tablets.
Aluminium blister pack
Blisters are made in a cold-forming process from an aluminium base web. Each tablet is
filled into a separate blister and a lidding foil of aluminium is welded on. The blisters
are opened by pressing the tablets through the lidding foil.
</code></pre>
<p>So there will be 3 groups for this text file.</p>
<p>The function is as follows:</p>
<pre><code>import csv
import re
import os
def extractor(filepath):
#pdb.set_trace()
TEXT_WITHOUT_COLOUR = 'Stage {counter} : Package Description: {sen} Values: {values}'
TEXT_WITH_COLOUR = TEXT_WITHOUT_COLOUR + ',' ' Colour: {colour}'
colours = ['White', 'Yellow', 'Blue', 'Red', 'Green', 'Black', 'Brown', 'Silver', 'Purple', 'Navy blue', 'Gray', 'Orange', 'Maroon', 'pink', 'colourless', 'blue']
counter = 1
result = []
unique_desc = [] #every unique description is stored
output = []
with open(filepath, encoding='utf-8') as f:
data=f.read()
paragraphs=data.split("\n\n")
inputfile = r"C:\metadata.csv"
inputm = []
with open(inputfile, "r") as f:
reader = csv.reader(f, delimiter="\t")
for row in reader:
#types = row.split(',')
inputm.append(row)
final_ref = []
for lists in inputm:
final_ref.append(str(lists[0]).split(','))
def is_missing(words, sen):
for w in words:
if w.lower() not in sen.lower():
return True
return False
for sen in paragraphs:
for words in final_ref:
if is_missing(words, sen):
continue
kwargs = {
'counter': counter,
'sen': sen,
'values': str(words)
}
if (words[0] == 'Bottle') or (words[0]=='Vial') or (words[0] =='Container') or (words[0] =='Ampoules') or (words[0] =='Occlusive Dressing'):
for wd in colours:
if wd.lower() in sen.lower():
kwargs['colour'] = wd
break
text_const = TEXT_WITH_COLOUR
else:
text_const = TEXT_WITHOUT_COLOUR
result.append(text_const.format(**kwargs).replace('\n', '').replace('\t', ''))
for desc in result:
compare = re.search(r'Package Description:(.*?)Values:',desc).group(1).replace(' ','') #clean spaces
if compare in unique_desc:
group = str(unique_desc.index(compare)+1) #index starts in 0 and group in 1
desc = re.sub('Stage \d','Group '+group, desc)
output.append(desc)
else:
unique_desc.append(compare)
group = str(len(unique_desc)) #new group
desc = re.sub('Stage \d','Group '+group, desc)
output.append(desc)
counter+=1
break
return output
</code></pre>
<p>which returns as output </p>
<pre><code>["Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cylindrically shaped Bottles', 'Polyethylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cylindrically shaped Bottles', 'Polyethylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Screw Type Cap', 'Polypropylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cylindrically shaped Bottles', 'Polyethylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Screw Type Cap', 'Polypropylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Tamper Proof Ring', ''], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cylindrically shaped Bottles', 'Polyethylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Screw Type Cap', 'Polypropylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Tamper Proof Ring', ''], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cap', 'Polypropylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cylindrically shaped Bottles', 'Polyethylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Screw Type Cap', 'Polypropylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Tamper Proof Ring', ''], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cap', 'Polypropylene'], Colour: White",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Foil', 'Aluminium']",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cylindrically shaped Bottles', 'Polyethylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Screw Type Cap', 'Polypropylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Tamper Proof Ring', ''], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cap', 'Polypropylene'], Colour: White",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Foil', 'Aluminium']",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Base Web', 'PVC/PVDC']",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cylindrically shaped Bottles', 'Polyethylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Screw Type Cap', 'Polypropylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Tamper Proof Ring', ''], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cap', 'Polypropylene'], Colour: White",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Foil', 'Aluminium']",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Base Web', 'PVC/PVDC']",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Base Web', 'PVC']",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cylindrically shaped Bottles', 'Polyethylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Screw Type Cap', 'Polypropylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Tamper Proof Ring', ''], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cap', 'Polypropylene'], Colour: White",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Foil', 'Aluminium']",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Base Web', 'PVC/PVDC']",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Base Web', 'PVC']",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Base Web', 'PVDC']",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cylindrically shaped Bottles', 'Polyethylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Screw Type Cap', 'Polypropylene'], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Tamper Proof Ring', ''], Colour: White",
"Group 1 : Package Description: The tablets are filled into cylindrically shaped bottles made of white colouredpolyethylene. The volumes of the bottles depend on the tablet strength and amount oftablets, ranging from 20 to 175 ml. The screw type cap is made of white colouredpolypropylene and is equipped with a tamper proof ring. Values: ['Bottle', 'Cap', 'Polypropylene'], Colour: White",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Foil', 'Aluminium']",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Base Web', 'PVC/PVDC']",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Base Web', 'PVC']",
"Group 2 : Package Description: Blisters are made in a thermo-forming process from a PVC/PVDC base web. Each tabletis filled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. PVDC foil is in contact withthe tablets. Values: ['Blister', 'Base Web', 'PVDC']",
"Group 3 : Package Description: Blisters are made in a cold-forming process from an aluminium base web. Each tablet isfilled into a separate blister and a lidding foil of aluminium is welded on. The blistersare opened by pressing the tablets through the lidding foil. Values: ['Blister', 'Foil', 'Aluminium']"]
</code></pre>
<p>The ones with the exact same entries of 'Package Description and Values' should be ignored from the output. I think there is an issue with my break statement and the counter variable. Any help regarding this.</p> | <p>If you prefer, you can achieve this with the help of <code>set</code>. But please note that <strong>order is not preserved</strong> though you can achieve uniqueness.</p>
<pre><code>lst = ['foo', 'bar', 'foo', 'bar']
s = set(lst)
print(s) # this will print foo and bar
</code></pre> | python|python-3.x|loops|for-loop|count | 1 |