title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
How to get all the tags in an XML using python?
38,790,012
<p>I have been researching in the Python Docs for a way to get the tag names from an XML file, but I haven't been very successful. Using the XML file below, one can get the country name tags, and all its associated child tags. Does anyone know how this is done?</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;data&gt; &lt;country name="Liechtenstein"&gt; &lt;rank&gt;1&lt;/rank&gt; &lt;year&gt;2008&lt;/year&gt; &lt;gdppc&gt;141100&lt;/gdppc&gt; &lt;neighbor name="Austria" direction="E"/&gt; &lt;neighbor name="Switzerland" direction="W"/&gt; &lt;/country&gt; &lt;country name="Singapore"&gt; &lt;rank&gt;4&lt;/rank&gt; &lt;year&gt;2011&lt;/year&gt; &lt;gdppc&gt;59900&lt;/gdppc&gt; &lt;neighbor name="Malaysia" direction="N"/&gt; &lt;/country&gt; &lt;country name="Panama"&gt; &lt;rank&gt;68&lt;/rank&gt; &lt;year&gt;2011&lt;/year&gt; &lt;gdppc&gt;13600&lt;/gdppc&gt; &lt;neighbor name="Costa Rica" direction="W"/&gt; &lt;neighbor name="Colombia" direction="E"/&gt; &lt;/country&gt; &lt;/data&gt; </code></pre>
0
2016-08-05T13:05:27Z
38,792,638
<p>Consider using element tree's <code>iterparse()</code> and build nested lists of tag and text pairs. Conditional <code>if</code> logic is used to group country items together and leave out elements with no text, then <code>replace()</code> is used to clean out the line breaks and multiple white spaces that <code>iterparse()</code> picks up:</p> <pre><code>import xml.etree.ElementTree as et data = [] for (ev, el) in et.iterparse(path): inner = [] if el.tag == 'country': for name, value in el.items(): inner.append([el.tag+'-'+name, str(value).replace('\n','').replace(' ','')]) for i in el: if str(i.text) != 'None': inner.append([i.tag, str(i.text).replace('\n','').replace(' ','')]) for name, value in i.items(): inner.append([i.tag+'-'+name, str(value).replace('\n','').replace(' ','')]) data.append(inner) print(data) # [[['country-name', 'Liechtenstein'], ['rank', '1'], ['year', '2008'], ['gdppc', '141100'], # ['neighbor-name', 'Austria'], ['neighbor-direction', 'E'], # ['neighbor-name', 'Switzerland'], ['neighbor-direction', 'W']] # [['country-name', 'Singapore'], ['rank', '4'], ['year', '2011'], ['gdppc', '59900'], # ['neighbor-name', 'Malaysia'], ['neighbor-direction', 'N']] # [['country-name', 'Panama'], ['rank', '68'], ['year', '2011'], ['gdppc', '13600'], # ['neighbor-name', 'CostaRica'], ['neighbor-direction', 'W'], # ['neighbor-name', 'Colombia'], ['neighbor-direction', 'E']]] </code></pre>
1
2016-08-05T15:15:21Z
[ "python", "xml", "python-3.x" ]
jedi fails to correctly autocomplete from package with the same name as the module that I'm in
38,790,067
<p>I'm using emacs and I have configured jedi.el so it autocompletes after dot. Let's assume that I'm writing a module <code>my_app.my_module</code> and I have package installed in env called <code>my_module</code>. My file <code>my_app/my_module.py</code> will look like:</p> <pre><code>import my_module class SomeClass: pass (...) my_module.&lt;here_i_expect_autocompletion_from_my_module_package&gt; </code></pre> <p>Now the thing is that jedi.el tries to autocomplete from <code>my_app.my_module</code>(giving me <code>SomeClass</code>etc.) not from <code>my_module</code> package installed in env. What should I do to get expected autocompletion?</p> <p><strong>Edit</strong>: Looks like this is an <code>jedi</code> issue not <code>jedi.el</code>, because i can reproduce issue using only <code>jedi</code>.</p>
1
2016-08-05T13:07:41Z
38,911,520
<p>It turned out that this is a problem of <code>jedi</code>, not of <code>jedi.el</code>. Furthermore it seems that this behavior is specific for projects based on <code>pyramid</code> framework.</p>
0
2016-08-12T06:42:33Z
[ "python", "emacs", "autocomplete", "jedi", "emacs-jedi" ]
An Error: 'Numpy.str_' object has no attribute 'decode'
38,790,126
<p>I tried to run a test on Crab(an open source recommender system) based on python3. Then an error occurred:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/Dennis/anaconda/lib/python3.5/site-packages/scikits/crab/datasets/base.py", line 201, in load_sample_movies data_songs[u_ix][i_ix] = float(rating) ValueError: could not convert string to float: "b'3.0'" </code></pre> <p>I tried to use 'decode()' to convert the string, but it's not working:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/Users/Dennis/anaconda/lib/python3.5/site-packages/scikits/crab/datasets/base.py", line 202, in load_sample_movies rating = rating.decode('utf-8') AttributeError: 'numpy.str_' object has no attribute 'decode' </code></pre> <p>Any help will be appreciated!</p>
0
2016-08-05T13:10:11Z
38,790,266
<p>The problem is that <code>rating</code> is a string within a string, so when you try casting a string like <code>"b'3.0'"</code> into a float, it gives a <code>valueError</code> because you still have the <code>b</code> in front which cannot be converted into float.</p> <p>I imagine you need the byte encoding in front of the <code>'3.0'</code>, so one way would be to evaluate <code>rating</code> to convert it from a string to bytes before typecasting it into a float (beware though, <a href="https://docs.python.org/3/library/functions.html#eval" rel="nofollow"><code>eval</code></a> can have some safety issues).</p> <pre><code>&gt;&gt;&gt; type(eval(rating)) &lt;class 'bytes'&gt; &gt;&gt;&gt; data_songs[u_ix][i_ix] = float(eval(rating)) </code></pre>
0
2016-08-05T13:16:34Z
[ "python", "python-3.x", "numpy", "attributes" ]
Django 1.10 python 3.5 django-admin-tools
38,790,152
<p>I am using Django 1.10 and installed django-admin-tools. Settings look like this:</p> <pre><code>INSTALLED_APPS = [ 'admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admindocs', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'cvix3.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'admin_tools.template_loaders.Loader', ] }, }, ] </code></pre> <p>Next I am trying to run </p> <pre><code>python3 ./manage.py migrate But this gives me an error. python3 ./manage.py migrate Traceback (most recent call last): File "./manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 353, in execute self.check() File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 310, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 303, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 665, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "/home/dick/PycharmProjects/cvix3/cvix3/urls.py", line 20, in &lt;module&gt; url(r'^admin_tools/', include('admin_tools.urls')) File "/usr/local/lib/python3.5/dist-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 665, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "/usr/local/lib/python3.5/dist-packages/admin_tools/urls.py", line 2, in &lt;module&gt; from django.conf.urls import patterns, url, include ImportError: cannot import name 'patterns' </code></pre> <p>It looks like an incompatibility between Django 1.9 and 1.10 but I am not sure. Anybody an idea?</p> <p>Cheers...</p>
0
2016-08-05T13:11:21Z
38,790,255
<p>It looks like you are running Django 1.10, not 1.9 as you originally said. In Django 1.10, <code>patterns</code> has been removed (<a href="https://docs.djangoproject.com/en/1.10/releases/1.10/#removed-features-1-10" rel="nofollow">release notes</a>).</p> <p>The issue <a href="https://github.com/django-admin-tools/django-admin-tools/commit/2bf278d6acc0b87b794ed36173ba46e9566b7ae4" rel="nofollow">has been fixed</a> in <code>django-admin-tools</code>, but it looks like there hasn't been a release yet. It should work fine with Django 1.9 for now.</p>
0
2016-08-05T13:15:42Z
[ "python", "django", "django-admin", "django-admin-tools", "django-1.10" ]
Django 1.10 python 3.5 django-admin-tools
38,790,152
<p>I am using Django 1.10 and installed django-admin-tools. Settings look like this:</p> <pre><code>INSTALLED_APPS = [ 'admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admindocs', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'cvix3.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] , 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'admin_tools.template_loaders.Loader', ] }, }, ] </code></pre> <p>Next I am trying to run </p> <pre><code>python3 ./manage.py migrate But this gives me an error. python3 ./manage.py migrate Traceback (most recent call last): File "./manage.py", line 10, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.5/dist-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 353, in execute self.check() File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 385, in check include_deployment_checks=include_deployment_checks, File "/usr/local/lib/python3.5/dist-packages/django/core/management/commands/migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "/usr/local/lib/python3.5/dist-packages/django/core/management/base.py", line 372, in _run_checks return checks.run_checks(**kwargs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/usr/local/lib/python3.5/dist-packages/django/core/checks/urls.py", line 24, in check_resolver for pattern in resolver.url_patterns: File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 310, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.5/dist-packages/django/urls/resolvers.py", line 303, in urlconf_module return import_module(self.urlconf_name) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 665, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "/home/dick/PycharmProjects/cvix3/cvix3/urls.py", line 20, in &lt;module&gt; url(r'^admin_tools/', include('admin_tools.urls')) File "/usr/local/lib/python3.5/dist-packages/django/conf/urls/__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 665, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "/usr/local/lib/python3.5/dist-packages/admin_tools/urls.py", line 2, in &lt;module&gt; from django.conf.urls import patterns, url, include ImportError: cannot import name 'patterns' </code></pre> <p>It looks like an incompatibility between Django 1.9 and 1.10 but I am not sure. Anybody an idea?</p> <p>Cheers...</p>
0
2016-08-05T13:11:21Z
38,791,282
<p>It was indeed 1.10 </p> <p>After downloading from github install migrate ran perfectly.</p> <p>However.....</p> <p>When I try to get the dashboard I get a 404 </p> <pre><code>http://127.0.0.1:8000/dashboard/ Using the URLconf defined in cvixweb.urls, Django tried these URL patterns, in this order: 1. ^admin_tools/ ^menu/ 2. ^admin_tools/ ^dashboard/ ^set_preferences/(?P&lt;dashboard_id&gt;.+)/$ [name='admin-tools-dashboard-set-preferences'] </code></pre>
0
2016-08-05T14:07:53Z
[ "python", "django", "django-admin", "django-admin-tools", "django-1.10" ]
Socio login in Django
38,790,339
<p>I am trying to build social login in Django, but it is not working fine.</p> <p>How am doing:</p> <ol> <li>Installed python-social-auth</li> <li><p>added this in INSTALLED_APPS:</p> <pre><code>'social.apps.django_app.default', </code></pre></li> <li><p>Migrated DB (with no errors)</p></li> <li><p>Added this in urls.py:</p> <pre><code>url('social-auth/',include('social.apps.django_app.urls', namespace='social')), </code></pre></li> <li><p>Got Facebook keys and added this to AUTHENTICATION_BACKENDS and keys in settings.py:</p> <pre><code>'social.backends.facebook.Facebook2OAuth2', </code></pre></li> <li><p>Added this to template:</p> <pre><code>&lt;div class="social"&gt; &lt;ul&gt; &lt;li class="facebook"&gt;&lt;a href="{% url "social:begin" "facebook"%}"&gt;Sign in with Facebook&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre></li> </ol> <p>But now when I click on Log in with Facebook, there's an error in template rendering : 'social' is not a registered namespace. I guess this is because social is not present in urls.py.</p> <p>But adding that dint work.</p> <p>What more should I do? thanks</p>
0
2016-08-05T13:20:07Z
38,790,705
<p>In point six replace</p> <pre><code>href="{% url "social:begin" "facebook"%}" </code></pre> <p>with</p> <pre><code>href="{% url 'social:begin' 'facebook'%}" </code></pre> <p>I think you are running into a problem when the first <code>"</code> in <code>"social:begin"</code> ends the <code>"</code> after <code>href=</code>, since <code>'</code> and <code>"</code> are replaceable you can do this.</p>
1
2016-08-05T13:37:34Z
[ "python", "django", "facebook", "python-social-auth" ]
generate a heatmap from a dataframe with python and seaborn
38,790,360
<p>I'm new to Python and fairly new to seaborn.</p> <p>I have a pandas dataframe named df which looks like:</p> <pre><code>TIMESTAMP ACT_TIME_AERATEUR_1_F1 ACT_TIME_AERATEUR_1_F2 ACT_TIME_AERATEUR_1_F3 ACT_TIME_AERATEUR_1_F4 ACT_TIME_AERATEUR_1_F5 ACT_TIME_AERATEUR_1_F6 2015-08-01 23:00:00 80 0 0 0 10 0 2015-08-01 23:20:00 60 0 20 0 10 10 2015-08-01 23:40:00 80 10 0 0 10 10 2015-08-01 00:00:00 60 10 20 40 10 10 df.info() &lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 38840 entries, 0 to 38839 Data columns (total 7 columns): TIMESTAMP 38840 non-null datetime64[ns] ACT_TIME_AERATEUR_1_F1 38696 non-null float64 ACT_TIME_AERATEUR_1_F3 38697 non-null float64 ACT_TIME_AERATEUR_1_F5 38695 non-null float64 ACT_TIME_AERATEUR_1_F6 38695 non-null float64 ACT_TIME_AERATEUR_1_F7 38693 non-null float64 ACT_TIME_AERATEUR_1_F8 38696 non-null float64 dtypes: datetime64[ns](1), float64(6) memory usage: 2.1 MB </code></pre> <p>I try to do a heatmap using this code :</p> <pre><code>data = sns.load_dataset("df") # Draw a heatmap with the numeric values in each cell sns.heatmap(data, annot=True, fmt="d", linewidths=.5) </code></pre> <p>But it does not work Can you help me pelase to find the error?</p> <p>Thanks</p> <p><strong>Edit</strong> First , I load dataframe from csv file : </p> <pre><code>df1 = pd.read_csv('C:/Users/Demonstrator/Downloads/Listeequipement.csv',delimiter=';', parse_dates=[0], infer_datetime_format = True) </code></pre> <p>Then, I select only rows which date '2015-08-01 23:10:00' and '2015-08-02 00:00:00'</p> <pre><code> import seaborn as sns df1['TIMESTAMP']= pd.to_datetime(df1_no_missing['TIMESTAMP'], '%d-%m-%y %H:%M:%S') df1['date'] = df_no_missing['TIMESTAMP'].dt.date df1['time'] = df_no_missing['TIMESTAMP'].dt.time date_debut = pd.to_datetime('2015-08-01 23:10:00') date_fin = pd.to_datetime('2015-08-02 00:00:00') df1 = df1[(df1['TIMESTAMP'] &gt;= date_debut) &amp; (df1['TIMESTAMP'] &lt; date_fin)] Then, construct the heatmap : sns.heatmap(df1.iloc[:,2:],annot=True, fmt="d", linewidths=.5) </code></pre> <p>I get this error : </p> <blockquote> <pre><code>TypeError Traceback (most recent call last) &lt;ipython-input-363-a054889ebec3&gt; in &lt;module&gt;() 7 df1 = df1[(df1['TIMESTAMP'] &gt;= date_debut) &amp; (df1['TIMESTAMP'] &lt; date_fin)] 8 ----&gt; 9 sns.heatmap(df1.iloc[:,2:],annot=True, fmt="d", linewidths=.5) C:\Users\Demonstrator\Anaconda3\lib\site-packages\seaborn\matrix.py in </code></pre> <p>heatmap(data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, linewidths, linecolor, cbar, cbar_kws, cbar_ax, square, ax, xticklabels, yticklabels, mask, **kwargs) 483 plotter = _HeatMapper(data, vmin, vmax, cmap, center, robust, annot, fmt, 484 annot_kws, cbar, cbar_kws, xticklabels, --> 485 yticklabels, mask) 486 487 # Add the pcolormesh kwargs here</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\seaborn\matrix.py in </code></pre> <p><strong>init</strong>(self, data, vmin, vmax, cmap, center, robust, annot, fmt, annot_kws, cbar, cbar_kws, xticklabels, yticklabels, mask) 165 # Determine good default values for the colormapping 166 self._determine_cmap_params(plot_data, vmin, vmax, --> 167 cmap, center, robust) 168 169 # Sort out the annotations</p> <pre><code>C:\Users\Demonstrator\Anaconda3\lib\site-packages\seaborn\matrix.py in </code></pre> <p>_determine_cmap_params(self, plot_data, vmin, vmax, cmap, center, robust) 202 cmap, center, robust): 203 """Use some heuristics to set good defaults for colorbar and range.""" --> 204 calc_data = plot_data.data[~np.isnan(plot_data.data)] 205 if vmin is None: 206 vmin = np.percentile(calc_data, 2) if robust else calc_data.min()</p> <pre><code>TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types </code></pre> <p>according to the casting rule ''safe''</p> </blockquote>
0
2016-08-05T13:20:45Z
38,790,687
<p>Remove the timestamp variables(i.e. first two columns) before passing it to sns.heatmap, no need for the load dataset as well, just use:</p> <pre><code>sns.heatmap(df.iloc[:,2:],annot=True, fmt="d", linewidths=.5) </code></pre> <h1>EDIT</h1> <p>Ok here is your dataframe, just changed the column names in the interest of time</p> <pre><code>df Out[9]: v1 v2 v3 v4 v5 v6 v7 v8 0 2015-08-01 23:00:00 80 0 0 0 10 0 1 2015-08-01 23:20:00 60 0 20 0 10 10 2 2015-08-01 23:40:00 80 10 0 0 10 10 3 2015-08-01 00:00:00 60 10 20 40 10 10 </code></pre> <p>Now seaborn cannot recognize timestamp variables for the heatmap right, so we will remove the first two columns and pass the dataframe to seaborn</p> <pre><code>import seaborn as sns sns.heatmap(df.iloc[:,2:],annot=True, fmt="d", linewidths=.5) </code></pre> <p>So we get the result as</p> <p><a href="http://i.stack.imgur.com/9BzZK.png" rel="nofollow"><img src="http://i.stack.imgur.com/9BzZK.png" alt="Output from seaborn"></a></p> <p>If you don't get the result by using this, please edit your question to include rest of your code. This is not the problem then.</p>
0
2016-08-05T13:36:26Z
[ "python", "heatmap", "seaborn" ]
Pandas: parse columns from csv
38,790,368
<p>I have data in csv file without header. I need to parse some columns.</p> <p>A part of data:</p> <pre><code>-1.0,-0.0246259814315,1174.60023796 1.0,-0.978057706084,1083.19880269 -1.0,0.314271994507,-1472.97760911 -1.0,0.179751565771,231.017267343 1.0,-1.26254374278,-778.271726463 -1.0,0.249969939456,-52.8014826538 1.0,-1.87039747875,-324.235348241 </code></pre> <p>I need to load only second and third columns. I use <code>train_X = pd.read_csv("perceptron-train.csv", sep=',', parse_dates=[1], usecols=[2, 3])</code> but it returns <code>IndexError: list index out of range</code></p>
0
2016-08-05T13:21:07Z
38,792,280
<p>IIUC indices are zero-based so you need:</p> <pre><code>train_X = pd.read_csv("perceptron-train.csv", sep=',', parse_dates=[1], usecols=[1, 2]) </code></pre> <p>Also I don't know if this also means you need to change your date col:</p> <pre><code>train_X = pd.read_csv("perceptron-train.csv", sep=',', parse_dates=[0], usecols=[1, 2]) </code></pre> <p>However, looking at your data I don't understand how to interpret the first or second column as a datetime as they look weird</p>
1
2016-08-05T14:57:38Z
[ "python", "pandas" ]
Python/Pyserial: reading incoming information from port
38,790,422
<p>I've just started using pyserial as I will eventually need to read/save information coming from a particular port. Using the following code I am merely printing the port used and then trying to write and then read in some text ("hello"). The port is printing fine, but the output of my string is coming out as 5. Any idea why this is?</p> <pre><code>import serial import sys from time import sleep try: ser = serial.Serial('\\.\COM8', 9600,timeout=None, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) except: sys.exit("Error connecting device") print ser.portstr x = ser.write("hello") print x ser.close() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; \.\COM8 5 &gt;&gt;&gt; </code></pre> <p>Also, is there a simple way for me to mimic a stream of text information coming through the port so that I can test reading in/saving the incoming info?</p> <p>I am using Python 2.7, and 'virtual serial port driver 8.0' [Eltima VSPD] to emulate a port for testing this stuff.</p> <p>Thanks, Steve</p>
1
2016-08-05T13:23:55Z
38,790,810
<pre><code>x = ser.write("hello") print x </code></pre> <p>You writing this as sended. It's not recieved info. Probably it writes the lenght of string you have sended. First you need to have a client side script which will response your sended information.</p> <p>And you have to use something like this on it.</p> <pre><code>... x = ser.read() # read one byte ... s = ser.read(10) # read up to ten bytes (timeout) ... line = ser.readline() # read a '\n' terminated line </code></pre>
0
2016-08-05T13:44:02Z
[ "python", "pyserial", "virtual-serial-port" ]
Python/Pyserial: reading incoming information from port
38,790,422
<p>I've just started using pyserial as I will eventually need to read/save information coming from a particular port. Using the following code I am merely printing the port used and then trying to write and then read in some text ("hello"). The port is printing fine, but the output of my string is coming out as 5. Any idea why this is?</p> <pre><code>import serial import sys from time import sleep try: ser = serial.Serial('\\.\COM8', 9600,timeout=None, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) except: sys.exit("Error connecting device") print ser.portstr x = ser.write("hello") print x ser.close() </code></pre> <p>Output:</p> <pre><code>&gt;&gt;&gt; \.\COM8 5 &gt;&gt;&gt; </code></pre> <p>Also, is there a simple way for me to mimic a stream of text information coming through the port so that I can test reading in/saving the incoming info?</p> <p>I am using Python 2.7, and 'virtual serial port driver 8.0' [Eltima VSPD] to emulate a port for testing this stuff.</p> <p>Thanks, Steve</p>
1
2016-08-05T13:23:55Z
38,792,398
<p>you can do it this way to test it. Firstly create a pair of ports in manage ports</p> <p>First port: COM199 Second Port: COM188</p> <p>Click Add Pair</p> <p><strong>On one console/script do the below steps:</strong></p> <pre><code>&gt;&gt;&gt; import serial &gt;&gt;&gt; ser = serial.Serial('COM196', 9600,timeout=None, parity=serial.PARITY_NONE, stopbits=serial.S BITS_ONE, bytesize=serial.EIGHTBITS) &gt;&gt;&gt; print ser.portstr COM196 &gt;&gt;&gt; x = ser.read(5) # It will be waiting till it receives data &gt;&gt;&gt; print x hello </code></pre> <p><strong>On the other console, perform below steps:</strong></p> <pre><code>&gt;&gt;&gt; import serial &gt;&gt;&gt; s = serial.Serial('COM188') &gt;&gt;&gt; s.write("hello") 5L </code></pre> <p>you can test it this way (or) by creating python programs for each of the ports</p>
1
2016-08-05T15:03:24Z
[ "python", "pyserial", "virtual-serial-port" ]
Python: How to plot heat map of 2D matrix by ignoring zeros?
38,790,536
<p>I have a matrix of size 500 X 28000, which contains a lot of zeros in between. But let us consider a working example with the matrix A: </p> <pre><code>A = [[0, 0, 0, 1, 0], [1, 0, 0, 2, 3], [5, 3, 0, 0, 0], [5, 0, 1, 0, 3], [6, 0, 0, 9, 0]] </code></pre> <p>I would like to plot a heatmap of the above matrix, but since it contains a lot of zeros, the heatmap contains almost white space as seen in the figure below. </p> <p><strong>How can I ignore the zeros in the matrix and plot the heatmap?</strong></p> <p>Here is the minimal working example that I tried:</p> <pre><code>im = plt.matshow(A, cmap=pl.cm.hot, norm=LogNorm(vmin=0.01, vmax=64), aspect='auto') # pl is pylab imported a pl plt.colorbar(im) plt.show() </code></pre> <p>which produces:</p> <p><a href="http://i.stack.imgur.com/kXmv6.png" rel="nofollow"><img src="http://i.stack.imgur.com/kXmv6.png" alt="enter image description here"></a></p> <p>as you can see it is because of the zeros the white spaces appear. </p> <p>But my original matrix of size 500X280000 contains a lot of zeros, which makes my colormap almost white!! </p>
1
2016-08-05T13:29:24Z
38,790,834
<p>If you remove the LogNorm, you get black squares instead of white:</p> <pre><code>im = plt.matshow(A, cmap=plt.cm.hot, aspect='auto') # pl is pylab imported a pl </code></pre> <p><a href="http://i.stack.imgur.com/05OBj.png" rel="nofollow"><img src="http://i.stack.imgur.com/05OBj.png" alt="enter image description here"></a></p> <hr> <p><strong>Edit</strong></p> <p>In a colormap you <em>always</em> have the complete grid filled with values. That's why you actually create the grid: You account for (say: interpolate) all the points that are not exactly in the grid. That means that your data <strong>has</strong> many zeroes and that the graph correctly reflects that by looking white (or black). By ignoring those values, you create a misleading graph, if you don't have a clear reason to do so. </p> <p>If the values different than zero are the ones of interest to you, then you need another type of diagram, like pointed out by <a href="http://stackoverflow.com/questions/38790536/python-how-to-plot-heat-map-of-2d-matrix-by-ignoring-zeros/38790834?noredirect=1#comment64952253_38790536">norio's comment</a>. For that, you may want to have a look at <a href="http://stackoverflow.com/a/30765484/776515">this answer</a>.</p> <hr> <p><strong>Edit 2</strong></p> <blockquote> <p>Adapted from <a href="http://stackoverflow.com/a/30765484/776515">this answer</a></p> </blockquote> <p>You can treat the values as 1D arrays and plot the points independently, instead of filling a mesh with non-desired values.</p> <pre><code>A = [[0, 0, 0, 1, 0], [1, 0, 0, 2, 3], [5, 3, 0, 0, 0], [5, 0, 1, 0, 3], [6, 0, 0, 9, 0]] A = np.array(A) lenx, leny = A.shape xx = np.array( [ a for a in range(lenx) for a in range(leny) ] ) # Convert 3D to 3*1D yy = np.array( [ a for a in range(lenx) for b in range(leny) ] ) zz = np.array( [ A[x][y] for x,y in zip(xx,yy) ] ) #--- xx = xx[zz!=0] # Drop zeroes yy = yy[zz!=0] zz = zz[zz!=0] #--- zi, yi, xi = np.histogram2d(yy, xx, bins=(10,10), weights=zz, normed=False) zi = np.ma.masked_equal(zi, 0) fig, ax = plt.subplots() ax.pcolormesh(xi, yi, zi, edgecolors='black') scat = ax.scatter(xx, yy, c=zz, s=200) fig.colorbar(scat) ax.margins(0.05) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/Adb6W.png" rel="nofollow"><img src="http://i.stack.imgur.com/Adb6W.png" alt="enter image description here"></a></p>
2
2016-08-05T13:45:26Z
[ "python", "python-2.7", "matplotlib", "heatmap", "colormap" ]
Python: How to plot heat map of 2D matrix by ignoring zeros?
38,790,536
<p>I have a matrix of size 500 X 28000, which contains a lot of zeros in between. But let us consider a working example with the matrix A: </p> <pre><code>A = [[0, 0, 0, 1, 0], [1, 0, 0, 2, 3], [5, 3, 0, 0, 0], [5, 0, 1, 0, 3], [6, 0, 0, 9, 0]] </code></pre> <p>I would like to plot a heatmap of the above matrix, but since it contains a lot of zeros, the heatmap contains almost white space as seen in the figure below. </p> <p><strong>How can I ignore the zeros in the matrix and plot the heatmap?</strong></p> <p>Here is the minimal working example that I tried:</p> <pre><code>im = plt.matshow(A, cmap=pl.cm.hot, norm=LogNorm(vmin=0.01, vmax=64), aspect='auto') # pl is pylab imported a pl plt.colorbar(im) plt.show() </code></pre> <p>which produces:</p> <p><a href="http://i.stack.imgur.com/kXmv6.png" rel="nofollow"><img src="http://i.stack.imgur.com/kXmv6.png" alt="enter image description here"></a></p> <p>as you can see it is because of the zeros the white spaces appear. </p> <p>But my original matrix of size 500X280000 contains a lot of zeros, which makes my colormap almost white!! </p>
1
2016-08-05T13:29:24Z
38,792,917
<p>This answer is in the same direction as 'Edit 2' section of Luis' answer. In fact, this is a simplified version of it. I am posting this just in order to correct my misleading statements in my comments. I saw a warning that we should not discuss in the comment area, so I am using this answering area.</p> <p>Anyway, first let me post my code. Please note that I used a larger matrix randomly generated inside the script, instead of your sample matrix <code>A</code>.</p> <pre><code>#!/usr/bin/python # # This script was written by norio 2016-8-5. import os, re, sys, random import numpy as np #from matplotlib.patches import Ellipse import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.image as img mpl.rcParams['lines.linewidth'] = 2 mpl.rcParams['lines.markeredgewidth'] = 1.0 mpl.rcParams['axes.formatter.limits'] = (-4,4) #mpl.rcParams['axes.formatter.limits'] = (-2,2) mpl.rcParams['axes.labelsize'] = 'large' mpl.rcParams['xtick.labelsize'] = 'large' mpl.rcParams['ytick.labelsize'] = 'large' mpl.rcParams['xtick.direction'] = 'out' mpl.rcParams['ytick.direction'] = 'out' ############################################ #numrow=500 #numcol=280000 numrow=50 numcol=28000 # .. for testing numelm=numrow*numcol eps=1.0e-9 # #numnz=int(1.0e-7*numelm) numnz=int(1.0e-5*numelm) # .. for testing vmin=1.0e-6 vmax=1.0 outfigname='stackoverflow38790536.png' ############################################ ### data matrix # I am generating a data matrix here artificially. print 'generating pseudo-data..' random.seed('20160805') matA=np.zeros((numrow, numcol)) for je in range(numnz): jr = random.uniform(0,numrow) jc = random.uniform(0,numcol) matA[jr,jc] = random.uniform(vmin,vmax) ### Actual processing for a given data will start from here print 'processing..' idxrow=[] idxcol=[] val=[] for ii in range(numrow): for jj in range(numcol): if np.abs(matA[ii,jj])&gt;eps: idxrow.append(ii) idxcol.append(jj) val.append( np.abs(matA[ii,jj]) ) print 'len(idxrow)=', len(idxrow) print 'len(idxcol)=', len(idxcol) print 'len(val)=', len(val) ############################################ # canvas setting for line plots ############################################ f_size = (8,5) a1_left = 0.15 a1_bottom = 0.15 a1_width = 0.65 a1_height = 0.80 # hspace=0.02 # ac_left = a1_left+a1_width+hspace ac_bottom = a1_bottom ac_width = 0.03 ac_height = a1_height ############################################ # plot ############################################ print 'plotting..' fig1=plt.figure(figsize=f_size) ax1 =plt.axes([a1_left, a1_bottom, a1_width, a1_height], axisbg='w') pc1=plt.scatter(idxcol, idxrow, s=20, c=val, cmap=mpl.cm.gist_heat_r) # cf. # http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter plt.xlabel('Column Index', fontsize=18) plt.ylabel('Row Index', fontsize=18) ax1.set_xlim([0, numcol-1]) ax1.set_ylim([0, numrow-1]) axc =plt.axes([ac_left, ac_bottom, ac_width, ac_height], axisbg='w') mpl.colorbar.Colorbar(axc,pc1, ticks=np.arange(0.0, 1.5, 0.1) ) plt.savefig(outfigname) plt.close() </code></pre> <p>This script output a figure, 'stackoverflow38790536.png', which will look like the following. <a href="http://i.stack.imgur.com/666Dq.png" rel="nofollow"><img src="http://i.stack.imgur.com/666Dq.png" alt="scatter plot of non-zero elements"></a></p> <p>As you can see in my code, I used <code>scatter</code> instead of <code>plot</code>. I realized that the <code>plot</code> command is not best suitable for the task here.</p> <p>Another of my words that I need to correct is that the <code>row_index</code> does not need to have as much as 140,000,000(=500*280000) elements. It only need to have the row indices of the non-zero elements. More correctly, the lists, <code>idxrow</code>, <code>idxcol</code>, and <code>val</code>, which enter into <code>scatter</code> command in the code above, has the lengths equal to the number of non-zero elements.</p> <p>Please note that both of these points have been correctly taken care of in Luis' answer.</p>
1
2016-08-05T15:31:36Z
[ "python", "python-2.7", "matplotlib", "heatmap", "colormap" ]
Python: How to plot heat map of 2D matrix by ignoring zeros?
38,790,536
<p>I have a matrix of size 500 X 28000, which contains a lot of zeros in between. But let us consider a working example with the matrix A: </p> <pre><code>A = [[0, 0, 0, 1, 0], [1, 0, 0, 2, 3], [5, 3, 0, 0, 0], [5, 0, 1, 0, 3], [6, 0, 0, 9, 0]] </code></pre> <p>I would like to plot a heatmap of the above matrix, but since it contains a lot of zeros, the heatmap contains almost white space as seen in the figure below. </p> <p><strong>How can I ignore the zeros in the matrix and plot the heatmap?</strong></p> <p>Here is the minimal working example that I tried:</p> <pre><code>im = plt.matshow(A, cmap=pl.cm.hot, norm=LogNorm(vmin=0.01, vmax=64), aspect='auto') # pl is pylab imported a pl plt.colorbar(im) plt.show() </code></pre> <p>which produces:</p> <p><a href="http://i.stack.imgur.com/kXmv6.png" rel="nofollow"><img src="http://i.stack.imgur.com/kXmv6.png" alt="enter image description here"></a></p> <p>as you can see it is because of the zeros the white spaces appear. </p> <p>But my original matrix of size 500X280000 contains a lot of zeros, which makes my colormap almost white!! </p>
1
2016-08-05T13:29:24Z
39,510,090
<p>Although the answer of norio is correct. I think one can give a much more to the point quick answer with only a few lines of code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt A = np.asarray(A) x,y = A.nonzero() #get the notzero indices plt.scatter(x,y,c=A[x,y],s=100,cmap='hot',marker='s') #adjust the size to your needs plt.colorbar() plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/atQgq.png" rel="nofollow"><img src="http://i.stack.imgur.com/atQgq.png" alt="enter image description here"></a></p> <p>Note that the axis are inverted. you could invert them by:</p> <pre><code>ax=plt.gca() ax.invert_xaxis() ax.invert_yaxis() </code></pre> <p>Also note that you have much more flexibility now:</p> <ul> <li>You can set the marker-size and the marker-type and transparancy optionally</li> <li>This procedure is faster, as the zeros are not parsed to matplotlib.</li> </ul>
0
2016-09-15T11:36:35Z
[ "python", "python-2.7", "matplotlib", "heatmap", "colormap" ]
python get data from div blocks
38,790,548
<p>I am trying to parse div block using Beautiful Soup </p> <p>Which is </p> <pre><code>&lt;div class="same-height-left" style="height: 20px;"&gt;&lt;span class="value-frame"&gt;&amp;nbsp;whatever&lt;/span&gt;&lt;/div&gt; </code></pre> <p>I want to get [what i expect]:</p> <p><code>whatever</code> or <code>&lt;span class="value-frame"&gt;&amp;nbsp;whatever&lt;/span&gt;</code></p> <p>I tried </p> <pre><code>response = requests.get('http://example.com') response.raise_for_status() soup = bs4.BeautifulSoup(response.text) div = soup.find('div', class_="same-height-left") </code></pre> <p>Result</p> <blockquote> <p>None</p> </blockquote> <p>And</p> <pre><code>soup = bs4.BeautifulSoup(response.text) div = soup.find_all('div', class_="same-height-left") </code></pre> <p>Result</p> <blockquote> <p>[]</p> </blockquote>
1
2016-08-05T13:29:50Z
38,791,471
<p>How about this:</p> <pre><code>from bs4 import BeautifulSoup html = """&lt;div class="same-height-left" style="height: 20px;"&gt;&lt;span class="value-frame"&gt;&amp;nbsp;whatever&lt;/span&gt;&lt;/div&gt;""" soup = BeautifulSoup(html, 'html.parser') method1 = soup.find('div').text method2 = soup.find('div').find('span').text method3 = soup.find('span', class_='value-frame').text print 'Result of method 1:' + method1 # prints " whatever" print 'Result of method 2:' + method2 # prints " whatever" print 'Result of method 3:' + method3 # prints " whatever" </code></pre>
1
2016-08-05T14:17:33Z
[ "python", "beautifulsoup" ]
pandas data frame: Find consecutive values and ignoring gaps of certain size
38,790,647
<p>I am struggeling with hourly precipitation data like e.g.</p> <pre><code>index=pd.date_range('1/1/2011', periods=365*24, freq='H') precipitation_indicator=np.random.randint(low=0, high=2, size=(365*24,)) precipitation_sum=np.random.ranf((365*24,))*6*precipitation_indicator prec_dataH=pd.DataFrame(data={'prec_ind':precipitation_indicator, prec_sum':precipitation_sum},index=index) </code></pre> <p>I want do define rain events if there is precipitation in consecutive time points, but also if there is a gap of a certain length within one event. I solved this with an rolling window by using the following code</p> <pre><code>gap_to_ignore=1 prec_dataH['event_ind']=prec_dataH['prec_ind'].rolling(window=(1+2*gap_to_ignore), center=True).max().dropna() </code></pre> <p>By doing so I get an event_ind of 1 whenever there is precipitation and also for breaks of 2 hours within the rainevent, but also for the timestamp 1 hour in advance and 1 hour after the rainevent. I now want to remove this 1 hour in advance and after the rainevent. I managed this by</p> <p>1.) giving an continous number to each change occouring in event_ind</p> <pre><code>prec_dataH['event_no'] = (prec_dataH['event_ind'].shift(1) != prec_dataH['event_ind']).astype(int).cumsum() </code></pre> <p>2.) assigning dry periods a NaN value for event_no</p> <pre><code>def reorder_eventNumbers_dryStart (event_numbers): if event_numbers % 2 !=0: return event_numbers/2 else: return np.NaN def reorder_eventNumbers_rainStart (event_numbers): if event_numbers % 2 ==0: return event_numbers/2 else: return np.NaN if prec_dataH.ix[1, 'event_ind']==1.: prec_dataH['event_no']=prec_dataH['event_no'].apply(reorder_eventNumbers_rainStart) elif prec_dataH.ix[1, 'event_ind']==0.: prec_dataH['event_no']=prec_dataH['event_no'].apply(reorder_eventNumbers_dryStart) </code></pre> <p>3.) Groupby the event_no, iterating through the groups and assigning NaN values to the values 1 hour in advance and 1 hour after the precipitation event and finaly concat the groups to a new DataFrame.</p> <p>This is quite time intensive and thereby a SettingWighCopyWarning occures and I don't understand why this occures. </p> <pre><code>A value is trying to be set on a copy of a slice from a DataFrame. </code></pre> <p>Here is the code I use:</p> <pre><code>rainEvents=prec_dataH.groupby('event_no') groups=[] for name, group in rainEvents: group.ix[0:gap_to_ignore,'event_ind'] =np.NaN group.ix[0:gap_to_ignore,'event_no'] =np.NaN group.ix[-gap_to_ignore:, 'event_ind']=np.NaN group.ix[-gap_to_ignore:,'event_no'] =np.NaN groups.append(group) rainEvents_corrected=pd.concat(groups) </code></pre> <p>So how can I avoid this SettingWithCopyWarning and how can I make my code more efficient??</p> <p>Thanks in advance, Axel</p>
0
2016-08-05T13:34:21Z
38,855,249
<p>Add <code>group = group.copy()</code> as the first line in the <code>for</code> loop. That gets rid of the <code>SettingWithCopyWarning</code> and speeds up your computation by a factor of ~60.</p> <pre><code>def approach1(): rainEvents=prec_dataH.groupby('event_no') groups=[] for name, group in rainEvents: group.ix[0:gap_to_ignore,'event_ind'] =np.NaN group.ix[0:gap_to_ignore,'event_no'] =np.NaN group.ix[-gap_to_ignore:, 'event_ind']=np.NaN group.ix[-gap_to_ignore:,'event_no'] =np.NaN groups.append(group) rainEvents_corrected=pd.concat(groups) def approach2(): rainEvents=prec_dataH.groupby('event_no') groups=[] for name, group in rainEvents: group = group.copy() group.ix[0:gap_to_ignore,'event_ind'] =np.NaN group.ix[0:gap_to_ignore,'event_no'] =np.NaN group.ix[-gap_to_ignore:, 'event_ind']=np.NaN group.ix[-gap_to_ignore:,'event_no'] =np.NaN groups.append(group) rainEvents_corrected=pd.concat(groups) %timeit approach1() # =&gt; 1 loop, best of 3: 1min 29s per loop %timeit approach2() # =&gt; 1 loop, best of 3: 1.42 s per loop </code></pre> <p>You can avoid the <code>for</code> loop by using <code>.apply()</code> on your <code>groupby</code> object with an appropriate function (which essentially mimics the body of your <code>for</code> loop). It seems to provide a 20-30% speedup with respect to the above.</p> <pre><code>def approach3(): def correct_rainEvents(g): g.ix[:gap_to_ignore, ['event_ind', 'event_no']] = np.nan g.ix[-gap_to_ignore:, ['event_ind', 'event_no']] = np.nan return g rainEvents_corrected = (prec_dataH.groupby('event_no') .apply(correct_rainEvents) .reset_index(level='event_no', drop=True)) %timeit approach3() # =&gt; 1 loop, best of 3: 1.12 s per loop </code></pre>
0
2016-08-09T15:48:17Z
[ "python", "pandas", "dataframe" ]
Mayavi: rotate around y axis
38,790,724
<p>I'm plotting a 3D mesh using mayavi's <code>triangular_mesh</code> method. The data describes a human silhouette laying face-down in 3D space (so the <code>cmap</code> can be used to denote distance from the camera).</p> <p>Here's the code used to generate the plot (the faces and vertices come from an external object, and there are far too many to show here):</p> <pre><code>from mayavi import mlab import math import numpy as np import sys import os fig = mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1), size=(1920, 980)) a = np.array(this_mesh.vertices - refC.conj().transpose()) # this_mesh is an object created from external data files this_mesh.faces = this_mesh.faces.astype(int) -1 # mesh data is generated by matlab, which is 1-indexed m = mlab.triangular_mesh(x, y, z, this_mesh.faces, opacity=0.75) mlab.axes(extent=[-1100, 1100, -1100, 1100, -1100, 1100]) </code></pre> <p>Without moving the camera, the silhouette lays face-down. In order to view the model face-on, I'm altering the azimuth and elevation of the camera to look at the graph top-down. This shows the silhouette as intended.</p> <pre><code>mlab.view(azimuth=0, elevation=180) mlab.show() </code></pre> <p>My next task is to create a series of images where the camera pans around the plot, starting with the silhouette facing to the right, and finishing with it facing to the left.</p> <p>The complication is that in order to get the colormap for the depth information, I'm already moving the view's azimuth and elevation (as shown in the code above). Mayavi has more options for moving the camera than matplotlib, but it doesn't seem to have a way to rotate around the Y axis, so I'm guessing I'll need to perform some complex calculations on the azimuth and elevation to achieve the same result - but I'm at a loss as to where to start (I'm new to working in 3D space, and my brain doesn't think that way yet).</p> <p>Can anyone point me in the right direction?</p>
8
2016-08-05T13:38:41Z
38,792,397
<p>You need some math here. Ok, here is how to do it in terms of code, its not the best code but I wanted to make it self-explanatory. I use the Rodrigues formula for rotation in 3d to achieve this, az_new and el_new are your new viewing angles. Change the value of theta to get a different viewing angle in your frame of reference, i have used 45 degrees in the code below:</p> <pre><code>import numpy as np import math def rotation_matrix(axis, theta): """ Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. """ axis = np.asarray(axis) theta = np.asarray(theta) axis = axis/math.sqrt(np.dot(axis, axis)) a = math.cos(theta/2.0) b, c, d = -axis*math.sin(theta/2.0) aa, bb, cc, dd = a*a, b*b, c*c, d*d bc, ad, ac, ab, bd, cd = b*c, a*d, a*c, a*b, b*d, c*d return np.array([[aa+bb-cc-dd, 2*(bc+ad), 2*(bd-ac)], [2*(bc-ad), aa+cc-bb-dd, 2*(cd+ab)], [2*(bd+ac), 2*(cd-ab), aa+dd-bb-cc]]) az = 90 el = -75 x = np.cos(np.deg2rad(el))*np.cos(np.deg2rad(az)) y = np.cos(np.deg2rad(el))*np.sin(np.deg2rad(az)) z = np.sin(np.deg2rad(el)) # So your viewing vector in x,y coordinates on unit sphere v = [x,y,z] # Since you want to rotate about the y axis from this viewing angle, we just increase the # elevation angle by 90 degrees to obtain our axis of rotation az2 = az el2 = el+90 x = np.cos(np.deg2rad(el2))*np.cos(np.deg2rad(az2)) y = np.cos(np.deg2rad(el2))*np.sin(np.deg2rad(az2)) z = np.sin(np.deg2rad(el2)) axis = [x,y,z] # Now to rotate about the y axis from this viewing angle we use the rodrigues formula # We compute our new viewing vector, lets say we rotate by 45 degrees theta = 45 newv = np.dot(rotation_matrix(axis,np.deg2rad(theta)), v) #Get azimuth and elevation for new viewing vector az_new = np.rad2deg(np.arctan(newv[1]/newv[0])) el_new = np.rad2deg(np.arcsin(newv[2])) </code></pre>
2
2016-08-05T15:03:24Z
[ "python", "3d", "mayavi" ]
Mayavi: rotate around y axis
38,790,724
<p>I'm plotting a 3D mesh using mayavi's <code>triangular_mesh</code> method. The data describes a human silhouette laying face-down in 3D space (so the <code>cmap</code> can be used to denote distance from the camera).</p> <p>Here's the code used to generate the plot (the faces and vertices come from an external object, and there are far too many to show here):</p> <pre><code>from mayavi import mlab import math import numpy as np import sys import os fig = mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1), size=(1920, 980)) a = np.array(this_mesh.vertices - refC.conj().transpose()) # this_mesh is an object created from external data files this_mesh.faces = this_mesh.faces.astype(int) -1 # mesh data is generated by matlab, which is 1-indexed m = mlab.triangular_mesh(x, y, z, this_mesh.faces, opacity=0.75) mlab.axes(extent=[-1100, 1100, -1100, 1100, -1100, 1100]) </code></pre> <p>Without moving the camera, the silhouette lays face-down. In order to view the model face-on, I'm altering the azimuth and elevation of the camera to look at the graph top-down. This shows the silhouette as intended.</p> <pre><code>mlab.view(azimuth=0, elevation=180) mlab.show() </code></pre> <p>My next task is to create a series of images where the camera pans around the plot, starting with the silhouette facing to the right, and finishing with it facing to the left.</p> <p>The complication is that in order to get the colormap for the depth information, I'm already moving the view's azimuth and elevation (as shown in the code above). Mayavi has more options for moving the camera than matplotlib, but it doesn't seem to have a way to rotate around the Y axis, so I'm guessing I'll need to perform some complex calculations on the azimuth and elevation to achieve the same result - but I'm at a loss as to where to start (I'm new to working in 3D space, and my brain doesn't think that way yet).</p> <p>Can anyone point me in the right direction?</p>
8
2016-08-05T13:38:41Z
38,895,027
<p>It turns out there's a bit of a workaround for this.</p> <p>You can rotate the actors on their axes independently of the camera. (This throws the visualization out of step with the data labeling, but as I'm actually hiding the axes of the figure it doesn't matter in this case.)</p> <p>All you need to do is:</p> <pre><code>m.actor.actor.rotate_y(desired_angle) </code></pre> <p>...and you're good to go.</p>
0
2016-08-11T11:24:23Z
[ "python", "3d", "mayavi" ]
numpy.frombuffer ValueError: buffer is smaller than requested size
38,790,819
<p>I have the error listed above, but have been unable to find what it means. I am new to numpy and its {.frombuffer()} command. The code where this error is triggering is:</p> <pre><code>ARRAY_1=400000004 fid=open(fn,'rb') fid.seek(w+x+y+z) #w+x+y+z= if(condition==0): b=fid.read(struct.calcsize(fmt+str(ARRAY_1)+'b')) myClass.y = numpy.frombuffer(b,'b',struct.calcsize(fmt+str(ARRAY_1)+'b')) else: b=fid.read(struct.calcsize(fmt+str(ARRAY_1)+'h')) myClass.y = numpy.frombuffer(b,'h',struct.calcsize(fmt+str(ARRAY_1)+'h')) #error this line </code></pre> <p>where fmt is '>' where condition==0 and '&lt;' where condition !=0. This is changing the way the <em>binary</em>file is read, big endian or little endian. fid is a binary file that has already been opened.</p> <p>Debugging up to this point, condition=1, so I have a feeling that there is also an error in the last statement of the if condition as well, I just don't see it right now.</p> <p>As I said before, I tried to find what the error meant, but haven't had any luck. If anyone knows why it's erroring out on me, I'd really like the help.</p>
0
2016-08-05T13:44:35Z
38,797,861
<p><code>calcsize</code> gives the number of bytes that the buffer will have given the format.</p> <pre><code>In [421]: struct.calcsize('&gt;100h') Out[421]: 200 In [422]: struct.calcsize('&gt;100b') Out[422]: 100 </code></pre> <p><code>h</code> takes 2 bytes per item, so for 100 items, it gives 200 bytes.</p> <p>For <code>frombuffer</code>, the 3rd argument is</p> <pre><code>count : int, optional Number of items to read. ``-1`` means all data in the buffer. </code></pre> <p>So I should give it <code>100</code>, not <code>200</code>.</p> <p>Reading a simple bytestring (in Py3):</p> <pre><code>In [429]: np.frombuffer(b'one two three ','b',14) Out[429]: array([111, 110, 101, 32, 116, 119, 111, 32, 116, 104, 114, 101, 101, 32], dtype=int8) In [430]: np.frombuffer(b'one two three ','h',14) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-430-30077e924a4c&gt; in &lt;module&gt;() ----&gt; 1 np.frombuffer(b'one two three ','h',14) ValueError: buffer is smaller than requested size In [431]: np.frombuffer(b'one two three ','h',7) Out[431]: array([28271, 8293, 30580, 8303, 26740, 25970, 8293], dtype=int16) </code></pre> <p>To read it with <code>h</code> I need to give it half the count of the <code>b</code> read.</p>
0
2016-08-05T21:15:54Z
[ "python", "numpy", "buffer" ]
Unable to properly install or load Tensorflow on Ubuntu 12.04 LTS with resultant ImportError
38,790,852
<p>I attempted the <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#anaconda-installation" rel="nofollow">Anaconda installation</a> for TensorFlow on my Ubuntu 12.04 LTS system, which went through, but while importing the library in Python, I came across an ImportError shown below.</p> <p>I went through a <a href="http://stackoverflow.com/questions/33655731/error-while-importing-tensorflow-in-python2-7-in-ubuntu-12-04-glibc-2-17-not-f">solution</a> given for a similar thread, but it didn't work for me.</p> <p>Basically here's what I did for the installation:</p> <pre><code>$ conda create -n tensorflow python=2.7 $ source activate tensorflow (tensorflow)$ conda install -c conda-forge tensorflow (tensorflow)$ source deactivate $ source activate tensorflow </code></pre> <p>Then from within the virtualenv I loaded Python, and tried to import tensorflow. What I got was the following error:</p> <pre><code>&gt;&gt;&gt; import tensorflow Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/anirudh/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/__init__.py", line 23, in &lt;module&gt; from tensorflow.python import * File "/home/anirudh/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 48, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/home/anirudh/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in &lt;module&gt; _pywrap_tensorflow = swig_import_helper() File "/home/anirudh/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description) ImportError: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.19' not found (required by /home/anirudh/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so) </code></pre> <p>How do I sort this?</p>
1
2016-08-05T13:46:06Z
38,791,345
<p>This error probably relates to you glibc version. There are some topics regarding this:<a href="http://stackoverflow.com/questions/16605623/where-can-i-get-a-copy-of-the-file-libstdc-so-6-0-15">Where can I get a copy of the file libstdc++.so.6.0.15</a></p> <p>First check whether the required version is on your system.</p> <pre><code> $ strings /usr/lib/x86_64-linux-gnu/libstdc++.so.6 | grep GLIBCXX </code></pre> <p>If it is not listed, you can try</p> <pre><code> $ sudo add-apt-repository ppa:ubuntu-toolchain-r/test $ sudo apt-get update $ sudo apt-get upgrade $ sudo apt-get dist-upgrade </code></pre> <p>"sudo apt-get dist-upgrade" may not be required.</p>
0
2016-08-05T14:10:52Z
[ "python", "ubuntu", "tensorflow", "anaconda" ]
Unable to properly install or load Tensorflow on Ubuntu 12.04 LTS with resultant ImportError
38,790,852
<p>I attempted the <a href="https://www.tensorflow.org/versions/r0.10/get_started/os_setup.html#anaconda-installation" rel="nofollow">Anaconda installation</a> for TensorFlow on my Ubuntu 12.04 LTS system, which went through, but while importing the library in Python, I came across an ImportError shown below.</p> <p>I went through a <a href="http://stackoverflow.com/questions/33655731/error-while-importing-tensorflow-in-python2-7-in-ubuntu-12-04-glibc-2-17-not-f">solution</a> given for a similar thread, but it didn't work for me.</p> <p>Basically here's what I did for the installation:</p> <pre><code>$ conda create -n tensorflow python=2.7 $ source activate tensorflow (tensorflow)$ conda install -c conda-forge tensorflow (tensorflow)$ source deactivate $ source activate tensorflow </code></pre> <p>Then from within the virtualenv I loaded Python, and tried to import tensorflow. What I got was the following error:</p> <pre><code>&gt;&gt;&gt; import tensorflow Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/anirudh/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/__init__.py", line 23, in &lt;module&gt; from tensorflow.python import * File "/home/anirudh/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/__init__.py", line 48, in &lt;module&gt; from tensorflow.python import pywrap_tensorflow File "/home/anirudh/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in &lt;module&gt; _pywrap_tensorflow = swig_import_helper() File "/home/anirudh/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description) ImportError: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.19' not found (required by /home/anirudh/anaconda/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/_pywrap_tensorflow.so) </code></pre> <p>How do I sort this?</p>
1
2016-08-05T13:46:06Z
38,793,952
<p>You need to install <a href="http://packages.ubuntu.com/precise/libstdc++6" rel="nofollow">libstdc++6</a> with some dependencies like <code>gcc</code> an <code>g++</code>, at least <code>gcc-4.6</code> version:</p> <pre><code>sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt-get update sudo apt-get install gcc-4.9 g++-4.9 sudo apt-get install libstdc++6 </code></pre> <p>Or you can install <code>linux-headers</code> and <code>build-essential</code> witch contains some useful tools like <code>gcc</code> compiler, <code>make</code> .... tools for compiling and building software from source.</p>
0
2016-08-05T16:31:41Z
[ "python", "ubuntu", "tensorflow", "anaconda" ]
Django1.8 'app' is not a registered namespace
38,790,872
<p>My error:</p> <pre><code> &lt;h1&gt;{{ question.question_text }}&lt;/h1&gt; {% if error_message %}&lt;p&gt;&lt;strong&gt;{{ error_message }}&lt;/strong&gt;&lt;/p&gt;{% endif %} &lt;form action="{% url 'app:vote' question.id %}" method="post"&gt; {% csrf_token %} {% for choice in question.choice_set.all %} &lt;input type="radio" name="choice" id="choice{{ forloop.counter}}" value="{{ choice.id }}" /&gt; &lt;label for="choice{{ forloop.counter }}"&gt;{{ choice.choice_text }}&lt;/label&gt;&lt;br /&gt; {% endfor %} &lt;input type="submit" value="Vote" /&gt; &lt;/form&gt; </code></pre> <p>I want to know why it's wrong here. This is the official website of the document is written</p> <p>This <code>detail.html</code>:</p> <pre><code>&lt;h1&gt;{{ question.question_text }}&lt;/h1&gt; {% if error_message %}&lt;p&gt;&lt;strong&gt;{{ error_message }}&lt;/strong&gt;&lt;/p&gt;{% endif %} &lt;form action="{% url 'app:vote' question.id %}" method="post"&gt; {% csrf_token %} {% for choice in question.choice_set.all %} &lt;input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /&gt; &lt;label for="choice{{ forloop.counter }}"&gt;{{ choice.choice_text }} &lt;/label&gt;&lt;br /&gt; {% endfor %} &lt;input type="submit" value="Vote" /&gt; &lt;/form&gt; </code></pre> <p>Now I know the problems is in <code>detail.html</code>, my main urls and my app called myapp URLCONF and <code>views.py</code></p> <p><code>views.py</code>:</p> <pre><code>def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) </code></pre> <p>My <code>urls.py</code>:</p> <pre><code>urlpatterns = [ url(r'^$',views.Index,name='index'), url(r'^(?P&lt;question_id&gt;\d+)/$',views.detail,name='detail'), url(r'^(?P&lt;question_id&gt;\d+)/results/$', views.results, name='results'), url(r'^(?P&lt;question_id&gt;\d+)/vote/$', views.vote, name='vote'), url(r'^admin/', admin.site.urls), ] </code></pre>
0
2016-08-05T13:47:20Z
38,791,077
<p>Namespacing is used when you include another url config inside your root <code>urls.py</code>. The example in the tutorial works because they have <code>include('polls.urls')</code> <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial01/#write-your-first-view" rel="nofollow">in tutorial 1</a>, and then in tutorial 3 they have set <code>app_name = 'polls'</code> in <code>polls/urls.py</code>, and changed the url tag to <code>{% 'polls:vote' question.id %}</code> <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial03/#namespacing-url-names" rel="nofollow">in tutorial 3</a>.</p> <p>In your case, all your url patterns are in the root config, so you should remove the namespace from your url tag.</p> <pre><code>{% url 'vote' question.id %} </code></pre>
0
2016-08-05T13:57:13Z
[ "python", "django" ]
Django1.8 'app' is not a registered namespace
38,790,872
<p>My error:</p> <pre><code> &lt;h1&gt;{{ question.question_text }}&lt;/h1&gt; {% if error_message %}&lt;p&gt;&lt;strong&gt;{{ error_message }}&lt;/strong&gt;&lt;/p&gt;{% endif %} &lt;form action="{% url 'app:vote' question.id %}" method="post"&gt; {% csrf_token %} {% for choice in question.choice_set.all %} &lt;input type="radio" name="choice" id="choice{{ forloop.counter}}" value="{{ choice.id }}" /&gt; &lt;label for="choice{{ forloop.counter }}"&gt;{{ choice.choice_text }}&lt;/label&gt;&lt;br /&gt; {% endfor %} &lt;input type="submit" value="Vote" /&gt; &lt;/form&gt; </code></pre> <p>I want to know why it's wrong here. This is the official website of the document is written</p> <p>This <code>detail.html</code>:</p> <pre><code>&lt;h1&gt;{{ question.question_text }}&lt;/h1&gt; {% if error_message %}&lt;p&gt;&lt;strong&gt;{{ error_message }}&lt;/strong&gt;&lt;/p&gt;{% endif %} &lt;form action="{% url 'app:vote' question.id %}" method="post"&gt; {% csrf_token %} {% for choice in question.choice_set.all %} &lt;input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /&gt; &lt;label for="choice{{ forloop.counter }}"&gt;{{ choice.choice_text }} &lt;/label&gt;&lt;br /&gt; {% endfor %} &lt;input type="submit" value="Vote" /&gt; &lt;/form&gt; </code></pre> <p>Now I know the problems is in <code>detail.html</code>, my main urls and my app called myapp URLCONF and <code>views.py</code></p> <p><code>views.py</code>:</p> <pre><code>def vote(request, question_id): p = get_object_or_404(Question, pk=question_id) try: selected_choice = p.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': p, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(p.id,))) </code></pre> <p>My <code>urls.py</code>:</p> <pre><code>urlpatterns = [ url(r'^$',views.Index,name='index'), url(r'^(?P&lt;question_id&gt;\d+)/$',views.detail,name='detail'), url(r'^(?P&lt;question_id&gt;\d+)/results/$', views.results, name='results'), url(r'^(?P&lt;question_id&gt;\d+)/vote/$', views.vote, name='vote'), url(r'^admin/', admin.site.urls), ] </code></pre>
0
2016-08-05T13:47:20Z
38,801,618
<p><a href="http://i.stack.imgur.com/4sBN2.png" rel="nofollow">My Project picture</a></p> <p>I added a new urls.py</p> <p>this code,mydjango/urls.py</p> <hr> <pre><code>from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^app/', include('app.urls')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>app/urls.py</p> <hr> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] </code></pre>
0
2016-08-06T07:17:28Z
[ "python", "django" ]
Python select.select monitoring sockets in separate threads
38,790,913
<p>Is it allowed to create connections in separate threds, and than put them in select input list, and then call <code>select.select(input_list, [], [])</code> from main thread if except that call main thread do not use these connections?</p>
1
2016-08-05T13:49:15Z
38,791,944
<p>Yes, it should be possible. Check out these (related) posts for more details: <a href="http://stackoverflow.com/questions/8273297/keeping-a-socket-opened-in-a-thread-and-sending-commands-from-main">first</a>, <a href="http://stackoverflow.com/questions/8282216/multiple-threaded-socket-connections-queues">second</a>.</p>
0
2016-08-05T14:40:59Z
[ "python", "python-2.7", "python-3.x" ]
Excel Workbook to html Django/Python
38,790,938
<p>Is there any way to take an excel workbook, and display it on a webpage with the same formatting as the workbook? Im wondering if there is a way to take an excel workbook and paste the contents on a webpage. Basically im looking for something to screenshot the excel document and paste in in my webpage... Is there any way to do this??? (Maybe something similar to Zoho Viewer: <a href="https://sheet.zoho.com/sheet/excelviewer" rel="nofollow">https://sheet.zoho.com/sheet/excelviewer</a>)</p> <p><strong>Current Wepbage:</strong> <a href="http://i.stack.imgur.com/H9sYr.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/H9sYr.jpg" alt="enter image description here"></a></p> <p><strong>After Adding the Excel Workbook</strong> <a href="http://i.stack.imgur.com/dKz0b.png" rel="nofollow"><img src="http://i.stack.imgur.com/dKz0b.png" alt="enter image description here"></a></p> <p>NOTE: I am using xlsxwriter to populate the excel sheet. </p>
1
2016-08-05T13:50:16Z
38,791,031
<p>There's many ways to get around doing what you're referring to. Would you be open to using Google Sheets or do it have to be MS Excel? If so, I'd say use google drive and Google Sync. This way, you can make your excel on your local machine, save it. Create a python script that copies the file from the saved location, to the google drive on your machine. Then google drive will update/sync it. Then it's just a matter of logging into google and copying the file link, then you can use that link so long as you don't change any names of the file. I used this as a solution at one of my previous jobs because google is free and available 24/7. I hoped that helps...</p>
0
2016-08-05T13:54:57Z
[ "python", "html", "django", "excel", "xlsxwriter" ]
Excel Workbook to html Django/Python
38,790,938
<p>Is there any way to take an excel workbook, and display it on a webpage with the same formatting as the workbook? Im wondering if there is a way to take an excel workbook and paste the contents on a webpage. Basically im looking for something to screenshot the excel document and paste in in my webpage... Is there any way to do this??? (Maybe something similar to Zoho Viewer: <a href="https://sheet.zoho.com/sheet/excelviewer" rel="nofollow">https://sheet.zoho.com/sheet/excelviewer</a>)</p> <p><strong>Current Wepbage:</strong> <a href="http://i.stack.imgur.com/H9sYr.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/H9sYr.jpg" alt="enter image description here"></a></p> <p><strong>After Adding the Excel Workbook</strong> <a href="http://i.stack.imgur.com/dKz0b.png" rel="nofollow"><img src="http://i.stack.imgur.com/dKz0b.png" alt="enter image description here"></a></p> <p>NOTE: I am using xlsxwriter to populate the excel sheet. </p>
1
2016-08-05T13:50:16Z
38,801,806
<p>should the xl file reside in your local machine? or are you open to storing it in the cloud ? Since you mentioned zoho viewer you might want to check out zoho office APIs <a href="https://www.zoho.com/docs/help/office-apis.html" rel="nofollow">here</a> using which you can use the API to upload a file and get back a link with the file rendered in a xl viewer which you can paste into an iFrame etc to display it on your page.</p>
1
2016-08-06T07:41:20Z
[ "python", "html", "django", "excel", "xlsxwriter" ]
Sengrid templates with custom image for every email
38,791,130
<p>How to send sengrid email with custom image which is inserto to template with tag?</p> <p>I have transactional email and I want insert image of item user is interested.</p> <p>I know how to add tags for custom information to template. But what about images?</p> <p>Maybe is possible to do something like this:</p> <pre><code>personalization.add_substitution(Substitution("%image_url%", "http://some_url.to.image )) </code></pre> <p>And than in place of %image_url% insert image which will be presented in email?</p>
1
2016-08-05T14:00:13Z
38,804,153
<p>Solved. I just need to create tag for image url.</p> <pre><code>personalization.add_substitution(Substitution("%image_url%", "http://some_url.to.image )) </code></pre>
0
2016-08-06T12:09:55Z
[ "python", "sendgrid" ]
ipdb how to bring the python debugger up to the frame which called the third-party code
38,791,146
<p>In my python code, I have several levels of call stacks like this:</p> <pre><code>f1:user_func1 f2:**user_func2** f3:third_party_func1 f4:third_party_func2 f5:exception happens here. </code></pre> <p>An exception happens somewhere in the third-party code (frame f5). I use ipdb to go the frame where the exception happened, and use the up command "u" to bring the debugger back to the frame where my code calls the third party code (frame f2).</p> <p>Sometimes there are many level in the third-party code so I need to press u many times. Is there way to quickly bring the debugger to the frame of your code that calls the third-party code?</p>
0
2016-08-05T14:01:15Z
39,272,786
<p>From ipdb command line:</p> <pre><code>ipdb&gt; help up u(p) [count] Move the current frame count (default one) levels up in the stack trace (to an older frame). </code></pre>
0
2016-09-01T13:25:08Z
[ "python", "debugging", "ipdb" ]
Rearrangement of string conditionally?
38,791,198
<p>I have spent the last 2 months working on a script that cleans, formats, and geocodes addresses. It is quite successful right now, however, there are some addresses that are giving me problems.</p> <p>For example:</p> <p>Addresses such as <code>7TH AVENUE 530 xxxxxxxxxxx</code> are causing my geolocation module to fail. You can assume that the x's are other text. The other text isn't causing errors, it's purely due to the street number coming after avenue. I currently have filters in my program to truncate the address after street suffixes, such as avenue, street, etc. Due to this the program will ultimately only send <code>7th avenue</code> to the cleaning module, which isn't accurate. </p> <p>How can I account for instances where there are a group of numbers immediately preceding the street suffix and then move them to the front of the address. Then I can continue as I already am and truncate the string after the suffix.</p> <p>You can assume that I have a list of all of the street suffixes named <code>patterns</code>.</p> <p>Thank you. Any help is greatly appreciated.</p> <p>FURTHER CLARIFICATION: I would only need to perform this rearrangement of the string if the group of numbers was 3 digits or less, because the zip code will frequently come after the address suffix, and in cases like that I wouldn't want to rearrange the string.</p>
0
2016-08-05T14:04:04Z
38,791,955
<p>I am not sure if this helps, but you can start with this:</p> <pre><code>import re address = '7TH AVENUE 530 xxxxxxxxxxx' m = re.search('(?&lt;=AVENUE )\d{1,3}', address) print (m.group(0)) &gt;&gt;&gt; 530 </code></pre> <p>Edit based on your comment:</p> <pre><code>import re original = '7TH AVENUE 530 xxxxxxxxxxx' patterns = ['street', 'avenue', 'road', 'place'] regex = r'(.*)(' + '|'.join(patterns) + r')(.*)' address = re.sub(regex, r'\1\2', original.lower()).lstrip() new_addr = re.search(r'(?&lt;=%s )\d{1,3} ' % address, original.lower()) resulting_address = ' '.join([new_addr.group(0).strip(),address]) if new_addr else address address = ' '.join(map(str.capitalize, resulting_address.split())) </code></pre>
0
2016-08-05T14:41:27Z
[ "python" ]
Is there any interpreter that works well for running multiprocessing in python 2.7 version on windows 7?
38,791,222
<p>I was trying to run a piece of code.This code is all about multiprocessing.It works fine on command prompt and it also generates some output.But when I try to run this code on pyscripter it just says that script runs ok and it doesn't generate any output nor even it displays any error message.It doesn't even crashes.It would be really helpful if anyone could help me out to find out a right interpreter where this multiprocessing works fine. Here is the piece of code:</p> <pre><code> from multiprocessing import Process def wait(): print "wait" clean() def clean(): print "clean" def main(): p=Process(target=wait) p.start() p.join() if _name_=='_main_': main() </code></pre>
1
2016-08-05T14:05:17Z
38,791,400
<p>The normal interpreter works just fine with <code>multiprocessing</code> on Windows 7 for me. (Your IDE might not like multiprocessing.) </p> <p>You just have to do</p> <pre><code>if __name__=='__main__': main() </code></pre> <p>with 2 underscores (<code>__</code>) each instead of 1 (<code>_</code>).</p> <p>Also - if you don't have an actual reason not to use it, <code>multiprocessing.Pool</code> is much easier to use than <code>multiprocessing.Process</code> in most cases. Have alook at <a href="https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool" rel="nofollow">https://docs.python.org/2/library/multiprocessing.html#module-multiprocessing.pool</a></p> <p>An implementation with a Pool would be</p> <pre><code>import multiprocessing def wait(): print "wait" clean() def clean(): print "clean" def main(): p=multiprocessing.Pool() p.apply_async(wait) p.close() p.join() if __name__=='__main__': main() </code></pre> <p>but which method of Pool to use strongly depends on what you actually want to do.</p>
0
2016-08-05T14:13:45Z
[ "python", "windows-7", "multiprocessing", "command-prompt", "interpreter" ]
How to properly create hist in matplotlib?
38,791,246
<p>I want to plot a histogram with three columns with heights <code>5</code>, <code>10</code> and <code>20</code>. Each column will have a width of 1. So the first column will have height <code>5</code> on the interval <code>[0,1]</code>, the second one <code>10</code> on the interval <code>[1,2]</code> and so on.</p> <pre><code>plt.hist([5, 10, 20], bins=range(0,4,1)) plt.show() </code></pre> <p>But as result I have nothing: <a href="http://i.stack.imgur.com/oZwNz.png" rel="nofollow"><img src="http://i.stack.imgur.com/oZwNz.png" alt="enter image description here"></a></p> <p>What did I do wrong? </p>
1
2016-08-05T14:06:15Z
38,791,449
<p><code>hist</code> computes the number of data samples that lies within a given bin and then displays the resulting frequencies as a bar plot. You don't actually need <code>hist</code> because you already <em>have</em> the frequencies. You simply need <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar" rel="nofollow"><code>bar</code></a> to display these frequencies as a bar plot. The first input specifies the left edge location of each bar and then we can use the <code>width</code> kwarg to specify the width of each bar.</p> <pre><code>import matplotlib.pyplot as plt plt.bar([0, 1, 2], [5, 10, 20], width=1) </code></pre> <p><a href="http://i.stack.imgur.com/tLeDnm.png" rel="nofollow"><img src="http://i.stack.imgur.com/tLeDnm.png" alt="enter image description here"></a></p>
2
2016-08-05T14:16:10Z
[ "python", "matplotlib", "histogram" ]
Difference between reading in vs declaring string python
38,791,298
<p>What is the difference (if any) between declaring a string in python vs reading in their value?</p> <p>I have a piece of my code code which looks like:</p> <pre><code>file = open('comport.txt','r') for line in file: if "comport" in line: comport = line[9:] </code></pre> <p>and the text file just looks like:</p> <pre><code>comport= COM1 </code></pre> <p>When I try to open up a serial port, I do:</p> <pre><code>ser = serial.Serial(comport,baudrate=115200) </code></pre> <p>which doesn't work (bunch of errors), but this works:</p> <pre><code>comport = 'COM1' ser = serial.Serial(comport,baudrate=115200) </code></pre> <p>I've tried putting the quotes in the text file and that didn't work either, i'm pretty sure i'm splitting my line correctly too because when I try printing it, it prints <code>COM1</code></p>
0
2016-08-05T14:08:36Z
38,791,398
<p>Probably there is still a linebreak <code>\n</code> after <code>"COM1"</code>. Try this: </p> <pre><code> comport = line[9:].strip() </code></pre> <p>or this: </p> <pre><code> comport = line.split("=")[1].strip() </code></pre> <p>Also, you should use <code>with</code> to open <em>and close</em> the file, and don't use <code>file</code> as a variable name.</p> <pre><code>with open('comport.txt','r') as f: for line in f: </code></pre>
2
2016-08-05T14:13:41Z
[ "python", "string", "pyserial" ]
Python: How to search and replace parts of a json file?
38,791,384
<p>I'm new to Python and I would like to search and replace titles of IDs in a JSON-file. Normally I would use R for this Task, but how to do it in Python. Here a sample of my JSON code (with a Service ID and a layer ID). I'm interested in replacing the titles in the layer IDs:</p> <pre><code> ...{"services": [ { "id": "service", "url": "http://...", "title": "GEW", "layers": [ { "id": "0", "title": "wrongTitle", }, { "id": "1", "title": "againTitleWrong", }, ], "options": {} },],} </code></pre> <p>For the replace I would use a table/csv like this:</p> <pre><code>serviceID layerID oldTitle newTitle service 0 wrongTitle newTitle1 service 1 againTitleWrong newTitle2 .... </code></pre> <p>Do you have ideas? Thanks</p>
0
2016-08-05T14:12:50Z
38,791,525
<p>You don't say which version of Python you are using but there are built-on JSON parsers for the language.</p> <p>For 2.x: <a href="https://docs.python.org/2.7/library/json.html" rel="nofollow">https://docs.python.org/2.7/library/json.html</a></p> <p>For 3.x: <a href="https://docs.python.org/3.4/library/json.html" rel="nofollow">https://docs.python.org/3.4/library/json.html</a></p> <p>These should be able to help you to parse the JSON and replace what you want.</p>
0
2016-08-05T14:19:59Z
[ "python", "json" ]
Python: How to search and replace parts of a json file?
38,791,384
<p>I'm new to Python and I would like to search and replace titles of IDs in a JSON-file. Normally I would use R for this Task, but how to do it in Python. Here a sample of my JSON code (with a Service ID and a layer ID). I'm interested in replacing the titles in the layer IDs:</p> <pre><code> ...{"services": [ { "id": "service", "url": "http://...", "title": "GEW", "layers": [ { "id": "0", "title": "wrongTitle", }, { "id": "1", "title": "againTitleWrong", }, ], "options": {} },],} </code></pre> <p>For the replace I would use a table/csv like this:</p> <pre><code>serviceID layerID oldTitle newTitle service 0 wrongTitle newTitle1 service 1 againTitleWrong newTitle2 .... </code></pre> <p>Do you have ideas? Thanks</p>
0
2016-08-05T14:12:50Z
38,792,955
<p>Here's an <a href="https://repl.it/Cjua/20" rel="nofollow">working example</a> on repl.it.</p> <p>Code: </p> <pre><code>import json import io import csv ### json input input = """ { "layers": [ { "id": "0", "title": "wrongTitle" }, { "id": "1", "title": "againTitleWrong" } ] } """ ### parse the json parsed_json = json.loads(input) #### csv input csv_input = """serviceID,layerID,oldTitle,newTitle service,0,wrongTitle,newTitle1 service,1,againTitleWrong,newTitle2 """ ### parse csv and generate a correction lookup parsed_csv = csv.DictReader(io.StringIO(csv_input)) lookup = {} for row in parsed_csv: lookup[row["layerID"]] = row["newTitle"] #correct and print json layers = parsed_json["layers"] for layer in layers: layer["title"] = lookup[layer["id"]] parsed_json["layers"] = layers print(json.dumps(parsed_json)) </code></pre>
2
2016-08-05T15:33:19Z
[ "python", "json" ]
Python: How to search and replace parts of a json file?
38,791,384
<p>I'm new to Python and I would like to search and replace titles of IDs in a JSON-file. Normally I would use R for this Task, but how to do it in Python. Here a sample of my JSON code (with a Service ID and a layer ID). I'm interested in replacing the titles in the layer IDs:</p> <pre><code> ...{"services": [ { "id": "service", "url": "http://...", "title": "GEW", "layers": [ { "id": "0", "title": "wrongTitle", }, { "id": "1", "title": "againTitleWrong", }, ], "options": {} },],} </code></pre> <p>For the replace I would use a table/csv like this:</p> <pre><code>serviceID layerID oldTitle newTitle service 0 wrongTitle newTitle1 service 1 againTitleWrong newTitle2 .... </code></pre> <p>Do you have ideas? Thanks</p>
0
2016-08-05T14:12:50Z
38,793,057
<p>As other users suggested, check the JSON module will be helpful. Here gives a basic example on python2.7:</p> <pre><code> import json j = '''{ "services": [{ "id": "service", "url": "http://...", "title": "GEW", "options": {}, "layers": [ { "id": "0", "title": "wrongTitle" }, { "id": "1", "title": "againTitleWrong" } ] }] }''' s = json.loads(j) s["services"][0]["layers"][0]["title"] = "new title" # save json object to file with open('file.json', 'w') as f: json.dump(s, f) </code></pre> <p>You can index the element and change its title according to your csv file, which requires the use of CSV module.</p>
0
2016-08-05T15:39:12Z
[ "python", "json" ]
How to create relations with django
38,791,442
<p>This will be my first post here so I hope that everything will be correct.</p> <p>I got some trouble with django, I try to make a little lottery game. For this game I have one app called bitcoinlottery and in that app 2 models. As for now they look like this:</p> <pre><code>from django.db import models from django.utils import timezone class Lottery(models.Model): owner = models.ForeignKey('auth.User') title = models.CharField(max_length=100) slug = models.SlugField(max_length=110) max_players = models.IntegerField() total_players = models.CharField(default=0) online = models.BooleanField(default=True) create_date = models.DateTimeField(default=timezone.now) class Ticket(models.Model): owner = #this most be related to the user that buy the ticket lottery_id = #this most be related to the id of the lottery ticket_id = #a random number </code></pre> <p>Now I have two problems that I can't figure out.</p> <p>The first one is how to create the number of tickets related on the Lottery max_players, the max_players will be a number of the maximum players/tickets available.</p> <p>The second question is there a option to see all the available tickets in a list on the admin page of the lotteries?, and if yes, what is the way to do this.</p> <p>Thanks for any help. Have a nice day.</p>
0
2016-08-05T14:15:52Z
38,793,136
<p>First of all I am not sure if your owner field would work. I don't see any imports for auth package</p> <pre><code>owner = models.ForeignKey('auth.User') </code></pre> <p>Firstly I would suggest you look at this <a href="http://stackoverflow.com/questions/19433630/how-to-use-user-as-foreign-key-in-django-1-5">post</a> for changing that relation. </p> <p>Both of your questions need a little bit more clarity regarding what you actually what to achieve. It would be helpful if the Ticket model is also completed. </p> <p>For the given information its hard to say if that is possible looking there is no relation between both the models. </p> <pre><code>class Ticket(models.Model): # This is not required unless you want it for some reason, you can use # this owner from the lotter_id owner = #this most be related to the user that buy the ticket lottery_id = models.ForiegnKey(Lottery) ticket_id = #a random number def __str__(self): return self.lottery_id, function_that_return_max_tickets() </code></pre> <p>Using the above relation you can write custom functions in the <a href="https://docs.djangoproject.com/en/1.10/topics/db/managers/" rel="nofollow">ModelManager</a>, according to your requirement. </p> <p>Read through the Mangers that Django provides, these can be used to write those functions which would calculate the max number of tickets and return if you like to use them in views.py using ORM. </p>
0
2016-08-05T15:44:04Z
[ "python", "django" ]
Issue handling file from command line with biopython SeqIO
38,791,527
<p>This is my first attempt at using commandline args other than the quick and dirty <code>sys.argv[]</code> and writing a more 'proper' python script. For some reason that I can now not figure out, it seems to be objecting to how I'm trying to use the input file from the command line.</p> <p>The script is meant to take an input file, some numerical indices, and then slice out a subset region of the file, however I keep getting errors that the variable I've given to the file I'm passing in is not defined:</p> <pre><code>joehealey@7c-d1-c3-89-86-2c:~/Documents/Warwick/PhD/Scripts$ python slice_genbank.py --input PAU_06042014.gbk -o test.gbk -s 3907329 -e 3934427 Traceback (most recent call last): File "slice_genbank.py", line 70, in &lt;module&gt; sub_record = record[start:end] NameError: name 'record' is not defined </code></pre> <p>Here's the code, where am I going wrong? (I'm sure its simple):</p> <pre><code>#!/usr/bin/python # This script is designed to take a genbank file and 'slice out'/'subset' # regions (genes/operons etc.) and produce a separate file. # Based upon the tutorial at http://biopython.org/DIST/docs/tutorial/Tutorial.html#htoc44 # Set up and handle arguments: from Bio import SeqIO import getopt def main(argv): record = '' start = '' end = '' try: opts, args = getopt.getopt(argv, 'hi:o:s:e:', [ 'help', 'input=', 'outfile=', 'start=', 'end=' ] ) if not opts: print "No options supplied. Aborting." usage() sys.exit(2) except getopt.GetoptError: print "Some issue with commandline args.\n" usage() sys.exit(2) for opt, arg in opts: if opt in ("-h", "--help"): usage() sys.exit(2) elif opt in ("-i", "--input"): filename = arg record = SeqIO.read(arg, "genbank") elif opt in ("-o", "--outfile"): outfile = arg elif opt in ("-s", "--start"): start = arg elif opt in ("-e", "--end"): end = arg print("Slicing " + filename + " from " + str(start) + " to " + str(end)) def usage(): print( """ This script 'slices' entries such as genes or operons out of a genbank, subsetting them as their own file. Usage: python slice_genbank.py -h|--help -i|--input &lt;genbank&gt; -o|--output &lt;genbank&gt; -s|--start &lt;int&gt; -e|--end &lt;int&gt;" Options: -h|--help Displays this usage message. No options will also do this. -i|--input The genbank file you which to subset a record from. -o|--outfile The file name you wish to give to the new sliced genbank. -s|--start An integer base index to slice the record from. -e|--end An integer base index to slice the record to. """ ) #Do the slicing sub_record = record[start:end] SeqIO.write(sub_record, outfile, "genbank") if __name__ == "__main__": main(sys.argv[1:]) </code></pre> <p>It's also possible there's an issue with the SeqIO.write syntax, but I haven't got as far as that yet.</p> <p>EDIT:</p> <p>Also forgot to mention that when I use `record = SeqIO.read("file.gbk", "genbank") and write the file name directly in to the script, it works correctly.</p>
0
2016-08-05T14:20:09Z
38,795,962
<p>As said in the comments, your variable <code>records</code> is only defined in the method <code>main()</code> (the same is true for <code>start</code> and <code>end</code>), thus it is not visible for the rest of the program. You can either return the values like this:</p> <pre><code>def main(argv): ... ... return record, start, end </code></pre> <p>Your call to <code>main()</code> can then look like this:</p> <pre><code>record, start, end = main(sys.argv[1:]) </code></pre> <p>Alternatively, you can move your main functionality into the <code>main</code> function (as you did).</p> <p>(Another way is to define the variables in the main program and the use the <code>global</code> keyword in your function, this is, however, not recommended.)</p>
1
2016-08-05T18:47:28Z
[ "python", "biopython", "getopt" ]
Finding the no. of digits of each element in the list
38,791,724
<p>I tried the following code but it is giving me an error.How should i fix this problem?.</p> <pre><code>import math mylist=[3,4,12,34] digits = int(math.log10(mylist))+1 Traceback (most recent call last): File "prog.py", line 3, in &lt;module&gt; TypeError: a float is required </code></pre>
0
2016-08-05T14:30:05Z
38,791,889
<p>You are passing a list to <code>log10()</code> function, and that's while it accepts a float. You can use a list comprehension to calculate the log for all items within the list:</p> <pre><code>&gt;&gt;&gt; digits = [int(math.log10(i)) + 1 for i in mylist] &gt;&gt;&gt; digits [1, 1, 2, 2] </code></pre>
0
2016-08-05T14:38:13Z
[ "python", "python-3.x", "math" ]
Finding the no. of digits of each element in the list
38,791,724
<p>I tried the following code but it is giving me an error.How should i fix this problem?.</p> <pre><code>import math mylist=[3,4,12,34] digits = int(math.log10(mylist))+1 Traceback (most recent call last): File "prog.py", line 3, in &lt;module&gt; TypeError: a float is required </code></pre>
0
2016-08-05T14:30:05Z
38,792,020
<p>This will return a list containing the number of digits of each element in <code>my_list</code>.</p> <pre><code>from math import log10 my_list = [3, 4, 12, 34] digits = [int(log10(n) + 1) for n in my_list] </code></pre>
0
2016-08-05T14:44:55Z
[ "python", "python-3.x", "math" ]
Finding the no. of digits of each element in the list
38,791,724
<p>I tried the following code but it is giving me an error.How should i fix this problem?.</p> <pre><code>import math mylist=[3,4,12,34] digits = int(math.log10(mylist))+1 Traceback (most recent call last): File "prog.py", line 3, in &lt;module&gt; TypeError: a float is required </code></pre>
0
2016-08-05T14:30:05Z
38,985,785
<p>Here's a working example:</p> <pre><code>import math def f(x): return int(math.log10(x)) + 1 mylist = [3, 4, 12, 34] digits = [] for x in mylist: fx = f(x) print("f({0})={1}".format(x, fx)) digits.append(fx) </code></pre>
0
2016-08-16T23:06:54Z
[ "python", "python-3.x", "math" ]
Double tap in IOS Simulator Not working
38,791,731
<p>I am trying to <code>double tap</code> an element in IOS Simulator using appium but unable to do so.</p> <pre><code>Methods tried: action.tap(x=xx, y=yy, count=1).release().perform() </code></pre> <p>2 times in a row,but it seems there is a 2 second gap which in real world would not be a double tap</p> <pre><code>element.click </code></pre> <p>same problem as above</p> <pre><code>action.press(x=xx, y=yy).wait(500).release().perform().press(x=0, y=0).wait(500).perform() </code></pre> <p>no result</p> <pre><code>action.tap(x=xx, y=yy, count=2).release().perform() </code></pre> <p>no result.</p> <p>Is there any thing else i can try or any other method which works on <code>ios</code>.</p>
3
2016-08-05T14:30:34Z
38,791,844
<p>You should do both of the press commands before calling <code>perform()</code>:</p> <pre><code>action.press(x=xx, y=yy).release().wait(500).press(x=xx, y=yy).release().perform() </code></pre>
1
2016-08-05T14:36:17Z
[ "python", "appium", "appium-ios", "python-appium" ]
Double tap in IOS Simulator Not working
38,791,731
<p>I am trying to <code>double tap</code> an element in IOS Simulator using appium but unable to do so.</p> <pre><code>Methods tried: action.tap(x=xx, y=yy, count=1).release().perform() </code></pre> <p>2 times in a row,but it seems there is a 2 second gap which in real world would not be a double tap</p> <pre><code>element.click </code></pre> <p>same problem as above</p> <pre><code>action.press(x=xx, y=yy).wait(500).release().perform().press(x=0, y=0).wait(500).perform() </code></pre> <p>no result</p> <pre><code>action.tap(x=xx, y=yy, count=2).release().perform() </code></pre> <p>no result.</p> <p>Is there any thing else i can try or any other method which works on <code>ios</code>.</p>
3
2016-08-05T14:30:34Z
38,857,992
<p>I call it in a similar way the first method you listed, its not as fast as double tap, but its less than one second delay <code>Appium::TouchAction.new.tap(x: xx, y: yy, count: 2).perform</code> </p> <p><code>.tap</code> dont need to use <code>release</code>, only <code>.press</code> need it</p>
1
2016-08-09T18:30:40Z
[ "python", "appium", "appium-ios", "python-appium" ]
Function annotation for subclasses of abstract class
38,791,739
<p>I'm trying to use function annotations in the hope that my editor will be better at refactoring. I however am stumbling over the following problem:</p> <p>I have an abstract base class Algorithm.</p> <pre><code>class Algorithm(metaclass=ABCMeta): def __init__(self): self.foo = 'bar' </code></pre> <p>I also have a function that uses instances of subclasses of Algorithm</p> <pre><code>def get_foo(foo_algorithm): return foo_algoritm.foo </code></pre> <p>the input foo_algorithm can be an instance of any of the subclasses of Algorithm. How do I sensibly annotate this input? I'm looking for something along the lines off:</p> <pre><code>def get_foo(foo_algorithm: subclassof(Algorithm)): return foo_algoritm.foo </code></pre> <p>But I couldn't find the right way to do this.</p>
0
2016-08-05T14:30:58Z
38,791,784
<p>Just use <code>Algorithm</code> directly:</p> <pre><code>def get_foo(foo_algorithm: Algorithm): return foo_algoritm.foo </code></pre> <p>and automatically any instance of a subclass will be acceptable (<code>isinstance(foo_algorithm, Algorithm)</code> must be true, which applies to all subclasses of a baseclass).</p> <p>If you can only accept <strong>classes</strong>, then use <code>Type[Algorithm]</code> as the type hint:</p> <pre><code>def get_foo(foo_algorithm: Type[Algorithm]): return foo_algoritm().foo </code></pre> <p>See the <a href="https://www.python.org/dev/peps/pep-0484/#the-type-of-class-objects" rel="nofollow"><em>The type of class objects</em> section</a> of PEP 484 -- <em>Type Hints</em>:</p> <blockquote> <p>Sometimes you want to talk about class objects, in particular class objects that inherit from a given class. This can be spelled as <code>Type[C]</code> where <code>C</code> is a class. To clarify: while <code>C</code> (when used as an annotation) refers to instances of class <code>C</code>, <code>Type[C]</code> refers to subclasses of <code>C</code>. </p> </blockquote> <p>Here I <em>called</em> the class object, since <code>.foo</code> is an instance attribute according to your code example; a class derived from <code>Algorithm</code> would not have such an attribute itself.</p>
1
2016-08-05T14:33:21Z
[ "python", "python-3.x", "annotations", "type-hinting" ]
Sublime Text 3 - Language specific Goto definition Keyboard Shortcut
38,791,826
<p>How can I set "Goto Definition" work according to the language I'm working on.</p> <p>For example:</p> <p>In Python I want to use PythonIDE's go to definition:</p> <pre><code>{ "keys": ["ctrl+d"], "command": "python_goto_definition" }, </code></pre> <p>And, for any other language, for instance Go, I want to use GoSublime's go to definition:</p> <pre><code>{ "keys": ["ctrl+d"], "command": "go_sublime_goto_definition" }, </code></pre> <p>I'm wondering how can I set the context?</p>
1
2016-08-05T14:35:22Z
38,796,045
<p>The context that you want is for <code>selector</code>:</p> <pre><code>{ "keys": ["ctrl+d"], "command": "python_goto_definition", "context": [ { "key": "selector", "operator": "equal", "operand": "source.python" } ] }, </code></pre> <p>You can add more or less specificity as needed. Use <kbd>Ctrl+Shift+Alt+P</kbd> or <kbd>Shift+Ctrl+P</kbd> (MacOS) to view the scope selector for the current position.</p>
1
2016-08-05T18:53:33Z
[ "python", "go", "sublimetext3" ]
Django ModelAdmin: update field without saving
38,791,857
<p>I have an admin page that looks like this: </p> <pre><code>class NameAdmin(admin.ModelAdmin): list_display = ['long_name', 'short_name'] search_fields = ['long_name','short_name'] </code></pre> <p>In my admin page I have created a button (it is called "getname"), which after being pressed, should update the short_name field (if it's empty, otherwise leave it). However, the inserted text SHOULD NOT be saved to the database, only shown. </p> <p>If the user agrees with the text, only then should he press "Save" and then it should be saved to the database. </p> <p>the save_model method does of course not work, as it saves it to the database. </p> <pre><code>def save_model(self, request, obj, form, change): if 'getshortname' in request.POST: if not obj.short_name: obj.short_name = model_support.parse_shortname(obj.long_name) </code></pre> <p>Any ideas?</p> <p>Many thanks</p>
-1
2016-08-05T14:36:57Z
38,793,540
<p>I would create a form in forms.py:</p> <pre><code>from django import forms from myapp.models import MyModel class MyModelForm(forms.ModelForm): update_me = forms.CharField(max_length=100, required=False) class Meta(Object): model = MyModel </code></pre> <p>Then in admin.py:</p> <pre><code>from django.contrib import admin from myapp.forms import MyModelForm class MyModelAdmin(admin.ModelAdmin): form = MyModelForm admin.site.register(MyModel, MyModelAdmin) </code></pre> <p>This way, you have a field in the model that will not be saved to the database, is not required, you can update it and using the <code>save_model</code> method you can pass the value to the relevant field of your model in order to be saved to the database.</p>
0
2016-08-05T16:05:42Z
[ "python", "django", "modeladmin" ]
How to control number of cores and processors in Python when we need to share state between processes
38,791,898
<p>In <a href="https://docs.python.org/2/library/multiprocessing.html#sharing-state-between-processes" rel="nofollow">document</a>, an example is shown about how to share state between processes. For the sake of time, I post the code in the document below.</p> <pre><code>from multiprocessing import Process, Value, Array def f(n, a): n.value = 3.1415927 for i in range(len(a)): a[i] = -a[i] if __name__ == '__main__': num = Value('d', 0.0) arr = Array('i', range(10)) p = Process(target=f, args=(num, arr)) p.start() p.join() print num.value print arr[:] </code></pre> <p>I am writing codes on a Linux supercomputing system, where I am allowed to assign a fixed number of cores and a number of cores per node. So how can I write a code to assign workers in this frame? Will Python make full use of cores automatically? And what is a correct way to assign parameters in order to make good use of competing resource in this frame?</p>
0
2016-08-05T14:38:38Z
38,792,458
<p>A possible answer:</p> <pre><code>from multiprocessing import Process, Value, Array, Pool import random def f(n, a): n.value = 3.1415927 a[random.randint(5)] = 0 if __name__ == '__main__': num = Value('d', 0.0) arr = Array('i', range(10)) # you can manually set the number of workers workers = 5 # or, if you want to use all cores, # use the maximum number of existing cores to set workers # workers = cpu_count() p = Pool(workers) results = p.map(f, (num, arr)) print num.value print arr[:] </code></pre> <p>In the code above, the print statements at the end should print <code>3.1415927</code> and <code>[0,0,0,0,0,6,7,8,9]</code>.</p> <p>If you want to use Process, you have to manually setup and manage the start and end of each process:</p> <pre><code>from multiprocessing import Process, Value, Array, Pool import random def f(n, a): n.value = 3.1415927 a[random.randint(5)] = 0 if __name__ == '__main__': num = Value('d', 0.0) arr = Array('i', range(10)) # if you want to use all cores, # use the maximum number of existing cores to set workers workers = cpu_count() prcs = [Process(target=f, args=(num, arr)).start() for i in range(workers)] results = [i.join() for i in prcs] print num.value print arr[:] </code></pre>
0
2016-08-05T15:06:22Z
[ "python", "linux", "python-multiprocessing" ]
How can I count a word from all lines that are 2 rows after a specific line?
38,791,960
<p>So, this might sound a bit confusing, I'll try to explain it. For example from these lines:</p> <pre><code>next line 1 ^^^^^^^^^^^^^^^^^^ red blue dark ten lemon next line 2 ^^^^^^^^^^^^^^^^^^^ hat 45 no dad fate orange next line 3 ^^^^^^^^^^^^^^^^^^^ tan rat lovely lemon eat you him lemon Daniel her" </code></pre> <p>I am only interested in the count of "lemon" from lines that have "next line" two lines above it. So, the output I expect is "2 lemons". </p> <p>Any help will be greatly appreciated! </p> <p>My attempt so far is:</p> <pre><code>#!/usr/bin/env python #import the numpy library import numpy as np lemon = 0 logfile = open('file','r') for line in logfile: words = line.split() words = np.array(words) if np.any(words == 'next line'): if np.any(words == 'lemon'): lemon +=1 print "Total number of lemons is %d" % (lemon) </code></pre> <p>but this counts "lemon" only if it's on the same line as "next line".</p>
2
2016-08-05T14:41:40Z
38,792,153
<p>For each line you need to be able to access to two line before it. For that aim you can use <code>itertools.tee</code> in order to create two independent file object (which are iterator-like objects) then use <code>itertools.izip()</code> in order to create your your expected pairs:</p> <pre><code>from itertools import tee, izip with open('file') as logfile: spam, logfile = tee(logfile) # consume first two line of spam next(spam) next(spam) for pre, line in izip(logfile, spam): if 'next line' in pre: print line.count('lemon') </code></pre> <p>Or if you just want to count the lines you can use a generator expression within <code>sum()</code>:</p> <pre><code>from itertools import tee, izip with open('file') as logfile: spam, logfile = tee(logfile) # consume first two lines of spam next(spam) next(spam) print sum(line.count('lemon') for pre, line in izip(logfile, spam) if 'next line' in pre) </code></pre>
3
2016-08-05T14:51:10Z
[ "python" ]
How can I count a word from all lines that are 2 rows after a specific line?
38,791,960
<p>So, this might sound a bit confusing, I'll try to explain it. For example from these lines:</p> <pre><code>next line 1 ^^^^^^^^^^^^^^^^^^ red blue dark ten lemon next line 2 ^^^^^^^^^^^^^^^^^^^ hat 45 no dad fate orange next line 3 ^^^^^^^^^^^^^^^^^^^ tan rat lovely lemon eat you him lemon Daniel her" </code></pre> <p>I am only interested in the count of "lemon" from lines that have "next line" two lines above it. So, the output I expect is "2 lemons". </p> <p>Any help will be greatly appreciated! </p> <p>My attempt so far is:</p> <pre><code>#!/usr/bin/env python #import the numpy library import numpy as np lemon = 0 logfile = open('file','r') for line in logfile: words = line.split() words = np.array(words) if np.any(words == 'next line'): if np.any(words == 'lemon'): lemon +=1 print "Total number of lemons is %d" % (lemon) </code></pre> <p>but this counts "lemon" only if it's on the same line as "next line".</p>
2
2016-08-05T14:41:40Z
38,792,688
<p>You can just loop over the file (which is an iterator) and call <code>next</code> two times whenever you find a <code>next line</code> line, then <code>count</code> how often <code>lemon</code> appears, with both the <code>for</code> loop and the calls to <code>next</code> are using the same iterator.</p> <pre><code>with open("data.txt") as f: lemon_count = 0 for line in f: if "next line" in line: next(f) # skip next line lemon_count += next(f).count("lemon") # get count for next-next line </code></pre> <p>For your example, <code>lemon_count</code> ends up as <code>2</code>. That is assuming that there is no other <code>next</code> line in between a <code>next</code> line and the <code>lemon</code> line, or that the <code>lemon</code> line itself is a <code>next</code> line.</p>
1
2016-08-05T15:18:02Z
[ "python" ]
Insert statement at row where MyCol is x
38,792,008
<p>I have 2 columns MyCol and NewCol. MyCol has already been populated, and may have duplicates (it's not the primary key). I need to insert a value y into NewCol at all rows where MyCol = x. I'm stuck here and not sure how to implement this.</p>
0
2016-08-05T14:44:24Z
38,792,680
<p>This is just an update statement</p> <pre><code>UPDATE TABLENAME SET NewCol = Y WHERE MyCol = x </code></pre> <p>Why exactly could you not find this in ANY introduction to SQL - book, article, reference, team-mate etc?</p>
1
2016-08-05T15:17:52Z
[ "python", "sql", "python-2.7", "sqlite3" ]
Unable to install Statsmodels...python
38,792,043
<p>I am using 32 bit cmd, 64 bit windows, python 2.7</p> <p>when I type the command pip install statsmodels</p> <p>I get the following error for some module of scipy...</p> <pre><code>Failed building wheel for Scipy Failed cleaning build dir for scipy </code></pre> <p><a href="http://i.stack.imgur.com/xcF7d.png" rel="nofollow"><img src="http://i.stack.imgur.com/xcF7d.png" alt="enter image description here"></a></p>
0
2016-08-05T14:46:07Z
38,792,465
<p>An easier way to install python libraries on Windows with C/C++/Fortran/... dependencies is to use <code>conda</code>. <code>conda</code> is available in <a href="http://conda.pydata.org/miniconda.html" rel="nofollow">MiniConda</a> or <a href="https://www.continuum.io/downloads#_windows" rel="nofollow">Anaconda</a> continuum products.</p> <p>Another easy way to install scientific python libraries on windows is to use <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">Christoph Gohlke's windows web page</a>.</p> <p>If you have no much idea about all of them and how to manage dependencies on windows I recommend you uninstalling your Python and installing anaconda. Anaconda already has Numpy, Scipy, Matplotlib,..., and statsmodels <a href="https://docs.continuum.io/anaconda/pkg-docs" rel="nofollow">pre-installed (see the list of the packages included in the anaconda distribution)</a>.</p>
3
2016-08-05T15:06:32Z
[ "python", "python-2.7", "scipy", "pip", "statsmodels" ]
Unable to install Statsmodels...python
38,792,043
<p>I am using 32 bit cmd, 64 bit windows, python 2.7</p> <p>when I type the command pip install statsmodels</p> <p>I get the following error for some module of scipy...</p> <pre><code>Failed building wheel for Scipy Failed cleaning build dir for scipy </code></pre> <p><a href="http://i.stack.imgur.com/xcF7d.png" rel="nofollow"><img src="http://i.stack.imgur.com/xcF7d.png" alt="enter image description here"></a></p>
0
2016-08-05T14:46:07Z
38,792,924
<p>install numpy</p> <pre><code>pip install numpy </code></pre> <p>If you face installation issues for numpy, get the pre-built windows installers from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a> for your python version (python version is different from windows version).</p> <p>numpy 32-bit: numpy-1.11.1+mkl-cp27-cp27m-win32.whl </p> <p>numpy 64-bit: numpy-1.11.1+mkl-cp27-cp27m-win_amd64.whl</p> <p>Later you require VC++ 9.0, then please get it from below link Microsoft Visual C++ 9.0 is required. Get it from <a href="http://aka.ms/vcpython27" rel="nofollow">http://aka.ms/vcpython27</a></p> <p>Then install</p> <p>Get the pre-built windows installers from <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="nofollow">http://www.lfd.uci.edu/~gohlke/pythonlibs/</a> for your python version (python version is different from windows version).</p> <p>Scipy 32-bit: scipy-0.18.0-cp27-cp27m-win32.whl</p> <p>Scipy 64-bit: scipy-0.18.0-cp27-cp27m-win_amd64.whl</p> <p>If it fails saying whl is not supported wheel on this platform , then upgrade pip using <code>python -m pip install --upgrade pip</code> and try installing scipy</p> <p>Now try</p> <pre><code>pip insatll scipy </code></pre> <p>Then try</p> <pre><code>pip install statsmodels </code></pre> <p>It should work like a charm</p>
1
2016-08-05T15:31:56Z
[ "python", "python-2.7", "scipy", "pip", "statsmodels" ]
How would you create two select menus where select menu B's contents are dependent on select menu A's selection?
38,792,077
<p>How do you create two select menus with one dict where select menu B has values that correspond and are dependent to the keys present in select menu A?</p> <p>In my Django views.py, I've created a dictionary that has a lists of Projects as keys, and corresponding Tasks as values within the dictionary. It looks like the following</p> <p>Project A: Task 1</p> <p>Project A: Task 2</p> <p>Project A: Task 3</p> <p>Project B: Task 1</p> <p>Project B: Task 2</p> <p>Project C: Task 1</p> <p>etc</p> <p>I've been able to successfully pass this information into my Django template, but I can't wrap my head around how I can do what I need to do with the information. </p> <p>I need to be able to take the information in the keys, ie the Projects, and create a drop down menu (A) which, when a key is selected, will display all of the corresponding tasks for the key in a second drop down menu (B)</p> <p>I'm up to any kind of solution. I'm thinking about using jquery and hacking something together, but I'm really at a loss as to how to begin. Does anyone have experience with something like this? </p>
2
2016-08-05T14:47:42Z
38,792,191
<p>You can use <a href="http://django-autocomplete-light.readthedocs.io/en/master/" rel="nofollow"><code>django-autocomplete-light</code></a> to do this. This basically provides autocompletion using a client library such as <a href="https://select2.github.io/" rel="nofollow"><code>select2</code></a>. But it also provides a way to <a href="http://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#filtering-results-based-on-the-value-of-other-fields-in-the-form" rel="nofollow">filter results based on another field</a>.</p> <p>You should likely also make a server verification in the form clean:</p> <pre><code>class MyForm(forms.Form): project = forms.ModelChoiceField(queryset=Project.objects.all()) task = forms.Model.ChoicField(queryset=Task.objects.all()) def clean(self): project = self.cleaned_data['project'] task = self.cleaned_data['task'] if task.project_id != project.pk: raise forms.ValidationError( "The selected task does not belong to the selected project.") </code></pre>
2
2016-08-05T14:53:13Z
[ "jquery", "python", "html", "css", "django" ]
How to change color of subtext in the Text widget (Python)
38,792,094
<p>Is there a way to change the color of specific text in the Text widget in Tkinter?</p> <p>Any answer will be welcomed.</p>
-1
2016-08-05T14:48:53Z
38,809,280
<p>The Library manual has a tkinter chapter that lists some online and paper materials. I mostly use the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html" rel="nofollow">NMT reference</a>. See its Text widget sections and in particular the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text-methods.html" rel="nofollow">text methods</a> section.</p> <p>Tags are the specific answer to your question. You can tag a slice of text with a string either when inserting or later (tag_add method). A slice can get multiple tags. A tag can be applied to multiple slices. One can customize 19 options for a given tag with the tag_config method. Color is just one of them, but perhaps the most common. It is used by syntax coloring. Minimal example:</p> <pre><code>from tkinter import Tk, Text root = Tk() text = Text(root) text.pack() text.insert('insert', 'normal text') text.insert('insert', ' red text', 'RED') text.tag_config('RED', foreground='red') root.mainloop() </code></pre>
1
2016-08-06T22:25:47Z
[ "python", "tkinter" ]
How to group and count rows by month and year using Pandas?
38,792,122
<p>I have a dataset with personal data such as name, height, weight and date of birth. I would build a graph with the number of people born in a particular month and year. I'm using python pandas to accomplish this and my strategy was to try to group by year and month and add using count. But the closest I got is to get the count of people by year or by month but not by both.</p> <pre><code>df['birthdate'].groupby(df.birthdate.dt.year).agg('count') </code></pre> <p>Other questions in stackoverflow point to a Grouper called TimeGrouper but searching in pandas documentation found nothing. Any idea?</p>
2
2016-08-05T14:49:47Z
38,792,175
<p>To group on multiple criteria, pass a list of the columns or criteria:</p> <pre><code>df['birthdate'].groupby([df.birthdate.dt.year, df.birthdate.dt.month]).agg('count') </code></pre> <p>Example:</p> <pre><code>In [165]: df = pd.DataFrame({'birthdate':pd.date_range(start=dt.datetime(2015,12,20),end=dt.datetime(2016,3,1))}) df.groupby([df['birthdate'].dt.year, df['birthdate'].dt.month]).agg({'count'}) Out[165]: birthdate count birthdate birthdate 2015 12 12 2016 1 31 2 29 3 1 </code></pre>
3
2016-08-05T14:52:27Z
[ "python", "pandas" ]
How to group and count rows by month and year using Pandas?
38,792,122
<p>I have a dataset with personal data such as name, height, weight and date of birth. I would build a graph with the number of people born in a particular month and year. I'm using python pandas to accomplish this and my strategy was to try to group by year and month and add using count. But the closest I got is to get the count of people by year or by month but not by both.</p> <pre><code>df['birthdate'].groupby(df.birthdate.dt.year).agg('count') </code></pre> <p>Other questions in stackoverflow point to a Grouper called TimeGrouper but searching in pandas documentation found nothing. Any idea?</p>
2
2016-08-05T14:49:47Z
38,792,452
<p>Another solution is to set <code>birthdate</code> as the index and resample:</p> <pre><code>import pandas as pd df = pd.DataFrame({'birthdate': pd.date_range(start='20-12-2015', end='3-1-2016')}) df.set_index('birthdate').resample('MS').size() </code></pre> <p>Output:</p> <pre class="lang-none prettyprint-override"><code>birthdate 2015-12-01 12 2016-01-01 31 2016-02-01 29 2016-03-01 1 Freq: MS, dtype: int64 </code></pre>
3
2016-08-05T15:06:04Z
[ "python", "pandas" ]
How to use dateutil.relativedelta in Python 3.x?
38,792,126
<p>Hello I am trying to use <code>relativedelta</code> from the <code>dateutil</code> module.</p> <p>I want to do what is mentioned <a href="http://stackoverflow.com/questions/4130922/how-to-increment-datetime-by-custom-months-in-python-without-using-library">here</a>, add some months to a given <code>datetime</code> object.</p> <p>But I'm trying to use Python 3 for this and I am getting the following error:</p> <pre><code>Traceback (most recent call last): File "bin/controller.py", line 2, in &lt;module&gt; from dateutil.relativedelta import relativedelta ImportError: No module named 'dateutil' </code></pre> <p>I then read that dateutil is now part of Python 3 but how do I import it? <code>import dateutil</code> does not seem to work:</p> <pre><code>Traceback (most recent call last): File "bin/controller.py", line 3, in &lt;module&gt; import dateutil ImportError: No module named 'dateutil' </code></pre> <p>I am using a virtualenv so I would like to install it with <code>pip</code>.</p>
0
2016-08-05T14:49:57Z
38,792,339
<p>It seems you have to pip-install it like this and it works :</p> <pre><code>pip install python-dateutil </code></pre>
1
2016-08-05T15:00:37Z
[ "python", "python-3.x", "datetime", "python-dateutil" ]
How to use dateutil.relativedelta in Python 3.x?
38,792,126
<p>Hello I am trying to use <code>relativedelta</code> from the <code>dateutil</code> module.</p> <p>I want to do what is mentioned <a href="http://stackoverflow.com/questions/4130922/how-to-increment-datetime-by-custom-months-in-python-without-using-library">here</a>, add some months to a given <code>datetime</code> object.</p> <p>But I'm trying to use Python 3 for this and I am getting the following error:</p> <pre><code>Traceback (most recent call last): File "bin/controller.py", line 2, in &lt;module&gt; from dateutil.relativedelta import relativedelta ImportError: No module named 'dateutil' </code></pre> <p>I then read that dateutil is now part of Python 3 but how do I import it? <code>import dateutil</code> does not seem to work:</p> <pre><code>Traceback (most recent call last): File "bin/controller.py", line 3, in &lt;module&gt; import dateutil ImportError: No module named 'dateutil' </code></pre> <p>I am using a virtualenv so I would like to install it with <code>pip</code>.</p>
0
2016-08-05T14:49:57Z
38,792,343
<p>You need to install it first using <code>pip3 install python-dateutil</code>. It's not included by default with Python 3, I don't know where you read that.</p> <p>I added a <code>pip3</code> and not just plain old <code>pip</code> because that will install it specifically for Python 3.</p>
2
2016-08-05T15:00:43Z
[ "python", "python-3.x", "datetime", "python-dateutil" ]
How to use dateutil.relativedelta in Python 3.x?
38,792,126
<p>Hello I am trying to use <code>relativedelta</code> from the <code>dateutil</code> module.</p> <p>I want to do what is mentioned <a href="http://stackoverflow.com/questions/4130922/how-to-increment-datetime-by-custom-months-in-python-without-using-library">here</a>, add some months to a given <code>datetime</code> object.</p> <p>But I'm trying to use Python 3 for this and I am getting the following error:</p> <pre><code>Traceback (most recent call last): File "bin/controller.py", line 2, in &lt;module&gt; from dateutil.relativedelta import relativedelta ImportError: No module named 'dateutil' </code></pre> <p>I then read that dateutil is now part of Python 3 but how do I import it? <code>import dateutil</code> does not seem to work:</p> <pre><code>Traceback (most recent call last): File "bin/controller.py", line 3, in &lt;module&gt; import dateutil ImportError: No module named 'dateutil' </code></pre> <p>I am using a virtualenv so I would like to install it with <code>pip</code>.</p>
0
2016-08-05T14:49:57Z
38,792,344
<p>Open up your console and type: <code>pip install python-dateutil</code></p>
1
2016-08-05T15:00:45Z
[ "python", "python-3.x", "datetime", "python-dateutil" ]
moving a sprite with a function in pygame
38,792,136
<p>i am spawning in an enemy using the spawn() class, and in the spawn(0 class, i am trying to use the function move() to move the enemy. when i run the program, the zombie spawns, but doesnt move.</p> <p>Below is the entire code if anybody was wondering. I am only having problems with the spawn() class and nothing else.</p> <pre><code>import pygame import time import random import math from pygame.locals import * pygame.init() ################################################################################# red = (255,0,0) green = (0,255,0) blue = (0,0,255) black = (0,0,0) white = (255,255,255) grey = (125,125,125) ################################################################################# leng = 1200 wid = 600 FPS = 60 size = 30 clock = pygame.time.Clock() font = pygame.font.SysFont('calibri',20) def message(msg,colour,loc): screen_text = font.render(msg, True, colour) screen.blit(screen_text, loc) def rot_center(image, angle): orig_rect = image.get_rect() rot_image = pygame.transform.rotate(image, angle) rot_rect = orig_rect.copy() rot_rect.center = rot_image.get_rect().center rot_image = rot_image.subsurface(rot_rect).copy() return rot_image def quit(): pygame.quit() screen=pygame.display.set_mode((leng,wid),0,32) background = pygame.image.load("background.png") ################################################################################ def gameLoop(): class spawn: def __init__(self,x,y, px,py,angle): self.x=x self.y=y self.px = px self.py = py self.angle = angle self.i = pygame.image.load("zombie.png") self.i2 = rot_center(self.i, self.angle) if self.x &gt; self.px: self.x -= 2 if self.x &lt; self.px: self.x += 2 if self.y &gt; self.py: self.y -= 2 if self.y &lt; self.py: self.y += 2 def render(self): screen.blit(self.i2, (self.x,self.y)) x = leng/2 y = wid/2 player = pygame.image.load("player.png") x_change = 0 y_change = 0 spr = 50 spr_change = 0 u = 2 spru = u*1.5 zu = u cursor = pygame.image.load("cursor.gif") mouseX = 0 mouseY = 0 mouse_click = 0 mouse_rev = 0 mm = 0 mr = 0 points = 0 accuracy = 0 shots = 0 kills = 0 health = 10 boost = pygame.image.load("boost.png") boost_x = random.randint(0, leng-20) boost_y = random.randint(0, wid-20) gun = pygame.image.load("gun.png") bullet = pygame.image.load("bullet.png") bullet_x = random.randint(0, leng-20) bullet_y = random.randint(0, wid-20) ammo = 12 zombie = pygame.image.load("zombie.png") zombie_x = random.randint(0,leng-30) zombie_y = random.randint(0,wid-30) z_angle = 0 z_rect = 0 ################################################################################ apple = pygame.image.load("cubeberry.png") apple_x = random.randint(0, leng-20) apple_y = random.randint(0, wid-20) ################################################################################## while True: mouseX, mouseY = pygame.mouse.get_pos() mouse_click, mm, mr = pygame.mouse.get_pressed() angle = math.degrees(math.atan2(mouseX-x, mouseY-y))+90 z_angle = math.degrees(math.atan2(x-zombie_x, y-zombie_y))+90 for event in pygame.event.get(): if event.type == QUIT: quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: if event.key == pygame.K_SPACE and spr &gt; 0: u = spru spr_change -= 1 x_change = -u #y_change = 0 if x &lt; 0: x_change = u if event.key == pygame.K_d: if event.key == pygame.K_SPACE and spr &gt; 0: u = spru spr_change -= 1 x_change = u #y_change = 0 if x &gt; leng- size: x_change = -u if event.key == pygame.K_w: if event.key == pygame.K_SPACE and spr &gt; 0: u = spru spr_change -= 1 y_change = -u #x_change = 0 if y &lt; 0: y_change = u if event.key == pygame.K_s: if event.key == pygame.K_SPACE and spr &gt; 0: u = spru spr_change -= 1 y_change = u #x_change = 0 if y &gt; wid - size: y_change = -u if event.key == pygame.K_SPACE and spr &gt; 0: u = spru spr_change -= 1 if event.key == pygame.K_a and event.key == pygame.K_w: if x &lt; 0 and y &lt; 0: x_change = u y_change = u if event.key == pygame.K_a and event.key == pygame.K_s: if x &lt; 0 and y &gt; wid - size: x_change = u y_change = -u if event.key == pygame.K_d and event.key == pygame.K_w: if x &gt; leng-size and y &lt; 0: x_change = -u y_change = u if event.key == pygame.K_d and event.key == pygame.K_s: if x &gt; leng-size and y &gt; wid-size: x_change = -u y_change = -u if event.type == pygame.KEYUP: if event.key == pygame.K_a: x_change = 0 if event.key == pygame.K_d: x_change = 0 if event.key == pygame.K_w: y_change = 0 if event.key == pygame.K_s: y_change = 0 if event.key == pygame.K_SPACE: u = spru/2 spr_change = 0 ########################################################################################## if spr &lt;= 0 : spr_change = 0 if x &lt; 0: x_change = u x += x_change x_change = 0 if x &gt; leng-size: x_change = -u x += x_change x_change = 0 if y &lt; 0: y_change = u y += y_change y_change = 0 if y &gt; wid-size: y_change = -u y += y_change y_change = 0 x += x_change y += y_change spr += spr_change ############################################################################# if apple_x &lt;= x &lt;= apple_x + size and apple_y &lt;= y &lt;= apple_y + size: apple_x = random.randint(0, leng-20) apple_y = random.randint(0, wid-20) points += 100 health += 2 if x &lt;= apple_x &lt;= x + size and y &lt;= apple_y &lt;= y + size: apple_x = random.randint(0, leng-20) apple_y = random.randint(0, wid-20) points += 100 health += 2 ################################################################################ if bullet_x &lt;= x &lt;= bullet_x + size and bullet_y &lt;= y &lt;= bullet_y + size: bullet_x = random.randint(0, leng-20) bullet_y = random.randint(0, wid-20) points += 50 ammo += 4 if x &lt;= bullet_x &lt;= x + size and y &lt;= bullet_y &lt;= y + size: bullet_x = random.randint(0, leng-20) bullet_y = random.randint(0, wid-20) points += 50 ammo += 4 ################################################################################## if mouse_click == 1 and ammo &gt;0 and mouse_rev == 0: ammo -= 1 shots += 1 mouse_rev = 1 if mouse_click == 0: mouse_rev = 0 if mouse_rev == 1 and zombie_x &lt;= mouseX &lt;= zombie_x + size and zombie_y &lt;= mouseY &lt;= zombie_y+ size and ammo &gt;=0: zombie_x = random.randint(0, leng-20) zombie_y = random.randint(0, wid-20) mouse_rev = 1 kills += 1 points += 250 ################################################################################### if boost_x &lt;= x &lt;= boost_x + size and boost_y &lt;= y &lt;= boost_y + size: boost_x = random.randint(0, leng-20) boost_y = random.randint(0, wid-20) points += 50 spr += 20 if x &lt;= boost_x &lt;= x + size and y &lt;= boost_y &lt;= y + size: boost_x = random.randint(0, leng-20) boost_y = random.randint(0, wid-20) points += 50 spr += 20 ################################################################################ if x &lt;= zombie_x &lt;= x + size and y &lt;= zombie_y &lt;= y + size: points -= 5 health -= 0.1 if zombie_x &lt;= x &lt;= zombie_x + size and zombie_y &lt;= y &lt;= zombie_y + size: points -= 5 health -= 0.1 if not shots == 0: accuracy = 100 * float(kills)/float(shots) else: accuracy = 0 ################################################################################### #player = pygame.image.load("player.png") rect_player = rot_center(player, angle) gun = pygame.image.load("gun.png") gun = pygame.transform.rotate(gun, angle) #zombie = pygame.image.load("zombie.png") #z_rect = rot_center(zombie, z_angle) z1 = spawn(zombie_x, zombie_y,x,y,z_angle) ################################################################################## screen.blit(pygame.transform.scale(background,(leng,wid)),(0,0)) #pygame.display.flip() screen.blit(apple, (apple_x,apple_y)) screen.blit(rect_player, (x,y)) screen.blit(gun, (x+10,y)) screen.blit(boost, (boost_x,boost_y)) #screen.blit(z_rect, (zombie_x,zombie_y)) z1.render() screen.blit(bullet, (bullet_x,bullet_y)) screen.blit(cursor, (mouseX -42.5, mouseY - 42.5)) message("Points: "+str(points), red, [0,0]) message("Ammo: " +str(ammo), black, [0,20]) message("Sprint: " +str(spr), blue, [0,40]) message("Accuracy: " +str(int(accuracy)), red, [0, 60]) message("Health: " + str(int(health)), blue,[0,80]) #pygame.display.update() pygame.display.flip() clock.tick(FPS) gameLoop() </code></pre>
0
2016-08-05T14:50:22Z
38,792,271
<p>Instead of this <code>return zombie_x , zombie_y as self.x, self.y</code> why are you not writing this? <code>self.x,self.y = zombie_x,zombie_y</code></p> <p>Edit: As mentioned by ninMonkey, <code>move</code> is not a function of class <code>spawn</code>. Put it in the class and it should work.</p>
0
2016-08-05T14:56:58Z
[ "python", "python-2.7", "pygame" ]
moving a sprite with a function in pygame
38,792,136
<p>i am spawning in an enemy using the spawn() class, and in the spawn(0 class, i am trying to use the function move() to move the enemy. when i run the program, the zombie spawns, but doesnt move.</p> <p>Below is the entire code if anybody was wondering. I am only having problems with the spawn() class and nothing else.</p> <pre><code>import pygame import time import random import math from pygame.locals import * pygame.init() ################################################################################# red = (255,0,0) green = (0,255,0) blue = (0,0,255) black = (0,0,0) white = (255,255,255) grey = (125,125,125) ################################################################################# leng = 1200 wid = 600 FPS = 60 size = 30 clock = pygame.time.Clock() font = pygame.font.SysFont('calibri',20) def message(msg,colour,loc): screen_text = font.render(msg, True, colour) screen.blit(screen_text, loc) def rot_center(image, angle): orig_rect = image.get_rect() rot_image = pygame.transform.rotate(image, angle) rot_rect = orig_rect.copy() rot_rect.center = rot_image.get_rect().center rot_image = rot_image.subsurface(rot_rect).copy() return rot_image def quit(): pygame.quit() screen=pygame.display.set_mode((leng,wid),0,32) background = pygame.image.load("background.png") ################################################################################ def gameLoop(): class spawn: def __init__(self,x,y, px,py,angle): self.x=x self.y=y self.px = px self.py = py self.angle = angle self.i = pygame.image.load("zombie.png") self.i2 = rot_center(self.i, self.angle) if self.x &gt; self.px: self.x -= 2 if self.x &lt; self.px: self.x += 2 if self.y &gt; self.py: self.y -= 2 if self.y &lt; self.py: self.y += 2 def render(self): screen.blit(self.i2, (self.x,self.y)) x = leng/2 y = wid/2 player = pygame.image.load("player.png") x_change = 0 y_change = 0 spr = 50 spr_change = 0 u = 2 spru = u*1.5 zu = u cursor = pygame.image.load("cursor.gif") mouseX = 0 mouseY = 0 mouse_click = 0 mouse_rev = 0 mm = 0 mr = 0 points = 0 accuracy = 0 shots = 0 kills = 0 health = 10 boost = pygame.image.load("boost.png") boost_x = random.randint(0, leng-20) boost_y = random.randint(0, wid-20) gun = pygame.image.load("gun.png") bullet = pygame.image.load("bullet.png") bullet_x = random.randint(0, leng-20) bullet_y = random.randint(0, wid-20) ammo = 12 zombie = pygame.image.load("zombie.png") zombie_x = random.randint(0,leng-30) zombie_y = random.randint(0,wid-30) z_angle = 0 z_rect = 0 ################################################################################ apple = pygame.image.load("cubeberry.png") apple_x = random.randint(0, leng-20) apple_y = random.randint(0, wid-20) ################################################################################## while True: mouseX, mouseY = pygame.mouse.get_pos() mouse_click, mm, mr = pygame.mouse.get_pressed() angle = math.degrees(math.atan2(mouseX-x, mouseY-y))+90 z_angle = math.degrees(math.atan2(x-zombie_x, y-zombie_y))+90 for event in pygame.event.get(): if event.type == QUIT: quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_a: if event.key == pygame.K_SPACE and spr &gt; 0: u = spru spr_change -= 1 x_change = -u #y_change = 0 if x &lt; 0: x_change = u if event.key == pygame.K_d: if event.key == pygame.K_SPACE and spr &gt; 0: u = spru spr_change -= 1 x_change = u #y_change = 0 if x &gt; leng- size: x_change = -u if event.key == pygame.K_w: if event.key == pygame.K_SPACE and spr &gt; 0: u = spru spr_change -= 1 y_change = -u #x_change = 0 if y &lt; 0: y_change = u if event.key == pygame.K_s: if event.key == pygame.K_SPACE and spr &gt; 0: u = spru spr_change -= 1 y_change = u #x_change = 0 if y &gt; wid - size: y_change = -u if event.key == pygame.K_SPACE and spr &gt; 0: u = spru spr_change -= 1 if event.key == pygame.K_a and event.key == pygame.K_w: if x &lt; 0 and y &lt; 0: x_change = u y_change = u if event.key == pygame.K_a and event.key == pygame.K_s: if x &lt; 0 and y &gt; wid - size: x_change = u y_change = -u if event.key == pygame.K_d and event.key == pygame.K_w: if x &gt; leng-size and y &lt; 0: x_change = -u y_change = u if event.key == pygame.K_d and event.key == pygame.K_s: if x &gt; leng-size and y &gt; wid-size: x_change = -u y_change = -u if event.type == pygame.KEYUP: if event.key == pygame.K_a: x_change = 0 if event.key == pygame.K_d: x_change = 0 if event.key == pygame.K_w: y_change = 0 if event.key == pygame.K_s: y_change = 0 if event.key == pygame.K_SPACE: u = spru/2 spr_change = 0 ########################################################################################## if spr &lt;= 0 : spr_change = 0 if x &lt; 0: x_change = u x += x_change x_change = 0 if x &gt; leng-size: x_change = -u x += x_change x_change = 0 if y &lt; 0: y_change = u y += y_change y_change = 0 if y &gt; wid-size: y_change = -u y += y_change y_change = 0 x += x_change y += y_change spr += spr_change ############################################################################# if apple_x &lt;= x &lt;= apple_x + size and apple_y &lt;= y &lt;= apple_y + size: apple_x = random.randint(0, leng-20) apple_y = random.randint(0, wid-20) points += 100 health += 2 if x &lt;= apple_x &lt;= x + size and y &lt;= apple_y &lt;= y + size: apple_x = random.randint(0, leng-20) apple_y = random.randint(0, wid-20) points += 100 health += 2 ################################################################################ if bullet_x &lt;= x &lt;= bullet_x + size and bullet_y &lt;= y &lt;= bullet_y + size: bullet_x = random.randint(0, leng-20) bullet_y = random.randint(0, wid-20) points += 50 ammo += 4 if x &lt;= bullet_x &lt;= x + size and y &lt;= bullet_y &lt;= y + size: bullet_x = random.randint(0, leng-20) bullet_y = random.randint(0, wid-20) points += 50 ammo += 4 ################################################################################## if mouse_click == 1 and ammo &gt;0 and mouse_rev == 0: ammo -= 1 shots += 1 mouse_rev = 1 if mouse_click == 0: mouse_rev = 0 if mouse_rev == 1 and zombie_x &lt;= mouseX &lt;= zombie_x + size and zombie_y &lt;= mouseY &lt;= zombie_y+ size and ammo &gt;=0: zombie_x = random.randint(0, leng-20) zombie_y = random.randint(0, wid-20) mouse_rev = 1 kills += 1 points += 250 ################################################################################### if boost_x &lt;= x &lt;= boost_x + size and boost_y &lt;= y &lt;= boost_y + size: boost_x = random.randint(0, leng-20) boost_y = random.randint(0, wid-20) points += 50 spr += 20 if x &lt;= boost_x &lt;= x + size and y &lt;= boost_y &lt;= y + size: boost_x = random.randint(0, leng-20) boost_y = random.randint(0, wid-20) points += 50 spr += 20 ################################################################################ if x &lt;= zombie_x &lt;= x + size and y &lt;= zombie_y &lt;= y + size: points -= 5 health -= 0.1 if zombie_x &lt;= x &lt;= zombie_x + size and zombie_y &lt;= y &lt;= zombie_y + size: points -= 5 health -= 0.1 if not shots == 0: accuracy = 100 * float(kills)/float(shots) else: accuracy = 0 ################################################################################### #player = pygame.image.load("player.png") rect_player = rot_center(player, angle) gun = pygame.image.load("gun.png") gun = pygame.transform.rotate(gun, angle) #zombie = pygame.image.load("zombie.png") #z_rect = rot_center(zombie, z_angle) z1 = spawn(zombie_x, zombie_y,x,y,z_angle) ################################################################################## screen.blit(pygame.transform.scale(background,(leng,wid)),(0,0)) #pygame.display.flip() screen.blit(apple, (apple_x,apple_y)) screen.blit(rect_player, (x,y)) screen.blit(gun, (x+10,y)) screen.blit(boost, (boost_x,boost_y)) #screen.blit(z_rect, (zombie_x,zombie_y)) z1.render() screen.blit(bullet, (bullet_x,bullet_y)) screen.blit(cursor, (mouseX -42.5, mouseY - 42.5)) message("Points: "+str(points), red, [0,0]) message("Ammo: " +str(ammo), black, [0,20]) message("Sprint: " +str(spr), blue, [0,40]) message("Accuracy: " +str(int(accuracy)), red, [0, 60]) message("Health: " + str(int(health)), blue,[0,80]) #pygame.display.update() pygame.display.flip() clock.tick(FPS) gameLoop() </code></pre>
0
2016-08-05T14:50:22Z
38,799,329
<p>Your code was very hard to read and you should consider the following:</p> <h2>Divide your code in functions</h2> <p>As of right now, you have one function that contains almost 300 lines of code. Try divide up the code in small functions that does one thing only. Your first two functions are great! Maybe your event loop could go into one function and the rendering to another and so on.</p> <p>Not only are small functions easier to read, but they're very useful when you need to repeat similar code to what you've already written. If you have code that looks similar just put what's identical inside the body of the function and what differs as parameters to the function.</p> <h2>Use descriptive names</h2> <p>I've been looking at your code for over an hour and still don't know what <em>spr</em>, <em>spru</em>, <em>u</em>, <em>zu</em>, <em>mm</em> or <em>mr</em> means or what they're used for. Try using names that better describe what the variables are to make it easier for others to read your code. For example, <em>length</em> and <em>width</em> are better names then <em>leng</em> and <em>wid</em> because they say what they are. Don't try to shortened already short words!</p> <p>Also, make sure to start a name of a class with a capital letter. This helps programmers to identify what's a class and what's a function. So name your <em>spawn</em> to <em>Spawn</em> instead.</p> <p>Follow the <a href="https://www.python.org/dev/peps/pep-0008/#prescriptive-naming-conventions" rel="nofollow">conventions</a> to make it easier for other people to understand your code and better help you. Not only the naming conventions, but also things like putting space around operators etc.</p> <h2>Try using classes</h2> <p>Classes are like a collection of variables. This could be very useful to have instead of creating 4-5 variables that are related separately, and also makes it possible to reuse code! You're probably going to need classes if you want to create more zombies or apples, and it could improve readability.</p> <h2>To answer your question</h2> <p>Right now you're code doesn't work because you don't have any method or function in your code named <em>move</em>. The error before your edit was a syntax error because you defined your parameters wrong. To fix the class and make it work with the rest of your code would require much of the other code to be changed. To be completely honest, I think all of your code needs to be rewritten to be able to do much more with your game.</p> <p>Try learn more about functions, loops and classes. I'm sorry but I believe you need more knowledge about these to progress any further.</p>
1
2016-08-06T00:12:47Z
[ "python", "python-2.7", "pygame" ]
Python: correct location of peaks in a 2D numpy array?
38,792,263
<p>I know this question falls within the category of peak detection and <a href="http://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array">there are answers available</a>, but I think my problem is pretty simplistic and refers to a proof of principle.</p> <p>Say I generate multiple, <code>nxn</code> 2D numpy arrays of float values like this, which refer to a regular grid of <code>nxn</code> points (discrete domain):</p> <pre><code>myarray= array([[ 0.82760819, 0.82113999, 0.811576 , 0.80308705, 0.81231903, 0.82296263, 0.78448964, 0.79308308, 0.82160627, 0.83475755, 0.8580934 , 0.8857617 , 0.89901092, 0.92479025, 0.91840606, 0.91029942, 0.88523943, 0.85798491, 0.84190422, 0.83350783, 0.83520675], [ 0.84971526, 0.84759644, 0.81429419, 0.79936736, 0.81750327, 0.81874686, 0.80666801, 0.82297348, 0.84980788, 0.85698662, 0.87819988, 0.89572185, 0.89009723, 0.90347858, 0.89703473, 0.90092666, 0.88362073, 0.86711197, 0.84791422, 0.83632138, 0.83685225], ...] #you can generate any nxn array of random values </code></pre> <p>Now let's normalize them:</p> <pre><code>peak_value=myarray.max() norm_array=myarray/peak_value </code></pre> <p>And proceed to locate the <code>(x,y)</code> coordinates of the peak:</p> <pre><code>from collections import Counter longit=[] #x values of the peak latit=[] #y values of the peak for x in range(myarray.shape[0]): for y in range(myarray.shape[1]): if norm_array[x][y]==1: longit.append(x) latit.append(y) x=numpy.array(longit) y=numpy.array(latit) c=zip(x,y) temp=Counter(elem for elem in c) #Counts the number of peaks in each (x,y) point in the 11x11 grid d=dict(Counter(temp)) #Has the shape d={(x,y): number of peaks} </code></pre> <p>Now this is just a single realization of the 2D numpy array. Given multiple arrays, the question is:</p> <p><strong>Is this the correct way to find the (x,y) of the peaks? Is there a more efficient way?</strong> Consider that there might be multiple peaks.</p>
0
2016-08-05T14:56:32Z
38,792,523
<p>In C/C++ it is considered dangerous to do <code>==</code> with floating point numbers.</p> <p>If there are no multiple exactly same pikes, you can use <code>numpy.argmax</code>:</p> <pre><code>a = random.rand(13, 11) idx_unrolled = argmax(a) the_peak = a[idx_unrolled/11, idx_unrolled%11] </code></pre> <p>If you need all pikes, you can get list of <code>i</code>, <code>j</code> indices using <code>numpy.where</code>:</p> <pre><code>i, j = where(a &gt; 0.99*the_peak) </code></pre> <p>Use required number of <code>9</code> to tune the margin. For single precision floating points it is not than close to <code>1</code>. </p> <p>The best way may be something like [<a href="http://stackoverflow.com/a/19141711/774971">http://stackoverflow.com/a/19141711/774971</a> ]:</p> <pre><code>i, j = where(a &gt; (1.0 - 5*np.finfo(a.dtype).eps)*the_peak) </code></pre>
2
2016-08-05T15:09:43Z
[ "python", "arrays", "numpy", "max", "detection" ]
Color coded plot Python
38,792,273
<p>I have a color coded plot. Here is a part of the code:</p> <pre><code>fig = plt.figure(figsize=(10,10)) color_scheme = plt.get_cmap('cool') gs = gridspec.GridSpec(1, 1) ax1 = plt.subplot(gs[0]) gs.update(left=0.15,bottom=0.15,right=0.80,top=0.95) cax = fig.add_axes([0.80, 0.15, 0.03, 0.80]) im = ax1.scatter(x, y, c=z, edgecolors='black', marker='.', s=40, lw=1, cmap=color_scheme, vmin=0, vmax=10) cb = fig.colorbar(im, cax=cax) for t in cb.ax.get_yticklabels(): t.set_fontsize(12) </code></pre> <p>The problem is that I want to connect the dots with a line, and it doesn't work to use marker='-' and it also doesn't work if I use ax1.plt. How can I do this?<br> What I actually need is to fit a line to some points and color it the same color as the points (the points I fit to will all have same color)</p>
1
2016-08-05T14:57:07Z
38,792,417
<p>Instead of using</p> <pre><code>ax1.scatter(x, y, ...) </code></pre> <p>use</p> <pre><code>ax1.plot(x, y, 'o-', ...) # three dots meaning you can configure markers, linestyle, etc. </code></pre> <p>This works bacause of <code>'o-'</code> argument, which is a line plot with markers at every data point.</p>
2
2016-08-05T15:04:26Z
[ "python", "matplotlib" ]
Color coded plot Python
38,792,273
<p>I have a color coded plot. Here is a part of the code:</p> <pre><code>fig = plt.figure(figsize=(10,10)) color_scheme = plt.get_cmap('cool') gs = gridspec.GridSpec(1, 1) ax1 = plt.subplot(gs[0]) gs.update(left=0.15,bottom=0.15,right=0.80,top=0.95) cax = fig.add_axes([0.80, 0.15, 0.03, 0.80]) im = ax1.scatter(x, y, c=z, edgecolors='black', marker='.', s=40, lw=1, cmap=color_scheme, vmin=0, vmax=10) cb = fig.colorbar(im, cax=cax) for t in cb.ax.get_yticklabels(): t.set_fontsize(12) </code></pre> <p>The problem is that I want to connect the dots with a line, and it doesn't work to use marker='-' and it also doesn't work if I use ax1.plt. How can I do this?<br> What I actually need is to fit a line to some points and color it the same color as the points (the points I fit to will all have same color)</p>
1
2016-08-05T14:57:07Z
38,792,457
<p>Plot the same x and y-data separately with a standard <code>ax.plot</code> behind your scatter plot. </p> <pre><code>ax1.plot(x, y, '-') im = ax1.scatter(x, y, c=z, edgecolors='black', marker='.', s=40, lw=1, cmap=color_scheme, vmin=0, vmax=10) </code></pre> <p>This should give you your cmapped scatter plot with the lines behind the scatter-points.</p>
1
2016-08-05T15:06:22Z
[ "python", "matplotlib" ]
Can you use the same decoder in Pocketsphinx for multiple files?
38,792,429
<p>Is it possible to use the same decoder for multiple wav files in Pocketsphinx (Python)? I have the following code snippet, which is very standard, except that I call the decoder twice on the same file. The outputs are not the same, however. I've also tried using the decoder twice on different files, and the outputs are different depending on the order in which I call the files - the first file decodes correctly, but the second file does not decode correctly. Furthermore, this only happens if there is some output from the first file - if the first file doesn't have any words, then the second file decodes fine. This makes me believe the decoder is modified in some way after decoding one file. Am I correct about this? Is there any way to reset the decoder, or in general make it work for multiple files? It seems like there should be given the example here: <a href="https://github.com/cmusphinx/pocketsphinx/blob/master/swig/python/test/decoder_test.py" rel="nofollow">https://github.com/cmusphinx/pocketsphinx/blob/master/swig/python/test/decoder_test.py</a>.</p> <pre><code>config = ps.Decoder.default_config() config.set_string('-hmm', os.path.join(MODELDIR, 'en-US/acoustic-model')) config.set_string('-lm', os.path.join(MODELDIR, 'en-US/language-model.lm.bin')) config.set_string('-dict', os.path.join(MODELDIR, 'en-US/pronounciation-dictionary.dict')) config.set_string('-logfn', 'pocketsphinxlog') decoder = ps.Decoder(config) wavname16_1 = os.path.join(DATADIR, 'arctic_a0001.wav') # Decode streaming data. decoder.start_utt() stream = open(wavname16_1, 'rb') while True: buf = stream.read(1024) if buf: decoder.process_raw(buf, False, False) else: break decoder.end_utt() stream.close() words = [(seg.word, seg.prob) for seg in decoder.seg()] print words wavname16_2 = os.path.join(DATADIR, 'arctic_a0002.wav') decoder.start_utt() stream = open(wavname16_2, 'rb') while True: buf = stream.read(1024) if buf: decoder.process_raw(buf, False, False) else: break decoder.end_utt() stream.close() words = [(seg.word, seg.prob) for seg in decoder.seg()] print "arctic2: " + words </code></pre> <p>EDIT - Some further information:</p> <p>If arctic_a0001.wav is <a href="http://festvox.org/cmu_arctic/cmu_arctic/cmu_us_bdl_arctic/wav/arctic_a0001.wav" rel="nofollow">http://festvox.org/cmu_arctic/cmu_arctic/cmu_us_bdl_arctic/wav/arctic_a0001.wav</a>, arctic_a0002.wav is <a href="http://festvox.org/cmu_arctic/cmu_arctic/cmu_us_bdl_arctic/wav/arctic_a0002.wav" rel="nofollow">http://festvox.org/cmu_arctic/cmu_arctic/cmu_us_bdl_arctic/wav/arctic_a0002.wav</a>, and the dictionary is the single line:</p> <pre><code>of AH V </code></pre> <p>then the current output is: </p> <pre><code>arctic1: [('&lt;s&gt;', 1), ('of', 1), ('of', -12001), ('&lt;sil&gt;', 0), ('of', -16211), ('&lt;sil&gt;', -1205), ('of', -13991), ('of', 0), ('&lt;sil&gt;', 0), ('of', -31232), ('&lt;/s&gt;', 0)] arctic2: [('&lt;s&gt;', -3), ('[SPEECH]', -725), ('&lt;sil&gt;', -1), ('[SPEECH]', -6), ('&lt;sil&gt;', -20), ('of', -6162), ('[SPEECH]', -397), ('&lt;/s&gt;', 0)] </code></pre> <p>but if we switch them, the output becomes</p> <pre><code>arctic2: [('&lt;s&gt;', 0), ('of', 0), ('&lt;sil&gt;', 0), ('of', -29945), ('&lt;sil&gt;', -20), ('of', -26004), ('of', 0), ('of', 0), ('&lt;sil&gt;', 0), ('of', -84868), ('of', -35690), ('&lt;/s&gt;', 0)] arctic1: [('&lt;s&gt;', -3), ('of', -14886), ('of', -30237), ('&lt;sil&gt;', 0), ('of', -22103), ('of', 1), ('&lt;sil&gt;', 0), ('of', -30795), ('of', -65040), ('&lt;/s&gt;', 0)] </code></pre> <p>so the outputs of arctic1 and arctic2 depend on the order. Furthermore, if we use arctic1 twice, the output is </p> <pre><code>[('&lt;s&gt;', 1), ('of', 1), ('of', -12001), ('&lt;sil&gt;', 0), ('of', -16211), ('&lt;sil&gt;', -1205), ('of', -13991), ('of', 0), ('&lt;sil&gt;', 0), ('of', -31232), ('&lt;/s&gt;', 0)] [('&lt;s&gt;', 1), ('of', -24424), ('of', -24554), ('&lt;sil&gt;', 2), ('[SPEECH]', -37257), ('of', -37008), ('&lt;sil&gt;', -461), ('of', -20422), ('of', 0), ('&lt;sil&gt;', 0), ('of', -3570), ('[SPEECH]', -42), ('&lt;/s&gt;', 0)] </code></pre> <p>Maybe it is a problem with me not using start_stream()? I am not sure how I should use it. Even if I use decoder.start_stream() (directly before decoder.start_utt()), the output is different - it becomes </p> <pre><code>[('&lt;s&gt;', 1), ('of', 1), ('of', -12001), ('&lt;sil&gt;', 0), ('of', -16211), ('&lt;sil&gt;', -1205), ('of', -13991), ('of', 0), ('&lt;sil&gt;', 0), ('of', -31232), ('&lt;/s&gt;', 0)] [('&lt;s&gt;', -2), ('of', -33113), ('of', -29715), ('&lt;sil&gt;', 1), ('[SPEECH]', -37258), ('of', -37009), ('&lt;sil&gt;', -461), ('of', -20422), ('of', 0), ('&lt;sil&gt;', 0), ('of', -3570), ('[SPEECH]', -42), ('&lt;/s&gt;', 0)] </code></pre> <p>If you want the entire log, here (<a href="http://pastebin.com/2dNeyS1x" rel="nofollow">http://pastebin.com/2dNeyS1x</a>) is the log for arctic1 before arctic2, and here (<a href="http://pastebin.com/Nkvj2G0g" rel="nofollow">http://pastebin.com/Nkvj2G0g</a>) is the log for arctic2 before arctic1, while here is the log for arctic1 two times in a row with start_stream (<a href="http://pastebin.com/HWq6j7X2" rel="nofollow">http://pastebin.com/HWq6j7X2</a>), and here is the log for arctic1 two times in a row without start_stream (<a href="http://pastebin.com/MsadW4nh" rel="nofollow">http://pastebin.com/MsadW4nh</a>).</p>
2
2016-08-05T15:05:05Z
38,797,212
<blockquote> <p>Is it possible to use the same decoder for multiple wav files in Pocketsphinx (Python)?</p> </blockquote> <p>Yes</p> <blockquote> <p>I have the following code snippet, which is very standard, except that I call the decoder twice on the same file. The outputs are not the same, however.</p> </blockquote> <p>You need to call <code>decoder.start_stream()</code> for the second file to reset the decoder timings.</p> <blockquote> <p>I've also tried using the decoder twice on different files, and the outputs are different depending on the order in which I call the files - the first file decodes correctly, but the second file does not decode correctly. Furthermore, this only happens if there is some output from the first file - if the first file doesn't have any words, then the second file decodes fine.</p> </blockquote> <p>Well, there could be different things what affect result. It is hard to say without example. You'd better provide sample files and the problematic output to get an answer on this question.</p>
0
2016-08-05T20:18:28Z
[ "python", "pocketsphinx" ]
Cross-platform Python Executables
38,792,459
<p>Is it possible to package together a Python executable that can be run across any platform - provided the correct version of Python is installed?</p> <p>If, for example, I created a Web Scraping script which included files such as chromium webdriver, the selenium package and other non-builtin Python packages, could I compile some .exe / .jar file that could be sent to a client to run this without having to configure an environment?</p>
0
2016-08-05T15:06:22Z
38,792,824
<p>Python is mainly cross platform - although I've had experience of reading/writing files being different on Windows/OS X/Linux because of the different directory and file structure (see <a href="https://automatetheboringstuff.com/chapter8/" rel="nofollow">Reading and Writing Files</a> for how to cope with that). Cross-platform Python for a GUI application is supposedly harder to do (reference: <a href="https://www.reddit.com/r/Python/comments/2vwm7g/python_for_crossplatform_applications/" rel="nofollow">Reddit</a>, I personally have never created a GUI in Python).</p> <p>It depends on what you want your Python program to do. If you want to install programs and packages then I don't think Python is your answer. Also, Python is not included by default on every system, and even when it is installed, you're not guaranteed to have the correct version running on each system.</p> <p>This website looks useful for using <a href="http://selenium-python.readthedocs.io/index.html" rel="nofollow">Selenium with Python</a>.</p>
0
2016-08-05T15:26:27Z
[ "python", "selenium", "executable" ]
environment variable in ubuntu
38,792,545
<p>I'm trying to install the python module 'Pycpx' but I'm getting an error that it can't find an environment variable </p> <p><a href="http://www.stat.washington.edu/~hoytak/code/pycpx/download.html" rel="nofollow">Pycpx</a></p> <blockquote> <p>Exception: CPLEX concert include directory not found: please set environment variable CPLEX_PATH to point to the base of the CPlex/Concert installation. Attempting to find files: ilconcert/iloexpression.h, ilconcert/iloalg.h, ilconcert/iloenv.h, ilconcert/ilosolution.h.</p> </blockquote> <p>I create a file called .bash_profile in my home directory and I put this line in it which points to the folder where these header files are located. </p> <pre><code>CPLEX_PATH = /home/joe/concert/include/ilconcert </code></pre> <p>Is this the correct way to add environment variables as I am still getting the error?</p> <p>I get this error whether I install with <code>easy_install pycpx</code> or I get the source tarball from here <a href="http://pypi.python.org/pypi/pycpx/" rel="nofollow">tarball</a> and run <code>python setup.py install</code>. </p> <p>Many thanks</p>
0
2016-08-05T15:10:46Z
38,792,615
<p>No, that's not right. You can't have those spaces around the <code>=</code> sign, and you should <code>export</code> the variable, like this: </p> <pre><code>export CPLEX_PATH=/home/joe/concert/include/ilconcert </code></pre>
1
2016-08-05T15:14:22Z
[ "python", "bash", "environment-variables", "ubuntu-14.04" ]
environment variable in ubuntu
38,792,545
<p>I'm trying to install the python module 'Pycpx' but I'm getting an error that it can't find an environment variable </p> <p><a href="http://www.stat.washington.edu/~hoytak/code/pycpx/download.html" rel="nofollow">Pycpx</a></p> <blockquote> <p>Exception: CPLEX concert include directory not found: please set environment variable CPLEX_PATH to point to the base of the CPlex/Concert installation. Attempting to find files: ilconcert/iloexpression.h, ilconcert/iloalg.h, ilconcert/iloenv.h, ilconcert/ilosolution.h.</p> </blockquote> <p>I create a file called .bash_profile in my home directory and I put this line in it which points to the folder where these header files are located. </p> <pre><code>CPLEX_PATH = /home/joe/concert/include/ilconcert </code></pre> <p>Is this the correct way to add environment variables as I am still getting the error?</p> <p>I get this error whether I install with <code>easy_install pycpx</code> or I get the source tarball from here <a href="http://pypi.python.org/pypi/pycpx/" rel="nofollow">tarball</a> and run <code>python setup.py install</code>. </p> <p>Many thanks</p>
0
2016-08-05T15:10:46Z
38,792,652
<p>The correct way of doing it is as follows:</p> <pre><code>export CPLEX_PATH=/home/joe/concert/include/ilconcert </code></pre>
3
2016-08-05T15:16:06Z
[ "python", "bash", "environment-variables", "ubuntu-14.04" ]
figtext datetime function matplotlib
38,792,564
<p>I am trying to create a text box within my graph in matplotlib where it gives me the date in which the graph was created. </p> <p>I have created a text box in the bottom right corner of my graph using the figtext function in matplotlib, but cannot figure out how to incorporate the python datetime function within the text box so it displays the date. Any ideas?</p> <p>Code and graph below:</p> <pre><code>#Stacked Bar Char- matplotlib #Create the general blog and the "subplots" i.e. the bars f, ax1 = plt.subplots(1, figsize=(8,5), dpi=1000) # Set the bar width bar_width = 0.50 # positions of the left bar-boundaries bar_l = [i+1 for i in range(len(df4['Pandas']))] # positions of the x-axis ticks (center of the bars as bar labels) tick_pos = [i+(bar_width/2) for i in bar_l] #Stack the negative bars by region #Start bottom at 0, and then use pandas to add bars together ax1.bar(bar_l, df4['cats1'], width=bar_width, label='cats',color='R', alpha=.4, align='center', bottom = 0) ax1.bar(bar_l, df4['dogs1'], width=bar_width,label='dogs',color='#ADD8E6',alpha=.4, fill=True, align='center', bottom =(df4['cats1'])) ax1.bar(bar_l, df4['zebras1'], width=bar_width, label='zebras',color='#FFA500',alpha=.4, align='center', bottom = np.array(df4['cats1'])+np.array(df4['dogs1'])) ax1.bar(bar_l, df4['pandas1'], width=bar_width, label='pandas', color='b',alpha=.5, fill=True, align='center', bottom = np.array(df4['cats1'])+np.array(df4['dogs1'])+np.array(df4['zebras1'])) #Stack the positive bars by region #Start bottom at 0, and then use pandas to add bars together ax1.bar(bar_l, df4['cats'], width=bar_width,color='R', alpha=.4, align='center', bottom = 0) ax1.bar(bar_l, df4['dogs'], width=bar_width,color='#ADD8E6',alpha=.4, fill=True, align='center', bottom =(df4['cats'])) ax1.bar(bar_l, df4['zebras'], width=bar_width ,color='#FFA500',alpha=.4, align='center', bottom = np.array(df4['cats'])+np.array(df4['dogs'])) ax1.bar(bar_l, df4['pandas'], width=bar_width, color='b',alpha=.5, fill=True, align='center', bottom = np.array(df4['cats'])+np.array(df4['dogs'])+np.array(df4['zebras'])) # set the x ticks with names plt.xticks(tick_pos, df4['Year'],fontsize=10) # Set the label and legends plt.title('Animals on the farm', fontweight='bold') ax1.set_ylim([-1600,1000]) ax1.set_ylabel("Count",fontsize=12) ax1.set_xlabel("Year",fontsize=12) plt.legend(loc='upper left', prop={'size':6}) ax1.axhline(y=0, color='k') ax1.axvline(x=0, color='k') plt.figtext(0, 0,"Data as of ", wrap=False, horizontalalignment='left',verticalalignment ='bottom', fontsize=8) plt.setp(ax1.get_yticklabels(), rotation='horizontal', fontsize=10) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/A7BqI.png" rel="nofollow">Graph= Animals on the Farm</a></p>
1
2016-08-05T15:12:11Z
38,792,660
<p>Here's an example with today's date:</p> <pre><code>import datetime as dt plt.figtext(0, 0,"Data as of {}".format(dt.date.today().strftime('%Y-%m-%d')), wrap=False, horizontalalignment='left',verticalalignment ='bottom', fontsize=8) </code></pre>
0
2016-08-05T15:16:31Z
[ "python", "datetime", "matplotlib" ]
figtext datetime function matplotlib
38,792,564
<p>I am trying to create a text box within my graph in matplotlib where it gives me the date in which the graph was created. </p> <p>I have created a text box in the bottom right corner of my graph using the figtext function in matplotlib, but cannot figure out how to incorporate the python datetime function within the text box so it displays the date. Any ideas?</p> <p>Code and graph below:</p> <pre><code>#Stacked Bar Char- matplotlib #Create the general blog and the "subplots" i.e. the bars f, ax1 = plt.subplots(1, figsize=(8,5), dpi=1000) # Set the bar width bar_width = 0.50 # positions of the left bar-boundaries bar_l = [i+1 for i in range(len(df4['Pandas']))] # positions of the x-axis ticks (center of the bars as bar labels) tick_pos = [i+(bar_width/2) for i in bar_l] #Stack the negative bars by region #Start bottom at 0, and then use pandas to add bars together ax1.bar(bar_l, df4['cats1'], width=bar_width, label='cats',color='R', alpha=.4, align='center', bottom = 0) ax1.bar(bar_l, df4['dogs1'], width=bar_width,label='dogs',color='#ADD8E6',alpha=.4, fill=True, align='center', bottom =(df4['cats1'])) ax1.bar(bar_l, df4['zebras1'], width=bar_width, label='zebras',color='#FFA500',alpha=.4, align='center', bottom = np.array(df4['cats1'])+np.array(df4['dogs1'])) ax1.bar(bar_l, df4['pandas1'], width=bar_width, label='pandas', color='b',alpha=.5, fill=True, align='center', bottom = np.array(df4['cats1'])+np.array(df4['dogs1'])+np.array(df4['zebras1'])) #Stack the positive bars by region #Start bottom at 0, and then use pandas to add bars together ax1.bar(bar_l, df4['cats'], width=bar_width,color='R', alpha=.4, align='center', bottom = 0) ax1.bar(bar_l, df4['dogs'], width=bar_width,color='#ADD8E6',alpha=.4, fill=True, align='center', bottom =(df4['cats'])) ax1.bar(bar_l, df4['zebras'], width=bar_width ,color='#FFA500',alpha=.4, align='center', bottom = np.array(df4['cats'])+np.array(df4['dogs'])) ax1.bar(bar_l, df4['pandas'], width=bar_width, color='b',alpha=.5, fill=True, align='center', bottom = np.array(df4['cats'])+np.array(df4['dogs'])+np.array(df4['zebras'])) # set the x ticks with names plt.xticks(tick_pos, df4['Year'],fontsize=10) # Set the label and legends plt.title('Animals on the farm', fontweight='bold') ax1.set_ylim([-1600,1000]) ax1.set_ylabel("Count",fontsize=12) ax1.set_xlabel("Year",fontsize=12) plt.legend(loc='upper left', prop={'size':6}) ax1.axhline(y=0, color='k') ax1.axvline(x=0, color='k') plt.figtext(0, 0,"Data as of ", wrap=False, horizontalalignment='left',verticalalignment ='bottom', fontsize=8) plt.setp(ax1.get_yticklabels(), rotation='horizontal', fontsize=10) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/A7BqI.png" rel="nofollow">Graph= Animals on the Farm</a></p>
1
2016-08-05T15:12:11Z
38,792,665
<p>If you have a <code>datetime</code> object, you can use the <a href="https://docs.python.org/2/library/datetime.html#datetime.date.strftime" rel="nofollow"><code>strftime</code></a> method to convert it to a string representation using the formatting you want:</p> <pre><code>from datetime import datetime plt.figtext(0, 0, 'Date as of ' + datetime.now().strftime('%Y-%m-%d')) </code></pre>
0
2016-08-05T15:16:38Z
[ "python", "datetime", "matplotlib" ]
Dynamically generate constraints list in CVXPY
38,792,618
<p>I am working on a minimum variance optimisation in python using CVXPY that takes in constraints in the form of</p> <pre><code>constraints = [ sum_entries(w) == 1, w[0:5] &gt;0.05, w[1] &gt; 0.05, w[6] == 0, sum_entries(w[country_mappings['France']]) == 0.39, w &gt;= 0,positive w[country_mappings['France']] &gt; 0.12 ] </code></pre> <p>With w being in the form of </p> <pre><code>w = Variable(n) </code></pre> <p>To run this more efficiently I want to create my list of constraints dynamically based on a file where I will store my settings.</p> <p>Reading in and creating a constraints list works fine, and by using </p> <pre><code>type(constraints) </code></pre> <p>it shows</p> <pre><code>&lt;type 'list'&gt; </code></pre> <p>But looking at the actual entries it contains</p> <pre><code>[EqConstraint(Expression(AFFINE, UNKNOWN, (1, 1)), Constant(CONSTANT, POSITIVE, (1, 1))), LeqConstraint(Constant(CONSTANT, POSITIVE, (1, 1)), Expression(AFFINE, UNKNOWN, (5, 1))), LeqConstraint(Constant(CONSTANT, POSITIVE, (1, 1)), Expression(AFFINE, UNKNOWN, (1, 1))), EqConstraint(Expression(AFFINE, UNKNOWN, (1, 1)), Constant(CONSTANT, ZERO, (1, 1))), EqConstraint(Expression(AFFINE, UNKNOWN, (1, 1)), Constant(CONSTANT, POSITIVE, (1, 1))), LeqConstraint(Constant(CONSTANT, ZERO, (1, 1)), Variable(10, 1)), LeqConstraint(Constant(CONSTANT, POSITIVE, (1, 1)), Expression(AFFINE, UNKNOWN, (3L, 1L)))] </code></pre> <p>whereas mine are in this format</p> <pre><code>['sum_entries(w) == 1', 'w[0:5] &gt; 0.05', 'w[1] &gt; 0.05', 'w[6] == 0', 'sum_entries(w[country_mappings['France']]) == 0.39', 'w &gt;= 0', 'w[country_mappings['France']] &gt; 0.12' ] </code></pre> <p>The code used to read in the data is </p> <pre><code>def read_in_config(filename): with open(filename) as f: content = f.read().splitlines() return content </code></pre> <p>Does anyone know how this can be done ? The problem is getting w in the variable format of CVXPY before it can be used.</p>
0
2016-08-05T15:14:40Z
38,795,858
<p>Ok so i have found a solution that works.</p> <p>One can read in the constraints and concatenate a string to get s.th like</p> <pre><code>'constraints = [sum_entries(w) == 1,w[0:5] &gt; 0.05,w[1] &gt; 0.05, w[6] == 0, sum_entries(w[country_mappings['France']]) == 0.39, w &gt;= 0, w[country_mappings['France']] &gt; 0.12 ]' </code></pre> <p>Then just use </p> <pre><code>exec 'string from above' </code></pre> <p>I know exec is not the safest option to use but it works. W has to be defined in the code</p> <pre><code>w = Variable(n) </code></pre>
0
2016-08-05T18:39:57Z
[ "python", "optimization", "constraint-programming", "quadratic-programming" ]
Pandas: Multi-index second-level slicing by integer
38,792,647
<p>I have a multi-index dataframe that look like this:</p> <pre><code>In [45]: df Out[45]: Last Days to expiry Date Ticker 1988-06-23 COU88 15.65 48 days COV88 15.65 78 days 1988-06-24 COU88 15.65 47 days COV88 15.56 77 days COX88 15.75 108 days 1988-06-27 COU88 15.10 44 days COV88 15.30 74 days 1988-06-28 COU88 15.27 43 days COV88 15.27 73 days 1988-06-29 COU88 14.97 42 days COV88 14.92 72 days 1988-06-30 COU88 14.85 41 days COV88 14.80 71 days </code></pre> <p>With two levels for indexes (namely 'Date' and 'Ticker'). I would like to slice it by integer taking for all dates the first row, meaning the first ticker. The result should look like this:</p> <pre><code> Last Days to expiry Date Ticker 1988-06-23 COU88 15.65 48 days 1988-06-24 COU88 15.65 47 days 1988-06-27 COU88 15.10 44 days 1988-06-28 COU88 15.27 43 days 1988-06-29 COU88 14.97 42 days 1988-06-30 COU88 14.85 41 days </code></pre> <p>Also, if possible I would like to filter the columns to get only the column named 'Last'. I do not manage to get the right syntax for df.iloc</p> <p>Thanks a lot for your tips</p>
3
2016-08-05T15:15:51Z
38,792,821
<p>You can <code>groupby</code> on the first index level and call <code>first</code>:</p> <pre><code>In [173]: df.groupby(level='Date').first() Out[173]: Last Days to expiry Date 1988-06-23 15.65 48 days 1988-06-24 15.65 47 days 1988-06-27 15.10 44 days 1988-06-28 15.27 43 days 1988-06-29 14.97 42 days 1988-06-30 14.85 41 days </code></pre>
3
2016-08-05T15:26:08Z
[ "python", "pandas", "group-by", "multi-index" ]
How to Update Scrollbar Position with Tkinter
38,792,704
<p>I am trying to create a GUI for a python script using Tkinter, and have a working scrollbar. However, the position of the 'bar' does not update when I scroll or drag the bar. I think the relevant portion of code is as follows:</p> <pre><code>#Setup window with text and scrollbar root = Tk() scrollbar = Scrollbar(root) app = App(root) t = Text(root) #GRID manager layout t.grid(row = 0, column = 1, sticky=N+S+W, padx = 5, pady = 5) scrollbar.grid(row = 0, column = 2, sticky=N+S+W, ) scrollbar.config( command = t.yview ) </code></pre> <p>I have tried searching for means to fix this, but cannot seem to figure out what I'm doing wrong. Any help would be really appreciated. My apologies if I've not included enough code, if you would like more, or to see the entire script (though it's 100 lines) I would be happy to oblige.</p> <p>Thanks again for your time.</p>
0
2016-08-05T15:18:49Z
38,792,777
<p>You should point it to the .yview of a Canvas, and put the Text into the canvas</p> <pre><code>the_window = Tk() vscrollbar = Scrollbar(the_window) vscrollbar.grid(...) the_canvas = Canvas( the_window, background = 'white', yscrollcommand = vscrollbar.set ) the_canvas.grid(...) vscrollbar.config(command=the_canvas.yview) </code></pre>
2
2016-08-05T15:23:44Z
[ "python", "tkinter", "scrollbar" ]
Flask Foreign Key Constraint
38,792,722
<p>I have an issue with foreign key in Flask. My model is the following : </p> <p><strong>Model.py</strong></p> <pre><code>class User(db.Model): __tablename__ = "users" __table_args__ = {'extend_existing': True} user_id = db.Column(db.BigInteger, primary_key=True) # EDIT alerts = db.relationship('Alert', backref='user', lazy='dynamic') def __init__(self, user_id): self.user_id = user_id class Alert(db.Model): __tablename__ = 'alert' __table_args__ = {'extend_existing': True} alert_id = db.Column(db.Integer, primary_key=True, autoincrement=True) user_id = db.Column(db.BigInteger, db.ForeignKey('users.user_id'), nullable=False) name = db.Column(db.String(ALERT_NAME_MAX_SIZE), nullable=False) def __init__(self, user_id, name): self.user_id = user_id self.name = name </code></pre> <p>I am able to add some user, for example</p> <pre><code>a = User(16) b = User(17) db.session.add(a) db.session.add(b) db.session.commit() </code></pre> <p>and some alerts : </p> <pre><code>c = Alert(16, 'test') d = Alert(17, 'name_test') db.session.add(c) db.session.add(d) db.session.commit() </code></pre> <p>I have two issues with the foreign key : First of all, when I try to modify the user_id alert, I am able to do it even if the user_id is not in the database </p> <pre><code> alert = Alert.query.get(1) alert.user_id = 1222 # not in the database db.session.commit() </code></pre> <p>and I am able to create a alert with an user_id not in the Database: </p> <pre><code>r = Alert(16223, 'test') db.session.add(r) </code></pre> <p>I don't understand why they is no relationship constraint. Thx, </p>
0
2016-08-05T15:20:11Z
38,793,154
<p>There is mistake in your code for initialisation of Alert class. You should use backref variable (which is 'user') instead of user_id while initializing Alert. Following code should work. </p> <pre><code>class User(db.Model): __tablename__ = "user" __table_args__ = {'extend_existing': True} user_id = db.Column(db.BigInteger, primary_key=True) alerts = db.relationship('Alert', backref='user', lazy='dynamic') def __init__(self, user_id): self.user_id = user_id class Alert(db.Model): __tablename__ = 'alert' alert_id = db.Column(db.Integer, primary_key=True, autoincrement=True) user_id = db.Column(db.BigInteger, db.ForeignKey('user.user_id'), nullable=False) name = db.Column(db.String(ALERT_NAME_MAX_SIZE), nullable=False) def __init__(self, user, name): self.user = user self.name = name </code></pre> <p>It works as below:</p> <pre><code>&gt;&gt;&gt; a = User(7) &gt;&gt;&gt; db.session.add(a) &gt;&gt;&gt; db.session.commit() &gt;&gt;&gt; b = Alert(a, 'test') &gt;&gt;&gt; db.session.add(b) &gt;&gt;&gt; db.session.commit() &gt;&gt;&gt; alert = Alert.query.get(1) &gt;&gt;&gt; alert.user_id 7 &gt;&gt;&gt; alert.user &lt;app.User object at 0x1045cb910&gt; &gt;&gt;&gt; alert.user.user_id 7 </code></pre> <p>It does not allow you to assign variable like <code>d = Alert(88, 'trdft')</code> </p> <p>I think you should read <a href="http://flask-sqlalchemy.pocoo.org/2.1/models/#one-to-many-relationships" rel="nofollow">Flask SqlAlchemy's One-to-Many Relationships</a> for more details.</p>
0
2016-08-05T15:44:55Z
[ "python", "flash", "flask-sqlalchemy", "foreign-key-relationship" ]
Flask Foreign Key Constraint
38,792,722
<p>I have an issue with foreign key in Flask. My model is the following : </p> <p><strong>Model.py</strong></p> <pre><code>class User(db.Model): __tablename__ = "users" __table_args__ = {'extend_existing': True} user_id = db.Column(db.BigInteger, primary_key=True) # EDIT alerts = db.relationship('Alert', backref='user', lazy='dynamic') def __init__(self, user_id): self.user_id = user_id class Alert(db.Model): __tablename__ = 'alert' __table_args__ = {'extend_existing': True} alert_id = db.Column(db.Integer, primary_key=True, autoincrement=True) user_id = db.Column(db.BigInteger, db.ForeignKey('users.user_id'), nullable=False) name = db.Column(db.String(ALERT_NAME_MAX_SIZE), nullable=False) def __init__(self, user_id, name): self.user_id = user_id self.name = name </code></pre> <p>I am able to add some user, for example</p> <pre><code>a = User(16) b = User(17) db.session.add(a) db.session.add(b) db.session.commit() </code></pre> <p>and some alerts : </p> <pre><code>c = Alert(16, 'test') d = Alert(17, 'name_test') db.session.add(c) db.session.add(d) db.session.commit() </code></pre> <p>I have two issues with the foreign key : First of all, when I try to modify the user_id alert, I am able to do it even if the user_id is not in the database </p> <pre><code> alert = Alert.query.get(1) alert.user_id = 1222 # not in the database db.session.commit() </code></pre> <p>and I am able to create a alert with an user_id not in the Database: </p> <pre><code>r = Alert(16223, 'test') db.session.add(r) </code></pre> <p>I don't understand why they is no relationship constraint. Thx, </p>
0
2016-08-05T15:20:11Z
38,797,940
<p>If you are using SQLite, foreign key constraints are by default not enforced. See <a href="https://www.sqlite.org/foreignkeys.html#fk_enable" rel="nofollow">Enabling Foreign Key Support</a> in the documentation for how to enable this. </p>
0
2016-08-05T21:22:30Z
[ "python", "flash", "flask-sqlalchemy", "foreign-key-relationship" ]
Flask Foreign Key Constraint
38,792,722
<p>I have an issue with foreign key in Flask. My model is the following : </p> <p><strong>Model.py</strong></p> <pre><code>class User(db.Model): __tablename__ = "users" __table_args__ = {'extend_existing': True} user_id = db.Column(db.BigInteger, primary_key=True) # EDIT alerts = db.relationship('Alert', backref='user', lazy='dynamic') def __init__(self, user_id): self.user_id = user_id class Alert(db.Model): __tablename__ = 'alert' __table_args__ = {'extend_existing': True} alert_id = db.Column(db.Integer, primary_key=True, autoincrement=True) user_id = db.Column(db.BigInteger, db.ForeignKey('users.user_id'), nullable=False) name = db.Column(db.String(ALERT_NAME_MAX_SIZE), nullable=False) def __init__(self, user_id, name): self.user_id = user_id self.name = name </code></pre> <p>I am able to add some user, for example</p> <pre><code>a = User(16) b = User(17) db.session.add(a) db.session.add(b) db.session.commit() </code></pre> <p>and some alerts : </p> <pre><code>c = Alert(16, 'test') d = Alert(17, 'name_test') db.session.add(c) db.session.add(d) db.session.commit() </code></pre> <p>I have two issues with the foreign key : First of all, when I try to modify the user_id alert, I am able to do it even if the user_id is not in the database </p> <pre><code> alert = Alert.query.get(1) alert.user_id = 1222 # not in the database db.session.commit() </code></pre> <p>and I am able to create a alert with an user_id not in the Database: </p> <pre><code>r = Alert(16223, 'test') db.session.add(r) </code></pre> <p>I don't understand why they is no relationship constraint. Thx, </p>
0
2016-08-05T15:20:11Z
38,826,981
<p>So I find how to do it with <a href="http://stackoverflow.com/questions/2614984/sqlite-sqlalchemy-how-to-enforce-foreign-keys">this stackoverflow question </a>, I find how to force foreign Key Constraint.</p> <p>I juste add this in <code>__init__.py</code> and change nothing to <code>models.py</code></p> <pre><code>@event.listens_for(Engine, "connect") def _set_sqlite_pragma(dbapi_connection, connection_record): if isinstance(dbapi_connection, SQLite3Connection): cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON;") cursor.close() </code></pre>
0
2016-08-08T10:34:25Z
[ "python", "flash", "flask-sqlalchemy", "foreign-key-relationship" ]
How would I modify/add text to a tkinter.Label?
38,792,787
<p>I am in the process of learning basic Python. I am currently attempting to create a simple calculator program that only has addition and subtraction. I have one issue though. I am not sure how I would add text to my Python label upon button press. Right now, upon pressing the '1' button, my program will change the display label to the text "1". However, I want my program to add text, not set it.</p> <p>For example, if I press 'button 1' 5 times, it currently will reset the label text 5 times and will result with a single 1. I want it to add the number to the label upon press, not replace.</p> <p>Current Result after pressing button 5 times: <strong>1</strong><br> Requested result after pressing button 5 times: <strong>11111</strong></p> <p>Here is my current code for the program. If anything is unclear, just ask; thanks.</p> <pre><code>from tkinter import * window = Tk() # Creating main label display = Label(window, text="") display.grid(row=0, columnspan=3) def add_one(): display.config(text='1') # Creating all number buttons one = Button(window, text="1", height=10, width=10, command=add_one) two = Button(window, text="2", height=10, width=10) three = Button(window, text="3", height=10, width=10) four = Button(window, text="4", height=10, width=10) five = Button(window, text="5", height=10, width=10) six = Button(window, text="6", height=10, width=10) seven = Button(window, text="7", height=10, width=10) eight = Button(window, text="8", height=10, width=10) nine = Button(window, text="9", height=10, width=10) zero = Button(window, text="0", height=10, width=10) # Placing all number buttons one.grid(row=1, column=0) two.grid(row=1, column=1) three.grid(row=1, column=2) four.grid(row=2, column=0) five.grid(row=2, column=1) six.grid(row=2, column=2) seven.grid(row=3, column=0) eight.grid(row=3, column=1) nine.grid(row=3, column=2) # Creating all other buttons add = Button(window, text="+", height=10, width=10) subtract = Button(window, text="-", height=10, width=10) equal = Button(window, text="=", height=10, width=10) # Placing all other buttons add.grid(row=4, column=0) subtract.grid(row=4, column=1) equal.grid(row=4, column=2) window.mainloop() </code></pre>
3
2016-08-05T15:24:14Z
38,792,942
<p>Is this what you're looking for:</p> <pre><code>from tkinter import * root = Tk() var = StringVar() def f1(): var.set(" ") var.set("1") def f2(): var.set(" ") var.set("2") label = Label(root, textvariable=var) label.pack() button1 = Button(root, text="One", command=f1) button1.pack() button2 = Button(root, text="Two", command=f2) button2.pack() </code></pre> <p>?</p>
0
2016-08-05T15:32:39Z
[ "python", "user-interface", "tkinter", "calculator" ]
How would I modify/add text to a tkinter.Label?
38,792,787
<p>I am in the process of learning basic Python. I am currently attempting to create a simple calculator program that only has addition and subtraction. I have one issue though. I am not sure how I would add text to my Python label upon button press. Right now, upon pressing the '1' button, my program will change the display label to the text "1". However, I want my program to add text, not set it.</p> <p>For example, if I press 'button 1' 5 times, it currently will reset the label text 5 times and will result with a single 1. I want it to add the number to the label upon press, not replace.</p> <p>Current Result after pressing button 5 times: <strong>1</strong><br> Requested result after pressing button 5 times: <strong>11111</strong></p> <p>Here is my current code for the program. If anything is unclear, just ask; thanks.</p> <pre><code>from tkinter import * window = Tk() # Creating main label display = Label(window, text="") display.grid(row=0, columnspan=3) def add_one(): display.config(text='1') # Creating all number buttons one = Button(window, text="1", height=10, width=10, command=add_one) two = Button(window, text="2", height=10, width=10) three = Button(window, text="3", height=10, width=10) four = Button(window, text="4", height=10, width=10) five = Button(window, text="5", height=10, width=10) six = Button(window, text="6", height=10, width=10) seven = Button(window, text="7", height=10, width=10) eight = Button(window, text="8", height=10, width=10) nine = Button(window, text="9", height=10, width=10) zero = Button(window, text="0", height=10, width=10) # Placing all number buttons one.grid(row=1, column=0) two.grid(row=1, column=1) three.grid(row=1, column=2) four.grid(row=2, column=0) five.grid(row=2, column=1) six.grid(row=2, column=2) seven.grid(row=3, column=0) eight.grid(row=3, column=1) nine.grid(row=3, column=2) # Creating all other buttons add = Button(window, text="+", height=10, width=10) subtract = Button(window, text="-", height=10, width=10) equal = Button(window, text="=", height=10, width=10) # Placing all other buttons add.grid(row=4, column=0) subtract.grid(row=4, column=1) equal.grid(row=4, column=2) window.mainloop() </code></pre>
3
2016-08-05T15:24:14Z
38,792,997
<p>You should use a StringVar for this. And your callback needs to get the current contents of the StringVar, modify it, and use the modified string to set the new value of the StringVar. Like this:</p> <pre><code>import tkinter as tk window = tk.Tk() # Creating main label display_text = tk.StringVar() display = tk.Label(window, textvariable=display_text) display.grid(row=0, columnspan=3) def add_one(): s = display_text.get() s += '1' display_text.set(s) one = tk.Button(window, text="1", height=10, width=10, command=add_one) one.grid(row=1, column=0) window.mainloop() </code></pre> <hr> <p>BTW, you should try to make your program a little more compact by using <code>for</code> loops to create and lay out your buttons, in accordance with the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself" rel="nofollow">DRY</a> principle.</p> <p>Also, it's not a good idea to use <code>from tkinter import *</code>. It imports over 130 names into your namespace, making it easy to create name collisions if you accidentally use a Tkinter name for one of your own variables or functions.</p>
2
2016-08-05T15:35:24Z
[ "python", "user-interface", "tkinter", "calculator" ]
How would I modify/add text to a tkinter.Label?
38,792,787
<p>I am in the process of learning basic Python. I am currently attempting to create a simple calculator program that only has addition and subtraction. I have one issue though. I am not sure how I would add text to my Python label upon button press. Right now, upon pressing the '1' button, my program will change the display label to the text "1". However, I want my program to add text, not set it.</p> <p>For example, if I press 'button 1' 5 times, it currently will reset the label text 5 times and will result with a single 1. I want it to add the number to the label upon press, not replace.</p> <p>Current Result after pressing button 5 times: <strong>1</strong><br> Requested result after pressing button 5 times: <strong>11111</strong></p> <p>Here is my current code for the program. If anything is unclear, just ask; thanks.</p> <pre><code>from tkinter import * window = Tk() # Creating main label display = Label(window, text="") display.grid(row=0, columnspan=3) def add_one(): display.config(text='1') # Creating all number buttons one = Button(window, text="1", height=10, width=10, command=add_one) two = Button(window, text="2", height=10, width=10) three = Button(window, text="3", height=10, width=10) four = Button(window, text="4", height=10, width=10) five = Button(window, text="5", height=10, width=10) six = Button(window, text="6", height=10, width=10) seven = Button(window, text="7", height=10, width=10) eight = Button(window, text="8", height=10, width=10) nine = Button(window, text="9", height=10, width=10) zero = Button(window, text="0", height=10, width=10) # Placing all number buttons one.grid(row=1, column=0) two.grid(row=1, column=1) three.grid(row=1, column=2) four.grid(row=2, column=0) five.grid(row=2, column=1) six.grid(row=2, column=2) seven.grid(row=3, column=0) eight.grid(row=3, column=1) nine.grid(row=3, column=2) # Creating all other buttons add = Button(window, text="+", height=10, width=10) subtract = Button(window, text="-", height=10, width=10) equal = Button(window, text="=", height=10, width=10) # Placing all other buttons add.grid(row=4, column=0) subtract.grid(row=4, column=1) equal.grid(row=4, column=2) window.mainloop() </code></pre>
3
2016-08-05T15:24:14Z
38,793,337
<p>You can define <code>add_one</code> like the following, to first get the existing value and then append a new value to it:</p> <pre><code>def add_one(): current_value = display.cget("text") new_value = current_value + "1" display.config(text=new_value) </code></pre>
1
2016-08-05T15:55:10Z
[ "python", "user-interface", "tkinter", "calculator" ]
matplotlib and engineering notation
38,792,849
<p>I'm using matplotlib to iterate a bunch of measurements over telnet...I set up the measurement with telnetlib and then read in the data, and set it up to be plotted. The problem is, I want it in engineering notation (exponents to multiples of three, so, kilo, mega, giga, etc.). However, I cannot make this work...Please see the code below...You'll notice I have commented out my latest attempt to force engineering notation with a call to a function that I defined manually.</p> <p>Any thoughts on how to do this?</p> <pre><code>import os import telnetlib import time import csv import sigan import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as mpatches from decimal import Decimal def eng(num): return Decimal(num).normalize().to_eng_string() print("What board revision is this?") # This name will be appended to the output files board=input() print("How long should I wait for the measurements to settle each time in seconds?") # This name will be appended to the output files rest=int(input()) ## Setup the Telnet link ## HOST = "192.168.0.118" tn = telnetlib.Telnet(HOST, "5024") ## Initialize the SA to a known State ## sigan.initialize_sa(tn) frequencies = [["30","100"],["100","500"],["500","1000"],["1000","2398"],["2485","3000"],["3000","3500"],["3500","4000"],["4000","4500"],["4500","5000"],["5000","5500"],["5500","6000"]] frequencies = [[str.encode(c) for c in s] for s in frequencies] tn.write(b'disp:wind:trac:y:rlev -25\r\n') tn.read_until(b'SCPI&gt;') tn.write(b'pow:aran on\r\n') tn.read_until(b'SCPI&gt;') tn.write(b'disp:wind:trac:y:pdiv 3\r\n') tn.read_until(b'SCPI&gt;') tn.write(b'trac:type maxh\r\n') tn.read_until(b'SCPI&gt;') tn.write(b'band:res 100khz\r\n') tn.read_until(b'SCPI&gt;') for i in range(len(frequencies)): if float(frequencies[1][0])&gt;=1000: tn.write(b'band:res 1mhz\r\n') tn.read_until(b'SCPI&gt;') print('Setting up the Analyzer for ' + str(frequencies [i][0]) + ' to ' + str(frequencies[i][1]) + ' Mhz') tn.write(b'sens:freq:stop '+frequencies[i][1]+b'mhz\r\n') tn.read_until(b'SCPI&gt;') tn.write(b'sens:freq:star '+frequencies[i][0]+b'mhz\r\n') tn.read_until(b'SCPI&gt;') print('Working on '+str(frequencies[i][0])[2:-1]+'MHz to ' +str(frequencies[i][1])[2:-1]+'MHz') print('Letting Maximum values settle out for ' + str(rest) + ' seconds') time.sleep(rest) tn.write(b'trac1:upd off\r\n') tn.read_until(b'SCPI&gt;') tn.write(b'read:san?\r\n') data=tn.read_until(b'SCPI&gt;') tn.write(b'trac1:upd on\r\n') tn.read_until(b'SCPI&gt;') data=data[:-7] data=np.fromstring(data.decode(),float,sep=',') x = data[::2] x_line=[30E6,6000E6] y_line=[-30,-30] y = data[1::2] # x = [eng(s) for s in x] plt.title(board+' at '+str(frequencies[i][0])[2:-1]+'MHz to '+str(frequencies[i][1])[2:-1]+'MHz') plt.xlabel('Frequency') plt.ylabel('Conducted Power (dBm)') plt.ylim(-60,-25) plt.xlim(float(x[1]),float(x[-1])) if (y&gt;-30).sum(): failure=mpatches.Patch(color='red', label='Failure') plt.legend(handles=[failure]) else: success=mpatches.Patch(color='green', label='Success') plt.legend(handles=[success]) plt.grid(True) plt.plot(x,y) plt.plot(x_line,y_line, color='r', linestyle='dashed', marker='x', markerfacecolor='black', markersize=12, lw=3, label='Threshold') plt.savefig(board+"_"+str(frequencies[i][0])[2:-1]+"_"+str(frequencies[i][1])[2:-1]) plt.cla() print("Test Finished and Images Written to '" + os.getcwd() + "'. SUCCESS!") tn.close() </code></pre>
0
2016-08-05T15:27:53Z
38,793,077
<p>One way is to get the tick-values and then format them and set the new formatted ones as labels. Look <a href="http://stackoverflow.com/questions/17973278/python-decimal-engineering-notation-for-mili-10e-3-and-micro-10e-6">here</a> for an example of the formatting. Sample code might be</p> <pre><code>xticks = ax.get_xticks() formatted_ticks = formatter_from_link_function(xticks) ax.set_xticklabels(formatted_ticks) </code></pre> <p>Another idea which might be a bit of overkill in your case is to use a user-defined formatter-function to the ticks. <a href="http://matplotlib.org/examples/pylab_examples/custom_ticker1.html" rel="nofollow">Here</a> is an example how to do that. With your own function formatter you can even return the string "kilo", "Mega", "atto" or whatever you like if you prefer that instead of the numerical "10e-3".</p>
0
2016-08-05T15:40:32Z
[ "python", "matplotlib" ]
For two lists, l1 and l2, how to check that for all e1 ∈ l1, ∃p(e1,e2) where e2 is some element in l2, efficiently in python?
38,793,001
<p>Ok, not sure if that was the best title, but I have two python lists. L1 and L2 which both have elements of type T and do not have the same length.</p> <p>I have a function p(T,T) which is a predicate checking a property about two elements of type T.</p> <p>I would like to check that for all elements e in L1, p(e,e') holds, where e' is SOME element in L2. so basically for each element in L1 I go over the second list, and check if the predicate holds for any of the elements. But I also want to check the same thing for the other list. </p> <p>p(T,T) is symmetric. So if p(e,e') then p(e',e). I do not want to do the same thing twice because of that symmetry. I need to somehow record that if I see p(e,e') then I know p(e',e) and not have to check again for the second list. </p> <p>What is the best way to do this in python? I thought about having another field for each element e1 in each list, telling us whether p(e1, e2) holds, where e2 is a member of the other list. But I think that requires copying both of those lists so I don't mutate them. Is there any good way to do this?</p>
0
2016-08-05T15:35:43Z
38,793,368
<p>The fact that <code>p</code> is symmetric is essentially useless. It's true that if you know <code>p(e, e')</code> holds, you know <code>p(e', e)</code> holds, but unless <code>e</code> and <code>e'</code> are both in both lists, you only get to make use of your predicate evaluation once instead of twice. Even if the lists are likely to have substantial overlap, it may still be more efficient to repeat <code>p</code> evaluations than to try to exploit symmetry.</p> <p>The best way to perform the check you want is probably going to involve reorganizing your data and taking advantage of some further structure of <code>e</code> to find a more efficient algorithm, but with the information we have, we can't help you with that. The best I can suggest is brute force:</p> <pre><code>def check(p, l1, l2): for a in l1: if not any(p(a, b) for b in l2): return False return True </code></pre>
2
2016-08-05T15:56:33Z
[ "python", "algorithm", "list", "iterator", "traversal" ]
For two lists, l1 and l2, how to check that for all e1 ∈ l1, ∃p(e1,e2) where e2 is some element in l2, efficiently in python?
38,793,001
<p>Ok, not sure if that was the best title, but I have two python lists. L1 and L2 which both have elements of type T and do not have the same length.</p> <p>I have a function p(T,T) which is a predicate checking a property about two elements of type T.</p> <p>I would like to check that for all elements e in L1, p(e,e') holds, where e' is SOME element in L2. so basically for each element in L1 I go over the second list, and check if the predicate holds for any of the elements. But I also want to check the same thing for the other list. </p> <p>p(T,T) is symmetric. So if p(e,e') then p(e',e). I do not want to do the same thing twice because of that symmetry. I need to somehow record that if I see p(e,e') then I know p(e',e) and not have to check again for the second list. </p> <p>What is the best way to do this in python? I thought about having another field for each element e1 in each list, telling us whether p(e1, e2) holds, where e2 is a member of the other list. But I think that requires copying both of those lists so I don't mutate them. Is there any good way to do this?</p>
0
2016-08-05T15:35:43Z
38,793,437
<p>I would just create a dictionary for each list (could be <code>dict1</code> and <code>dict2</code>), and when you iterate through the first list, you set both <code>dict1[e] = e'</code> and <code>dict2[e'] = e</code>. Then, when iterating through <code>L2</code>, you just check first that the current <code>e</code> isn't in <code>dict2</code>. Could also add this check to the first iteration in <code>L1</code> if there are duplicate <code>e</code> values. Hope that makes sense - writing this on my phone.</p>
0
2016-08-05T15:59:36Z
[ "python", "algorithm", "list", "iterator", "traversal" ]
replacing lines in file
38,793,047
<p>I have a file that looks like this (columns ar coordinates x,y,z and lines represents some objects):</p> <pre><code> 1.02 0.63 0.0003 -1.34 0.61 0.0002 0.0 0.0 0.0 -1.91 0.25 0.87 -1.32 1.70 0.0 0.02 -1.12 -0.06 </code></pre> <p>I want to: </p> <p>1) multiply second line by 3;</p> <p>2) find the differences between new values in line 2 and old valuesn(those I got by multiplying) in the same columns (i.e. the difference between second line's column one new value and old value, secons line's column two new value and old etc.) </p> <p>3)replace values in line 2 by new values;</p> <p>4) add the differences I got to the values in lines 4 and 5.</p> <p>So the output should look like:</p> <pre><code> 1.02 0.63 0.0003 -4.02 1.83 0.0006 0.0 0.0 0.0 -4.59 1.47 0.8704 -4.00 2.92 0.0004 -2.66 0.10 -0.0596 </code></pre> <p>What I got so far is:</p> <pre><code>import numpy as np a=np.loadtxt('geometry.in') C=s[1] b=np.array((a)[C]) #read second line as array x_old=b[0] #define coordinate x y_old=b[1] #define coordinate y z_old=b[2] #define coordinate z C_new=b*3 #multiplying all line by 3 x=C_new[0] #defining new values in columns of the line y=C_new[1] z=C_new[2] dx=x-x_old #the differene that I need to add to the first column of lines 4 and 5 dy=y-y_old dz=z-z_old </code></pre> <p>I tried a.replace(x_old, x) but it didn't work and I got really stuck in this.</p>
0
2016-08-05T15:38:25Z
38,795,489
<p>If you have to use numpy, here is an example you can work on: load the whole data as a numpy array "ao"</p> <pre><code> old2 = ao[1,:] new2 = ao[1,:]*3 diff = new2 - old2 ao[1,:] = new2 ao[3:,:] = ao[3:,:] + diff </code></pre>
0
2016-08-05T18:11:18Z
[ "python", "arrays", "replace", "lines" ]
I am trying to sort list of all the files in a folder on basis of modification date
38,793,106
<p>I am a beginner and trying to write code to display files in a folder on basis of their modification date in ascending order.</p> <p>I tried below code but i want to know how can i proceed to sort it.</p> <pre><code>import os file_path = "c:\\albert\\david" file1 = os.listdir(file_path) file2 = [os.path.join(file_path, f)for f in file1] print(file2) i=0 for f in file2: while (i&lt;11): file3=[(file2[i], os.path.getmtime(file2[i]), s.path.getsize(file2[i]))] i = i+1 print(file3) </code></pre> <p>I need help in how should i proceed now to sort it and print it.</p>
3
2016-08-05T15:42:15Z
38,796,386
<p>Change the lines after your <code>print(file2)</code> line, for a list comprehension similar to the one you used to form the <code>file2</code>:</p> <pre><code>file3 = [(f, os.path.getmtime(f), s.path.getsize(f)) for f in file2] </code></pre> <p>Now you only need to sort it on the second element of the tuple (the modification time), in ascending order (default).</p> <pre><code>from operator import itemgetter print(sorted(file3, key=itemgetter(1))) </code></pre>
1
2016-08-05T19:17:45Z
[ "python", "sorting" ]
Can a python program configure logging before running the rest of code?
38,793,237
<p><strong>NOTE</strong>: This question was based on an assumption that Python emits its error messages via logging. The answers show that the assumption is wrong.</p> <hr> <p>I'm developing a program that is not started from a command line, but by a daemon. Stderr is redirected to null device.</p> <p>Normally it logs messages to a file, but when some error is preventing a regular start, there is no error message to read, because it was sent to the null device.</p> <p>To save a little debugging time in such case I tried a little "launcher" which adds a file handler to the root logger as the very first thing.</p> <p>I have tested it with a deliberate syntax error in the <code>realprog</code> module. It logs the two "start" messages to the file, but the traceback from the syntax error is still printed to stderr. Could you please help?</p> <pre><code>import logging logger = logging.getLogger() logger.setLevel(logging.INFO) logger.addHandler(logging.FileHandler('test.log')) logger.info("logging start") def real_start(): # assume e.g. a syntax error in the realprog import realprog realprog.main() if __name__ == '__main__': logger.info("program start") real_start() </code></pre>
0
2016-08-05T15:49:23Z
38,793,621
<p>You could use:</p> <pre><code>if __name__ == '__main__': logger.info("program start") try: real_start() except Exception: # This will log the traceback. logger.exception("An error ocurred.") </code></pre> <p>However, you should increase your logger level to, at least, <code>logging.ERROR</code>.</p> <p>Hope it helps!</p>
1
2016-08-05T16:10:35Z
[ "python", "logging" ]
Can a python program configure logging before running the rest of code?
38,793,237
<p><strong>NOTE</strong>: This question was based on an assumption that Python emits its error messages via logging. The answers show that the assumption is wrong.</p> <hr> <p>I'm developing a program that is not started from a command line, but by a daemon. Stderr is redirected to null device.</p> <p>Normally it logs messages to a file, but when some error is preventing a regular start, there is no error message to read, because it was sent to the null device.</p> <p>To save a little debugging time in such case I tried a little "launcher" which adds a file handler to the root logger as the very first thing.</p> <p>I have tested it with a deliberate syntax error in the <code>realprog</code> module. It logs the two "start" messages to the file, but the traceback from the syntax error is still printed to stderr. Could you please help?</p> <pre><code>import logging logger = logging.getLogger() logger.setLevel(logging.INFO) logger.addHandler(logging.FileHandler('test.log')) logger.info("logging start") def real_start(): # assume e.g. a syntax error in the realprog import realprog realprog.main() if __name__ == '__main__': logger.info("program start") real_start() </code></pre>
0
2016-08-05T15:49:23Z
38,793,808
<p>You are not passing your exception to your logger, so there is no way for it to write it. </p> <p>inside your <code>real_start()</code>, put your import statement and your function call in a try, catch and then log the exception.</p> <p>Lets say for example your <code>realprog.main()</code> divides a number by zero, I want to log the exception, so I do this.</p> <pre><code>def real_start(): try: import realprog realprog.main() except ZeroDivisionError as e: logger.info(e, exc_info=True) </code></pre> <p>If you check your file, you should have the exception inside it. </p>
1
2016-08-05T16:22:01Z
[ "python", "logging" ]
NoReverseMatch following v1.9 to v1.10 upgrade
38,793,258
<p>I've just upgraded to django v1.10 and I'm running through tests to check everything works fine but I've getting <code>Reverse for 'django.contrib.auth.views.login' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []</code> on my login page.</p> <p>I'm using django-registration and have made a call to get the login page using <code>&lt;a href="/accounts/login/"&gt;Login&lt;/a&gt;</code>.</p> <p>I then get the error message against this the html and it is <code>&lt;form method="post" action="{% url 'django.contrib.auth.views.login' %}"&gt;</code> which is throwing up the error.</p> <pre><code>&lt;div class="container"&gt; &lt;div class="row text-center"&gt; &lt;div class="col-sm-12"&gt; &lt;form method="post" action="{% url 'django.contrib.auth.views.login' %}"&gt;{% csrf_token %} &lt;span style="color:green"&gt;{{msg}}&lt;/span&gt;&lt;br&gt; &lt;table align="center"&gt;{{ form }}&lt;/table&gt; &lt;button type="submit" class="btn btn-primary btn-sm"&gt;Login&lt;/button&gt; &lt;/form&gt; &lt;a href="/password/recover" class="btn btn-primary btn-sm"&gt;Forgotten Password&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I've not changed urls.py which looks includes:</p> <pre><code>url(r'^accounts/', include('registration.backends.hmac.urls')), </code></pre> <p>I've changed nothing going from 1.9 to 1.10 (and what I changed trying to fix this I've reverted). Any help gratefully received.</p>
2
2016-08-05T15:50:45Z
38,793,513
<p>From <a href="https://docs.djangoproject.com/en/stable/releases/1.10/#features-removed-in-1-10" rel="nofollow">Django 1.10 release notes</a>:</p> <blockquote> <p>The ability to <strong>reverse()</strong> URLs using a dotted Python path is removed.</p> </blockquote> <p>The <code>url</code> template tag uses <code>reverse()</code>. Thus this is <strong>not valid anymore</strong>:</p> <pre><code>{% url 'django.contrib.auth.views.login' %} </code></pre> <p>You must use the route name.</p> <p>See <a href="https://docs.djangoproject.com/en/stable/releases/1.8/#passing-a-dotted-path-to-reverse-and-url" rel="nofollow">Django 1.8 release notes</a> for details.</p>
1
2016-08-05T16:03:05Z
[ "python", "django" ]
Python 3.5: I am getting an error: "NameError: name 'multiprocessing' is not defined"
38,793,278
<p>I am getting an error: </p> <pre><code> pool = multiprocessing.Pool(5) NameError: name 'multiprocessing' is not defined </code></pre> <p>So, how to fix it ? Thank you very much :)</p> <pre><code>from multiprocessing import Pool from selenium.common.exceptions import TimeoutException from bs4 import BeautifulSoup from selenium import webdriver if __name__ == '__main__': driver = webdriver.Firefox() driver.get("https://www.facebook.com/") driver.find_element_by_css_selector("#email").send_keys("myemail@gmail.com") driver.find_element_by_css_selector("#pass").send_keys("mypassword") driver.find_element_by_css_selector("#u_0_m").click() pool = multiprocessing.Pool(5) pool.map(friend_uid_list, uid_list) </code></pre>
0
2016-08-05T15:51:53Z
38,793,313
<p>You are importing <code>Pool</code>, not <code>multiprocessing</code>.</p> <p>Replace <code>from multiprocessing import Pool</code> with <code>import multiprocessing</code></p>
0
2016-08-05T15:54:05Z
[ "python", "facebook", "multiprocessing" ]
Python 3.5: I am getting an error: "NameError: name 'multiprocessing' is not defined"
38,793,278
<p>I am getting an error: </p> <pre><code> pool = multiprocessing.Pool(5) NameError: name 'multiprocessing' is not defined </code></pre> <p>So, how to fix it ? Thank you very much :)</p> <pre><code>from multiprocessing import Pool from selenium.common.exceptions import TimeoutException from bs4 import BeautifulSoup from selenium import webdriver if __name__ == '__main__': driver = webdriver.Firefox() driver.get("https://www.facebook.com/") driver.find_element_by_css_selector("#email").send_keys("myemail@gmail.com") driver.find_element_by_css_selector("#pass").send_keys("mypassword") driver.find_element_by_css_selector("#u_0_m").click() pool = multiprocessing.Pool(5) pool.map(friend_uid_list, uid_list) </code></pre>
0
2016-08-05T15:51:53Z
38,793,318
<p>You haven't declared what <em>multiprocessing</em> is. You haven't imported the module either, you just imported <em>Pool</em> from <em>multiprocessing</em>. In other words, multiprocessing is not in your namespace, hence NameError. Try import the whole module and it should work.</p> <pre><code>import multiprocessing </code></pre> <p>Otherwise, since you imported <em>Pool</em>, you could just write:</p> <pre><code>pool = Pool(5) </code></pre>
0
2016-08-05T15:54:19Z
[ "python", "facebook", "multiprocessing" ]
Python 3.5: I am getting an error: "NameError: name 'multiprocessing' is not defined"
38,793,278
<p>I am getting an error: </p> <pre><code> pool = multiprocessing.Pool(5) NameError: name 'multiprocessing' is not defined </code></pre> <p>So, how to fix it ? Thank you very much :)</p> <pre><code>from multiprocessing import Pool from selenium.common.exceptions import TimeoutException from bs4 import BeautifulSoup from selenium import webdriver if __name__ == '__main__': driver = webdriver.Firefox() driver.get("https://www.facebook.com/") driver.find_element_by_css_selector("#email").send_keys("myemail@gmail.com") driver.find_element_by_css_selector("#pass").send_keys("mypassword") driver.find_element_by_css_selector("#u_0_m").click() pool = multiprocessing.Pool(5) pool.map(friend_uid_list, uid_list) </code></pre>
0
2016-08-05T15:51:53Z
38,793,435
<p>You have already <code>import Pool</code> from <code>multiprocessing</code>. So you need to replace the line</p> <pre><code>pool = multiprocessing.Pool(5) </code></pre> <p>by</p> <pre><code>pool = Pool(5) </code></pre>
0
2016-08-05T15:59:32Z
[ "python", "facebook", "multiprocessing" ]
What is the unit of height variable in "barh" of matplotlib?
38,793,456
<p>In the definition of the function barh of matplotlib:</p> <p><code>matplotlib.pyplot.barh(bottom, width, height=0.8, left=None, hold=None, **kwargs)</code></p> <p>The default "height" is 0.8, but when I draw some figures with different Figure's height for example (30, 40,..) and dpi=100. I see the Bar's height is changed. It's not fixed. So I wonder what is the unit of the height in barh and how to make it fixed (not depend on figure's height).</p>
3
2016-08-05T16:00:29Z
38,797,802
<p>I'll split this into two parts:</p> <blockquote> <p>I wonder what is the unit of the height in barh</p> </blockquote> <p>(Apparently people have been wondering this <a href="https://sourceforge.net/p/matplotlib/mailman/message/23874862/" rel="nofollow">since 2009</a>... so I guess you're in good company!)</p> <p>This question is the easier part - it's a percentage of the height allotted to the bar in the figure. For example, the default <code>height=0.8</code> means the height of the bar will be <code>0.8 * (plot_height / n_bars)</code>. You can see this by setting <code>height=1.0</code> (or even a value > 1, the bars will overlap).</p> <p>If you really want to be sure, here's the <a href="https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_axes.py#L2179" rel="nofollow">source of <code>axes.barh</code></a>. This just calls <code>axes.bar</code> - take a look at <a href="https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_axes.py#L2020" rel="nofollow">these lines</a>:</p> <pre><code>nbars = len(bottom) if len(left) == 1: left *= nbars if len(height) == 1: height *= nbars </code></pre> <p>And <a href="https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/axes/_axes.py#L2096" rel="nofollow">later on</a>...</p> <pre><code>args = zip(left, bottom, width, height, color, edgecolor, linewidth) for l, b, w, h, c, e, lw in args: if h &lt; 0: b += h h = abs(h) if w &lt; 0: l += w w = abs(w) r = mpatches.Rectangle( xy=(l, b), width=w, height=h, facecolor=c, edgecolor=e, linewidth=lw, label='_nolegend_', margins=margins ) r.update(kwargs) r.get_path()._interpolation_steps = 100 #print r.get_label(), label, 'label' in kwargs self.add_patch(r) patches.append(r) </code></pre> <p>So you see the height is scaled by <code>nbars</code>, and when you draw the rectangle they are spaced out by this height.</p> <blockquote> <p>how to make it fixed</p> </blockquote> <p>This is harder, you will have to manually set it. The bars on the chart are ultimately <code>matplotlib.patches.Rectangle</code> objects, which have a width and height... which is also a percentage. I think the best solution is to compute the appropriate percentage manually.</p> <p>Here's a short example, based off a <a href="http://matplotlib.org/examples/lines_bars_and_markers/barh_demo.html" rel="nofollow">barh demo</a>:</p> <pre><code>import matplotlib.pyplot as plt plt.rcdefaults() import numpy as np import matplotlib.pyplot as plt # Example data people = ('Tom', 'Dick', 'Harry', 'Slim', 'Jim') y_pos = np.arange(len(people)) performance = 3 + 10 * np.random.rand(len(people)) error = np.random.rand(len(people)) plt.figure(figsize=(5,5), dpi=80) myplot = plt.barh(y_pos, performance, height=0.8, xerr=error, align='center', alpha=0.4) plt.yticks(y_pos, people) plt.xlabel('Performance') plt.title('How fast do you want to go today?') for obj in myplot: # Let's say we want to set height of bars to always 5px.. desired_h = 5 current_h = obj.get_height() current_y = obj.get_y() pixel_h = obj.get_verts()[2][1] - obj.get_verts()[0][1] print("current position = ", current_y) print("current pixel height = ", pixel_h) # (A) Use ratio of pixels to height-units to calculate desired height h = desired_h / (pixel_h/current_h) obj.set_height(h) pixel_h = obj.get_verts()[2][1] - obj.get_verts()[0][1] print("now pixel height = ", pixel_h) # (B) Move the rectangle so it still aligns with labels and error bars y_diff = current_h - h # height is same units as y new_y = current_y + y_diff/2 obj.set_y(new_y) print("now position = ", obj.get_y()) plt.show() </code></pre> <p>Part A calculates <code>pixel_h/current_h</code> to get a conversion between pixels and height-units. Then we can divide <code>desired_h</code> (pixels) by that ratio to obtain <code>desired_h</code> in height-units. This sets the bar width to 5 px, but the bottom of the bar stays in the same place, so it's no longer aligned with the labels and error bars.</p> <p>Part B calculates the new y position. Since <code>y</code> and <code>height</code> are in the same units, we can just add half the height difference (<code>y_diff</code>) to get the new position. This keeps the bar centered around whatever original y-position it had.</p> <p>Note that this only sets the initial size. If you resize the plot, for example, the bars will still scale - you'd have to override that event to resize the bars appropriately.</p>
1
2016-08-05T21:09:39Z
[ "python", "matplotlib" ]
Django Celery Received unregistered task of type 'appname.tasks.add'
38,793,547
<p>Following the documentation and the Demo Django project here <a href="https://github.com/celery/celery/tree/3.1/examples/django" rel="nofollow">https://github.com/celery/celery/tree/3.1/examples/django</a></p> <p><strong>Project Structure</strong></p> <pre><code>piesup2 | piesup2 | |__init__.py | |celery.py | |settings.py | |urls.py reports |tasks.py |models.py |etc.... </code></pre> <p><strong>My Code</strong></p> <p><code>piesup2/celery.py</code></p> <pre><code>from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'piesup2.settings') from django.conf import settings # noqa app = Celery('piesup2') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) </code></pre> <p><code>piesup2/__init__.py</code></p> <pre><code>from __future__ import absolute_import # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app # noqa </code></pre> <p><code>piesup2/reports/tasks.py</code></p> <pre><code>from __future__ import absolute_import from celery import shared_task @shared_task def add(x, y): return x + y </code></pre> <p>After starting Celery from the command line with: </p> <pre><code>celery -A piesup2 worker -l info </code></pre> <p>When I attempt to run a task from within my models.py file like this:</p> <pre><code> def do_stuff(self): from reports.tasks import add number = add.delay(2, 2) print(number) </code></pre> <p>I get the following error:</p> <blockquote> <p>[2016-08-05 16:50:31,625: ERROR/MainProcess] Received unregistered task of type 'reports.tasks.add'. The message has been ignored and discarded.</p> <p>Did you remember to import the module containing this task? Or maybe you are using relative imports? Please see <a href="http://docs.celeryq.org/en/latest/userguide/tasks.html#task-names" rel="nofollow">http://docs.celeryq.org/en/latest/userguide/tasks.html#task-names</a> for more information.</p> <p>The full contents of the message body was: {'callbacks': None, 'retries': 0, 'chord': None, 'errbacks': None, 'task': 'reports.tasks.add', 'args': [2, 2], 'timelimit': [None, None], 'kwargs': {}, 'id': 'b12eb387-cf8c-483d-b53e-f9ce0ad6b421', 'taskset': None, 'eta': None, 'expires': None, 'utc': True} (258b) Traceback (most recent call last): File "/home/jwe/piesup2/venv/lib/python3.4/site-packages/celery/worker/consumer.py", line 456, in on_task_received strategies[name](message, body, KeyError: 'reports.tasks.add'</p> </blockquote>
0
2016-08-05T16:06:17Z
38,836,969
<p>In your django settings you need to add each module that has a celery task to CELERY_IMPORTS</p> <pre><code>CELERY_IMPORTS = ( 'reports.tasks', 'some_app.some_module', ) </code></pre>
2
2016-08-08T19:20:35Z
[ "python", "django", "celery" ]
python module names with same name as existing modules
38,793,579
<p>I have a number of small utils modules that i organize under a 'msa' namespace so I can use in a number of different research projects. Currently I have them organized like this:</p> <pre><code># folder structure: packages &lt;-- in my pythonpath --msa ----msa_utils.py ----msa_geom.py ----msa_pyglet.py ----msa_math.py ----etc # imported and used this like from msa import msa_pyglet from msa import msa_math msa_pyglet.draw_rect(msa_math.lerp(...)) </code></pre> <p>However I would like to avoid the 'msa_' in the names and use like this:</p> <pre><code># folder structure: packages &lt;-- in my pythonpath --msa ----utils.py ----geom.py ----pyglet.py ----math.py ----etc # imported and used this like import msa.pyglet import msa.math msa.pyglet.draw_rect(msa.math.lerp(...)) </code></pre> <p>This shouldn't cause name conflicts when importing from outside, however there are name conflicts when the modules themselves import modules with conflicting names. E.g. msa/pyglet needs to imports pyglet (the external one), but ends up trying to import itself. Likewise any module which tries to import the standard math library imports only my math module. Which is all understandable. But what is the usual pythonic way of dealing with this? Do I have to give each module file a globally unique name? </p>
0
2016-08-05T16:07:34Z
38,793,613
<p>In Python 2, imports in packages without a package qualifier indeed first look for <em>package local</em> modules.</p> <p>Thus, <code>import pyglet</code> will find <code>msa.pyglet</code> before the top-level <code>pyglet</code> is considered.</p> <p>Switch to absolute imports to make the Python 3 behaviour the default, where unqualified names are always <em>top level</em> names:</p> <pre><code>from __future__ import absolute_import </code></pre> <p>Now <code>import pyglet</code> can only ever find the top-level name, never <code>msa.pyglet</code>. To reference other modules within your <code>msa</code> namespace, use <code>from . import pyglet</code> or <code>from msa import pyglet</code>.</p> <p>See <a href="https://www.python.org/dev/peps/pep-0328/" rel="nofollow">PEP 328 -- <em>Imports: Multi-Line and Absolute/Relative</em></a> for more details.</p>
2
2016-08-05T16:10:06Z
[ "python", "module" ]
What happens when an exception occurs in a module initialization
38,793,581
<p>I have a module, and in this module I initialize some variables as soon as the module is imported.</p> <p>my_mobule.py:</p> <pre><code>def _build_service(): # ...do some stuffs _service = _build_service() </code></pre> <p>In this case, what will happen if the <code>_build_service</code> method raises an exception? And how my module can recover from an exception and try to invoke the <code>_build_service</code> again?</p> <p>Thank you guys.</p>
1
2016-08-05T16:07:37Z
38,793,648
<p>It's pretty similar to the behaviour should you call a function which raises an exception - if you don't handle the exception in the module itself, then it will be simply bump up the stack to whoever imported your module. </p> <p>That would look like this:</p> <pre><code>&gt;&gt;&gt; import my_mobule # sic UhohError: something went wrong </code></pre> <p>If you have an opportunity to handle it in the module, you could do it like so:</p> <pre><code>try: _service = _build_service() except UhohError: # your handling code here </code></pre>
1
2016-08-05T16:11:47Z
[ "python", "python-2.7", "python-module" ]
Create Gtk3 Treeview with CellRendererToggle and Names from List with Python
38,793,605
<p>I try to create a Gtk.TreeView with header names from a list. Because I want to use it to show entries from different databases later.</p> <p>The problem: When I click on a cell and try to activate it all cells in the row getting activated. More strange, they look not activated, only if I move the cursor over them (not clicking). </p> <p>What is the problem with this code?</p> <pre><code>#!/usr/bin/env python #-*- coding: utf-8 -*- import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import Gdk class CellRendererToggleWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="CellRendererToggle Example") self.set_default_size(400, 200) self.mainbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing = 10) self.add(self.mainbox) self.myliststore = Gtk.ListStore(bool,bool,str) self.treeview = Gtk.TreeView(self.myliststore) for n, header_text in enumerate(["Aktive", "Warning", "Text"]): if header_text in ["Aktive", "Warning"]: cell = Gtk.CellRendererToggle() cell.connect("toggled", self.on_sync_treeview_button_toggled, n, header_text ) column = Gtk.TreeViewColumn(header_text, cell) else: cell = Gtk.CellRendererText() cell.set_property('editable', True) column = Gtk.TreeViewColumn(header_text, cell, text=n) column.set_sort_column_id(n) self.treeview.append_column(column) self.myliststore.append([True, True, "Super6!"]) self.myliststore.append([True, True, "Super7!"]) self.myliststore.append([True, True, "Super8!"]) self.mainbox.pack_start(self.treeview, True, True, 0) def on_sync_treeview_button_toggled(self, widget, path, column, data): widget.set_active( [True,False][widget.get_active()] ) win = CellRendererToggleWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main() </code></pre>
1
2016-08-05T16:09:36Z
38,854,444
<p>The concept of 'selecting a cell' is not really implemented in a <code>GtkTreeView</code>. If you look over all the functions available for TreeView, very few of them really addresses single cells.</p> <p>That leaves you with these options: </p> <ol> <li><p>Implement your own 'single cell' highlighting (such as adding a border or changing the background color, eg. by adding extra columns which change the properties of the cells.</p></li> <li><p>Using a <code>Gtk.Grid</code>, where the 'granularity' is one cell, but which does not have the niceties of column headers, and a nice model to load the data into.</p></li> <li><p>Another solution to highlight a cell (the row is already highlighted), is to change the color (or other property) of the corresponding column header.</p></li> </ol> <p>None of the options is really attractive, and each method requires some work.</p>
0
2016-08-09T15:09:34Z
[ "python", "gtk3" ]
Create Gtk3 Treeview with CellRendererToggle and Names from List with Python
38,793,605
<p>I try to create a Gtk.TreeView with header names from a list. Because I want to use it to show entries from different databases later.</p> <p>The problem: When I click on a cell and try to activate it all cells in the row getting activated. More strange, they look not activated, only if I move the cursor over them (not clicking). </p> <p>What is the problem with this code?</p> <pre><code>#!/usr/bin/env python #-*- coding: utf-8 -*- import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import Gdk class CellRendererToggleWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="CellRendererToggle Example") self.set_default_size(400, 200) self.mainbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing = 10) self.add(self.mainbox) self.myliststore = Gtk.ListStore(bool,bool,str) self.treeview = Gtk.TreeView(self.myliststore) for n, header_text in enumerate(["Aktive", "Warning", "Text"]): if header_text in ["Aktive", "Warning"]: cell = Gtk.CellRendererToggle() cell.connect("toggled", self.on_sync_treeview_button_toggled, n, header_text ) column = Gtk.TreeViewColumn(header_text, cell) else: cell = Gtk.CellRendererText() cell.set_property('editable', True) column = Gtk.TreeViewColumn(header_text, cell, text=n) column.set_sort_column_id(n) self.treeview.append_column(column) self.myliststore.append([True, True, "Super6!"]) self.myliststore.append([True, True, "Super7!"]) self.myliststore.append([True, True, "Super8!"]) self.mainbox.pack_start(self.treeview, True, True, 0) def on_sync_treeview_button_toggled(self, widget, path, column, data): widget.set_active( [True,False][widget.get_active()] ) win = CellRendererToggleWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main() </code></pre>
1
2016-08-05T16:09:36Z
38,955,150
<p>TreeViewColumn needs an attribute for "active" with the position in the store:</p> <pre><code>column.add_attribute(cell, "active", n) </code></pre> <p>And I also had to change the underlying store and not the widget:</p> <pre><code>self.myliststore[path][column] = not self.myliststore[path][column] </code></pre> <p>Thanks for this example: <a href="https://github.com/Programmica/python-gtk3-tutorial/blob/master/_examples/cellrenderertoggle.py" rel="nofollow">https://github.com/Programmica/python-gtk3-tutorial/blob/master/_examples/cellrenderertoggle.py</a></p> <p>Now it is working:</p> <pre><code>#!/usr/bin/env python #-*- coding: utf-8 -*- import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk from gi.repository import Gdk class CellRendererToggleWindow(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="CellRendererToggle Example") self.set_default_size(400, 200) self.mainbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing = 10) self.add(self.mainbox) self.myliststore = Gtk.ListStore(bool,bool,str) self.treeview = Gtk.TreeView(self.myliststore) for n, header_text in enumerate(["Aktive", "Warning", "Text"]): if header_text in ["Aktive", "Warning"]: cell = Gtk.CellRendererToggle() cell.connect("toggled", self.on_sync_treeview_button_toggled, n, header_text ) column = Gtk.TreeViewColumn(header_text, cell) column.add_attribute(cell, "active", n) else: cell = Gtk.CellRendererText() cell.set_property('editable', True) column = Gtk.TreeViewColumn(header_text, cell, text=n) column.set_sort_column_id(n) self.treeview.append_column(column) self.myliststore.append([True, False, "Super6!"]) self.myliststore.append([True, True, "Super7!"]) self.myliststore.append([False, True, "Super8!"]) self.mainbox.pack_start(self.treeview, True, True, 0) def on_sync_treeview_button_toggled(self, widget, path, column, data): self.myliststore[path][column] = not self.myliststore[path][column] win = CellRendererToggleWindow() win.connect("delete-event", Gtk.main_quit) win.show_all() Gtk.main() </code></pre>
1
2016-08-15T12:31:45Z
[ "python", "gtk3" ]
Python lru_cache usage optimization
38,793,633
<p>Say I have this method that I cache using <a href="https://docs.python.org/3/library/functools.html" rel="nofollow"><code>lru_cache</code></a>:</p> <pre><code>@lru_cache(maxsize=8) def very_expensive_call(number): # do something that's very expensive return number </code></pre> <p>I am calling this method like this:</p> <pre><code>print([very_expensive_call(i) for i in range(10)]) # call_1 </code></pre> <p>Because the maxsize of the cache is 8, only numbers 2-9 are cached at this point. </p> <p>After call_1, I am doing call_2:</p> <pre><code>print([very_expensive_call(i) for i in range(10)]) # call_2 </code></pre> <p>During call_2, again first number <code>0</code> is called (not in cache!), and after that numbers 0 and 3-9 are cached. Then number <code>1</code> is called (not in cache!) and after that numbers 0-1 and 4-9 are cached. Well, you see where this is going: the cache is never used...</p> <p>I understand that for this specific example I could alternate between <code>range(...</code> and <code>reverse(range(...</code> but in a more complicated scenario that's probably not possible.</p> <p><strong>Question</strong>: Is it possible to inspect which numbers are cached and to order the calls based on that? What would be the overhead for this?</p>
0
2016-08-05T16:11:18Z
38,795,337
<p>No, no, the <code>cache</code> used in <code>lru</code> is specifically designed to not be public-facing. All its internals <a href="https://hg.python.org/cpython/file/3.5/Lib/functools.py#l411" rel="nofollow"><em>are encapsulated</em></a> for thread safety and in order to not break code if the implementation changes.</p> <p>Apart from that, I don't think it is a good idea to base your input based on caching, you should cache based on your input. If your callable is not periodically called with the same arguments, maybe a cache is not the best option. </p>
1
2016-08-05T18:00:45Z
[ "python", "python-3.x", "caching", "optimization" ]
How do I silence output to stdout in rpy2?
38,793,688
<p>I have an R function that I call from my Python script using rpy2. The R function prints to stdout; is there a parameter in rpy2 that silences stdout when an R script is called?</p>
0
2016-08-05T16:14:38Z
38,798,986
<p>rpy2 lets you redefine R's own interaction with a terminal as python function.</p> <p>The following example from the documentation shows how to append output to <code>stdout</code> to a Python list (limited usefulness in the grand scheme of things, but it makes a simple examples of the feature):</p> <pre><code>buf = [] def f(x): # function that append its argument to the list 'buf' buf.append(x) # output from the R console will now be appended to the list 'buf' rinterface.set_writeconsole(f) date = rinterface.baseenv['date'] rprint = rinterface.baseenv['print'] rprint(date()) # the output is in our list (as defined in the function f above) print(buf) # restore default function rinterface.set_writeconsole(rinterface.consolePrint) </code></pre> <p>The documentation is here: <a href="http://rpy2.readthedocs.io/en/version_2.8.x/callbacks.html#console-i-o" rel="nofollow">http://rpy2.readthedocs.io/en/version_2.8.x/callbacks.html#console-i-o</a></p>
0
2016-08-05T23:20:41Z
[ "python", "rpy2" ]
Python sort a list of objects/dictionaries with a given sortKey function
38,793,694
<p>(I use Python 2 here)</p> <p>I have a list of dictionaries, say</p> <pre><code>dei = [{'name': u'Thor'}, {'name': u'Œdipus'}, {'name': u'Creon'}] </code></pre> <p>I would like to sort that list by their <code>'name'</code> attribute. This is easily done so:</p> <pre><code>dei.sort(key=lambda d: d['name']) </code></pre> <p>Now, because Python’s alphabetical sorting is ASCII-driven, the result will be</p> <pre><code>[{'name': u'Creon'}, {'name': u'Thor'}, {'name': u'Œdipus'}] </code></pre> <p>while I’d like Œdipus to be between Creon and Thor.</p> <p>Following <a href="http://stackoverflow.com/a/11124645">this suggestion</a>, I use PyICU’s <code>collator.getSortKey()</code> function (let’s rename it <code>sortKey()</code> for readability), which works this way on a list <code>strings</code> of strings:</p> <pre><code>strings.sort(key=sortKey) </code></pre> <p>My problem here: as I cannot modify the <code>sortKey()</code> function anyhow, how can I use it to sort a list of more complex objects (here, dictionaries) according to some attribute?</p> <p>The only way I found for the moment is by extracting the values of the dictionary in a separate list, sorting it, then implementing a custom <code>compare(a, b)</code> function returning −1, 0 or 1 depending on the index of <code>a</code> and <code>b</code> in the separate list, and calling <code>sort()</code> with this <code>compare()</code> function:</p> <pre><code>names = sorted([d['name'] for d in dei], key=sortKey) def compare(a, b): if names.index(a) &lt; names.index(b): return -1 elif names.index(a) &gt; names.index(b): return 1 else: return 0 results = dei.sort(key=lambda d: d['name'], cmp=compare) </code></pre> <p>which I don’t find very elegant.</p>
3
2016-08-05T16:15:01Z
38,794,186
<p>You can use your own key that internally calls <code>getSortKey</code> with correct value:</p> <pre><code>&gt;&gt;&gt; import icu &gt;&gt;&gt; dei = [{'name': u'Thor'}, {'name': u'Œdipus'}, {'name': u'Creon'}] &gt;&gt;&gt; collator = icu.Collator.createInstance() &gt;&gt;&gt; dei.sort(key=lambda x: collator.getSortKey(x['name'])) &gt;&gt;&gt; dei [{'name': 'Creon'}, {'name': 'Œdipus'}, {'name': 'Thor'}] </code></pre>
0
2016-08-05T16:47:34Z
[ "python", "sorting", "dictionary", "pyicu" ]
Numpy std calculation: TypeError: cannot perform reduce with flexible type
38,793,713
<p>I am trying to read lines of numbers starting at line 7 and compiling the numbers into a list until there is no more data, then calculate standard deviation and %rms on this list. Seems straightforward but I keep getting the error:</p> <pre><code>Traceback (most recent call last): File "rmscalc.py", line 21, in &lt;module&gt; std = np.std(values) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/fromnumeric.py", line 2817, in std keepdims=keepdims) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/_methods.py", line 116, in _std keepdims=keepdims) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/numpy/core/_methods.py", line 86, in _var arrmean = um.add.reduce(arr, axis=axis, dtype=dtype, keepdims=True) TypeError: cannot perform reduce with flexible type </code></pre> <p>Here is my code below: </p> <pre><code>import numpy as np import glob import os values = [] line_number = 6 road = '/Users/allisondavis/Documents/HCl' for pbpfile in glob.glob(os.path.join(road, 'pbpfile*')): lines = open(pbpfile, 'r').readlines() while line_number &lt; 400 : if lines[line_number] == '\n': break else: variables = lines[line_number].split() values.append(variables) line_number = line_number + 3 print values a = np.asarray(values).astype(np.float32) std = np.std(a) rms = std * 100 print rms </code></pre> <p>Edit: It produces an rms (which is wrong - not sure why yet) but the following error message is confusing: I need the count to be high (picked 400 just to ensure it would get the entire file no matter how large)</p> <pre><code> Traceback (most recent call last): File "rmscalc.py", line 13, in &lt;module&gt; if lines[line_number] == '\n': IndexError: list index out of range </code></pre>
0
2016-08-05T16:16:03Z
38,794,051
<p><code>values</code> is a string array and so is <code>a</code>. Convert <code>a</code> into a numeric type using <code>astype</code>. For example,</p> <pre><code>a = np.asarray(values).astype(np.float32) std = np.std(a) </code></pre>
1
2016-08-05T16:37:57Z
[ "python", "error-handling" ]
Distributed Tensorflow: ValueError “When: When using replicas, all Variables must have their device set” set: name: "Variable"
38,793,718
<p>I am trying to write a distributed variational auto encoder on tensorflow in <code>standalone mode</code>.</p> <p>My cluster includes 3 machines, naming m1, m2 and m3. I am trying to run 1 ps server on m1, and 2 worker servers on m2 and m3. (Example trainer program in <a href="https://www.tensorflow.org/versions/r0.10/how_tos/distributed/index.html" rel="nofollow">distributed tensorflow documentation</a>) On m3 I got the following error message:</p> <pre><code>Traceback (most recent call last): File "/home/yama/mfs/ZhuSuan/examples/vae.py", line 241, in &lt;module&gt; save_model_secs=600) File "/mfs/yama/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/training/supervisor.py", line 334, in __init__ self._verify_setup() File "/mfs/yama/tensorflow/local/lib/python2.7/site-packages/tensorflow/python/training/supervisor.py", line 863, in _verify_setup "their device set: %s" % op) ValueError: When using replicas, all Variables must have their device set: name: "Variable" op: "Variable" attr { key: "container" value { s: "" } } attr { key: "dtype" value { type: DT_INT32 } } attr { key: "shape" value { shape { } } } attr { key: "shared_name" value { s: "" } } </code></pre> <p>And this is the part of my code, which defines the network and Supervisor.</p> <pre><code>if FLAGS.job_name == "ps": server.join() elif FLAGS.job_name == "worker": #set distributed device with tf.device(tf.train.replica_device_setter( worker_device="/job:worker/task:%d" % FLAGS.task_index, cluster=clusterSpec)): # Build the training computation graph x = tf.placeholder(tf.float32, shape=(None, x_train.shape[1])) optimizer = tf.train.AdamOptimizer(learning_rate=0.001, epsilon=1e-4) with tf.variable_scope("model") as scope: with pt.defaults_scope(phase=pt.Phase.train): train_model = M1(n_z, x_train.shape[1]) train_vz_mean, train_vz_logstd = q_net(x, n_z) train_variational = ReparameterizedNormal( train_vz_mean, train_vz_logstd) grads, lower_bound = advi( train_model, x, train_variational, lb_samples, optimizer) infer = optimizer.apply_gradients(grads) #print(type(lower_bound)) # Build the evaluation computation graph with tf.variable_scope("model", reuse=True) as scope: with pt.defaults_scope(phase=pt.Phase.test): eval_model = M1(n_z, x_train.shape[1]) eval_vz_mean, eval_vz_logstd = q_net(x, n_z) eval_variational = ReparameterizedNormal( eval_vz_mean, eval_vz_logstd) eval_lower_bound = is_loglikelihood( eval_model, x, eval_variational, lb_samples) eval_log_likelihood = is_loglikelihood( eval_model, x, eval_variational, ll_samples) #saver = tf.train.Saver() summary_op = tf.merge_all_summaries() global_step = tf.Variable(0) init_op = tf.initialize_all_variables() # Create a "supervisor", which oversees the training process. sv = tf.train.Supervisor(is_chief=(FLAGS.task_index == 0), logdir=LogDir, init_op=init_op, summary_op=summary_op, # saver=saver, global_step=global_step, save_model_secs=600) print("create sv done") </code></pre> <p>I think there must be something wrong with my code, but I don't know how to fix it. Any advice? Thanks a lot!</p>
2
2016-08-05T16:16:12Z
38,794,027
<p>The problem stems from the definition of your <code>global_step</code> variable:</p> <pre><code>global_step = tf.Variable(0) </code></pre> <p>This definition is outside the scope of the <code>with tf.device(tf.train.replica_device_setter(...)):</code> block above, so no device is assigned to <code>global_step</code>. In replicated training, this is often a source of error (because if different replicas decide to place the variable on a different device, they won't share the same value), so TensorFlow includes a sanity check that prevents this.</p> <p>Fortunately, the solution is simple. You can either define <code>global_step</code> inside the <code>with tf.device(tf.train.replica_device_setter(...)):</code> block above, or add a small <code>with tf.device("/job:ps/task:0"):</code> block as follows:</p> <pre><code>with tf.device("/job:ps/task:0"): global_step = tf.Variable(0, name="global_step") </code></pre>
1
2016-08-05T16:36:22Z
[ "python", "tensorflow" ]
Remove numbers conditionally?
38,793,863
<p>I'm sorry if the title isn't very descriptive. I don't exactly know how to sum up my problem in a few words.</p> <p>Here's my issue. I'm cleaning addresses and some of them are causing some issues.</p> <p>I have a list of delimiters (avenue, street, road, place, etc etc etc) named <code>patterns</code>.</p> <p>Let's say I have this address for example: <code>SUITE 1603 200 PARK AVENUE SOUTH NEW YORK</code></p> <p>I would like the output to be <code>SUITE 200 PARK AVENUE SOUTH NEW YORK</code></p> <p>Is there any way I could somehow look to see if there are 2 batches of numbers (in this case <code>1603</code> and <code>200</code>) before one of my patterns and if so, strip the first batch of numbers from my string? i.e remove <code>1603</code> and keep <code>200</code>.</p> <p>Update: I've added this line to my code: </p> <p><code>address = re.sub("\d+", "", address)</code> however it's currently removing all the numbers. I thought that by putting ,1 after address it would only remove the first occurrence but that wasn't the case</p>
1
2016-08-05T16:25:54Z
38,794,269
<p>Your description of what you want to do isn't very clear, but if I understand correctly you want to is to delete the first occurrence of a number sequence?</p> <p>You could do this without using a <em>regex</em>,</p> <pre><code>s = 'SUITE 1603 200 PARK AVENUE SOUTH NEW YORK' l = s.split(' ') for i, w in enumerate(l): for c in w: if c.isdigit(): del l[i] break print ' '.join(l) </code></pre> <p><strong>Output:</strong> <code>&gt;&gt;&gt; SUITE 200 PARK AVENUE SOUTH NEW YORK</code></p>
1
2016-08-05T16:52:59Z
[ "python" ]