title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Secret key is there though it is saying no secret key in django | 39,217,362 | <p>When i'm running python manage.py runserver or python manage.py migrate. I'm getting these errors</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 190, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 40, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 14, in <module>
from django.db.migrations.executor import MigrationExecutor
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 6, in <module>
from .loader import MigrationLoader
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 10, in <module>
from django.db.migrations.recorder import MigrationRecorder
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 9, in <module>
class MigrationRecorder(object):
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 23, in MigrationRecorder
class Migration(models.Model):
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 24, in Migration
app = models.CharField(max_length=255)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1081, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 161, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 113, in __init__
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
</code></pre>
<p>This is my development settings</p>
<pre><code>"""
Django settings for kgecweb project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'my_secret key here'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#DEBUG = False
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'administration',
'stdimage',
'dept',
'trplc', # Training and Placement app
'faculty',
'student',
'hostels',
'nkn',
'clibrary',
'page',
'contact'
)
MIDDLEWARE_CLASSES = (
'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',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'kgecweb.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',
],
},
},
]
WSGI_APPLICATION = 'kgecweb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
#'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.mysql'),
'USER': 'root',
'PASSWORD': '713331',
'HOST': '192.168.33.19',
'PORT': '3306',
#'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATICFILES_DIRS = (os.path.join(BASE_DIR, "../static"),)
#STATIC_ROOT= os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, '../media')
MEDIA_URL = '/media/'
</code></pre>
<p>I also have made the sql command for initializing database and secret key is also not empty here. Though it keep on saying. i don't know how to tackle this.
This is my project directory
<a href="http://i.stack.imgur.com/iJvj0.png" rel="nofollow"><img src="http://i.stack.imgur.com/iJvj0.png" alt="enter image description here"></a></p>
<p>I even tried making a settings.py file then also this error is coming.</p>
| 0 | 2016-08-30T01:07:04Z | 39,217,791 | <p>From the vanilla <code>settings.py</code> you can specify what settings to do by setting an environment variable to tell settings which to use. For example.</p>
<p>Suppose you have an env variable called DJANGO_ENV='prod' then in your settings.py</p>
<pre><code>import os
environment = os.environ.get('DJANGO_ENV', 'dev')
if environment == 'prod':
from project_folder.production_settings import *
else:
from project_folder.development_settings import *
#rest of code
</code></pre>
| 0 | 2016-08-30T02:13:45Z | [
"python",
"django"
] |
Secret key is there though it is saying no secret key in django | 39,217,362 | <p>When i'm running python manage.py runserver or python manage.py migrate. I'm getting these errors</p>
<pre><code>Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 190, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 40, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
__import__(name)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 14, in <module>
from django.db.migrations.executor import MigrationExecutor
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 6, in <module>
from .loader import MigrationLoader
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 10, in <module>
from django.db.migrations.recorder import MigrationRecorder
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 9, in <module>
class MigrationRecorder(object):
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 23, in MigrationRecorder
class Migration(models.Model):
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 24, in Migration
app = models.CharField(max_length=255)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 1081, in __init__
super(CharField, self).__init__(*args, **kwargs)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py", line 161, in __init__
self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__
self._setup(name)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/home/sroy8091/college/local/lib/python2.7/site-packages/django/conf/__init__.py", line 113, in __init__
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
</code></pre>
<p>This is my development settings</p>
<pre><code>"""
Django settings for kgecweb project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'my_secret key here'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
#DEBUG = False
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django_extensions',
'administration',
'stdimage',
'dept',
'trplc', # Training and Placement app
'faculty',
'student',
'hostels',
'nkn',
'clibrary',
'page',
'contact'
)
MIDDLEWARE_CLASSES = (
'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',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'kgecweb.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',
],
},
},
]
WSGI_APPLICATION = 'kgecweb.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
#'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.mysql'),
'USER': 'root',
'PASSWORD': '713331',
'HOST': '192.168.33.19',
'PORT': '3306',
#'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Kolkata'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
STATICFILES_DIRS = (os.path.join(BASE_DIR, "../static"),)
#STATIC_ROOT= os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, '../media')
MEDIA_URL = '/media/'
</code></pre>
<p>I also have made the sql command for initializing database and secret key is also not empty here. Though it keep on saying. i don't know how to tackle this.
This is my project directory
<a href="http://i.stack.imgur.com/iJvj0.png" rel="nofollow"><img src="http://i.stack.imgur.com/iJvj0.png" alt="enter image description here"></a></p>
<p>I even tried making a settings.py file then also this error is coming.</p>
| 0 | 2016-08-30T01:07:04Z | 39,240,194 | <p>You <strong>misspelled</strong> the name of the file.</p>
<p>change </p>
<pre><code>devlopment.py
</code></pre>
<p>to </p>
<pre><code>development.py
</code></pre>
<p>and everything should work with calling the file directly</p>
| 0 | 2016-08-31T03:17:22Z | [
"python",
"django"
] |
One out of four radio buttons hidden | 39,217,462 | <p>I have four sets of radio buttons, each set wrapped in a div called "choiceSet". On firefox for windows I see all four sets of radio buttons. My coworker only sees three sets in firefox. Both of us see only 3/4 sets in chrome. In linux I don't see the offending set of radio buttons regardless of the browser. </p>
<p>Any ideas? Whenever I have a problem like this in Python it turns out that I used a reserved word for something. </p>
<p>The html is here:
<a href="https://github.com/melvyniandrag/SentimentLabeler/blob/master/mysite/polls/templates/polls/detail.html" rel="nofollow">https://github.com/melvyniandrag/SentimentLabeler/blob/master/mysite/polls/templates/polls/detail.html</a></p>
<p>Here is the offending html/django:</p>
<pre><code><div class="choiceSet">
<h3>Ad?</h3>
{% for advertisement in question.advertisement_set.all %}
{% if 'not' in advertisement.ad_text %}
<input type="radio" name="advertisement" id="advertisement{{ forloop.counter }}" value="{{ advertisement.id }}" checked/>
{% endif %}
{% if 'not' not in advertisement.ad_text %}
<input type="radio" name="advertisement" id="advertisement{{ forloop.counter }}" value="{{ advertisement.id }}" />
{% endif %}
<label for="advertisement{{ forloop.counter }}">{{ advertisement.ad_text }}</label><br />
{% endfor %}
</div>
</code></pre>
<p>which becomes:</p>
<pre><code><div class="choiceSet">
<h3>Ad?</h3>
<input type="radio" class="radiobutton" name="advertisement" id="advertisement1" value="17" />
<label for="advertisement1">advertisement</label><br />
<input type="radio" class="radiobutton" name="advertisement" id="advertisement2" value="18" checked/>
<label for="advertisement2">not advertisement</label><br />
</div>
</code></pre>
<p>the css is here: <code><a href="https://github.com/melvyniandrag/SentimentLabeler/blob/master/mysite/polls/static/polls/detail.css" rel="nofollow">https://github.com/melvyniandrag/SentimentLabeler/blob/master/mysite/polls/static/polls/detail.css</a></code></p>
<p>If you </p>
<pre><code>git clone https://github.com/melvyniandrag/SentimentLabeler.git
cd mysite
python manage.py runserver
open 127.0.0.1:8000
login a/password
</code></pre>
<p>you will see the problem.</p>
| 1 | 2016-08-30T01:21:16Z | 39,218,069 | <p>This was pretty interesting :)</p>
<p>I was able to reproduce this. The problem is that the second choiceSet has radio buttons with id "advertisement*", which triggers the AdBlockPlus Plugin in chrome and automatically hides that div, acting as a false positive!</p>
<p>Here is a small proof:</p>
<p><a href="http://i.stack.imgur.com/csMHa.gif" rel="nofollow"><img src="http://i.stack.imgur.com/csMHa.gif" alt="enter image description here"></a></p>
<p><a href="http://i.stack.imgur.com/FwjKZ.png" rel="nofollow"><img src="http://i.stack.imgur.com/FwjKZ.png" alt="enter image description here"></a></p>
<p>The solution is just to change the value of id to something like "adv-mnt1"</p>
| 3 | 2016-08-30T02:52:20Z | [
"python",
"html",
"css",
"django"
] |
Updating a 3D graph every n minutes in Python | 39,217,485 | <p>I have the following code to plot a 3D graph in Python</p>
<pre><code>data = # taken from an SQL query in (x, y, z) format #
x, y, z = zip(*data)
z = map(float, z)
grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j]
grid_z = griddata((x, y), z, (grid_x, grid_y), method='cubic')
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
plt.show()
</code></pre>
<p>I want the plot to be undated every 1 minute. I can get the data from the table using a thread every 1 minute but I am unable to update the plot. </p>
<p>Can you help me with a suggestion?</p>
<p>Thanks in advance!</p>
| 0 | 2016-08-30T01:23:49Z | 39,218,368 | <p>Try this</p>
<pre><code>while True:
plt.pause(1)
x1,x2,x3=random.uniform(-10,0),random.uniform(0,10),random.uniform(0,0.5)
y1,y2,y3=random.uniform(-10,0),random.uniform(0,10),random.uniform(0,0.5)
X,Y=np.arange(x1,x2,x3),np.arange(y1,y2,y3)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
plt.draw()
</code></pre>
<p><a href="http://matplotlib.org/api/pyplot_api.html?highlight=pause#matplotlib.pyplot.pause" rel="nofollow">matplotlib.pyplot.pause</a> </p>
<pre><code>Pause for interval seconds.
If there is an active figure it will be updated and displayed, and the GUI event loop will run during the pause.
If there is no active figure, or if a non-interactive backend is in use, this executes time.sleep(interval).
This can be used for crude animation. For more complex animation, see matplotlib.animation.
This function is experimental; its behavior may be changed or extended in a future release.
</code></pre>
<p>If it works,please accept this answer.</p>
| 0 | 2016-08-30T03:32:20Z | [
"python",
"matplotlib",
"plot"
] |
Updating a 3D graph every n minutes in Python | 39,217,485 | <p>I have the following code to plot a 3D graph in Python</p>
<pre><code>data = # taken from an SQL query in (x, y, z) format #
x, y, z = zip(*data)
z = map(float, z)
grid_x, grid_y = np.mgrid[min(x):max(x):100j, min(y):max(y):100j]
grid_z = griddata((x, y), z, (grid_x, grid_y), method='cubic')
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral)
plt.show()
</code></pre>
<p>I want the plot to be undated every 1 minute. I can get the data from the table using a thread every 1 minute but I am unable to update the plot. </p>
<p>Can you help me with a suggestion?</p>
<p>Thanks in advance!</p>
| 0 | 2016-08-30T01:23:49Z | 39,323,711 | <p>After some research I found a way of doing this with matplotlib.animation.</p>
<p>The below Youtube link was of great help.</p>
<p><a href="https://www.youtube.com/watch?v=7w8jk0r4lxA" rel="nofollow">https://www.youtube.com/watch?v=7w8jk0r4lxA</a></p>
| 0 | 2016-09-05T03:55:19Z | [
"python",
"matplotlib",
"plot"
] |
-bash: cd: Resources: No such file or directory | 39,217,582 | <p>the directory /Library/Frameworks/Python.framework/ contains the following four elements:
Headers Python Resources Versions</p>
<p>When I try to cd into either Headers, Python or Resources (e.g. cd Resources), I get an error message telling me that the element does not exist (e.g.: "-bash: cd: Resources: No such file or directory").</p>
<p>What's going on here?</p>
| 0 | 2016-08-30T01:39:52Z | 39,286,424 | <ol>
<li>Try to use autocompletion on TAB key press — maybe names contain some whitespace (less probably)</li>
<li>Check <code>ls -l</code> output — maybe these directories are just broken symbolic links</li>
</ol>
| 0 | 2016-09-02T07:15:34Z | [
"python",
"terminal",
"directory"
] |
Convert Python dict files into MATLAB struct | 39,217,618 | <p>I have a function in Python that outputs a dict. I run this function into MATLAB and save the output to a parameter (say <code>tmp</code>) which is a dict of nested other dicts itself. Now I want to convert this file into a useful format such as structure.</p>
<p>To elaborate: <code>tmp</code> is a dict. <code>data = struct(tmp)</code> is a structure but the fields are other dicts. I tried to go through every field and convert it individually, but this is not very efficient. </p>
<p>Another option: I have the output saved in a JSON file and can load it into MATLAB. However, it is still not useable. </p>
| 0 | 2016-08-30T01:45:46Z | 39,229,405 | <p>So python -> MATLAB is a bit tricky with dictionaries/structs because the type of object that MATLAB is expecting is a dictionary object where each key is a single variable you want from python as a simple data type (array,int, etc). It doesn't like having nested dictionaries. </p>
<p>I recommend
1: Store each dictionary separately instead of as part of a higher level object.<br>
or 2: even though it is not very nice converting the structs to individual variables.</p>
<p>MATLAB should be able to handle simple non-nested structures like that.</p>
| 0 | 2016-08-30T13:52:06Z | [
"python",
"matlab",
"dictionary",
"struct"
] |
Problems with special characters (\r) when writing and reading csv files | 39,217,629 | <p>I'm using pandas to load csv files created by excel, do some analysis, and then save results to csv files. I've noticed the pandas to_csv and from_csv methods don't seem capable of handling special characters such as \r but don't raise any errors either.</p>
<pre><code>In [7]: import pandas as pd
In [8]: data = {
'A': ['one', 'two', 'three'],
'B': ['four', 'five', 'six']
}
In [9]: df = pd.DataFrame(data)
In [10]: df
Out[10]:
A B
0 one four
1 two five
2 three six
In [11]: df.loc[1,'A'] = 't' + '\r' + 'o'
In [12]: df
Out[12]:
A B
0 one four
1 t\ro five
2 three six
In [13]: df.to_csv("my_df.csv")
In [14]: df2 = pd.DataFrame.from_csv("my_df.csv")
In [15]: df2
Out[15]:
A B
0 one four
1 t NaN
o five NaN
2 three six
</code></pre>
<p>Since I'm not specifying any encoding here I am assuming it is using ASCII but even when I specify encoding='utf-8' for the writing and reading I get the same result.</p>
<p>How do I write a robust csv writing and reading script so that the rows/columns are not corrupted or other unexpected things happen? If the only solution is to check and 'clean' every string before writing to csv then what is the easiest way to do that?</p>
| 0 | 2016-08-30T01:49:08Z | 39,219,503 | <p>Unless someone has a better suggestion, I'm dealing with the specific issue as follows - by pre-processing every csv file before loading with Pandas. It seems to work on my current system but not convinced it's fool proof.</p>
<pre><code>In [30]: f = open("my_df.csv")
In [31]: content = f.read().replace('\r',' ')
In [32]: with open("my_df2.csv", "w") as g:
....: g.write(content)
....:
In [33]: df2 = pd.DataFrame.from_csv("my_df2.csv")
In [34]: df2
Out[34]:
A B
0 one four
1 t o five
2 three six
</code></pre>
| 1 | 2016-08-30T05:40:48Z | [
"python",
"pandas",
"special-characters",
"export-to-csv"
] |
Problems with special characters (\r) when writing and reading csv files | 39,217,629 | <p>I'm using pandas to load csv files created by excel, do some analysis, and then save results to csv files. I've noticed the pandas to_csv and from_csv methods don't seem capable of handling special characters such as \r but don't raise any errors either.</p>
<pre><code>In [7]: import pandas as pd
In [8]: data = {
'A': ['one', 'two', 'three'],
'B': ['four', 'five', 'six']
}
In [9]: df = pd.DataFrame(data)
In [10]: df
Out[10]:
A B
0 one four
1 two five
2 three six
In [11]: df.loc[1,'A'] = 't' + '\r' + 'o'
In [12]: df
Out[12]:
A B
0 one four
1 t\ro five
2 three six
In [13]: df.to_csv("my_df.csv")
In [14]: df2 = pd.DataFrame.from_csv("my_df.csv")
In [15]: df2
Out[15]:
A B
0 one four
1 t NaN
o five NaN
2 three six
</code></pre>
<p>Since I'm not specifying any encoding here I am assuming it is using ASCII but even when I specify encoding='utf-8' for the writing and reading I get the same result.</p>
<p>How do I write a robust csv writing and reading script so that the rows/columns are not corrupted or other unexpected things happen? If the only solution is to check and 'clean' every string before writing to csv then what is the easiest way to do that?</p>
| 0 | 2016-08-30T01:49:08Z | 39,233,080 | <p>Preprocessing may be the best option. But if you're looking for something else, you may try <code>lineterminator</code> argument in <code>read_csv</code>:</p>
<pre><code>df = pd.read_csv("my_df.csv", index_col=0, lineterminator='\n')
</code></pre>
<p>(Works for me on linux but can't guarantee for other platforms.)</p>
| 0 | 2016-08-30T16:53:05Z | [
"python",
"pandas",
"special-characters",
"export-to-csv"
] |
How to run python script on a web server? | 39,217,637 | <p>I have been learning Django, the python webframework, so that I can use python scripts in my website. While I've learned the basics, I'm still a little unsure as to how to actually implement my own scripts into the website. </p>
<p>When I run the script on my computer, it spits out a small graph. Can somebody please help explain to me how to get the graph to be displayed on a web page in Django?</p>
| -1 | 2016-08-30T01:50:18Z | 39,217,657 | <p>Python script can be run on web servers using the Flask framework. Flask is a micro web framework written in Python. Also Django can be used alongside Flask for building REST API.</p>
| -1 | 2016-08-30T01:54:19Z | [
"python",
"django"
] |
How to run python script on a web server? | 39,217,637 | <p>I have been learning Django, the python webframework, so that I can use python scripts in my website. While I've learned the basics, I'm still a little unsure as to how to actually implement my own scripts into the website. </p>
<p>When I run the script on my computer, it spits out a small graph. Can somebody please help explain to me how to get the graph to be displayed on a web page in Django?</p>
| -1 | 2016-08-30T01:50:18Z | 39,217,686 | <p>You can either implement your scripts in your or call the already existing ones in <code>views.py</code>. At any rate, I highly recommend that you read the <a href="https://docs.djangoproject.com/en/1.10/" rel="nofollow">official docs</a>, they are a amazing source of high quality materials, including a highly in-depth tutorial.</p>
| 1 | 2016-08-30T01:58:08Z | [
"python",
"django"
] |
How to convert a list by mapping an element into multiple elements in python? | 39,217,639 | <p>For example,
how to convert [1, 5, 7] into [1,2,5,6,7,8] into python?
[x, x+1 for x in [1,5,7]] can't work for sure...</p>
| 5 | 2016-08-30T01:50:27Z | 39,217,666 | <p>Not sure if this is the best way, but I would do:</p>
<pre><code>l = [1, 5, 7]
print([y for x in l for y in (x, x + 1)])
</code></pre>
<p>Another way using <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.from_iterable</code></a>:</p>
<pre><code>from itertools import chain
l = [1, 5, 7]
print(list(chain.from_iterable((x, x + 1) for x in l)))
</code></pre>
| 3 | 2016-08-30T01:55:37Z | [
"python"
] |
How to convert a list by mapping an element into multiple elements in python? | 39,217,639 | <p>For example,
how to convert [1, 5, 7] into [1,2,5,6,7,8] into python?
[x, x+1 for x in [1,5,7]] can't work for sure...</p>
| 5 | 2016-08-30T01:50:27Z | 39,217,670 | <p>You can do your list comprehension logic with tuples and then flatten the resulting list:</p>
<p><code>[n for pair in [(x, x+1) for x in [1,5,7]] for n in pair]</code></p>
| 1 | 2016-08-30T01:56:10Z | [
"python"
] |
How to convert a list by mapping an element into multiple elements in python? | 39,217,639 | <p>For example,
how to convert [1, 5, 7] into [1,2,5,6,7,8] into python?
[x, x+1 for x in [1,5,7]] can't work for sure...</p>
| 5 | 2016-08-30T01:50:27Z | 39,217,679 | <p>If you just want to fill the list with the numbers between the min and max+1 values you can use <code>[i for i in range (min(x),max(x)+2)]</code> assuming <code>x</code> is your list.</p>
| 0 | 2016-08-30T01:56:58Z | [
"python"
] |
How to convert a list by mapping an element into multiple elements in python? | 39,217,639 | <p>For example,
how to convert [1, 5, 7] into [1,2,5,6,7,8] into python?
[x, x+1 for x in [1,5,7]] can't work for sure...</p>
| 5 | 2016-08-30T01:50:27Z | 39,217,730 | <p>And you can always overcomplicate the problem with <a href="https://docs.python.org/2/library/operator.html" rel="nofollow"><code>operator</code></a>, <a href="https://docs.python.org/2/library/itertools.html#itertools.imap" rel="nofollow"><code>imap()</code></a>, <a href="https://docs.python.org/2/library/functools.html#functools.partial" rel="nofollow"><code>partial()</code></a>, <a href="https://docs.python.org/2/library/itertools.html#itertools.izip" rel="nofollow"><code>izip()</code></a> and <a href="https://docs.python.org/2/library/itertools.html#itertools.chain" rel="nofollow"><code>chain()</code></a>:</p>
<pre><code>>>> from itertools import chain, izip, imap
>>> from operator import add
>>> from functools import partial
>>>
>>> l = [1, 5, 7]
>>>
>>> list(chain(*izip(l, imap(partial(add, 1), l))))
[1, 2, 5, 6, 7, 8]
</code></pre>
<p>What happens here:</p>
<ul>
<li>we make an iterator over <code>l</code> that applies an <a href="https://docs.python.org/2/library/operator.html#operator.add" rel="nofollow"><code>add</code> function</a> with <code>1</code> as an argument</li>
<li>we zip the initial list with the iterator returned by <code>imap()</code> to produce pairs of x, x+1 values</li>
<li>we <a href="http://stackoverflow.com/a/953097/771848">flatten the list with <code>chain()</code></a> and convert it to the list to see the result</li>
</ul>
| 2 | 2016-08-30T02:04:14Z | [
"python"
] |
How to convert a list by mapping an element into multiple elements in python? | 39,217,639 | <p>For example,
how to convert [1, 5, 7] into [1,2,5,6,7,8] into python?
[x, x+1 for x in [1,5,7]] can't work for sure...</p>
| 5 | 2016-08-30T01:50:27Z | 39,217,895 | <p>A simple way to think about the problem is to make a second list of incremented values and add it to the original list, then sort it:</p>
<pre><code>l = [1, 5, 7]
m = l + [i+1 for i in l]
m.sort()
print m # [1, 2, 5, 6, 7, 8]
</code></pre>
| 2 | 2016-08-30T02:27:37Z | [
"python"
] |
How to convert a list by mapping an element into multiple elements in python? | 39,217,639 | <p>For example,
how to convert [1, 5, 7] into [1,2,5,6,7,8] into python?
[x, x+1 for x in [1,5,7]] can't work for sure...</p>
| 5 | 2016-08-30T01:50:27Z | 39,218,076 | <p>You can combine some ideas from alecxe's answer and what you already had:</p>
<pre><code>>>> import itertools
>>>
>>> a = [1, 5, 7]
>>> b = ((x, x+1) for x in a)
>>>
>>> list(itertools.chain(*b))
[1, 2, 5, 6, 7, 8]
</code></pre>
<p>What I have done is :</p>
<ol>
<li><p>Define in <code>b</code> a <a href="https://docs.python.org/3/tutorial/classes.html#generator-expressions" rel="nofollow">generator expression</a> which allows us to have (something that looks like) a tuple that would have looked like <code>((1, 2), (5, 6), (7, 8))</code> but without evaluating it right away. It would have also worked with a list comprehension.</p></li>
<li><p><a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">Unpack <code>b</code> in the argument list</a> of itertools.chain(). It would be the equivalent of <code>itertools.chain((1, 2), (5, 6), (7, 8))</code>. That function concatenates its arguments.</p></li>
<li><p>Use list() to create a list from the return value of the <code>itertools.chain()</code> function since it's an iterator.</p></li>
</ol>
<p>This could also have worked without any intermediate step:</p>
<pre><code>>>> import itertools
>>> list(itertools.chain(*((x, x+1) for x in [1, 5, 7])))
[1, 2, 5, 6, 7, 8]
</code></pre>
<p>But "Simple is better than complex"</p>
<p>I hope this helps.</p>
<p>I would have put more links if I had more reputation, sorry.</p>
| 2 | 2016-08-30T02:53:10Z | [
"python"
] |
How to convert a list by mapping an element into multiple elements in python? | 39,217,639 | <p>For example,
how to convert [1, 5, 7] into [1,2,5,6,7,8] into python?
[x, x+1 for x in [1,5,7]] can't work for sure...</p>
| 5 | 2016-08-30T01:50:27Z | 39,218,319 | <p>Make a generator function that iterates over the list and yields, in turn, each element and that element plus one. Iterate over your generator.</p>
<pre><code>def foo(lyst):
for element in lyst:
yield element
yield element + 1
>>> print(list(foo([1, 5, 7])))
[1, 2, 5, 6, 7, 8]
>>>
>>> print([element for element in foo([1, 5, 7])])
[1, 2, 5, 6, 7, 8]
>>>
</code></pre>
| 2 | 2016-08-30T03:25:19Z | [
"python"
] |
Load URL without graphical interface | 39,217,787 | <p>In Python3, I need to load a URL every set interval of time, but without a graphical interface / browser window. There is no JavaScript, all it needs to do is load the page, and then quit it. This needs to run as a console application.</p>
<p>Is there any way to do this?</p>
| 0 | 2016-08-30T02:13:15Z | 39,217,960 | <p>You could use <code>threading</code> and create a <code>Timer</code> that calls your function after every specified interval of time.</p>
<pre><code>import time, threading, urllib.request
def fetch_url():
threading.Timer(10, fetch_url).start()
req = urllib.request.Request('http://www.stackoverflow.com')
with urllib.request.urlopen(req) as response:
the_page = response.read()
fetch_url()
</code></pre>
| 0 | 2016-08-30T02:36:41Z | [
"python",
"python-3.x",
"web"
] |
Load URL without graphical interface | 39,217,787 | <p>In Python3, I need to load a URL every set interval of time, but without a graphical interface / browser window. There is no JavaScript, all it needs to do is load the page, and then quit it. This needs to run as a console application.</p>
<p>Is there any way to do this?</p>
| 0 | 2016-08-30T02:13:15Z | 39,217,986 | <p>The requests library may have what you're looking for.</p>
<pre><code>import requests, time
url = "url.you.need"
website_object = requests.get(url)
# Repeat as necessary
</code></pre>
| 0 | 2016-08-30T02:42:05Z | [
"python",
"python-3.x",
"web"
] |
How to convert to Python list comprehension | 39,217,882 | <pre><code>ls = ['abc', 56, 49, 63, 66, 80]
for i in ls:
if(isinstance(i, int) or isinstance(i, float)):
for i in range(len(ls)):
ls[i] = str(ls[i])
</code></pre>
<p>May I know how to create the list comprehension of above code?</p>
<p>I am trying the following but not working</p>
<pre><code>if (s for s in ls isinstance(s, int) or isinstance(s, float)):
for i in range(len(ls)):
ls[i] = str(ls[i])
</code></pre>
| 1 | 2016-08-30T02:25:31Z | 39,217,897 | <p>For your example where you have either strings or integers or floats, you can use a simple list comprehension:</p>
<pre><code>ls = ['abc', 56, 49, 63, 66, 80]
print([str(l) for l in ls])
</code></pre>
<p>Or alternatively, you can use <a href="https://docs.python.org/3/library/functions.html#map"><code>map</code></a>:</p>
<pre><code>print(list(map(str, ls)))
</code></pre>
<p>If you only want to convert floats and integers to strings (and ignore anything else like booleans, decimal objects, etc.):</p>
<pre><code>print([str(l) if isinstance(l, int) or isinstance(l, float) else l for l in ls])
</code></pre>
| 6 | 2016-08-30T02:27:48Z | [
"python",
"list",
"python-3.x",
"for-comprehension"
] |
Regex to parse out a part of URL using python | 39,217,906 | <p>I am having data as follows,</p>
<pre><code>data['url']
http://hostname.com/aaa/uploads/2013/11/a-b-c-d.jpg https://www.aaa.com/
http://hostname.com/bbb/uploads/2013/11/e-f-g-h.gif https://www.aaa.com/
http://hostname.com/ccc/uploads/2013/11/e-f-g-h.png http://hostname.com/ccc/uploads/2013/11/a-a-a-a.html
http://hostname.com/ddd/uploads/2013/11/w-e-r-t.ico
http://hostname.com/ddd/uploads/2013/11/r-t-y-u.aspx https://www.aaa.com/
http://hostname.com/bbb/uploads/2013/11/t-r-w-q.jpeg https://www.aaa.com/
</code></pre>
<p>I want to find out the formats such as .jpg, .gif, .png, .ico, .aspx, .html, .jpeg and parse it out backwards until it finds a "/". Also I want to check for several occurance all through the string. My output should be,</p>
<pre><code>data['parsed']
a-b-c-d
e-f-g-h
e-f-g-h a-a-a-a
w-e-r-t
r-t-y-u
t-r-w-q
</code></pre>
<p>I am thinking instead of writing individual commands for each of the formats, is there a way to write everything under a single command.</p>
<p>Can anybody help me in writing for theses commands? I am new to regex and any help would be appreciated.</p>
| -1 | 2016-08-30T02:29:00Z | 39,217,977 | <p>this builds a list of name to extension pairs</p>
<pre><code>import re
results = []
for link in data:
matches = re.search(r'/(\w-\w-\w-\w)\.(\w{2,})\b', link)
results.append((matches.group(1), matches.group(2)))
</code></pre>
| 1 | 2016-08-30T02:41:06Z | [
"python",
"regex",
"python-2.7",
"python-3.x",
"regex-negation"
] |
Regex to parse out a part of URL using python | 39,217,906 | <p>I am having data as follows,</p>
<pre><code>data['url']
http://hostname.com/aaa/uploads/2013/11/a-b-c-d.jpg https://www.aaa.com/
http://hostname.com/bbb/uploads/2013/11/e-f-g-h.gif https://www.aaa.com/
http://hostname.com/ccc/uploads/2013/11/e-f-g-h.png http://hostname.com/ccc/uploads/2013/11/a-a-a-a.html
http://hostname.com/ddd/uploads/2013/11/w-e-r-t.ico
http://hostname.com/ddd/uploads/2013/11/r-t-y-u.aspx https://www.aaa.com/
http://hostname.com/bbb/uploads/2013/11/t-r-w-q.jpeg https://www.aaa.com/
</code></pre>
<p>I want to find out the formats such as .jpg, .gif, .png, .ico, .aspx, .html, .jpeg and parse it out backwards until it finds a "/". Also I want to check for several occurance all through the string. My output should be,</p>
<pre><code>data['parsed']
a-b-c-d
e-f-g-h
e-f-g-h a-a-a-a
w-e-r-t
r-t-y-u
t-r-w-q
</code></pre>
<p>I am thinking instead of writing individual commands for each of the formats, is there a way to write everything under a single command.</p>
<p>Can anybody help me in writing for theses commands? I am new to regex and any help would be appreciated.</p>
| -1 | 2016-08-30T02:29:00Z | 39,218,096 | <p>This pattern returns the file names. I have just used one of your urls to demonstrate, for more, you could simply append the matches to a list of results:</p>
<pre><code>import re
url = "http://hostname.com/ccc/uploads/2013/11/e-f-g-h.png http://hostname.com/ccc/uploads/2013/11/a-a-a-a.html"
p = r'((?:[a-z]-){3}[a-z]).'
matches = re.findall(p, url)
>>> print('\n'.join(matches))
e-f-g-h
a-a-a-a
</code></pre>
<p>There is the assumption that the urls all have the general form you provided.</p>
| 1 | 2016-08-30T02:55:26Z | [
"python",
"regex",
"python-2.7",
"python-3.x",
"regex-negation"
] |
Regex to parse out a part of URL using python | 39,217,906 | <p>I am having data as follows,</p>
<pre><code>data['url']
http://hostname.com/aaa/uploads/2013/11/a-b-c-d.jpg https://www.aaa.com/
http://hostname.com/bbb/uploads/2013/11/e-f-g-h.gif https://www.aaa.com/
http://hostname.com/ccc/uploads/2013/11/e-f-g-h.png http://hostname.com/ccc/uploads/2013/11/a-a-a-a.html
http://hostname.com/ddd/uploads/2013/11/w-e-r-t.ico
http://hostname.com/ddd/uploads/2013/11/r-t-y-u.aspx https://www.aaa.com/
http://hostname.com/bbb/uploads/2013/11/t-r-w-q.jpeg https://www.aaa.com/
</code></pre>
<p>I want to find out the formats such as .jpg, .gif, .png, .ico, .aspx, .html, .jpeg and parse it out backwards until it finds a "/". Also I want to check for several occurance all through the string. My output should be,</p>
<pre><code>data['parsed']
a-b-c-d
e-f-g-h
e-f-g-h a-a-a-a
w-e-r-t
r-t-y-u
t-r-w-q
</code></pre>
<p>I am thinking instead of writing individual commands for each of the formats, is there a way to write everything under a single command.</p>
<p>Can anybody help me in writing for theses commands? I am new to regex and any help would be appreciated.</p>
| -1 | 2016-08-30T02:29:00Z | 39,218,184 | <p>You might try this:</p>
<pre><code>data['parse'] = re.findall(r'[^/]+\.[a-z]+ ',data['url'])
</code></pre>
<p>That will pick out all of the file names with their extensions. If you want to remove the extensions, the code above returns a list which you can then process with list comprehension and re.sub like so:</p>
<pre><code>[re.sub('\.[a-z]+$','',exp) for exp in data['parse']]
</code></pre>
<p>Use the .join function to create a string as demonstrated in Totem's answer</p>
| 0 | 2016-08-30T03:10:13Z | [
"python",
"regex",
"python-2.7",
"python-3.x",
"regex-negation"
] |
split string on commas but ignore commas with in single quotes and create a dictionary after string split in python | 39,217,929 | <p>I have a string as shown below,</p>
<pre><code>someVariable1='9',someVariable2='some , value, comma,present',somevariable5='N/A',someVariable6='some text,comma,= present,'
</code></pre>
<p>I have to split above string on commas but ignore commas within quotes in python and i have to create a dictionary to get the values of variables.</p>
<p>Example:</p>
<pre><code>somedictionary.get('someVariable1')
</code></pre>
<p>I am new to python please help me how can i achieve this in python</p>
| 0 | 2016-08-30T02:32:41Z | 39,218,090 | <p>Build a copy of the string, looping through each character of the original string, and keeping track of the number of single-quotes you've encountered.</p>
<p>Whenever you see a comma, refer to the single-quote count. If it's odd (meaning you're currently inside a quoted string), don't add the comma onto the string copy; instead add some unique placeholder value (i.e. something like PEANUTBUTTER that would never actually appear in the string.)</p>
<p>When you're finished building the string copy, it won't have any commas inside quotes, because you replaced all those with PEANUTBUTTER, so you can safely split on commas.</p>
<p>Then, in the list you got from splitting, go back and replace PEANUTBUTTER with commas.</p>
| 0 | 2016-08-30T02:54:49Z | [
"python",
"string",
"python-3.x",
"python-2.x"
] |
split string on commas but ignore commas with in single quotes and create a dictionary after string split in python | 39,217,929 | <p>I have a string as shown below,</p>
<pre><code>someVariable1='9',someVariable2='some , value, comma,present',somevariable5='N/A',someVariable6='some text,comma,= present,'
</code></pre>
<p>I have to split above string on commas but ignore commas within quotes in python and i have to create a dictionary to get the values of variables.</p>
<p>Example:</p>
<pre><code>somedictionary.get('someVariable1')
</code></pre>
<p>I am new to python please help me how can i achieve this in python</p>
| 0 | 2016-08-30T02:32:41Z | 39,218,097 | <p>Try this regular expression <code>,(?=(?:[^']*\'[^']*\')*[^']*$)</code> for splitting:</p>
<pre><code>import re
re.split(",(?=(?:[^']*\'[^']*\')*[^']*$)",s)
# ["someVariable1='9'",
# "someVariable2='some , value, comma,present'",
# "somevariable5='N/A'",
# "someVariable6='some text,comma,= present,'"]
</code></pre>
<ul>
<li>This uses look ahead syntax <code>(?=...)</code> to find out specific comma to split; </li>
<li>The look up pattern is <code>(?:[^']*\'[^']*\')*[^']*$</code></li>
<li><code>$</code> matches the end of string and optionally matches non <code>'</code> characters <code>[^']*</code></li>
<li>Use non-captured group <code>(?:..)</code> to define a double quote pattern <code>[^']*\'[^']*\'</code> which could appear behind the comma that can acts as a delimiter.</li>
</ul>
<p>This assumes the quotes are always paired.</p>
<p>To convert the above to a dictionary, you can split each sub expression by <code>=</code>:</p>
<pre><code>lst = re.split(",(?=(?:[^']*\'[^']*\')*[^']*$)",s)
dict_ = {k: v for exp in lst for k, v in [re.split("=(?=\')", exp)]}
dict_
# {'someVariable1': "'9'",
# 'someVariable2': "'some , value, comma,present'",
# 'someVariable6': "'some text,comma,= present,'",
# 'somevariable5': "'N/A'"}
dict_.get('someVariable2')
# "'some , value, comma,present'"
</code></pre>
| 1 | 2016-08-30T02:55:41Z | [
"python",
"string",
"python-3.x",
"python-2.x"
] |
pandas: 'join' failing to compile | 39,217,985 | <p>I'm having a bit of a problem trying to get my code to compile. Looks like the line with <code>main_df = df</code> is causing a failure, and I don't quite understand why.</p>
<p>Any help is much appreciated.</p>
<pre><code>import quandl
import pandas as pd
# API key was removed
api_key = 'X'
fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states',flavor='html5lib')
main_df = pd.DataFrame()
for abbv in fiddy_states[0][0][1:]:
query = "FMAC/HPI_"+str(abbv)
df = quandl.get(query, authtoken=api_key)
if main_df.empty:
main_df = df
else:
main_df = main_df.join(df)
print(main_df.head())
</code></pre>
<p>I get this error:</p>
<blockquote>
<p>Traceback (most recent call last):
File "C:/Users/Dave/Documents/Python Files/helloworld.py", line 17, in
main_df = main_df.join(df)</p>
<p>File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 4385, in join
rsuffix=rsuffix, sort=sort)</p>
<p>File "C:\Python35\lib\site-packages\pandas\core\frame.py", line 4399, in _join_compat
suffixes=(lsuffix, rsuffix), sort=sort)</p>
<p>File "C:\Python35\lib\site-packages\pandas\tools\merge.py", line 39, in merge
return op.get_result()</p>
<p>File "C:\Python35\lib\site-packages\pandas\tools\merge.py", line 223, in get_result
rdata.items, rsuf)</p>
<p>File "C:\Python35\lib\site-packages\pandas\core\internals.py", line 4445, in items_overlap_with_suffix
to_rename)
ValueError: columns overlap but no suffix specified: Index(['Value'], dtype='object')</p>
</blockquote>
| 0 | 2016-08-30T02:42:00Z | 39,218,220 | <p>You can pass a list of codes to the <code>quandl.get</code> function, then you get a dataframe back with data for each code in a column. Code: </p>
<pre><code>import quandl
import pandas as pd
fiddy_states = pd.read_html('https://simple.wikipedia.org/wiki/List_of_U.S._states', flavor='html5lib')
data = quandl.get(["FMAC/HPI_"+s for s in fiddy_states[0][0][1:]])
</code></pre>
| 1 | 2016-08-30T03:15:06Z | [
"python",
"pandas",
"join",
"quandl"
] |
How to focus on pydev console prompt with keyboard? | 39,217,997 | <p>It seems there is no way to focus pydev console prompt even with window switch. Does anyone know how?</p>
<p><a href="http://i.stack.imgur.com/wDc0B.png" rel="nofollow"><img src="http://i.stack.imgur.com/wDc0B.png" alt=""></a></p>
| 0 | 2016-08-30T02:43:16Z | 39,218,688 | <p>I think i had to hack this by using a windows macro program to put a mouse click there :)
I used Macro Express</p>
| 0 | 2016-08-30T04:16:47Z | [
"python",
"eclipse",
"eclipse-plugin",
"console",
"pydev"
] |
How to pass string parameters to C++ function using ctypes, python | 39,218,021 | <p>I have a C++ DLL library. One function is shown as below.</p>
<p>The DLL import in Python is correct.</p>
<pre><code>int _ParseLogin2Resp(const std::string& username,
const std::string& password,
char szErr[1024]);
</code></pre>
<p>In fact, I have tried many ways to pass parameters. I know the difference between C++ <code>std::string</code> and <code>char *</code>.</p>
<p>1.Use the c_char_p() and byref()</p>
<pre><code>username = ctypes.c_char_p("username")
_ParseLogin2Resp(ctypes.byref(username),...)
</code></pre>
<p>2.Use create_string_buffer()</p>
<pre><code>username = ctypes.create_string_buffer("username")
_ParseLogin2Resp(username,...)
</code></pre>
<p>But function ERROR returns </p>
<blockquote>
<p>The username or password is empty.</p>
</blockquote>
<p>So I couldn't find any solution to pass string parameters to my function.</p>
<p>My Question is.</p>
<p>Is it possibility that I could pass correct parameters to call my function as expected or I have to rewrite my dll library to make function work correctly?</p>
| 0 | 2016-08-30T02:46:12Z | 39,218,723 | <p>Python doc says ctypes provides C compatible data types, it is better to use c style API interface in your DLL.</p>
| 0 | 2016-08-30T04:20:37Z | [
"python",
"c++",
"dll",
"ctypes"
] |
Python dictionary converting to json or yaml | 39,218,060 | <p>I have parsed a string and converted into a dictionary. however I would like to be able to get more information from my dictionary and I was thinking creating a son file or yaml file would be more useful.
please feel free to comment on another way of solving this problem.</p>
<pre><code>import re
regex = '(\w+) \[(.*?)\] "(.*?)" (\d+) "(.*?)" "(.*?)"'
sample2= 'this [condo] "number is" 28 "owned by" "james"'
patern = '(?P<host>\S+)\s(?P<tipe>\[\w+\])\s(?P<txt>"(.*?))\s(?P<number>\d+)\s(?P<txt1>"\w+\s\w+")\s(?P<owner>"\w+)'
m =re.match(patern, sample2)
res = m.groupdict()
print res
</code></pre>
<p>and I would get:</p>
<pre><code>{'tipe': '[condo]', 'number': '28', 'host': 'this', 'owner': '"james', 'txt': '"number is"', 'txt1': '"owned by"'}
</code></pre>
<p>I would like to be able to sort by owner name and write out the type of house and the house number. for example:</p>
<p>James:{ type:condo, number: 28}</p>
<p>or any other suggestions?</p>
| 0 | 2016-08-30T02:51:34Z | 39,218,085 | <p>The question of json vs yaml boils down to what are you doing with the data you are saving? If you are reusing the data in JS or in another python script then you could use JSON. If you were using it in something that uses YAML then use YAML. But in terms of your question, unless there is a particular end game or use case for your data, it doesn't matter the format, you could even just do a typical TSV/CSV and it'd be the same.</p>
<p>To answer your question about how to make a dict in to a json.</p>
<p>From your example once you have the <code>res</code> dictionary made.</p>
<pre><code>import json
with open('someFile.json', 'wb') as outfile:
json.dump(res, outfile)
</code></pre>
<p>Your output file <code>someFile.json</code> will be your dictionary <code>res</code></p>
| 0 | 2016-08-30T02:54:12Z | [
"python",
"json",
"dictionary"
] |
Reading text from image | 39,218,106 | <p>Any suggestions on converting these images to text? I'm using pytesseract and it's working wonderfully in most cases except this. Ideally I'd read these numbers exactly. Worst case I can just try to use PIL to determine if the number to the left of the '/' is a zero. Start from the left and find the first white pixel, then </p>
<p><a href="http://i.stack.imgur.com/kIrvO.png" rel="nofollow"><img src="http://i.stack.imgur.com/kIrvO.png" alt="enter image description here"></a>
<a href="http://i.stack.imgur.com/iCqkW.png" rel="nofollow"><img src="http://i.stack.imgur.com/iCqkW.png" alt="enter image description here"></a></p>
<pre><code>from PIL import Image
from pytesseract import image_to_string
myText = image_to_string(Image.open("tmp/test.jpg"),config='-psm 10')
myText = image_to_string(Image.open("tmp/test.jpg"))
</code></pre>
<p>The slash in the middle causes issues here. I've also tried using PIL's '.paste' to add lots of extra black around the image. There might be a few other PIL tricks I could try, but i'd rather not go that route unless I have to. </p>
<p>I tried using config='-psm 10' but my 8's were coming through as ":" sometimes, and random characters other times. And my 0's were coming through as nothing. </p>
<p>Reference to: <a href="http://stackoverflow.com/questions/31643216/pytesseract-dont-work-with-one-digit-image">pytesseract don't work with one digit image</a> for the -psm 10</p>
<p><strong>_____________EDIT_______________</strong>
Additional samples:</p>
<p><a href="http://i.stack.imgur.com/RCKPc.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/RCKPc.jpg" alt="enter image description here"></a>
1BJ2I]</p>
<p><a href="http://i.stack.imgur.com/wlFJJ.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/wlFJJ.jpg" alt="enter image description here"></a>
DIS</p>
<p><a href="http://i.stack.imgur.com/4eGlZ.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/4eGlZ.jpg" alt="enter image description here"></a>
10.I'10</p>
<p><a href="http://i.stack.imgur.com/0JqEW.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/0JqEW.jpg" alt="enter image description here"></a>
20.I20</p>
<p>So I'm doing some voodoo conversions that seem to be working for now. But looks very error prone:</p>
<pre><code>def ConvertPPTextToReadableNumbers(text):
text = RemoveNonASCIICharacters(text)
text = text.replace("I]", "0")
text = text.replace("|]", "0")
text = text.replace("l]", "0")
text = text.replace("B", "8")
text = text.replace("D", "0")
text = text.replace("S", "5")
text = text.replace(".I'", "/")
text = text.replace(".I", "/")
text = text.replace("I'", "/")
text = text.replace("J", "/")
return text
</code></pre>
<p>Ultimately generates:</p>
<pre><code>ConvertPPTextToReadableNumbers return text = 18/20
ConvertPPTextToReadableNumbers return text = 0/5
ConvertPPTextToReadableNumbers return text = 10/10
ConvertPPTextToReadableNumbers return text = 20/20
</code></pre>
| 3 | 2016-08-30T02:56:51Z | 39,234,595 | <p>Generally speaking, most OCR tools (like Tesseract) are tuned for working with high-resolution scans of printed text. They do not perform well on low-resolution or pixellated images.</p>
<p>Two possible approaches here are:</p>
<ol>
<li><p>If the font, background, and layout of your images are completely predictable, you don't need Tesseract at all; it's just complicating matters. Build a library of images representing each character you need to recognize, and <a href="http://effbot.org/zone/pil-comparing-images.htm" rel="nofollow">check whether parts of the image are equal to the reference image</a>.</p></li>
<li><p>If that isn't an option, or if it seems too hard, you could upscale the pixellated image using one of <a href="https://en.wikipedia.org/wiki/Hqx" rel="nofollow">the hq*x algorithms</a>. The added detail may be sufficient to get Tesseract to reliably recognize the characters.</p></li>
</ol>
| 0 | 2016-08-30T18:24:39Z | [
"python",
"image-processing",
"pytesser"
] |
What are valid values for platforms in python setup.py? | 39,218,107 | <p>The official documentation <a href="http://docs.python.org/2/distutils/apiref.html" rel="nofollow">mentions this parameter</a> but says nothing about possible values.</p>
<p>Is it necessary to use <code>Operating System</code> key in <code>classifiers</code> ?</p>
| 3 | 2016-08-30T02:56:54Z | 39,220,097 | <p>Well its not needed every time. But if you are doing something w.r.t platform and you don't intend to support all platforms in your program, then you need to base your program on platform.</p>
<p>Following are the os names that are currently registered in python</p>
<pre><code>'posix', 'nt', 'os2', 'ce', 'java', 'riscos'
</code></pre>
<p>sys.builtin_module_names will list all the platforms that your python version supports. Again it will bring the modules based on your platform during installation.</p>
<p>you can base your program based on os.name</p>
<pre><code>if os.name == 'nt':
# do something for Windows
elif os.name == 'posix':
# do something for all Linux and Mac platforms
elif os.name == 'os2':
# do something
elif os.name == 'ce':
# do something
elif os.name == 'java':
# do something for java based platforms
elif os.name == 'riscos':
# do something
</code></pre>
| 0 | 2016-08-30T06:18:34Z | [
"python",
"distutils"
] |
Import files not in the current working directory | 39,218,109 | <p>Let's say the program asks the user for a file name to read and then a file to write the processed data into. </p>
<p>Is there a way to get the directory of the needed file so the program can alter the current directory to use it? Or is there another way to access that file?</p>
| 0 | 2016-08-30T02:57:23Z | 39,218,124 | <p>If the user enters the complete file path with the directory, you can parse it (using sys.path) and then os.chdir() there.</p>
| 0 | 2016-08-30T02:59:50Z | [
"python",
"directory",
"cwd"
] |
Import files not in the current working directory | 39,218,109 | <p>Let's say the program asks the user for a file name to read and then a file to write the processed data into. </p>
<p>Is there a way to get the directory of the needed file so the program can alter the current directory to use it? Or is there another way to access that file?</p>
| 0 | 2016-08-30T02:57:23Z | 39,218,226 | <p>You could make it even easier for the user by using Tkinter to prompt them with a file upload box rather than asking them to type it in. When they select a file it will give you the full file path.</p>
<pre><code>from tkinter import filedialog
# this gives you the full file path
filepath = askopenfilename()
print filepath
# or do whatever you want with the file path
</code></pre>
<p>Not saying that asking users to type in a full file path will cause issues, but from personal experience not everyone gives you the input that you'd like (not to mention not everyones knows file path syntax), and this example would reduce the error margin.</p>
| 0 | 2016-08-30T03:15:58Z | [
"python",
"directory",
"cwd"
] |
Import files not in the current working directory | 39,218,109 | <p>Let's say the program asks the user for a file name to read and then a file to write the processed data into. </p>
<p>Is there a way to get the directory of the needed file so the program can alter the current directory to use it? Or is there another way to access that file?</p>
| 0 | 2016-08-30T02:57:23Z | 39,218,707 | <p>Welp, this is my first answer on SO, so hopefully I don't misunderstand the question and get off to a bad start. Here goes nothing...</p>
<p>Quite frankly, there isn't too much more to be said than what prior comments and answers have provided. While there are <a href="http://stackoverflow.com/questions/10174211/make-an-always-relative-to-current-module-file-path">"portable" ways to "ask" for a path relative to your current working directory</a>, such a design choice isn't quite as explicit, particularly with respect to what the user might think is happening. If this were all behind-the-scenes file manipulation, that's one thing, but in this case, <b>I, like the others, recommend you ask for the entire path to both the read and write files.</b> For the sake of completeness, you could start with this:</p>
<pre><code># responses should be of the form
# full/path/from/home/directory/to/file/my_read_and_write_files.txt
fileToReadPath = input("Provide the full path to your read file: ")
fileToWritePath = input("Provide the full path to your write file: ")
with open(fileToReadPath, 'r') as readFile, open(fileToWritePath, 'w') as writeFile:
# do stuff with your files here!
# e.g. copy line by line from readFile to writeFile
for line in readFile:
writeFile.write(line)
</code></pre>
<p>Notice that the context manager (<code>with</code>) will automatically close the files for you when you're done. For simple stuff like this, I think the link above, <a href="https://docs.python.org/3/library/os.html#files-and-directories" rel="nofollow">this section on the os module</a> and <a href="https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files" rel="nofollow">this section on the IO itself</a> of the python docs do a pretty good job of explaining your options and the toy example. </p>
| 0 | 2016-08-30T04:18:50Z | [
"python",
"directory",
"cwd"
] |
How to output all unassigned strings in a python file | 39,218,253 | <p>I have a python file (a script) that looks like this:</p>
<h3>script.py</h3>
<pre><code>"""
Multiline comment with unique
text pertaining to the Foo class
"""
class Foo():
pass
"""
Multiline comment with unique
text pertaining to the Bar class
"""
class Bar():
pass
"""
Multiline comment with unique
text pertaining to the FooBar class
"""
class FooBar():
pass
def print_comments():
# NotImplementedError
</code></pre>
<p>Is there some way for <code>print_comments</code> to detect and output all the unassigned strings so I could see this:</p>
<blockquote>
<p>Multiline comment with unique
text pertaining to the Foo class</p>
<p>Multiline comment with unique
text pertaining to the Bar class</p>
<p>Multiline comment with unique
text pertaining to the FooBar class</p>
</blockquote>
| 0 | 2016-08-30T03:19:17Z | 39,218,416 | <p>Assuming the formatting you indicated in your question, something like this should do it:</p>
<pre><code>class Show_Script():
def construct(self):
with open(os.path.abspath(__file__)) as f:
my_lines = f.readlines()
comments = []
in_comment = 0
for line in my_lines:
# detected the start of a comment
if line.strip().startswith('"""') and in_comment == 0:
in_comment = 1
comments.append('')
# detected the end of a comment
elif line.strip().endswith('"""') and in_comment == 1:
in_comment = 0
# the contents of a comment
elif in_comment == 1:
comments[-1] += line
print '\n'.join(comments)
</code></pre>
| 1 | 2016-08-30T03:40:35Z | [
"python",
"string",
"unassigned-variable"
] |
How to output all unassigned strings in a python file | 39,218,253 | <p>I have a python file (a script) that looks like this:</p>
<h3>script.py</h3>
<pre><code>"""
Multiline comment with unique
text pertaining to the Foo class
"""
class Foo():
pass
"""
Multiline comment with unique
text pertaining to the Bar class
"""
class Bar():
pass
"""
Multiline comment with unique
text pertaining to the FooBar class
"""
class FooBar():
pass
def print_comments():
# NotImplementedError
</code></pre>
<p>Is there some way for <code>print_comments</code> to detect and output all the unassigned strings so I could see this:</p>
<blockquote>
<p>Multiline comment with unique
text pertaining to the Foo class</p>
<p>Multiline comment with unique
text pertaining to the Bar class</p>
<p>Multiline comment with unique
text pertaining to the FooBar class</p>
</blockquote>
| 0 | 2016-08-30T03:19:17Z | 39,218,573 | <p>Using regex:</p>
<pre><code>$ cat script.py
from __future__ import print_function
import sys, re
"""
Multiline comment with unique
text pertaining to the Foo class
"""
class Foo():
pass
"""
Multiline comment with unique
text pertaining to the Bar class
"""
class Bar():
pass
"""
Multiline comment with unique
text pertaining to the FooBar class
"""
class FooBar():
pass
def print_comments():
with open(sys.argv[0]) as f:
file_contents = f.read()
map(print, re.findall(r'"""\n([^"""]*)"""', file_contents, re.S))
print_comments()
$ python script.py
Multiline comment with unique
text pertaining to the Foo class
Multiline comment with unique
text pertaining to the Bar class
Multiline comment with unique
text pertaining to the FooBar class
</code></pre>
<p>Regex Explanation:</p>
<pre><code>"""\n([^"""]*)"""
</code></pre>
<p><img src="https://www.debuggex.com/i/ADIqnLkWvzSG2UzQ.png" alt="Regular expression visualization"></p>
<p><a href="https://www.debuggex.com/r/ADIqnLkWvzSG2UzQ" rel="nofollow">Debuggex Demo</a></p>
<p>The ideal way to do this would be to use the ast module, parse the entire document and then print call ast.get_docstring on all nodes of type ast.FunctionDef, ast.ClassDef or ast.Module. However, your comments are not docstrings. If the file would have been something like this:</p>
<pre><code>$ cat script.py
import sys, re, ast
class Foo():
"""
Multiline comment with unique
text pertaining to the Foo class
"""
pass
class Bar():
"""
Multiline comment with unique
text pertaining to the Bar class
"""
pass
class FooBar():
"""
Multiline comment with unique
text pertaining to the FooBar class
"""
pass
def print_docstrings():
with open(sys.argv[0]) as f:
file_contents = f.read()
tree = ast.parse(file_contents)
class_nodes = filter((lambda x: type(x) in [ast.ClassDef, ast.FunctionDef, ast.Module]), ast.walk(tree))
for node in class_nodes:
doc_str = ast.get_docstring(node)
if doc_str:
print doc_str
print_docstrings()
$ python script.py
Multiline comment with unique
text pertaining to the Foo class
Multiline comment with unique
text pertaining to the Bar class
Multiline comment with unique
text pertaining to the FooBar class
</code></pre>
| 1 | 2016-08-30T04:01:48Z | [
"python",
"string",
"unassigned-variable"
] |
python pandas: merge two data frame but didn't merge the repeat rows | 39,218,298 | <p>I have two dataframe: df1 and df2.</p>
<p>df1 is following:</p>
<pre><code> name exist
a 1
b 1
c 1
d 1
e 1
</code></pre>
<p>df2 (just have one column:name)is following:</p>
<pre><code> name
e
f
g
a
h
</code></pre>
<p>I want to merge these two dataframe, and didn't merge repeat names, I mean, if the name in df2 exist in df1, just show one time, else if the name is df2 not exist in df1, set the exist value is 0 or Nan. for example as df1(there is a and e), and df2(there is a and e, just showed a, e one time), I want to be the following df:</p>
<pre><code> a 1
b 1
c 1
d 1
e 1
f 0
g 0
h 0
</code></pre>
<p>I used the concat function to do it, my code is following:</p>
<pre><code>import pandas as pd
df1 = pd.DataFrame({'name': ['a', 'b', 'c', 'd', 'e'],
'exist': ['1', '1', '1', '1', '1']})
df2 = pd.DataFrame({'name': ['e', 'f', 'g', 'h', 'a']})
df = pd.concat([df1, df2])
print(df)
</code></pre>
<p>but the result is wrong(name a and e is repeated to be showed):</p>
<pre><code> exist name
0 1 a
1 1 b
2 1 c
3 1 d
4 1 e
0 NaN e
1 NaN f
2 NaN g
3 NaN h
4 NaN a
</code></pre>
<p>please give your hands, thanks in advance!</p>
| 0 | 2016-08-30T03:23:24Z | 39,218,344 | <p>As indicated by your title, you can use <code>merge</code> instead of <code>concat</code> and specify <code>how</code> parameter as <code>outer</code> since you want to keep all records from <code>df1</code> and <code>df2</code> which defines an outer join:</p>
<pre><code>import pandas as pd
pd.merge(df1, df2, on = 'name', how = 'outer').fillna(0)
# exist name
# 0 1 a
# 1 1 b
# 2 1 c
# 3 1 d
# 4 1 e
# 5 0 f
# 6 0 g
# 7 0 h
</code></pre>
| 1 | 2016-08-30T03:28:32Z | [
"python",
"pandas",
"merge",
"concat"
] |
Python -- Curl works, requests lib doesn't | 39,218,313 | <p>This works from the command line:</p>
<pre><code> curl -H "Content-Type: application/json" -X POST -d '<my data>' http://my_user:my_pass@my_url
</code></pre>
<p>This doesn't work from a python script:</p>
<pre><code> res=requests.post(
'http://my_user:my_pass@my_url',
json='<my data>')
</code></pre>
<p>What happens is it hits the server, but doesn't authorize. The REST API is built with Django Rest Framework, and I get </p>
<pre><code>{"detail":"Invalid username/password."}
</code></pre>
<p><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/" rel="nofollow">http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/</a></p>
<p>Password includes these special characters % ( \ </p>
<p>I escaped \ , so it's a double backslash. I also tried with r in front of string, and 4 backslashes.</p>
<p>I tried with <code>auth=('my_user','my_pass')</code> with the different escapes too.</p>
<p>I ran it through <a href="http://curl.trillworks.com/" rel="nofollow">http://curl.trillworks.com/</a> and still that didn't work.</p>
<p>Tomorrow I'm going to change my password to something simple and test.</p>
<p>If that doesn't work, I'm giving up and adding a bash script at the end that just runs that curl command.</p>
| 0 | 2016-08-30T03:24:57Z | 39,218,395 | <p>You need to try setting the authentication using <code>requests</code> library like this:</p>
<pre><code>from requests.auth import HTTPBasicAuth
response = requests.post(url, json=payload, auth=HTTPBasicAuth('user', 'pass'))
</code></pre>
<p><a href="http://docs.python-requests.org/en/master/user/authentication/#basic-authentication" rel="nofollow">http://docs.python-requests.org/en/master/user/authentication/#basic-authentication</a></p>
| 2 | 2016-08-30T03:36:03Z | [
"python",
"curl",
"django-rest-framework",
"python-requests",
"pycurl"
] |
Python -- Curl works, requests lib doesn't | 39,218,313 | <p>This works from the command line:</p>
<pre><code> curl -H "Content-Type: application/json" -X POST -d '<my data>' http://my_user:my_pass@my_url
</code></pre>
<p>This doesn't work from a python script:</p>
<pre><code> res=requests.post(
'http://my_user:my_pass@my_url',
json='<my data>')
</code></pre>
<p>What happens is it hits the server, but doesn't authorize. The REST API is built with Django Rest Framework, and I get </p>
<pre><code>{"detail":"Invalid username/password."}
</code></pre>
<p><a href="http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/" rel="nofollow">http://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/</a></p>
<p>Password includes these special characters % ( \ </p>
<p>I escaped \ , so it's a double backslash. I also tried with r in front of string, and 4 backslashes.</p>
<p>I tried with <code>auth=('my_user','my_pass')</code> with the different escapes too.</p>
<p>I ran it through <a href="http://curl.trillworks.com/" rel="nofollow">http://curl.trillworks.com/</a> and still that didn't work.</p>
<p>Tomorrow I'm going to change my password to something simple and test.</p>
<p>If that doesn't work, I'm giving up and adding a bash script at the end that just runs that curl command.</p>
| 0 | 2016-08-30T03:24:57Z | 39,226,684 | <blockquote>
<p>I escaped \ , so it's a double backslash. I also tried with r in front
of string, and 4 backslashes.</p>
</blockquote>
<p>The \ in the curl command was to escape a parenthesis. It wasn't part of the password.</p>
<p>I removed it and now it works.</p>
| 0 | 2016-08-30T11:47:41Z | [
"python",
"curl",
"django-rest-framework",
"python-requests",
"pycurl"
] |
How can I search and parse multiple, session-specific search results with Scrapy? | 39,218,466 | <p>[EDIT: Code is revised to show my attempt at doing Granitosaurus' suggestion]</p>
<p>I need to execute some predefined searches and crawl the results 1 level deep, then parse those pages. This has to be done sequentially because the site will not allow results to be crawled unless those results were just retrieved pursuant to a search.</p>
<p>My predefined searches are in a list and I'm trying to loop through that list, but I cannot get it to work. Scrapy either jumps all around or loops through all the start_requests without parsing each as it goes. Can anyone show me a way to do this? Thanks!</p>
<p>The search terms are simply pairs of date ranges which I've stored in a list at the beginning.</p>
<p>Here's my [NEWLY EDITED] code with my non-working loop commented out:</p>
<pre><code>import scrapy
monthlist = [{'from_date': '9/1/13', 'to_date': '9/30/13'},
{'from_date': '10/1/13', 'to_date': '10/31/13'},
{'from_date': '11/1/13', 'to_date': '11/30/13'},
{'from_date': '12/1/13', 'to_date': '12/31/13'},
{'from_date': '1/1/14', 'to_date': '1/31/14'},
{'from_date': '2/1/14', 'to_date': '2/28/14'},
{'from_date': '3/1/14', 'to_date': '3/31/14'},
{'from_date': '4/1/14', 'to_date': '4/30/14'},
{'from_date': '5/1/14', 'to_date': '5/31/14'},
{'from_date': '6/1/14', 'to_date': '6/30/14'},
{'from_date': '7/1/14', 'to_date': '7/31/14'},
{'from_date': '8/1/14', 'to_date': '8/31/14'},
{'from_date': '9/1/14', 'to_date': '9/30/14'}]
# remainder of list snipped for this post
class docketSpider(scrapy.Spider):
name = 'robey'
custom_settings = {
'DEPTH_PRIORITY': 1,
'SCHEDULER_DISK_QUEUE': 'scrapy.squeues.PickleFifoDiskQueue',
'SCHEDULER_MEMORY_QUEUE': 'scrapy.squeues.FifoMemoryQueue'
}
start_urls = ['http://justice1.dentoncounty.com/PublicAccessDC/default.aspx']
monkeycount = 0
def start_requests(self):
for i in range(33):
self.monkeycount =+ 1
yield scrapy.Request('http://justice1.dentoncounty.com/PublicAccessDC/default.aspx', dont_filter=True)
yield scrapy.Request('http://justice1.dentoncounty.com/PublicAccessDC/default.aspx', self.parse, dont_filter=True)
# yield scrapy.Request('http://justice1.dentoncounty.com/PublicAccessDC/Search.aspx?ID=200&NodeID=1256&NodeDesc=393rd%20Judicial%20District%20Court', dont_filter=True)
def parse(self, response):
request = scrapy.Request('http://justice1.dentoncounty.com/PublicAccessDC/Search.aspx?ID=200&NodeID=1256&NodeDesc=393rd%20Judicial%20District%20Court',
callback=self.retrieve_caselist)
return request
def retrieve_caselist(self, response):
# caserange = {'from_date': '9/1/2013', 'to_date': '9/30/2013'}
# for caserange in monthlist:
yield scrapy.FormRequest.from_response(
response,
url='http://justice1.dentoncounty.com/PublicAccessDC/Search.aspx?ID=200&NodeID=1256&NodeDesc=393rd%20Judicial%20District%20Court',
formdata={'CaseSearchMode': 'CaseNumber', 'SearchBy': '6', 'ExactName': 'on', 'PartySearchMode': 'Name', 'AttorneySearchMode': 'Name', 'cboState': 'AA', 'CaseStatusType': '0', 'SortBy': 'fileddate', 'SearchSubmit': 'Search', 'SearchType': 'CASE', 'StatusType': 'true', 'AllStatusTypes': 'true', 'SearchParams': 'DateFiled~~Search By:~~6~~Date Filed||chkExactName~~Exact Name:~~on~~on||AllOption~~Case Status:~~0~~All||DateFiledOnAfter~~Date Filed On or After:~~' + monthlist[self.monkeycount]['from_date'] + '~~' + monthlist[self.monkeycount]['from_date'] + '||DateFiledOnBefore~~Date Filed On or Before:~~' + monthlist[self.monkeycount]['to_date'] + '~~' + monthlist[self.monkeycount]['to_date'] + '||selectSortBy~~Sort By:~~Filed Date~~Filed Date', 'SearchMode': 'FILED', 'DateFiledOnAfter': monthlist[self.monkeycount]['from_date'], 'DateFiledOnBefore': monthlist[self.monkeycount]['to_date']},
callback=self.parse_caselist,
dont_filter=True
)
def parse_caselist(self, response):
for href in response.xpath('//html/body/table/tr/td/a/@href').extract():
full_url = response.urljoin(href)
yield scrapy.Request(full_url, callback=self.parse_casedetail)
def parse_casedetail(self, response):
yield {
'case_num': response.xpath('/html/body/div[2]/span/text()').extract(),
'attorneys': response.xpath('/html/body/table[4]/tr/td/b/text()').extract(),
'file_date': response.xpath('/html/body/table[3]/tr/td[3]/table/tr/td/table/tr[2]/td/b/text()').extract(),
'case_type': response.xpath('/html/body/table[3]/tr/td[3]/table/tr/td/table/tr[1]/td/b/text()').extract()
}
</code></pre>
<p>When this runs, it loops through the loop making each request, but it fails to call self.parse on each loop (along with all the callables that run in turn, after self.parse). After the loop, it parses a single set of search results, then acts like it's finished. Here's the <a href="http://pastebin.com/embed/7Bn0DM3U" rel="nofollow">pastebin log of it running</a> from PyCharm. Any ideas? </p>
| 0 | 2016-08-30T03:48:16Z | 39,220,261 | <p>Seems like you are being restricted by the website session. What you could try is to spawn multiple sessions in <code>start_requests()</code> and then for each session yield unique search query.</p>
<p>Something like: </p>
<pre><code>class MySpider(scrapy.Spider):
name = "myspider"
start_url = "http://scrapy.org"
search_options = [
{'name': 'john', 'last_name': 'snow'},
{'name': 'james', 'last_name': 'bond'},
]
def start_requests(self):
# Start a web session for every search option
for i, option in enumerate(self.search_options):
yield Request(self.start_url,
dont_filter=True,
meta={'search_option': option,
'cookiejar': i})
def parse(self, response):
# make search request with those specific options!
yield FormRequest.from_response(response,
callback=self.parse_search,
meta=response.meta,
formdata=response['search_option'])
def parse_search(self, response):
# parse your search here
</code></pre>
| 0 | 2016-08-30T06:29:16Z | [
"python",
"asp.net",
"scrapy"
] |
Towers of Hanoi recursive calls | 39,218,491 | <pre><code>1
2 def printMove (to, fr):
3 '''Prints the moves to be executed'''
4 print 'move from ' + str (fr) + ' to ' + str (to)
5
6 def towers (n, fr, to, sp):
7 if n == 1:
8
9 printMove (to, fr) #
10
11 else:
12 towers (n-1, fr, sp, to)
13
14
15
16 towers (1, fr, to, sp)
17 towers (n - 1, sp, to, fr)
18
19 towers (3, 'fr', 'to', 'sp')
</code></pre>
<p>Please can someone explain why this code completes the recursive call on line 12 with <code>n</code> decrementing to 1, then does another call to <code>n = 2</code> again and then move to line 16 after? I have been using python tutor and am trying to understand each step and why the algorithm works.</p>
| 1 | 2016-08-30T03:51:43Z | 39,218,717 | <p>First, an aside: the code you show contains an error on line 9, which is not indented legally.</p>
<p>Execution begins with line 19, which calls towers(3,...), which proceeds up to line 12, where it calls towers(2,...), which proceeds up to line 12, where it calls towers(1,...), which prints something and returns. When it returns, execution resumes in the towers(2,...) invocation, and resumes at line 16, as you observed.</p>
| 1 | 2016-08-30T04:19:39Z | [
"python",
"algorithm",
"recursion",
"towers-of-hanoi"
] |
Towers of Hanoi recursive calls | 39,218,491 | <pre><code>1
2 def printMove (to, fr):
3 '''Prints the moves to be executed'''
4 print 'move from ' + str (fr) + ' to ' + str (to)
5
6 def towers (n, fr, to, sp):
7 if n == 1:
8
9 printMove (to, fr) #
10
11 else:
12 towers (n-1, fr, sp, to)
13
14
15
16 towers (1, fr, to, sp)
17 towers (n - 1, sp, to, fr)
18
19 towers (3, 'fr', 'to', 'sp')
</code></pre>
<p>Please can someone explain why this code completes the recursive call on line 12 with <code>n</code> decrementing to 1, then does another call to <code>n = 2</code> again and then move to line 16 after? I have been using python tutor and am trying to understand each step and why the algorithm works.</p>
| 1 | 2016-08-30T03:51:43Z | 39,219,204 | <p>First of all, your code is not perfectly alright. Here is the changed <code>towers</code> function for you -></p>
<pre><code>def towers (n, fr, to, sp):
if n == 1:
printMove (to, fr)
else:
towers (n-1, fr, sp, to)
printMove (to,fr)
towers (n-1, sp, to, fr)
</code></pre>
<p>And here goes the explanation. Look at the picture -></p>
<p><a href="http://i.stack.imgur.com/krc1J.png"><img src="http://i.stack.imgur.com/krc1J.png" alt="enter image description here"></a></p>
<p>By calling <code>Movetower(3,a,b,c)</code>, you intend to move all the 3 discs from tower <code>A</code> to tower <code>B</code>. So the sequential calls are -></p>
<pre><code>1. Movetower(3,a,b,c) // No Move needed
2. Movetower(2,a,c,b) // No move needed
3. Movetower(1,a,b,c) // Here is the time to move, move disc1 from a to b
4. Movetower(2,a,c,b) // Returning to this call again, this is the time to move disc2 from a to c
5. Movetower(1,b,c,a) // Again the time to move, this time disc1 from b to c
6. Movetower(3,a,b,c) // Returning to this call again, this is the time to move disc3 from a to b
7. Movetower(2,c,b,a) // Not the time to move
8. Movetower(1,c,a,b) // Here is the time to move, move disc1 from c to a
9. Movetower(2,c,b,a) // Returning to this call again, this is the time to move disc2 from c to b
10.Movetower(1,c,a,b) // Here is the time to move, move disc1 from a to b
</code></pre>
<p>Hope it helps :)</p>
<p>You can also find some good explanations here : <a href="http://stackoverflow.com/questions/1223305/tower-of-hanoi-recursive-algorithm">Tower of Hanoi: Recursive Algorithm</a></p>
<p>For Animation : <a href="https://www.cs.cmu.edu/~cburch/survey/recurse/hanoiex.html">https://www.cs.cmu.edu/~cburch/survey/recurse/hanoiex.html</a></p>
| 5 | 2016-08-30T05:14:51Z | [
"python",
"algorithm",
"recursion",
"towers-of-hanoi"
] |
create 3D binary image | 39,218,556 | <p>I have a 2D array, <code>a</code>, comprising a set of 100 x,y,z coordinates: </p>
<pre><code>[[ 0.81 0.23 0.52]
[ 0.63 0.45 0.13]
...
[ 0.51 0.41 0.65]]
</code></pre>
<p>I would like to create a 3D binary image, <code>b</code>, with 101 pixels in each of the x,y,z dimensions, of coordinates ranging between 0.00 and 1.00.
Pixels at locations defined by <code>a</code> should take on a value of 1, all other pixels should have a value of 0.</p>
<p>I can create an array of zeros of the right shape with <code>b = np.zeros((101,101,101))</code>, but how do I assign coordinate and slice into it to create the ones using <code>a</code>?</p>
| 4 | 2016-08-30T04:00:34Z | 39,219,766 | <p>You could do something like this -</p>
<pre><code># Get the XYZ indices
idx = np.round(100 * a).astype(int)
# Initialize o/p array
b = np.zeros((101,101,101))
# Assign into o/p array based on linear index equivalents from indices array
np.put(b,np.ravel_multi_index(idx.T,b.shape),1)
</code></pre>
<hr>
<p>Runtime on the assignment part -</p>
<p>Let's use a bigger grid for timing purposes.</p>
<pre><code>In [82]: # Setup input and get indices array
...: a = np.random.randint(0,401,(100000,3))/400.0
...: idx = np.round(400 * a).astype(int)
...:
In [83]: b = np.zeros((401,401,401))
In [84]: %timeit b[list(idx.T)] = 1 #@Praveen soln
The slowest run took 42.16 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 6.28 ms per loop
In [85]: b = np.zeros((401,401,401))
In [86]: %timeit np.put(b,np.ravel_multi_index(idx.T,b.shape),1) # From this post
The slowest run took 45.34 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 5.71 ms per loop
In [87]: b = np.zeros((401,401,401))
In [88]: %timeit b[idx[:,0],idx[:,1],idx[:,2]] = 1 #Subscripted indexing
The slowest run took 40.48 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 6.38 ms per loop
</code></pre>
| 4 | 2016-08-30T05:58:42Z | [
"python",
"numpy",
"indexing",
"binary",
"ndimage"
] |
create 3D binary image | 39,218,556 | <p>I have a 2D array, <code>a</code>, comprising a set of 100 x,y,z coordinates: </p>
<pre><code>[[ 0.81 0.23 0.52]
[ 0.63 0.45 0.13]
...
[ 0.51 0.41 0.65]]
</code></pre>
<p>I would like to create a 3D binary image, <code>b</code>, with 101 pixels in each of the x,y,z dimensions, of coordinates ranging between 0.00 and 1.00.
Pixels at locations defined by <code>a</code> should take on a value of 1, all other pixels should have a value of 0.</p>
<p>I can create an array of zeros of the right shape with <code>b = np.zeros((101,101,101))</code>, but how do I assign coordinate and slice into it to create the ones using <code>a</code>?</p>
| 4 | 2016-08-30T04:00:34Z | 39,219,890 | <p>First, start off by safely rounding your floats to ints. In context, see <a href="http://stackoverflow.com/q/3387655/525169">this</a> question.</p>
<pre><code>a_indices = np.rint(a * 100).astype(int)
</code></pre>
<p>Next, assign those indices in <code>b</code> to 1. But be careful to use an ordinary <code>list</code> instead of the array, or else you'll trigger the usage of <a href="http://docs.scipy.org/doc/numpy/user/basics.indexing.html#index-arrays" rel="nofollow">index arrays</a>. It seems as though performance of this method is comparable to that of alternatives (Thanks @Divakar! :-)</p>
<pre><code>b[list(a_indices.T)] = 1
</code></pre>
<p>I created a small example with size 10 instead of 100, and 2 dimensions instead of 3, to illustrate:</p>
<pre><code>>>> a = np.array([[0.8, 0.2], [0.6, 0.4], [0.5, 0.6]])
>>> a_indices = np.rint(a * 10).astype(int)
>>> b = np.zeros((10, 10))
>>> b[list(a_indices.T)] = 1
>>> print(b)
[[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.]
[ 0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]
</code></pre>
| 4 | 2016-08-30T06:07:10Z | [
"python",
"numpy",
"indexing",
"binary",
"ndimage"
] |
Using BeautifulSoup to Search Through Yahoo Finance | 39,218,742 | <p>I'm trying to pull information from the 'Key Statistics' page for a ticker in Yahoo (since this isn't supported in the Pandas library). </p>
<p>Example for AAPL:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
url = 'http://finance.yahoo.com/quote/AAPL/key-statistics?p=AAPL'
page = requests.get(url)
soup = BeautifulSoup(page.text, 'lxml')
enterpriseValue = soup.findAll('$ENTERPRISE_VALUE', attrs={'class': 'yfnc_tablehead1'}) #HTML tag for where enterprise value is located
print(enterpriseValue)
</code></pre>
<p>Edit: thanks Andy!</p>
<p>Question: This is printing an empty array. How do I change my <code>findAll</code> to return <code>598.56B</code>?</p>
| 4 | 2016-08-30T04:23:53Z | 39,218,917 | <p>Well, the reason the list that <code>find_all</code> returns is empty is because that data is generated with a separate call that isn't completed by just sending a <code>GET</code> request to that URL. If you look through the Network tab on Chrome/Firefox and filter by XHR, by examining the requests and responses of each network action, you can find what you URL you ought to be sending the <code>GET</code> request too. </p>
<p>In this case, it's <code>https://query2.finance.yahoo.com/v10/finance/quoteSummary/AAPL?formatted=true&crumb=8ldhetOu7RJ&lang=en-US&region=US&modules=defaultKeyStatistics%2CfinancialData%2CcalendarEvents&corsDomain=finance.yahoo.com</code>, as we can see here:
<a href="http://i.stack.imgur.com/B4TBz.png" rel="nofollow"><img src="http://i.stack.imgur.com/B4TBz.png" alt="enter image description here"></a></p>
<p>So, how do we recreate this? Simple! :</p>
<pre><code>from bs4 import BeautifulSoup
import requests
r = requests.get('https://query2.finance.yahoo.com/v10/finance/quoteSummary/AAPL?formatted=true&crumb=8ldhetOu7RJ&lang=en-US&region=US&modules=defaultKeyStatistics%2CfinancialData%2CcalendarEvents&corsDomain=finance.yahoo.com')
data = r.json()
</code></pre>
<p>This will return the <code>JSON</code> response as a <code>dict</code>. From there, navigate through the <code>dict</code> until you find the data you're after:</p>
<pre><code>financial_data = data['quoteSummary']['result'][0]['defaultKeyStatistics']
enterprise_value_dict = financial_data['enterpriseValue']
print(enterprise_value_dict)
>>> {'fmt': '598.56B', 'raw': 598563094528, 'longFmt': '598,563,094,528'}
print(enterprise_value_dict['fmt'])
>>> '598.56B'
</code></pre>
| 3 | 2016-08-30T04:46:07Z | [
"python",
"beautifulsoup",
"yahoo-finance"
] |
Find numpy vectors in a set quickly | 39,218,768 | <p>I have a numpy array, for example:</p>
<pre><code>a = np.array([[1,2],
[3,4],
[6,4],
[5,3],
[3,5]])
</code></pre>
<p>and I also have a set</p>
<pre><code>b = set((1,2),(6,4),(9,9))
</code></pre>
<p>I want to find the index of vectors that exist in set b, here is</p>
<pre><code>[0, 2]
</code></pre>
<p>but I use a for loop to implement this, is there a convinient way to do this job avoiding for loop?
The for loop method I used:</p>
<pre><code>record = []
for i in range(a.shape[0]):
if (a[i, 0], a[i, 1]) in b:
record.append(i)
</code></pre>
| 1 | 2016-08-30T04:26:16Z | 39,218,831 | <p>You can use filter:</p>
<pre><code>In [8]: a = np.array([[1,2],
[3,4],
[6,4],
[5,3],
[3,5]])
In [9]: b = {(1,2),(6,4)}
In [10]: filter(lambda x: tuple(a[x]) in b, range(len(a)))
Out[10]: [0, 2]
</code></pre>
| 1 | 2016-08-30T04:35:08Z | [
"python",
"numpy",
"set",
"vectorization",
"lookup"
] |
Find numpy vectors in a set quickly | 39,218,768 | <p>I have a numpy array, for example:</p>
<pre><code>a = np.array([[1,2],
[3,4],
[6,4],
[5,3],
[3,5]])
</code></pre>
<p>and I also have a set</p>
<pre><code>b = set((1,2),(6,4),(9,9))
</code></pre>
<p>I want to find the index of vectors that exist in set b, here is</p>
<pre><code>[0, 2]
</code></pre>
<p>but I use a for loop to implement this, is there a convinient way to do this job avoiding for loop?
The for loop method I used:</p>
<pre><code>record = []
for i in range(a.shape[0]):
if (a[i, 0], a[i, 1]) in b:
record.append(i)
</code></pre>
| 1 | 2016-08-30T04:26:16Z | 39,219,030 | <p>First off, convert the set to a NumPy array -</p>
<pre><code>b_arr = np.array(list(b))
</code></pre>
<p>Then, based on <a href="http://stackoverflow.com/a/38674038/3293881"><code>this post</code></a>, you would have three approaches. Let's use the second approach for efficiency -</p>
<pre><code>dims = np.maximum(a.max(0),b_arr.max(0)) + 1
a1D = np.ravel_multi_index(a.T,dims)
b1D = np.ravel_multi_index(b_arr.T,dims)
out = np.flatnonzero(np.in1d(a1D,b1D))
</code></pre>
<p>Sample run -</p>
<pre><code>In [89]: a
Out[89]:
array([[1, 2],
[3, 4],
[6, 4],
[5, 3],
[3, 5]])
In [90]: b
Out[90]: {(1, 2), (6, 4), (9, 9)}
In [91]: b_arr = np.array(list(b))
In [92]: dims = np.maximum(a.max(0),b_arr.max(0)) + 1
...: a1D = np.ravel_multi_index(a.T,dims)
...: b1D = np.ravel_multi_index(b_arr.T,dims)
...: out = np.flatnonzero(np.in1d(a1D,b1D))
...:
In [93]: out
Out[93]: array([0, 2])
</code></pre>
| 1 | 2016-08-30T04:58:33Z | [
"python",
"numpy",
"set",
"vectorization",
"lookup"
] |
Find numpy vectors in a set quickly | 39,218,768 | <p>I have a numpy array, for example:</p>
<pre><code>a = np.array([[1,2],
[3,4],
[6,4],
[5,3],
[3,5]])
</code></pre>
<p>and I also have a set</p>
<pre><code>b = set((1,2),(6,4),(9,9))
</code></pre>
<p>I want to find the index of vectors that exist in set b, here is</p>
<pre><code>[0, 2]
</code></pre>
<p>but I use a for loop to implement this, is there a convinient way to do this job avoiding for loop?
The for loop method I used:</p>
<pre><code>record = []
for i in range(a.shape[0]):
if (a[i, 0], a[i, 1]) in b:
record.append(i)
</code></pre>
| 1 | 2016-08-30T04:26:16Z | 39,220,519 | <p>For reference, a straight forward list comprehension (loop) answer:</p>
<pre><code>In [108]: [i for i,v in enumerate(a) if tuple(v) in b]
Out[108]: [0, 2]
</code></pre>
<p>basically the same speed as the <code>filter</code> approach:</p>
<pre><code>In [111]: timeit [i for i,v in enumerate(a) if tuple(v) in b]
10000 loops, best of 3: 24.5 µs per loop
In [114]: timeit list(filter(lambda x: tuple(a[x]) in b, range(len(a))))
10000 loops, best of 3: 29.7 µs per loop
</code></pre>
<p>But this is a toy example, so timings aren't meaningful.</p>
<p>If <code>a</code> wasn't already an array, these list approaches would be faster than the array ones, due to the overhead of creating arrays.</p>
<p>There are some numpy set operations, but they work with 1d arrays. We can get around that by converting 2d arrays to 1d structured.</p>
<pre><code>In [117]: a.view('i,i')
Out[117]:
array([[(1, 2)],
[(3, 4)],
[(6, 4)],
[(5, 3)],
[(3, 5)]],
dtype=[('f0', '<i4'), ('f1', '<i4')])
In [119]: np.array(list(b),'i,i')
Out[119]:
array([(1, 2), (6, 4), (9, 9)],
dtype=[('f0', '<i4'), ('f1', '<i4')])
</code></pre>
<p>There is a version of this using <code>np.void</code>, but it's easier to remember and play with this 'i,i' dtype.</p>
<p>So this works:</p>
<pre><code>In [123]: np.nonzero(np.in1d(a.view('i,i'),np.array(list(b),'i,i')))[0]
Out[123]: array([0, 2], dtype=int32)
</code></pre>
<p>but it is much slower than the iterations:</p>
<pre><code>In [124]: timeit np.nonzero(np.in1d(a.view('i,i'),np.array(list(b),'i,i')))[0]
10000 loops, best of 3: 153 µs per loop
</code></pre>
<p>As discussed in other recent <code>union</code> questions, <code>np.in1d</code> uses several strategies. One is based on broadcasting and <code>where</code>. The other uses <code>unique</code>, <code>concatenation</code>, <code>sorting</code> and differences.</p>
<p>A broadcasting solution (yes, it's messy) - but faster than <code>in1d</code>.</p>
<pre><code>In [150]: timeit np.nonzero((a[:,:,None,None]==np.array(list(b))[:,:]).any(axis=-1).any(axis=-1).all(axis=-1))[0]
10000 loops, best of 3: 52.2 µs per loop
</code></pre>
| 0 | 2016-08-30T06:45:20Z | [
"python",
"numpy",
"set",
"vectorization",
"lookup"
] |
Find numpy vectors in a set quickly | 39,218,768 | <p>I have a numpy array, for example:</p>
<pre><code>a = np.array([[1,2],
[3,4],
[6,4],
[5,3],
[3,5]])
</code></pre>
<p>and I also have a set</p>
<pre><code>b = set((1,2),(6,4),(9,9))
</code></pre>
<p>I want to find the index of vectors that exist in set b, here is</p>
<pre><code>[0, 2]
</code></pre>
<p>but I use a for loop to implement this, is there a convinient way to do this job avoiding for loop?
The for loop method I used:</p>
<pre><code>record = []
for i in range(a.shape[0]):
if (a[i, 0], a[i, 1]) in b:
record.append(i)
</code></pre>
| 1 | 2016-08-30T04:26:16Z | 39,222,152 | <p>A one line solution using a list comprehension:</p>
<pre><code>In [62]: a = np.array([[1,2],
...: [3,4],
...: [6,4],
...: [5,3],
...: [3,5]])
In [63]: b = set(((1,2),(6,4),(9,9)))
In [64]: where([tuple(e) in b for e in a])[0]
Out[64]: array([0, 2])
</code></pre>
| 0 | 2016-08-30T08:12:46Z | [
"python",
"numpy",
"set",
"vectorization",
"lookup"
] |
Improving performance for SQLAlchemy? | 39,218,781 | <p>I am currently running a Flask + SQLAlchemy + uWSGI + nginx stack for an API backend that I am developing for my application.
I was attempting to see what is the maximum amount of concurrent connection I can have on my server by using ApacheBench and sending different amounts of concurrent requests to an endpoint on the server.</p>
<p>This endpoint would take a JSON request body, extract certain values, run a query, then return a JSON response based on the results of the query.</p>
<p>I ran a base test of <strong>1 concurrent request</strong> for 10 requests, and I got an average response time of 60 milliseconds.<br>
Running another test with <strong>10 concurrent requests</strong> for 100 requests returned an average of 150ms, <strong>100 concurrent requests</strong> for 1000 returned 1500ms and <strong>500 concurrent requests</strong> returned around 7000-9000ms. </p>
<pre><code>Concurrency Level: 500
Time taken for tests: 38.710 seconds
Complete requests: 5000
Failed requests: 0
Total transferred: 1310000 bytes
Total body sent: 1105000
HTML transferred: 110000 bytes
Requests per second: 129.17 [#/sec] (mean)
Time per request: 3870.986 [ms] (mean)
Time per request: 7.742 [ms] (mean, across all concurrent requests)
Transfer rate: 33.05 [Kbytes/sec] received
27.88 kb/s sent
60.93 kb/s total
Connection Times (ms)
min mean[+/-sd] median max
Connect: 24 63 185.1 25 3025
Processing: 161 3737 2778.7 3316 26719
Waiting: 157 3737 2778.7 3316 26719
Total: 187 3800 2789.7 3366 26744
Percentage of the requests served within a certain time (ms)
50% 3366
66% 4135
75% 4862
80% 5711
90% 7449
95% 9158
98% 11794
99% 13373
100% 26744 (longest request)
</code></pre>
<p>The latency seems to be linearly increasing which makes sense, but it seemed to increase TOO quickly. After doing a lot of tinkering and profiling, I found that the bottleneck was the queries.</p>
<p>At the start of the benchmark, the queries would process and return quickly under 10-50ms, but it quickly increased and in some cases latencies of 10000-15000 ms were being seen. </p>
<p>I couldn't figure out why the db was slowing down so much especially since it is empty (barring test data). </p>
<p>I tried running the application WITHOUT a connection pool, and the results showed that latency went down (7-9s to 5-6s). I did not think this was possible because everything I read suggested having a connection pool will always make things faster because you avoid the overhead of establishing a new connection every time you make a request. </p>
<p>I also experimented with INCREASING the connection pool size (from the default 5 to 50), and that decreased latency even more than the pool-less setup(5-6s to 3-4s). </p>
<pre><code>Concurrency Level: 500
Time taken for tests: 4.842 seconds
Complete requests: 836
Failed requests: 0
Non-2xx responses: 679
Total transferred: 272673 bytes
Total body sent: 294593
HTML transferred: 126353 bytes
Requests per second: 172.67 [#/sec] (mean)
Time per request: 2895.662 [ms] (mean)
Time per request: 5.791 [ms] (mean, across all concurrent requests)
Transfer rate: 55.00 [Kbytes/sec] received
59.42 kb/s sent
114.42 kb/s total
Connection Times (ms)
min mean[+/-sd] median max
Connect: 24 170 273.1 93 1039
Processing: 25 665 1095.2 149 4753
Waiting: 25 665 1095.2 149 4753
Total: 51 835 1123.9 279 4786
Percentage of the requests served within a certain time (ms)
50% 279
66% 487
75% 1050
80% 1059
90% 2935
95% 3658
98% 4176
99% 4337
100% 4786 (longest request)
</code></pre>
<p>The latency is still extremely high (3-4 seconds for an API seems unreasonable by any standard), and I am trying to figure out how I can decrease it even more. Is the answer just more connections? </p>
<p>Note:
I am running 4 uWSGI processes with 100 threads each on a server with 4GB ram and a quad core processor.
I am using the psycopg2-cffi adapter for the connection, and the application is running on PyPy. </p>
| 0 | 2016-08-30T04:28:05Z | 39,238,424 | <p>The linear increase is very much normal, if the database has to process your queries sequentially. Essentially, all concurrent requests get started at the same time, but finish one after another, so, assuming a pool with a single connection, 60ms per request, and 10 concurrent requests, you're going to see requests taking 60ms, 120ms, 180ms, 240ms, 300ms, 360ms, 420ms, 480ms, 540ms, 600ms, 600ms, ..., 600ms, 540ms, 480ms, ... . We can calculate how much time it takes for the average request, given <code>n</code> requests and <code>m</code> concurrent requests:</p>
<pre><code>f(n, m) = 60ms * (((m + 1) * m / 2) * 2 + (n - 2m) * m) / n
f(100, 10) = 546ms
f(1000, 100) = 5406ms
f(1000, 500) = 15,030ms
</code></pre>
<p>These numbers are similar to what you are seeing.</p>
<p>Now comes the big question. Why does the database process queries almost sequentially? I can think of a few reasons:</p>
<ul>
<li>Locking: each started transaction needs to lock some resource exclusively so only one (or few) transaction can run at a time</li>
<li>CPU-bound query: each transaction takes significant CPU resources so other transactions must wait for CPU time</li>
<li>Large table scans: the database cannot keep the entirety of the table in memory and therefore must read from disk for every transaction</li>
</ul>
<p>How do you fix this? This is a complicated question, but a few potential solutions:</p>
<ul>
<li>Optimize your queries; either optimize it so that they don't all fight for the same resource, or, optimize it so that they don't take as long</li>
<li>Batch your queries so that you need to run fewer in total</li>
<li>Cache your responses so that they don't hit the database at all</li>
</ul>
| 0 | 2016-08-30T23:12:04Z | [
"python",
"performance",
"sqlalchemy",
"database-connection"
] |
Allow only editing the current selected Foreign Key in Django Admin | 39,218,783 | <p>So currently I have something like this:</p>
<p>Model:</p>
<pre><code>class ConfirmEmail(models.Model):
report = models.ForeignKey(Report)
owner = models.CharField(max_length = 100)
emails = models.ManyToManyField(Sdm)
</code></pre>
<p>Admin: </p>
<pre><code>@admin.register(ConfirmEmail)
class ConfirmEmailAdmin(admin.ModelAdmin):
change_form_template = 'admin/phone/index.html'
readonly_fields = ('owner',)
filter_horizontal = ('emails',)
list_display = ('owner','report')
</code></pre>
<p>I create these objects in code - meaning I set the report object. But what I would like in the <code>Django admin</code> is if I could allow a user to edit that report object but only the one set. They would be allowed to change it (so hopefully the drop down menu would no longer be there) so the nice pencil icon would still be there, but things like that "+" icon would be gone.</p>
<p>And this is not to say the user can't edit all reports, it's just that in the <code>ConfirmEmail Admin</code> they can only view that specific report attached to it.</p>
<p>I've been smacking away at this and can't seem to get it work. </p>
<p>I would also be inclined to just have the current Report Form embedded into the <code>ConfirmEmail</code> form - but don't know how I would go about doing that.</p>
| 1 | 2016-08-30T04:28:12Z | 39,220,140 | <p>You should first introduce a model admin for your Report model, then override the <strong>has_add_permission</strong> function of your ReportAdmin.</p>
<pre><code>@admin.register(Report)
class ReportAdmin(admin.ModelAdmin):
# whatever you want here
def has_add_permission(self, request):
return False
</code></pre>
<p>You can also remove/disable the + button <strong>using javascript</strong> in the page, but be aware that the user can cause damage if he knows the add url, or disables javascript.</p>
| 0 | 2016-08-30T06:22:05Z | [
"python",
"django",
"django-admin"
] |
Is there an attribute called rect.center in pygame? | 39,218,842 | <p>I was looking through a pygame tutorial and encountered the following part of a script: </p>
<pre><code>fontObj = pygame.font.Font('freesansbold.ttf', 32)
textSurfaceObj = fontObj.render('hellow world', True, Green, Blue)
textRectObj = textSurfaceObj.get_rect()
textRectObj.center = (200,150)
</code></pre>
<p>The last line set the center of the rect at (200.150)
I looked through the pygame documentation and there is no center attribute in the Rect class.
But the script works... why ?</p>
| 0 | 2016-08-30T04:36:15Z | 39,219,038 | <p>According to the <a href="http://www.pygame.org/docs/ref/rect.html" rel="nofollow">docs on rect</a>:</p>
<blockquote>
<p>The Rect object has several virtual attributes which can be used to move and align the Rect:</p>
<p>x,y</p>
<p>top, left, bottom, right</p>
<p>topleft, bottomleft, topright, bottomright</p>
<p>midtop, midleft, midbottom, midright</p>
<p><strong>center</strong>, centerx, centery</p>
<p>size, width, height</p>
<p>w,h</p>
</blockquote>
<p>I've bolded <code>center</code>.</p>
| 0 | 2016-08-30T04:59:29Z | [
"python",
"pygame"
] |
Please explain the output of this python code | 39,218,862 | <p>Here the code.</p>
<pre><code>a = False
if a == True or True:
print "Hell yeah,I'm genius"
else:
print "shit,I am a fool"
</code></pre>
<p>Output is '<code>Hell yeah,I'm genius</code>'</p>
| -2 | 2016-08-30T04:38:36Z | 39,219,006 | <p>Anything True , it will run that section ...</p>
<pre><code>if True:
print "Hell yeah,I'm genius"
else:
print "shit,I am a fool"
</code></pre>
<p>This one also returns <code>"Hell yeah,I'm genius"</code></p>
| -1 | 2016-08-30T04:56:09Z | [
"python"
] |
Please explain the output of this python code | 39,218,862 | <p>Here the code.</p>
<pre><code>a = False
if a == True or True:
print "Hell yeah,I'm genius"
else:
print "shit,I am a fool"
</code></pre>
<p>Output is '<code>Hell yeah,I'm genius</code>'</p>
| -2 | 2016-08-30T04:38:36Z | 39,219,168 | <pre><code>a ==True or True
</code></pre>
<p>Consider True is 1 and 0 is False.</p>
<p>Since a is set to False (a=False in first statement of code), the first part 'a==True' i.e. 0 ==1 will return 0 (False).</p>
<p>Then remaining will be False or True since 'a==True' is False.
So it will be like 0 or 1 (False or True).</p>
<p>We know that</p>
<ul>
<li>0 AND 0 = 0</li>
<li>1 AND 0 = 0</li>
<li>1 AND 1 = 1</li>
<li>0 OR 0 = 0 </li>
<li>0 OR 1 = 1 </li>
<li>1 OR 1 = 1</li>
</ul>
<p>So in your case, 0 OR 1 will result to 1 i.e. True. </p>
<p><strong>Summary :</strong></p>
<pre><code>a == True or True => False or True => True
</code></pre>
<p>That's why "Hell yeah,I'm genius" will be printed.</p>
| 2 | 2016-08-30T05:11:43Z | [
"python"
] |
Python ttk notebook showing selected tab wrongly | 39,218,863 | <pre><code>from tkinter import *
from tkinter import ttk
class MainGame(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def tab_change(self, event):
tab_id = self.page.index('current')
print(tab_id, self.page.tab(tab_id, 'text'))
def initUI(self):
global canvas
self.parent.title('PythonPage')
self.pack(fill = BOTH, expand = 1)
self.page = ttk.Notebook(self, width = 646 ,height = 629)
self.page1 = Frame(self)
self.page2 = Frame(self)
self.page.add(self.page1, text = 'Tab1')
self.page.add(self.page2, text = 'Tab2')
self.page.bind('<ButtonPress-1>', self.tab_change)
self.page.pack(expand = 0, anchor = 'w', side = 'top')
root = Tk()
root.geometry('925x650')
main = MainGame(root)
root.mainloop()
</code></pre>
<p><code>tab_change</code> can show their id and names, but not correctly.</p>
<p>When <code>Tab1</code> is clicked, I clicked <code>Tab2</code> but it still print <code>0 Tab1</code>, it needs one more click to print <code>1 Tab2</code> .</p>
<p><code>Tab2</code> click to <code>Tab1</code> is the same, it needs one more click to show the current selected tab.</p>
<p>I want to find why the tabs need double click? And how can I get selected tab correctly by a single click?</p>
| 0 | 2016-08-30T04:38:49Z | 39,219,156 | <p>Change:</p>
<pre><code>self.page.bind('<ButtonPress-1>', self.tab_change)
</code></pre>
<p>To:</p>
<pre><code>self.page.bind('<ButtonRelease-1>', self.tab_change)
</code></pre>
<p>Because unless you have released the pressed button, the tab hasn't changed!</p>
<p><a href="http://i.stack.imgur.com/xLNxC.gif" rel="nofollow"><img src="http://i.stack.imgur.com/xLNxC.gif" alt="enter image description here"></a></p>
| 0 | 2016-08-30T05:10:46Z | [
"python",
"tkinter",
"tabs",
"ttk"
] |
django registration redux ignoring changes in templates | 39,218,872 | <p>I've been struggling with django registration redux over the past two weeks.. I'm using the templates the were provided in the documentation but I've made a couple of changes like adding crispy forms and changing the button and some other stuff but the problem is that none of these changes are being shown on <a href="http://127.0.0.1:8000/accounts/register" rel="nofollow">http://127.0.0.1:8000/accounts/register</a> or any other link.
I'm using djang registration redux 1.4, django 1.8, python 2.7.10</p>
<p>Any help appreciated, thanks</p>
| 0 | 2016-08-30T04:40:12Z | 39,231,115 | <p>Putting your customized templates in <code>templates/registration</code> (not register) should work.</p>
<p>At least if your <code>TEMPLATES</code> setting is correctly configured: <a href="https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/templates/upgrading/</a></p>
<p>And you probably already checked this hint from the project's <a href="https://django-registration-redux.readthedocs.io/en/latest/faq.html?highlight=templates#troubleshooting" rel="nofollow">FAQ</a>?</p>
<blockquote>
<p>I want to use custom templates, but django keeps using the admin
templates instead of mine!</p>
<p>To fix this, make sure that in the INSTALLED_APPS of your settings.py
the entry for the registration app is placed above
django.contrib.admin.</p>
</blockquote>
| 0 | 2016-08-30T15:06:45Z | [
"python",
"django",
"html5",
"twitter-bootstrap-3",
"django-registration"
] |
how to convert print output into variable/string with "more than 3 arguments"? (python 3) | 39,218,880 | <p>Basically I'm trying to take the print output for my code and make it into a variable. I tried to do this by converting it to a string but it gave me an error saying "TypeError: str() takes at most 3 arguments (6 given)"</p>
<p>my code:</p>
<pre><code>x = [1,2,3,4,5]
print(*x, sep='_') ##gives me the output "1_2_3_4_5"
#problem part:
a = str(*x, sep='_')
print(a) ##gives error
</code></pre>
<p>Is there either a way to convert the output to a string despite the "6 argument" thing or some other "str()"-like thing that would work?</p>
| 0 | 2016-08-30T04:41:09Z | 39,218,909 | <p>You can convert the list of ints to a list of strings using <a href="https://docs.python.org/3/library/functions.html#map" rel="nofollow"><code>map</code></a>, then use <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="nofollow"><code>join</code></a> to bind them together:</p>
<pre><code>x = [1, 2, 3, 4, 5]
a = '_'.join(map(str, x))
print(a) # '1_2_3_4_5'
</code></pre>
<p>Note: Your code did not work because <a href="https://docs.python.org/3/library/functions.html#print" rel="nofollow"><code>print</code></a> does some work for you:</p>
<blockquote>
<p>All non-keyword arguments are converted to strings like str() does and written to the stream.</p>
</blockquote>
<p>So, print did the string conversion step for you. When you call <a href="https://docs.python.org/3/library/stdtypes.html#str" rel="nofollow"><code>str()</code></a>, it expects only an object to convert to a string, with two optional keyword arguments (<code>encoding</code> and <code>errors</code>). By calling <code>str(*x, sep='_')</code>, you are passing in 5 arguments plus a separator, which is not a valid call.</p>
| 4 | 2016-08-30T04:44:56Z | [
"python",
"string",
"python-3.x",
"printing",
"arguments"
] |
how to convert print output into variable/string with "more than 3 arguments"? (python 3) | 39,218,880 | <p>Basically I'm trying to take the print output for my code and make it into a variable. I tried to do this by converting it to a string but it gave me an error saying "TypeError: str() takes at most 3 arguments (6 given)"</p>
<p>my code:</p>
<pre><code>x = [1,2,3,4,5]
print(*x, sep='_') ##gives me the output "1_2_3_4_5"
#problem part:
a = str(*x, sep='_')
print(a) ##gives error
</code></pre>
<p>Is there either a way to convert the output to a string despite the "6 argument" thing or some other "str()"-like thing that would work?</p>
| 0 | 2016-08-30T04:41:09Z | 39,218,945 | <p><code>*x</code> supplies much too many arguments to <code>str()</code> causing the error, and <code>sep</code> isn't an argument of <code>str()</code>. <code>str()</code> expects one object to be converted, and <code>*x</code> gives 5. Try this:</p>
<pre><code>x = [1, 2, 3, 4, 5]
a = '_'.join(str(i) for i in x)
print(a)
</code></pre>
<p>This will go through the list and join each element together with an underscore between.</p>
<p><a href="https://ideone.com/dLHFqx" rel="nofollow">Try it on IDEOne</a></p>
<hr>
<p>You can also use <code>map(function, sequence)</code> to shorten the <code>join()</code>. The function being applied is <code>str()</code> to convert the numbers into string form, and to the <code>x</code> list. Here's with <code>map()</code>:</p>
<pre><code>x = [1, 2, 3, 4, 5]
a = '_'.join(map(str, x))
print(a)
</code></pre>
| 3 | 2016-08-30T04:49:05Z | [
"python",
"string",
"python-3.x",
"printing",
"arguments"
] |
Close all browser instance in one go | 39,218,979 | <p>I am trying to close all browser instance opened by a test case in one go that is immediately when the test fails. I have opened more than one instance of same kind that is i am trying to automate chat application so i need to open two instance of same browser kind. But once the test fails, both the instance needs to be closed, but my test closes the browser for whom a particular step is failed. how to close both the browser instance when test fails for instance alone. <code>driver.quit()</code> is not working. As I have opened browser instance with different driver names i.e.</p>
<pre><code>brow1.get(url)
</code></pre>
<p>and</p>
<pre><code>brow2.get(url)
</code></pre>
| 0 | 2016-08-30T04:53:17Z | 39,219,188 | <p>What about calling <code>quit()</code> for both of them</p>
<pre><code>brow1.quit();
brow2.quit();
</code></pre>
<p>Or for more generic way keep them in list and iterate over it.</p>
<pre><code>browsers = []
browsers.append(brow1)
browsers.append(brow2)
for browser in browsers:
browser.quit()
</code></pre>
| 2 | 2016-08-30T05:13:47Z | [
"python",
"python-2.7",
"selenium",
"selenium-webdriver"
] |
Is there a way to prevent dtype from changing from Int64 to float64 when reindexing/upsampling a time-series? | 39,219,023 | <p>I am using pandas 0.17.0 and have a <code>df</code> similar to this one:</p>
<pre><code>df.head()
Out[339]:
A B C
DATE_TIME
2016-10-08 13:57:00 in 5.61 1
2016-10-08 14:02:00 in 8.05 1
2016-10-08 14:07:00 in 7.92 0
2016-10-08 14:12:00 in 7.98 0
2016-10-08 14:17:00 out 8.18 0
df.tail()
Out[340]:
A B C
DATE_TIME
2016-11-08 13:42:00 in 8.00 0
2016-11-08 13:47:00 in 7.99 0
2016-11-08 13:52:00 out 7.97 0
2016-11-08 13:57:00 in 8.14 1
2016-11-08 14:02:00 in 8.16 1
</code></pre>
<p>with following <code>dtypes</code>:</p>
<pre><code>print (df.dtypes)
A object
B float64
C int64
dtype: object
</code></pre>
<p>When I reindex my <code>df</code> to minute intervals all the columns <code>int64</code> change to <code>float64</code>. </p>
<pre><code>index = pd.date_range(df.index[0], df.index[-1], freq="min")
df2 = df.reindex(index)
print (df2.dtypes)
A object
B float64
C float64
dtype: object
</code></pre>
<p>Also, if I try to resample</p>
<p><code>df3 = df.resample('Min')</code></p>
<p>The <code>int64</code> will turn into a <code>float64</code> and for some reason I loose my <code>object</code> column.</p>
<p><code>print (df3.dtypes)</code></p>
<pre><code>print (df3.dtypes)
B float64
C float64
dtype: object
</code></pre>
<p>Since I want to interpolate the columns differently based on this distinction in an subsequent step (after concatenating the <code>df</code> with another <code>df</code>), I need them to maintain their original <code>dtype</code>. My real <code>df</code> has far more columns of each type, for which reason I am looking for a solution that does not depend on calling the columns individually by their label. </p>
<p>Is there a way to maintain their <code>dtype</code> throughout the reindexing? Or is there a way how I can assign them their <code>dtype</code> afterwards (they are the only columns consisiting only of integers besides NANs)?
Can anybody help me?</p>
| 2 | 2016-08-30T04:57:42Z | 39,219,097 | <p>It is <a href="http://pandas.pydata.org/pandas-docs/stable/gotchas.html#na-type-promotions" rel="nofollow">impossible</a>, because if you get at least one <code>NaN</code> value in some column, <code>int</code> is converted to <code>float</code>.</p>
<pre><code>index = pd.date_range(df.index[0], df.index[-1], freq="min")
df2 = df.reindex(index)
print (df2)
A B C
2016-10-08 13:57:00 in 5.61 1.0
2016-10-08 13:58:00 NaN NaN NaN
2016-10-08 13:59:00 NaN NaN NaN
2016-10-08 14:00:00 NaN NaN NaN
2016-10-08 14:01:00 NaN NaN NaN
2016-10-08 14:02:00 in 8.05 1.0
2016-10-08 14:03:00 NaN NaN NaN
2016-10-08 14:04:00 NaN NaN NaN
2016-10-08 14:05:00 NaN NaN NaN
2016-10-08 14:06:00 NaN NaN NaN
2016-10-08 14:07:00 in 7.92 0.0
2016-10-08 14:08:00 NaN NaN NaN
2016-10-08 14:09:00 NaN NaN NaN
2016-10-08 14:10:00 NaN NaN NaN
2016-10-08 14:11:00 NaN NaN NaN
2016-10-08 14:12:00 in 7.98 0.0
2016-10-08 14:13:00 NaN NaN NaN
2016-10-08 14:14:00 NaN NaN NaN
2016-10-08 14:15:00 NaN NaN NaN
2016-10-08 14:16:00 NaN NaN NaN
2016-10-08 14:17:00 out 8.18 0.0
print (df2.dtypes)
A object
B float64
C float64
dtype: object
</code></pre>
<p>But if use parameter <code>fill_value</code> in <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a>, <code>dtypes</code> are not changed:</p>
<pre><code>index = pd.date_range(df.index[0], df.index[-1], freq="min")
df2 = df.reindex(index, fill_value=0)
print (df2)
A B C
2016-10-08 13:57:00 in 5.61 1
2016-10-08 13:58:00 0 0.00 0
2016-10-08 13:59:00 0 0.00 0
2016-10-08 14:00:00 0 0.00 0
2016-10-08 14:01:00 0 0.00 0
2016-10-08 14:02:00 in 8.05 1
2016-10-08 14:03:00 0 0.00 0
2016-10-08 14:04:00 0 0.00 0
2016-10-08 14:05:00 0 0.00 0
2016-10-08 14:06:00 0 0.00 0
2016-10-08 14:07:00 in 7.92 0
2016-10-08 14:08:00 0 0.00 0
2016-10-08 14:09:00 0 0.00 0
2016-10-08 14:10:00 0 0.00 0
2016-10-08 14:11:00 0 0.00 0
2016-10-08 14:12:00 in 7.98 0
2016-10-08 14:13:00 0 0.00 0
2016-10-08 14:14:00 0 0.00 0
2016-10-08 14:15:00 0 0.00 0
2016-10-08 14:16:00 0 0.00 0
2016-10-08 14:17:00 out 8.18 0
print (df2.dtypes)
A object
B float64
C int64
dtype: object
</code></pre>
<p>Better is use <code>method='ffill</code> in <code>reindex</code>:</p>
<pre><code>index = pd.date_range(df.index[0], df.index[-1], freq="min")
df2 = df.reindex(index, method='ffill')
print (df2)
A B C
2016-10-08 13:57:00 in 5.61 1
2016-10-08 13:58:00 in 5.61 1
2016-10-08 13:59:00 in 5.61 1
2016-10-08 14:00:00 in 5.61 1
2016-10-08 14:01:00 in 5.61 1
2016-10-08 14:02:00 in 8.05 1
2016-10-08 14:03:00 in 8.05 1
2016-10-08 14:04:00 in 8.05 1
2016-10-08 14:05:00 in 8.05 1
2016-10-08 14:06:00 in 8.05 1
2016-10-08 14:07:00 in 7.92 0
2016-10-08 14:08:00 in 7.92 0
2016-10-08 14:09:00 in 7.92 0
2016-10-08 14:10:00 in 7.92 0
2016-10-08 14:11:00 in 7.92 0
2016-10-08 14:12:00 in 7.98 0
2016-10-08 14:13:00 in 7.98 0
2016-10-08 14:14:00 in 7.98 0
2016-10-08 14:15:00 in 7.98 0
2016-10-08 14:16:00 in 7.98 0
2016-10-08 14:17:00 out 8.18 0
print (df2.dtypes)
A object
B float64
C int64
dtype: object
</code></pre>
<hr>
<p>If use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.resample.html" rel="nofollow"><code>resample</code></a>, you can get column <code>A</code> back by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.unstack.html" rel="nofollow"><code>unstack</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a>, but unfortuntely there is still problem with <code>float</code>:</p>
<pre><code>df3 = df.set_index('A', append=True)
.unstack()
.resample('Min', fill_method='ffill')
.stack()
.reset_index(level=1)
print (df3)
A B C
DATE_TIME
2016-10-08 13:57:00 in 5.61 1.0
2016-10-08 13:58:00 in 5.61 1.0
2016-10-08 13:59:00 in 5.61 1.0
2016-10-08 14:00:00 in 5.61 1.0
2016-10-08 14:01:00 in 5.61 1.0
2016-10-08 14:02:00 in 8.05 1.0
2016-10-08 14:03:00 in 8.05 1.0
2016-10-08 14:04:00 in 8.05 1.0
2016-10-08 14:05:00 in 8.05 1.0
2016-10-08 14:06:00 in 8.05 1.0
2016-10-08 14:07:00 in 7.92 0.0
2016-10-08 14:08:00 in 7.92 0.0
2016-10-08 14:09:00 in 7.92 0.0
2016-10-08 14:10:00 in 7.92 0.0
2016-10-08 14:11:00 in 7.92 0.0
2016-10-08 14:12:00 in 7.98 0.0
2016-10-08 14:13:00 in 7.98 0.0
2016-10-08 14:14:00 in 7.98 0.0
2016-10-08 14:15:00 in 7.98 0.0
2016-10-08 14:16:00 in 7.98 0.0
2016-10-08 14:17:00 out 8.18 0.0
print (df3.dtypes)
A object
B float64
C float64
dtype: object
</code></pre>
<p>I try modify previous <a href="http://stackoverflow.com/a/39176650/2901002">answer</a> for casting to `int:</p>
<pre><code>int_cols = df.select_dtypes(['int64']).columns
print (int_cols)
Index(['C'], dtype='object')
index = pd.date_range(df.index[0], df.index[-1], freq="s")
df2 = df.reindex(index)
for col in df2:
if col == int_cols:
df2[col].ffill(inplace=True)
df2[col] = df2[col].astype(int)
elif df2[col].dtype == float:
df2[col].interpolate(inplace=True)
else:
df2[col].ffill(inplace=True)
#print (df2)
print (df2.dtypes)
A object
B float64
C int32
dtype: object
</code></pre>
| 3 | 2016-08-30T05:05:27Z | [
"python",
"pandas",
"types",
"resampling",
"reindex"
] |
What is the time complexity of dict.keys() in Python? | 39,219,065 | <p>I came across a question when I solve <a href="https://leetcode.com/problems/insert-delete-getrandom-o1/">this LeetCode problem</a>. Although my solution got accepted by the system, I still do not have any idea after searching online for the following question:
<code>What is the time complexity of dict.keys() operation?</code> Does it return a view of the keys or a real list (stores in memory) of the keys?</p>
| 9 | 2016-08-30T05:01:33Z | 39,219,129 | <p>In Python 2, it's O(n), and it builds a new list. In Python 3, it's O(1), but it doesn't return a list. To draw a random element from a dict's <code>keys</code>, you'd need to convert it to a list.</p>
<p>It sounds like you were probably using <code>random.choice(d.keys())</code> for part 3 of that problem. If so, that was O(n), and you got it wrong. You need to either implement your own hash table or maintain a separate list of elements, without sacrificing average-case O(1) insertions and deletions.</p>
| 3 | 2016-08-30T05:08:22Z | [
"python"
] |
how to take exact matched phrases using regular expression when multiple braces are present | 39,219,302 | <p>I have texts like</p>
<pre><code>1) <img="" id="">data</img>
2) (hi "hello") data (some text)
</code></pre>
<p>I want to remove only the text with braces and angular brackets and extract in between data. I tried</p>
<pre><code>re.compile(r"\(.*\)")
re.compile(r"<.*>")
</code></pre>
<p>but since closing braces are at the end of text, whole text is getting deleted when re.sub is used.
How to take the only data in between multiple braces (angular or flower brackets)</p>
| 1 | 2016-08-30T05:24:49Z | 39,219,346 | <p>Try non-greedy regular expressions, i.e.</p>
<pre><code>re.compile(r"\(.*?\)")
re.compile(r"<.*?>")
</code></pre>
| 2 | 2016-08-30T05:28:47Z | [
"python",
"regex",
"text-processing"
] |
how to take exact matched phrases using regular expression when multiple braces are present | 39,219,302 | <p>I have texts like</p>
<pre><code>1) <img="" id="">data</img>
2) (hi "hello") data (some text)
</code></pre>
<p>I want to remove only the text with braces and angular brackets and extract in between data. I tried</p>
<pre><code>re.compile(r"\(.*\)")
re.compile(r"<.*>")
</code></pre>
<p>but since closing braces are at the end of text, whole text is getting deleted when re.sub is used.
How to take the only data in between multiple braces (angular or flower brackets)</p>
| 1 | 2016-08-30T05:24:49Z | 39,219,353 | <pre><code>In [68]: re.sub(r'<(.+?)>', '', '<img="" id="">data</img>')
Out[68]: 'data'
</code></pre>
<p>Regex explanation:</p>
<pre><code><(.+?)>
</code></pre>
<p><img src="https://www.debuggex.com/i/dRCzoEj0k9pnANPt.png" alt="Regular expression visualization"></p>
<p><a href="https://www.debuggex.com/r/dRCzoEj0k9pnANPt" rel="nofollow">Debuggex Demo</a></p>
<pre><code>In [68]: re.sub(r'\((.+?)\)', '', '(hi "hello") data (some text)')
Out[68]: ' data '
</code></pre>
<p>Regex explanation: </p>
<pre><code>\((.+?)\)
</code></pre>
<p><img src="https://www.debuggex.com/i/9YhgsadiKl-9cXc-.png" alt="Regular expression visualization"></p>
<p><a href="https://www.debuggex.com/r/9YhgsadiKl-9cXc-" rel="nofollow">Debuggex Demo</a></p>
<p>Read the section 'Watch Out for The Greediness!' at <a href="http://www.regular-expressions.info/repeat.html" rel="nofollow">http://www.regular-expressions.info/repeat.html</a></p>
| 1 | 2016-08-30T05:29:16Z | [
"python",
"regex",
"text-processing"
] |
In TensorFlow, how can I get nonzero values and their indices from a tensor with python? | 39,219,414 | <p>I want to do something like this.<br>
Let's say we have a tensor A. </p>
<pre><code>A = [[1,0],[0,4]]
</code></pre>
<p>And I want to get nonzero values and their indices from it. </p>
<pre><code>Nonzero values: [1,4]
Nonzero indices: [[0,0],[1,1]]
</code></pre>
<p>There are similar operations in Numpy.<br>
<code>np.flatnonzero(A)</code> return indices that are non-zero in the flattened A.<br>
<code>x.ravel()[np.flatnonzero(x)]</code> extract elements according to non-zero indices.<br>
Here's <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.flatnonzero.html" rel="nofollow">a link</a> for these operations.</p>
<p>How can I do somthing like above Numpy operations in Tensorflow with python?<br>
(Whether a matrix is flattened or not doesn't really matter.)</p>
| 0 | 2016-08-30T05:34:07Z | 39,223,400 | <p>You can achieve same result in Tensorflow using <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/control_flow_ops.html#not_equal" rel="nofollow">not_equal</a> and <a href="https://www.tensorflow.org/versions/r0.10/api_docs/python/control_flow_ops.html#where" rel="nofollow">where</a> methods. </p>
<pre><code>zero = tf.constant(0, dtype=tf.float32)
where = tf.not_equal(A, zero)
</code></pre>
<p><code>where</code> is a tensor of the same shape as <code>A</code> holding <code>True</code> or <code>False</code>, in the following case </p>
<pre><code>[[True, False],
[False, True]]
</code></pre>
<p>This would be sufficient to select zero or non-zero elements from <code>A</code>. If you want to obtain indices you can use <code>where</code>method as follows:</p>
<pre><code>indices = tf.where(where)
</code></pre>
<p><code>where</code> tensor has two <code>True</code> values so <code>indices</code> tensor will have two entries. <code>where</code> tensor has rank of two, so entries will have two indices:</p>
<pre><code>[[0, 0],
[1, 1]]
</code></pre>
| 2 | 2016-08-30T09:15:53Z | [
"python",
"tensorflow",
"indices"
] |
Failing to export to CSV in Python, multiple formats | 39,219,424 | <p>I am trying to export to CSV files from a Jupyter notebook. Even when I test examples copy-pasted from the documentation (see below), I get a "'str' object is not callable" error message. I have fiddled endlessly with the parameters. The same thing happens with a Pandas dataframe and I try to use to_csv.</p>
<p>Basically:</p>
<pre><code>import csv
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile)
</code></pre>
<p>yields</p>
<pre><code> TypeError Traceback (most recent call last)
<ipython-input-169-cc34b7e892ee> in <module>()
1 import csv
2 with open('eggs.csv', 'w', newline='') as csvfile:
----> 3 spamwriter = csv.writer(csvfile)
TypeError: 'str' object is not callable
</code></pre>
<p>I'm new to coding, so I don't really know how to troubleshoot past this point...can anyone help?</p>
| 0 | 2016-08-30T05:34:51Z | 39,219,596 | <p>The error you are seeing can only be explained if <code>csv.writer</code> is a string. This recreates your error:</p>
<pre><code>In [1]: import csv
In [2]: csv.writer = 'test' # <- cause error
In [3]: %paste
import csv
with open('eggs.csv', 'w', newline='') as csvfile:
spamwriter = csv.writer(csvfile)
## -- End pasted text --
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-cc34b7e892ee> in <module>()
1 import csv
2 with open('eggs.csv', 'w', newline='') as csvfile:
----> 3 spamwriter = csv.writer(csvfile)
TypeError: 'str' object is not callable
</code></pre>
<p>I'm guessing you are either working in an environment like Spyder which by default keeps a single session alive for code to run in, or you are experimenting in a REPL like IPython or a Jupyter notebook. At some point you mistakenly assigned a new value to <code>csv.writer</code>. The problem will go away if you reset your environment, since there is nothing wrong with your code.</p>
<p>To reset, for IPython or Spyder just exit and start again. For Jupyter notebook select "Kernel|Restart" from the menu.</p>
| 0 | 2016-08-30T05:47:30Z | [
"python",
"python-3.x",
"csv",
"pandas",
"jupyter"
] |
Can't use the import os command in python | 39,219,509 | <p>I'm using the python compiler in java and I tried <code>import os</code> .</p>
<p>My problem is when I couldn't input it to continue the next line while it just sent back this message <code>os is not yet implemented in skulpt on line 1</code> .</p>
<p>I already tried with another app and still get a same result. I tried to search Google but no result. I read in learning web and it's never seem the existence of this error. </p>
<p>What is skulpt? Please help me</p>
| -3 | 2016-08-30T05:41:22Z | 39,219,820 | <p>To find which standard modules the most recent version of <code>skulpt</code> supports and which it doesn't, get a copy of the source code:</p>
<pre><code>git clone https://github.com/skulpt/skulpt.git
</code></pre>
<p>And, look through the <code>src/lib</code> directory. Every successfully implemented module will be <a href="https://github.com/skulpt/skulpt/issues/60" rel="nofollow">a directory in <code>/src/lib</code></a>. <code>os</code> is not one of those directories. <strong>Module <code>os</code> is not implemented in <code>skulpt</code>.</strong></p>
| 0 | 2016-08-30T06:02:19Z | [
"python",
"python-2.7",
"python-3.x",
"ipython"
] |
how to access character pointer value using ctypes? | 39,219,526 | <p>I have a written a DLL in which I'm getting one of the paths:</p>
<pre><code>//demo.h
__declspec(dllexport) void pathinfo(char * path);
</code></pre>
<p>Something is being done in the code to get this path.
And now, the python script that I have written to retrieve this path from the DLL is as shown:</p>
<pre><code>//demo.py
import sys
import ctypes
from ctypes import *
class demo(object):
def __init__(self):
self.demoDLL=CDLL("demo.dll")
def pathinfo(self):
path=c_char()
self.demoDLL.pathinfo.argtypes(POINTER(c_char))
self.demoDLL.pathinfo.result=None
self.demoDLL.pathinfo(byref(path))
return path.value
if __name__=='__main__':
abc=demo()
path_info=abc.pathinfo()
print "information of the path:",path_info
</code></pre>
<p>But the value that I'm able to see is just the first character of the path instead of the whole string.</p>
<p>Can anybody help me with this problem?</p>
| 0 | 2016-08-30T05:43:05Z | 39,219,960 | <p>Haven't done it, but have done the following:</p>
<p>To pass an array of <code>ints</code>, for example, use this:</p>
<p>Create a type of, say, 20 ints:</p>
<pre><code>Ints20 = c_int * 20
</code></pre>
<p>Create an instance:</p>
<pre><code>data = Ints20()
</code></pre>
<p>And then you can pass <code>data</code>.
Extract the numbers from <code>data</code> by using the <code>list</code> function:</p>
<pre><code>values = list(data)
</code></pre>
<p>So may be you can do the same with chars:</p>
<pre><code>Chars20 = c_char * 20
path = Chars20()
</code></pre>
<p>and then:</p>
<pre><code>self.demoDLL.pathinfo(path)
</code></pre>
<p>In the case of c_char array there is no need to use the <code>list</code> function, but this works:</p>
<pre><code>return path.value
</code></pre>
| 0 | 2016-08-30T06:11:02Z | [
"python",
"dll",
"ctypes"
] |
how to access character pointer value using ctypes? | 39,219,526 | <p>I have a written a DLL in which I'm getting one of the paths:</p>
<pre><code>//demo.h
__declspec(dllexport) void pathinfo(char * path);
</code></pre>
<p>Something is being done in the code to get this path.
And now, the python script that I have written to retrieve this path from the DLL is as shown:</p>
<pre><code>//demo.py
import sys
import ctypes
from ctypes import *
class demo(object):
def __init__(self):
self.demoDLL=CDLL("demo.dll")
def pathinfo(self):
path=c_char()
self.demoDLL.pathinfo.argtypes(POINTER(c_char))
self.demoDLL.pathinfo.result=None
self.demoDLL.pathinfo(byref(path))
return path.value
if __name__=='__main__':
abc=demo()
path_info=abc.pathinfo()
print "information of the path:",path_info
</code></pre>
<p>But the value that I'm able to see is just the first character of the path instead of the whole string.</p>
<p>Can anybody help me with this problem?</p>
| 0 | 2016-08-30T05:43:05Z | 39,220,458 | <p>The reason you see only the first character is that by calling <code>c_char()</code> you create a single <code>char</code> value that Python treats like a <code>str</code> (Python 2) object or <code>bytes</code> (Python 3) object of length 1. You are probably lucky that you do not get a segmentation fault. By writing more than 1 byte or a NULL-terminated string of length > 0 (e.g. with <code>strcpy</code>) in the C code, you actually produce an undetected buffer overflow. <code>ctypes</code> does not know how many bytes you have written at the pointer's memory location. <code>path.value</code> is still a <code>str</code> / <code>bytes</code> of length 1.</p>
<p>It would be better to change the C <code>pathinfo</code> function into someting like</p>
<pre><code>size_t pathinfo(char* path, size_t bsize);
</code></pre>
<p>Use <code>ctypes.create_string_buffer()</code> to allocate memory in your Python code and let <code>pathinfo</code> return the length of the result. Of course you have to check, whether <code>char* path</code> is large enough using <code>bsize</code> in your C-Code.</p>
<p>The Python-code would look like this:</p>
<pre><code>buf = ctypes.create_string_buffer(256)
result_len = pathinfo(buf, len(buf))
if result_len == len(buf):
# buffer may have been too short,
# try again with larger buffer
...
restlt_str = buf[0:result_len].decode('utf-8') # or another encoding
</code></pre>
<p>Also be aware of NULL-termination in the C domain, character encodings when converting python strings to <code>char*</code> and back, the changes regarding <code>str</code> / <code>bytes</code> in <code>ctypes</code> regarding Python 2 and Python 3.</p>
| 1 | 2016-08-30T06:41:17Z | [
"python",
"dll",
"ctypes"
] |
Regex Matching - A letter not preceded by another letter | 39,219,532 | <p>What could be regex which match <code>anystring</code> followed by <code>daily</code> but it must not match <code>daily</code> preceded by <code>m</code>?</p>
<p>For example it should match following string </p>
<ul>
<li><code>beta.daily</code></li>
<li><code>abcdaily</code></li>
<li><code>dailyabc</code></li>
<li><code>daily</code></li>
</ul>
<p>But it must not match</p>
<ul>
<li><code>mdaily</code> or</li>
<li><code>abcmdaily</code> or</li>
<li><code>mdailyabc</code></li>
</ul>
<p>I have tried following and other regex but failed each time:</p>
<ul>
<li><code>r'[^m]daily'</code>: But it doesn't match with <code>daily</code></li>
<li><code>r'[^m]?daily'</code> : It match with string containing <code>mdaily</code> which is not intended</li>
</ul>
| 1 | 2016-08-30T05:43:26Z | 39,219,598 | <p>Just add a negative lookbehind, <code>(?<!m)d</code>, before <code>daily</code>:</p>
<pre><code>(?<!m)daily
</code></pre>
<p>The zero width negative lookbehind, <code>(?<!m)</code>, makes sure <code>daily</code> is not preceded by <code>m</code>.</p>
<p><a href="https://regex101.com/r/wJ8mV5/1">Demo</a></p>
| 6 | 2016-08-30T05:47:34Z | [
"python",
"regex"
] |
Regex Matching - A letter not preceded by another letter | 39,219,532 | <p>What could be regex which match <code>anystring</code> followed by <code>daily</code> but it must not match <code>daily</code> preceded by <code>m</code>?</p>
<p>For example it should match following string </p>
<ul>
<li><code>beta.daily</code></li>
<li><code>abcdaily</code></li>
<li><code>dailyabc</code></li>
<li><code>daily</code></li>
</ul>
<p>But it must not match</p>
<ul>
<li><code>mdaily</code> or</li>
<li><code>abcmdaily</code> or</li>
<li><code>mdailyabc</code></li>
</ul>
<p>I have tried following and other regex but failed each time:</p>
<ul>
<li><code>r'[^m]daily'</code>: But it doesn't match with <code>daily</code></li>
<li><code>r'[^m]?daily'</code> : It match with string containing <code>mdaily</code> which is not intended</li>
</ul>
| 1 | 2016-08-30T05:43:26Z | 39,219,634 | <pre><code>re.match(r"[^m]*daily.*",yourstring)
</code></pre>
<p>Try this regex.</p>
| -1 | 2016-08-30T05:49:28Z | [
"python",
"regex"
] |
how to download images using google earth engine's python API | 39,219,705 | <p>I am using Google's Earth Engine API to access LandSat images.
The program is as given below,</p>
<pre><code>import ee
ee.Initialize()
</code></pre>
<p><strong>Load a landsat image and select three bands.</strong></p>
<pre><code>landsat = ee.Image('LANDSAT/LC8_L1T_TOA
/LC81230322014135LGN00').select(['B4', 'B3', 'B2']);
</code></pre>
<p><strong>Create a geometry representing an export region.</strong></p>
<pre><code>geometry = ee.Geometry.Rectangle([116.2621, 39.8412, 116.4849, 40.01236]);
</code></pre>
<p><strong>Export the image, specifying scale and region.</strong></p>
<pre><code> export.image.toDrive({
image: landsat,
description: 'imageToDriveExample',
scale: 30,
region: geometry
});
</code></pre>
<p>it throws the following error. </p>
<pre><code>Traceback (most recent call last):
File "e6.py", line 11, in <module>
export.image.toDrive({
NameError: name 'export' is not defined
</code></pre>
<p>Please Help. I am unable to find the right function to download images. </p>
| 0 | 2016-08-30T05:54:05Z | 39,220,017 | <p>There is a typo in your code, <code>Export</code> should start from the capital letter. See <a href="https://developers.google.com/earth-engine/exporting" rel="nofollow">documentation</a>.</p>
| 0 | 2016-08-30T06:14:08Z | [
"python",
"google-earth-engine"
] |
Python namespace change of `import package.sub_module; from package import *` | 39,219,722 | <p>The <a href="https://docs.python.org/3/tutorial/modules.html#importing-from-a-package" rel="nofollow">Python documentation</a> says</p>
<blockquote>
<p>Consider this code:</p>
</blockquote>
<pre><code>import sound.effects.echo
import sound.effects.surround
from sound.effects import *
</code></pre>
<blockquote>
<p>In this example, the echo and surround modules are imported in the
current namespace because they are defined in the sound.effects
package when the from...import statement is executed. <strong>(This also works
when __all__ is defined.)</strong></p>
</blockquote>
<p>I try the following code</p>
<pre><code># package/
# __init__.py
# sub_module.py
import package.sub_module
from package import *
print(sub_module)
</code></pre>
<p>When <code>package/__init__.py</code> is empty, the code works fine. However, when <code>package/__init__.py</code> contains <code>__all__ = []</code>, <code>print(sub_module)</code> will raise <code>NameError</code>.
What is <em>(This also works when <strong>all</strong> is defined.)</em> from the documentation means?</p>
<hr>
<p>The codes:</p>
<pre><code>package/
__init__.py
sub_module.py # empty file
main.py
</code></pre>
<p>In main.py:</p>
<pre><code>import package.sub_module
from package import *
print(sub_module)
</code></pre>
<p>When <code>package/__init__.py</code> is empty, executing <code>python3 main.py</code> gets
<code><module 'package.sub_module' from '/path/to/package/sub_module.py'</code></p>
<p>When <code>package/__init__.py</code> contains <code>__all__ = []</code>, executing <code>python3 main.py</code> gets</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 3, in <module>
print(sub_module)
NameError: name 'sub_module' is not defined
</code></pre>
| 1 | 2016-08-30T05:55:43Z | 39,220,664 | <p>If a module <code>package</code> defines <code>__all__</code>, it is the list of module names that are imported by <code>from package import *</code></p>
<p>So if you define <code>__all__</code> as empty list, <code>from package import *</code> will import nothing.</p>
<p>Try defining it like this:</p>
<pre><code>__all__ = ['sub_module']
</code></pre>
<p>Also note that you don't have to do <code>from package import *</code> to use <code>sub_module</code></p>
<p>You can also just do:</p>
<pre><code>import package.sub_module
print(package.sub_module)
</code></pre>
| 2 | 2016-08-30T06:53:25Z | [
"python"
] |
Python namespace change of `import package.sub_module; from package import *` | 39,219,722 | <p>The <a href="https://docs.python.org/3/tutorial/modules.html#importing-from-a-package" rel="nofollow">Python documentation</a> says</p>
<blockquote>
<p>Consider this code:</p>
</blockquote>
<pre><code>import sound.effects.echo
import sound.effects.surround
from sound.effects import *
</code></pre>
<blockquote>
<p>In this example, the echo and surround modules are imported in the
current namespace because they are defined in the sound.effects
package when the from...import statement is executed. <strong>(This also works
when __all__ is defined.)</strong></p>
</blockquote>
<p>I try the following code</p>
<pre><code># package/
# __init__.py
# sub_module.py
import package.sub_module
from package import *
print(sub_module)
</code></pre>
<p>When <code>package/__init__.py</code> is empty, the code works fine. However, when <code>package/__init__.py</code> contains <code>__all__ = []</code>, <code>print(sub_module)</code> will raise <code>NameError</code>.
What is <em>(This also works when <strong>all</strong> is defined.)</em> from the documentation means?</p>
<hr>
<p>The codes:</p>
<pre><code>package/
__init__.py
sub_module.py # empty file
main.py
</code></pre>
<p>In main.py:</p>
<pre><code>import package.sub_module
from package import *
print(sub_module)
</code></pre>
<p>When <code>package/__init__.py</code> is empty, executing <code>python3 main.py</code> gets
<code><module 'package.sub_module' from '/path/to/package/sub_module.py'</code></p>
<p>When <code>package/__init__.py</code> contains <code>__all__ = []</code>, executing <code>python3 main.py</code> gets</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 3, in <module>
print(sub_module)
NameError: name 'sub_module' is not defined
</code></pre>
| 1 | 2016-08-30T05:55:43Z | 39,220,672 | <p>If you define <code>__all__</code>, then <em>only</em> the attributes mentioned there will be imported via <code>*</code>, while the excluded ones have to be imported <em>explicitly</em>. So either use</p>
<pre><code>from package import submodule
</code></pre>
<p>or if you <em>really</em> want to use the (discouraged!) <code>from package import *</code>, declare</p>
<pre><code>__all__ = ['submodule']
</code></pre>
<p>in <code>package</code>. Note how tedious it will become to keep this up-to-date...</p>
| 0 | 2016-08-30T06:53:48Z | [
"python"
] |
Python namespace change of `import package.sub_module; from package import *` | 39,219,722 | <p>The <a href="https://docs.python.org/3/tutorial/modules.html#importing-from-a-package" rel="nofollow">Python documentation</a> says</p>
<blockquote>
<p>Consider this code:</p>
</blockquote>
<pre><code>import sound.effects.echo
import sound.effects.surround
from sound.effects import *
</code></pre>
<blockquote>
<p>In this example, the echo and surround modules are imported in the
current namespace because they are defined in the sound.effects
package when the from...import statement is executed. <strong>(This also works
when __all__ is defined.)</strong></p>
</blockquote>
<p>I try the following code</p>
<pre><code># package/
# __init__.py
# sub_module.py
import package.sub_module
from package import *
print(sub_module)
</code></pre>
<p>When <code>package/__init__.py</code> is empty, the code works fine. However, when <code>package/__init__.py</code> contains <code>__all__ = []</code>, <code>print(sub_module)</code> will raise <code>NameError</code>.
What is <em>(This also works when <strong>all</strong> is defined.)</em> from the documentation means?</p>
<hr>
<p>The codes:</p>
<pre><code>package/
__init__.py
sub_module.py # empty file
main.py
</code></pre>
<p>In main.py:</p>
<pre><code>import package.sub_module
from package import *
print(sub_module)
</code></pre>
<p>When <code>package/__init__.py</code> is empty, executing <code>python3 main.py</code> gets
<code><module 'package.sub_module' from '/path/to/package/sub_module.py'</code></p>
<p>When <code>package/__init__.py</code> contains <code>__all__ = []</code>, executing <code>python3 main.py</code> gets</p>
<pre><code>Traceback (most recent call last):
File "main.py", line 3, in <module>
print(sub_module)
NameError: name 'sub_module' is not defined
</code></pre>
| 1 | 2016-08-30T05:55:43Z | 39,221,462 | <p><strong>Solution</strong>: you have <code>__all__</code> set to empty list i.e. <code>from package import *</code> basically imports nothing</p>
<p>set it to <code>__all__ = ['submodule']</code> in <code>__init__.py</code></p>
<hr>
<blockquote>
<p>What exactly is <strong>__all__</strong> ?</p>
</blockquote>
<p>In simplest words <strong>all</strong> help customizing the <code>from package import *</code> i.e. with <strong>all</strong> we can set what will be imported and what not.</p>
<p><strong>From the <a href="https://docs.python.org/3/reference/simple_stmts.html#the-import-statement" rel="nofollow">docs</a></strong>:</p>
<blockquote>
<p>The public names defined by a module are determined by checking the
moduleâs namespace for a variable named <strong>all</strong>; if defined, it must
be a sequence of strings which are names defined or imported by that
module. The names given in <strong>all</strong> are all considered public and are
required to exist. If <strong>all</strong> is not defined, the set of public names
includes all names found in the moduleâs namespace which do not begin
with an underscore character ('_'). <strong>all</strong> should contain the entire
public API. It is intended to avoid accidentally exporting items that
are not part of the API (such as library modules which were imported
and used within the module).</p>
</blockquote>
<hr>
<p>One important thing to note here is - <strong>Imports without <code>*</code> are not affected by <code>__all__</code></strong> i.e. Members that are not mentioned in <code>__all__</code> are accessible from outside the module using direct import - <code>from <module> import <member></code>.</p>
<p><strong>An Example</strong>: the following code in a <code>module.py</code> explicitly exports the symbols <code>foo</code> and <code>bar</code>:</p>
<pre><code>__all__ = ['foo', 'bar']
waz = 5
foo = 10
def bar(): return 'bar'
</code></pre>
<p>These symbols can then be imported like so:</p>
<pre><code>from foo import *
print foo
print bar
# now import `waz` will trigger an exception,
# as it is not in the `__all__`, hence not a public member.
print waz
</code></pre>
| 0 | 2016-08-30T07:34:53Z | [
"python"
] |
Reverse for 'registration_register' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] | 39,219,732 | <p>I am trying to make a link in the sidebar of my Person model as persons. For that I made a templatetags folder where my member_template_tags.py:</p>
<pre><code>from django import template
from member.models import Person
register = template.Library()
@register.inclusion_tag('member/person_list.html')
def get_person_list():
persons= Person.objects.all(),
return {'persons': persons}
</code></pre>
<p>and my view file: </p>
<pre><code>class PersonListView(generic.ListView):
model = Person
context_object_name = 'persons'
</code></pre>
<p>my person_list.html:</p>
<pre><code>{% extends 'member/base.html' %}
{% block content %}
<h2>Members</h2>
<table>
<tr>
<th>sl.</th>
<th>Name and Position</th>
<th>Photo</th>
<th>Organisation & Address</th>
<th>Contact</th>
</tr>
{% for person in object_list %}
<tr>
<td>{{forloop.counter}}.</td>
<td>{{person.name}}<br>
{{person.present_position}}
</td>
<td><a href="{% url 'member:person-list' %}">
<img src="{{ person.photo_url|default_if_none:'#'}}" class="img-responsive">
</a></td>
<td>
{{person.organization}}<br>
{{person.address}}
</td>
<td>
{{person.tele_land}}<br>
{{person.tele_cell}}<br>
{{person.email}}
</td>
</tr>
</table>
{% endblock %}
</code></pre>
<p>and in base.html, sidebar code is:</p>
<pre><code><div class="col-sm-3 col-md-2 sidebar">
{% block sidebar_block %}
{% get_person_list %}
{% endblock %}
</div>
</code></pre>
<p>When I tried it gives following traceback:
Template error:</p>
<pre><code>In template /home/ohid/test_venv/alumni/member/templates/member/person_list.html, error at line 0
Reverse for 'registration_register' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
1 : {% extends 'member/base.html' %}
2 :
3 :
4 :
5 : <h2>Members</h2>
6 : <table>
7 :
8 : <tr>
9 : <th>sl.</th>
10 : <th>Name and Position</th>
Traceback:
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/defaulttags.py" in render
507. current_app=current_app)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
508. (lookup_view_s, args, kwargs, len(patterns), patterns))
During handling of the above exception (Reverse for 'alumni.registration_register' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []), another exception occurred:
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
174. response = self.process_exception_by_middleware(e, request)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
172. response = response.render()
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/response.py" in render
160. self.content = self.rendered_content
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/response.py" in rendered_content
137. content = template.render(context, self._request)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/backends/django.py" in render
95. return self.template.render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in render
206. return self._render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in _render
197. return self.nodelist.render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in render
992. bit = node.render_annotated(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in render_annotated
959. return self.render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/loader_tags.py" in render
173. return compiled_parent._render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in _render
197. return self.nodelist.render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in render
992. bit = node.render_annotated(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in render_annotated
959. return self.render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/defaulttags.py" in render
326. return nodelist.render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in render
992. bit = node.render_annotated(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in render_annotated
959. return self.render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/defaulttags.py" in render
513. six.reraise(*exc_info)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/utils/six.py" in reraise
686. raise value
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/defaulttags.py" in render
499. url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/urlresolvers.py" in reverse
600. return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/urlresolvers.py" in _reverse_with_prefix
508. (lookup_view_s, args, kwargs, len(patterns), patterns))
</code></pre>
<p>Exception Type: NoReverseMatch at /person/</p>
<p><strong>Edit:</strong></p>
<p>When I use </p>
<pre><code><div class="col-sm-3 col-md-2 sidebar">
{% block sidebar_block %}
{% get_person_list persons %}
{% endblock %}
</div>
</code></pre>
<p>The same code gives 'get_person_list' received too many positional arguments errors. The new traceback:</p>
<pre><code>Template error:
In template /home/ohid/test_venv/alumni/member/templates/member/base.html, error at line 57
'get_person_list' received too many positional arguments 47 :
48 : </nav>
49 : </div>
50 :
51 : </nav>
52 :
53 : <div class="container-fluid">
54 : <div class="row">
55 : <div class="col-sm-3 col-md-2 sidebar">
56 : {% block sidebar_block %}
57 : {% get_person_list persons %}
58 : {% endblock %}
59 : </div>
60 : <div class="col-sm-9 offset-sm-3 col-md-10 offset-md-2 main">
61 : {% block body_block %}{% endblock %}
62 :
63 :
64 : </div>
65 : </div>
66 : </div>
67 :
Traceback:
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/library.py" in parse_bits
296. unhandled_params.pop(0)
During handling of the above exception (pop from empty list), another exception occurred:
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
174. response = self.process_exception_by_middleware(e, request)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
172. response = response.render()
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/response.py" in render
160. self.content = self.rendered_content
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/response.py" in rendered_content
137. content = template.render(context, self._request)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/backends/django.py" in render
95. return self.template.render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in render
206. return self._render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in _render
197. return self.nodelist.render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in render
992. bit = node.render_annotated(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in render_annotated
959. return self.render(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/loader_tags.py" in render
151. compiled_parent = self.get_parent(context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/loader_tags.py" in get_parent
148. return self.find_template(parent, context)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/loader_tags.py" in find_template
128. template_name, skip=history,
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/engine.py" in find_template
157. name, template_dirs=dirs, skip=skip,
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/loaders/base.py" in get_template
46. contents, origin, origin.template_name, self.engine,
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in __init__
189. self.nodelist = self.compile_nodelist()
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in compile_nodelist
231. return parser.parse()
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in parse
516. raise self.error(token, e)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in parse
514. compiled_result = compile_func(self, token)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/loader_tags.py" in do_block
241. nodelist = parser.parse(('endblock',))
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in parse
516. raise self.error(token, e)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/base.py" in parse
514. compiled_result = compile_func(self, token)
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/library.py" in compile_func
163. takes_context, function_name,
File "/home/ohid/test_venv/lib/python3.5/site-packages/django/template/library.py" in parse_bits
301. name)
Exception Type: TemplateSyntaxError at /person/
Exception Value: 'get_person_list' received too many positional arguments
</code></pre>
<p>How do I fix this error and make link in the sidebar so that it gives the full view of person_list template?</p>
<p>Any help will be much appreciated.</p>
| 0 | 2016-08-30T05:56:22Z | 39,220,774 | <p>There are too many issues with your code to correctly identify what is the problem.</p>
<ol>
<li><p>You have an extra comma in your custom tag:</p>
<pre><code>@register.inclusion_tag('member/person_list.html')
def get_person_list():
persons= Person.objects.all(), # <-- remove this comma
return {'persons': persons}
</code></pre></li>
<li><p>Your context variable is called <code>persons</code>, yet you are using <code>object_list</code> in your template, this needs to be corrected.</p></li>
<li><p>Your template has a for loop, but its missing a <code>endfor</code></p></li>
<li><p>You have <code>{% url 'member:person-list' %}</code> this is a <a href="https://docs.djangoproject.com/en/1.10/topics/http/urls/#url-namespaces" rel="nofollow">namespaced URL</a>. Make you have <a href="https://docs.djangoproject.com/en/1.10/intro/tutorial03/#namespacing-url-names" rel="nofollow">set it up correctly</a> in your <code>urls.py</code>.</p></li>
<li><p>Your tag doesn't take any arguments, yet you are passing it a context variable in <code>{% get_person_list persons %}</code>.</p></li>
</ol>
<p>Once you solve all these, you have to figure out where the actual error is coming from. Chances are, it is in your base template which you are inheriting as its obvious you don't have a <code>registration_register</code> url tag in the code you have posted.</p>
| 0 | 2016-08-30T06:58:41Z | [
"python",
"django"
] |
Import error with remote interpreter in pycharm | 39,219,761 | <p>I am trying to run my code in the server using ssh remote interpreter. </p>
<p>The connection and the deployment work but when I want to import libraries located in the server it gives an import error </p>
<blockquote>
<p>ssh://nour@****.com:22/usr/bin/python -u</p>
<p>/home/nour/myProject/main.py Traceback
(most recent call last): File
"/home/nour/main.py", line 11,
in
from clplibs.clp import ContinuousLearningPlatform as clp ImportError: No module named clplibs.clp</p>
<p>Process finished with exit code 1</p>
</blockquote>
| 0 | 2016-08-30T05:58:25Z | 39,244,970 | <p>I've found a solution, the environment variables (including python path) should be defined from pycharm: Run/Debug configurations-> Environment variables. Pycharm won't use bashrc paths.</p>
| 0 | 2016-08-31T08:52:03Z | [
"python",
"ssh",
"pycharm",
"interpreter"
] |
Creating a shallow copy of an instance of a class inheriting from collections.OrderedDict | 39,219,821 | <p>I have a class inheriting from <code>collections.OrderedDict</code> with an initializer that takes a positional argument <em>without default</em>. My goal is to create a <em>shallow</em> copy of the instance. However, my initial naive approach below does not work and raises a type error as the positional argument must be supplied when building the new instance.</p>
<pre><code>class B(collections.OrderedDict):
def __init__(self, whatever):
super().__init__()
self.whatever = whatever
b = B(3)
b.update({'a':1})
print(b.copy())
</code></pre>
<p>A solution could be to add:</p>
<pre><code>def copy(self):
new = collections.OrderedDict(self)
new.whatever = self.whatever
return new
</code></pre>
<p>But this becomes unwieldy when the number of attribute grows. Is there a better, more direct solution to this problem?</p>
<p><strong>EDIT</strong>:
I am using Python 3.5</p>
| 0 | 2016-08-30T06:02:21Z | 39,219,882 | <p>you can use python <a href="https://docs.python.org/2/library/copy.html" rel="nofollow">copy</a> library:</p>
<pre><code>copied_object = copy.copy(b)
</code></pre>
| 0 | 2016-08-30T06:06:45Z | [
"python"
] |
Handling null inputs for countdown timer: invalid literal for int() with base 10: '' | 39,219,944 | <p>I've just started out Python and was trying to make a countdown timer and make it unbreakable as possible, however when I enter blank inputs, the while loop won't handle it, and this message would show up instead: invalid literal for int() with base 10: ''. It also pointed the error occurring at the line where it asks for count-down.</p>
<p>Any help will be appreciated.</p>
<pre><code>while countdown == 0 or countdown == "":
print("We need a person to countdown.")
countdown = int(input("How many seconds would you like the countdown to be?: "))
while countdown > 30:
try:
countdown = int(input("Enter non-extreme values please: "))
except ValueError:
print("Enter possible value.")
while countdown > 0: #Countdown sequence
time.sleep(2)
countdown -= 1
print(countdown)
print("BLASTTT OFFFFFFFFFFFFFF!!!")
print("We have a liftoff...")
</code></pre>
| 0 | 2016-08-30T06:10:02Z | 39,220,112 | <p>A bad string that can not be converted to an int, will raise a ValueError. You catch that exception and just repeat the prompt like this:</p>
<pre><code>countdown = 0
while countdown <= 0:
try:
countdown = int(input("How many seconds would you like the countdown to be?: "))
except ValueError:
pass
</code></pre>
<p>As soon as a proper integer > 0 has been entered the <code>while</code> will break.</p>
| 1 | 2016-08-30T06:19:43Z | [
"python",
"input",
"while-loop",
"countdown"
] |
Permanently changing an outside variable inside a function | 39,219,957 | <p>I am a huge beginner, but I have a variable that has a value, and I'd like to change it within a function, so that outside of the function the variable is permanently changed. Searching around I've found some information on how to access outside variables (I think their called global variables), but not permanently modifying them in any way. </p>
<p>Here's a little bit of code to <em>represent</em> what it is I'm trying to do:</p>
<pre><code>x = 0
def variableChanger():
global x
x =+ 1
variableChanger()
print(x)
variableChanger()
print(x)
variableChanger()
print(x)
</code></pre>
<p>The idea is that it would have the console output...</p>
<pre><code>>>> 1
>>> 2
>>> 3
</code></pre>
<p>since it is changing the global <code>x</code> variable by adding one to it. But instead it is creating a new global variable called <code>x</code>, and setting it's value to <code>1</code> every time I run the <code>variableChanger()</code> function, and I just end up with...</p>
<pre><code>>>> 1
>>> 1
>>> 1
</code></pre>
<p>What I want to do is access the variable <code>x</code> that's at the top of the code and increment that, so that whenever and wherever I access it later, it has the incremented value. </p>
<p>Is there a way to do that?</p>
| -1 | 2016-08-30T06:10:54Z | 39,220,008 | <p>This is because <em>you do</em> re-assign <code>x</code> every time. <code>x =+ 1 != x += 1</code>. <code>x =+ 1</code> assigns <code>x</code> to <code>1</code>; <code>x += 1</code>, the <em><a href="https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements" rel="nofollow">augmented assignment statement</a></em>, increments <code>x</code> by one:</p>
<pre><code>x = 0
def variableChanger():
global x
x += 1
variableChanger()
print(x)
variableChanger()
print(x)
variableChanger()
print(x)
</code></pre>
| 2 | 2016-08-30T06:13:39Z | [
"python",
"python-3.x",
"global-variables"
] |
Permanently changing an outside variable inside a function | 39,219,957 | <p>I am a huge beginner, but I have a variable that has a value, and I'd like to change it within a function, so that outside of the function the variable is permanently changed. Searching around I've found some information on how to access outside variables (I think their called global variables), but not permanently modifying them in any way. </p>
<p>Here's a little bit of code to <em>represent</em> what it is I'm trying to do:</p>
<pre><code>x = 0
def variableChanger():
global x
x =+ 1
variableChanger()
print(x)
variableChanger()
print(x)
variableChanger()
print(x)
</code></pre>
<p>The idea is that it would have the console output...</p>
<pre><code>>>> 1
>>> 2
>>> 3
</code></pre>
<p>since it is changing the global <code>x</code> variable by adding one to it. But instead it is creating a new global variable called <code>x</code>, and setting it's value to <code>1</code> every time I run the <code>variableChanger()</code> function, and I just end up with...</p>
<pre><code>>>> 1
>>> 1
>>> 1
</code></pre>
<p>What I want to do is access the variable <code>x</code> that's at the top of the code and increment that, so that whenever and wherever I access it later, it has the incremented value. </p>
<p>Is there a way to do that?</p>
| -1 | 2016-08-30T06:10:54Z | 39,220,372 | <p>The + sign in the assignment operator is on the wrong side. It should be on the left like this:</p>
<pre><code>def variableChanger():
global x
x += 1
</code></pre>
<p>What you're doing is simply assigning x to the value of +1 over and over; it will just keep getting assigned to 1.</p>
| 0 | 2016-08-30T06:36:21Z | [
"python",
"python-3.x",
"global-variables"
] |
Python: Getting Traceback error while executing the code | 39,220,086 | <p>When I run the code as <code>bzt test.yml</code> I am getting the error.
Before it was working fine.</p>
<pre><code>C:\etc\tmp\my-test>more test.yml
---
execution:
concurrency: 50
hold-for: 2m30s
ramp-up: 1m
scenario:
requests:
- url: http://server12:12012/
C:\etc\tmp\my-test>bzt test.yml
Traceback (most recent call last):
File "C:\Python27\Scripts\bzt-script.py", line 9, in <module>
load_entry_point('bzt==1.6.7', 'console_scripts', 'bzt')()
File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 564, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 2621, in load_entry_point
return ep.load()
File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 2281, in load
return self.resolve()
File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 2287, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "c:\python27\lib\site-packages\bzt\cli.py", line 32, in <module>
from bzt.engine import Engine, Configuration, ScenarioExecutor
File "c:\python27\lib\site-packages\bzt\engine.py", line 37, in <module>
from bzt.six import build_opener, install_opener, urlopen, request, numeric_types, iteritems
File "c:\python27\lib\site-packages\bzt\six\__init__.py", line 35, in <module>
import elementtree.ElementTree as etree
ImportError: No module named elementtree.ElementTree
</code></pre>
| 0 | 2016-08-30T06:18:03Z | 39,220,862 | <pre><code>ImportError: No module named elementtree.ElementTree
</code></pre>
<p>Are you sure it shouldn't be </p>
<pre><code>import xml.etree.ElementTree as etree
</code></pre>
<p>Otherwise check if you have this dependency installed or if you have a <strong>"elementtree" folder</strong> in your current project that screws with the import lookup.</p>
| 0 | 2016-08-30T07:02:46Z | [
"python",
"elementtree",
"bzt"
] |
Python: Getting Traceback error while executing the code | 39,220,086 | <p>When I run the code as <code>bzt test.yml</code> I am getting the error.
Before it was working fine.</p>
<pre><code>C:\etc\tmp\my-test>more test.yml
---
execution:
concurrency: 50
hold-for: 2m30s
ramp-up: 1m
scenario:
requests:
- url: http://server12:12012/
C:\etc\tmp\my-test>bzt test.yml
Traceback (most recent call last):
File "C:\Python27\Scripts\bzt-script.py", line 9, in <module>
load_entry_point('bzt==1.6.7', 'console_scripts', 'bzt')()
File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 564, in load_entry_point
return get_distribution(dist).load_entry_point(group, name)
File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 2621, in load_entry_point
return ep.load()
File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 2281, in load
return self.resolve()
File "c:\python27\lib\site-packages\pkg_resources\__init__.py", line 2287, in resolve
module = __import__(self.module_name, fromlist=['__name__'], level=0)
File "c:\python27\lib\site-packages\bzt\cli.py", line 32, in <module>
from bzt.engine import Engine, Configuration, ScenarioExecutor
File "c:\python27\lib\site-packages\bzt\engine.py", line 37, in <module>
from bzt.six import build_opener, install_opener, urlopen, request, numeric_types, iteritems
File "c:\python27\lib\site-packages\bzt\six\__init__.py", line 35, in <module>
import elementtree.ElementTree as etree
ImportError: No module named elementtree.ElementTree
</code></pre>
| 0 | 2016-08-30T06:18:03Z | 39,233,309 | <p>Sounds like missing or corrupt <a href="http://lxml.de/" rel="nofollow">lxml</a> package to me. </p>
<p>Workarounds are in:</p>
<ol>
<li>Try out <a href="http://gettaurus.org/msi/" rel="nofollow">Taurus Installer</a></li>
<li>Reinstall <code>lxml</code> and/or <code>bzt</code> packages via pip. </li>
</ol>
<p>Check out:</p>
<ul>
<li><a href="http://gettaurus.org/install/Installation/#Windows" rel="nofollow">Taurus -> Installing and Upgrading -> Windows</a></li>
<li><p><a href="https://www.blazemeter.com/blog/taurus-new-star-test-automation-tools-constellation" rel="nofollow">Taurus: A New Star in the Test Automation Tools Constellation</a> </p>
<p>for detailed setup instructions. </p></li>
</ul>
<p>If the problem persists update your question with the <em>bzt.log</em> file contents. </p>
| 0 | 2016-08-30T17:07:18Z | [
"python",
"elementtree",
"bzt"
] |
Error Import Impyla library on Windows | 39,220,102 | <p>I'm having trouble with using impyla library on windows</p>
<p>I installed impyla library </p>
<p><code>pip install impyla</code></p>
<p>Error occured when I tried to import impyla libary in python code</p>
<pre><code>from impala.dbapi import connect # error occured
from impala.util import as_pandas
conn = connect(host='10.xx.xx.xx', database='xx_xx', port=21050)`
</code></pre>
<blockquote>
<p>Traceback (most recent call last): ...</p>
<p>File "D:/test/test.py", line 14, in
<strong>from impala.dbapi import connect</strong></p>
<p>File "C:\Anaconda3\lib\site-packages\impala\dbapi.py", line 28, in
<strong>import impala.hiveserver2 as hs2</strong></p>
<p>File "C:\Anaconda3\lib\site-packages\impala\hiveserver2.py", line 32, in
<strong>from impala._thrift_api import (</strong></p>
<p>File "C:\Anaconda3\lib\site-packages\impala_thrift_api.py", line 73, in
<strong>include_dirs=[thrift_dir])</strong></p>
<p>File "C:\Anaconda3\lib\site-packages\thriftpy\parser__init__.py", line 30, in load
<strong>include_dir=include_dir)</strong></p>
<p>File "C:\Anaconda3\lib\site-packages\thriftpy\parser\parser.py", line 496, in parse
url_scheme))</p>
<p><strong>thriftpy.parser.exc.ThriftParserError: ThriftPy does not support generating module with path in protocol 'c'</strong></p>
</blockquote>
<p>when I tried to print include_dir, which was </p>
<p><code>D:/test\thrift</code></p>
<p>I just cannot import libray at all</p>
<p>help me</p>
| 1 | 2016-08-30T06:18:56Z | 39,291,522 | <p>I had the same problem with thriftpy, the problem on windows is an absolute path is like <strong>C:\foo\bar.thrift</strong> </p>
<p>But, the way the thrift library parses the file, it detects the <strong>C:</strong> as if it were a protocol like <strong>http:</strong> or <strong>https:</strong> </p>
<p>Its pretty easy to workaround you just have to strip the first two characters from the path with a slice like <strong>path[2:]</strong></p>
<p>Just slice when you call <code>thriftpy.load</code> or in the library file </p>
<pre><code>File "C:\Anaconda3\lib\site-packages\thriftpy\parser__init__.py", line 30
path = "C:\foo\bar.thrift"
thrift.load(path[2:], module_name, include_dirs=include_dirs,
include_dir=include_dir)
</code></pre>
<p><strong>OR</strong> </p>
<p>You can go a bit deeper and make the same change that I already submitted as a patch on the <a href="https://github.com/eleme/thriftpy/pull/236" rel="nofollow">github page</a>... perhaps it will be incorporated in the next version of thrift. </p>
<pre><code>File "C:\Anaconda3\lib\site-packages\thriftpy\parser\parser.py", line 488
- if url_scheme == '':
+ if len(url_scheme) <= 1:
</code></pre>
<p>My justification of why this change is valid is in the pull request. If its incorporated then you wont have to worry about making the same change again when you update the library. If not then just strip the two characters again. </p>
| 0 | 2016-09-02T11:40:42Z | [
"python",
"windows",
"impyla"
] |
Grouping of documents having the same phone number | 39,220,120 | <p>My database consists of collection of a large no. of hotels (approx 121,000). </p>
<p>This is how my collection looks like :</p>
<pre><code>{
"_id" : ObjectId("57bd5108f4733211b61217fa"),
"autoid" : 1,
"parentid" : "P01982.01982.110601173548.N2C5",
"companyname" : "Sheldan Holiday Home",
"latitude" : 34.169552,
"longitude" : 77.579315,
"state" : "JAMMU AND KASHMIR",
"city" : "LEH Ladakh",
"pincode" : 194101,
"phone_search" : "9419179870|253013",
"address" : "Sheldan Holiday Home|Changspa|Leh Ladakh-194101|LEH Ladakh|JAMMU AND KASHMIR",
"email" : "",
"website" : "",
"national_catidlineage_search" : "/10255012/|/10255031/|/10255037/|/10238369/|/10238380/|/10238373/",
"area" : "Leh Ladakh",
"data_city" : "Leh Ladakh"
}
</code></pre>
<p>Each document can have 1 or more phone numbers separated by "|" delimiter.</p>
<p>I have to group together documents having same phone number.</p>
<p>By real time, I mean when a user opens up a particular hotel to see its details on the web interface, I should be able to display all the hotels linked to it grouped by common phone numbers.</p>
<p>While grouping, if one hotel links to another and that hotels links to another, then all 3 should be grouped together.</p>
<blockquote>
<p>Example : Hotel A has phone numbers 1|2, B has phone numbers 3|4 and C
has phone numbers 2|3, then A, B and C should be grouped together.</p>
</blockquote>
<pre><code>from pymongo import MongoClient
from pprint import pprint #Pretty print
import re #for regex
#import unicodedata
client = MongoClient()
cLen = 0
cLenAll = 0
flag = 0
countA = 0
countB = 0
list = []
allHotels = []
conContact = []
conId = []
hotelTotal = []
splitListAll = []
contactChk = []
#We'll be passing the value later as parameter via a function call
#hId = 37443;
regx = re.compile("^Vivanta", re.IGNORECASE)
#Connection
db = client.hotel
collection = db.hotelData
#Finding hotels wrt search input
for post in collection.find({"companyname":regx}):
list.append(post)
#Copying all hotels in a list
for post1 in collection.find():
allHotels.append(post1)
hotelIndex = 11 #Index of hotel selected from search result
conIndex = hotelIndex
x = list[hotelIndex]["companyname"] #Name of selected hotel
y = list[hotelIndex]["phone_search"] #Phone numbers of selected hotel
try:
splitList = y.split("|") #Splitting of phone numbers and storing in a list 'splitList'
except:
splitList = y
print "Contact details of",x,":"
#Printing all contacts...
for contact in splitList:
print contact
conContact.extend(contact)
cLen = cLen+1
print "No. of contacts in",x,"=",cLen
for i in allHotels:
yAll = allHotels[countA]["phone_search"]
try:
splitListAll.append(yAll.split("|"))
countA = countA+1
except:
splitListAll.append(yAll)
countA = countA + 1
# print splitListAll
#count = 0
#This block has errors
#Add code to stop when no new links occur and optimize the outer for loop
#for j in allHotels:
for contactAll in splitListAll:
if contactAll in conContact:
conContact.extend(contactAll)
# contactChk = contactAll
# if (set(conContact) & set(contactChk)):
# conContact = contactChk
# contactChk[:] = [] #drop contactChk list
conId = allHotels[countB]["autoid"]
countB = countB+1
print "Printing the list of connected hotels..."
for final in collection.find({"autoid":conId}):
print final
</code></pre>
<p>This is one code I wrote in Python. In this one, I tried performing linear search in a for loop. I am getting some errors as of now but it should work when rectified.</p>
<p>I need an optimized version of this as liner search has poor time complexity.</p>
<p>I am pretty new to this so any other suggestions to improve the code are welcome. </p>
<p>Thanks.</p>
| 0 | 2016-08-30T06:20:16Z | 39,223,350 | <p>The easiest answer to any Python in-memory search-for question is "use a dict". Dicts give O(ln N) key-access speed, lists give O(N).</p>
<p>Also remember that you can put a Python object into as many dicts (or lists), and as many times into one dict or list, as it takes. They are not copied. It's just a reference.</p>
<p>So the essentials will look like</p>
<pre><code>for hotel in hotels:
phones = hotel["phone_search"].split("|")
for phone in phones:
hotelsbyphone.setdefault(phone,[]).append(hotel)
</code></pre>
<p>At the end of this loop, <code>hotelsbyphone["123456"]</code> will be a list of hotel objects which had "123456" as one of their <code>phone_search</code> strings. The key coding feature is the <code>.setdefault(key, [])</code> method which initializes an empty list if the key is not already in the dict, so that you can then append to it.</p>
<p>Once you have built this index, this will be fast</p>
<pre><code>try:
hotels = hotelsbyphone[x]
# and process a list of one or more hotels
except KeyError:
# no hotels exist with that number
</code></pre>
<p>Alternatively to <code>try ... except</code>, test <code>if x in hotelsbyphone:</code></p>
| 0 | 2016-08-30T09:14:03Z | [
"python",
"mongodb",
"real-time",
"aggregation-framework",
"mongodb-aggregation"
] |
comparision between django model version control packages | 39,220,205 | <p>I need to implement Django model history version & compare view. </p>
<p>I found there are packages like <strong>django-reversion</strong>, <strong>django-simple-history</strong>, <strong>django-revisions</strong> to implement model history version and <strong>django-reversion-compare</strong> for compare view. My requirement focuses mainly on <strong>implementing version history & compare view outside admin</strong>. </p>
<p>Can someone share the feedback on these packages? I found few references like <a href="http://treyhunner.com/2011/09/django-and-model-history/" rel="nofollow">http://treyhunner.com/2011/09/django-and-model-history/</a>, but it's still not clear to me. I am interested to know the <strong>ease & limitations</strong> of implementing these packages. </p>
| -2 | 2016-08-30T06:26:16Z | 39,222,778 | <p>You need <code>django-reversion</code> + <code>django-reversion-compare</code>. I have been using <code>django-reversion</code> for at least 5 years and <code>django-reversion-compare</code> is just an add-on for <code>django-reversion</code>, which makes it possible to compare different revisions of the same object/record.</p>
<p>Additionally see the following <a href="https://djangopackages.org/grids/g/versioning/" rel="nofollow">grid</a>.</p>
| 0 | 2016-08-30T08:47:10Z | [
"python",
"django"
] |
Summing List Elements | 39,220,215 | <p>I'm trying to do this question for this online coding course I'm part of, and one of the questions requires me to add together integers in a list. I've tried to find the answer (and visited a few other pages on this site), but I can't think of anything. Help please!</p>
<p>Here's my code so far:</p>
<pre><code>total = 0
att = input("RSVPs: ")
att = att.split(",")
for i in att:
print(sum(iatt) for i in att)
</code></pre>
<p><a href="http://i.stack.imgur.com/H0ZBM.png" rel="nofollow"><img src="http://i.stack.imgur.com/H0ZBM.png" alt="enter image description here"></a></p>
| 0 | 2016-08-30T06:26:37Z | 39,220,287 | <p>Your error is caused because you provide sum with an integer value (<code>iatt = int(i)</code>) when you should be providing it with the contents of the list which is split on <code>','</code>.</p>
<p>You have a couple of options for this. Either provide a comprehension to <code>sum</code> and cast every element to an <code>int</code> inside the comprehension:</p>
<pre><code>print(sum(int(i) for i in att))
</code></pre>
<p>or, use a built-in like <code>map</code> which pretty much does the same thing:</p>
<pre><code>print(sum(map(int,att)))
</code></pre>
<p>in both cases, <code>sum</code> expects something that can be iterated through and it handles the summing.</p>
<p>Of course, you could manually loop over the contents of <code>att</code>, adding <code>int(i)</code> to <code>total</code> as you go:</p>
<pre><code>for i in att:
total += int(i)
print(total)
</code></pre>
| 6 | 2016-08-30T06:31:12Z | [
"python",
"list",
"python-3.x"
] |
some bug of scikit learn auc function? | 39,220,293 | <p>Here is the code and output, I think from the output, it mean when fpr is 0, tpr is 0, this is correct as the prediction results marks everything to be 0.</p>
<p>But the output also said, when fpr is 1, tpr is also 1. I think it is not correct, since the predictor never predict something to be positive (label to be <code>1</code>), so how could the fpr (= # of correct prediction of 1/total # of 1) and tpr (= # of prediction of 1 / total # of 0) both to be 1?</p>
<pre><code>import numpy as np
from sklearn import metrics
y = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
pred = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
fpr, tpr, thresholds = metrics.roc_curve(y, pred)
print fpr
print tpr
print thresholds
print metrics.auc(fpr, tpr)
</code></pre>
<p><strong>Output</strong>,</p>
<pre><code>[ 0. 1.]
[ 0. 1.]
[1 0]
0.5
</code></pre>
| 1 | 2016-08-30T06:31:37Z | 39,222,863 | <p>These two illustrations would give you a better understanding of how the <em>FPR</em> and <em>TPR</em> get computed.</p>
<p><strong><em>Case-1:</em></strong></p>
<pre><code>y = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
pred = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
# -^- see the change here
</code></pre>
<p><em>True Positive = 0 <br>
False Positive = 0 <br>
True Negative = 9 <br>
False Negative = 1 <br></em> </p>
<p><em>True Positive Ratio, (tpr) = True Positive/(True Positive + False Negative)</em><br>
Therefore, <em>tpr = 0/(0+1) = 0.</em></p>
<p><em>False Positive Ratio, (fpr) = False Positive/(False Positive + True Negative)</em><br>
Therefore, <em>fpr = 0/(0+9) = 0.</em></p>
<pre><code>#Output:
fpr â [ 0. 1.]
tpr â [ 0. 1.]
</code></pre>
<p><strong><em>Case-2:</em></strong></p>
<pre><code>y = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
pred = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 1])
# -^- see the change here
</code></pre>
<p><em>True Positive = 1 <br>
False Positive = 0 <br>
True Negative = 9 <br>
False Negative = 0 <br></em> </p>
<p><em>True Positive Ratio, (tpr) = True Positive/(True Positive + False Negative)</em><br>
Therefore, <em>tpr = 1/(1+0) = 1.</em></p>
<p><em>False Positive Ratio, (fpr) = False Positive/(False Positive + True Negative)</em><br>
Therefore, <em>fpr = 0/(0+9) = 0.</em></p>
<pre><code>#Output:
fpr â [ 0. 1.]
tpr â [ 1. 1.]
</code></pre>
<hr>
<p><strong>Note:</strong> </p>
<p>According to the <a href="http://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_curve.html" rel="nofollow"><code>roc_curve documentation</code></a>, it is clearly stated that thresholds[0] represents no instances being predicted and is arbitrarily set to <code>max(pred)+1</code>.
[Here, 2 for binary classification task]</p>
<p>This becomes valid when the <code>fpr</code> and <code>tpr</code> when calculated becomes a fraction and cannot be quantified to 0 or 1. Hence, the <code>threshold</code> varies from 0, 1, 2.
For eg, when the last 2 values of <code>pred</code> array become 1, you get 3 values for threshold as <code>fpr</code> and <code>tpr</code> become fractional values.</p>
<p>But in our case, both <code>fpr</code> and <code>tpr</code> had been either of 0 or 1 and hence there wasn't any need for a third value of the <code>threshold</code>.</p>
<p>Also, the array elements in both <code>fpr</code> and <code>tpr</code> form an increasing sequence, i.e vary from 0 â1 and must satisfy a shape >= 2. Therefore, it is mandatory to have both 0's and 1's in the array as the starting and terminal values.</p>
<p>Incase of fractional values of <code>fpr</code> and <code>tpr</code>, the middle column would contain these values enclosed by 0 and 1 on either side of the array.</p>
| 2 | 2016-08-30T08:52:03Z | [
"python",
"machine-learning",
"scikit-learn",
"roc",
"auc"
] |
Error:list index out of range | 39,220,365 | <p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p>
<p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4."</p>
<p>Here is my code which works if I create a list and then run it locally (on codingbat.com it is necessary to create a function but I do not create a function to test my code locally):</p>
<pre><code>arr = [14,9,28,55,66,33,789,4548]
for i in range (4):
if arr[i] == 9:
print('True')
print('False')*
</code></pre>
<p>Here is the code I'm trying to run on codingbat.com but I receive "Error:list index out of range" error:</p>
<pre><code>def array_front9(arr):
for i in range(4):
if arr[i] == 9:
return True
return False
</code></pre>
<p>Here is the solution according to codingbat.com:</p>
<pre><code>def array_front9(nums):
# First figure the end for the loop
end = len(nums)
if end > 4:
end = 4
for i in range(end): # loop over index [0, 1, 2, 3]
if nums[i] == 9:
return True
return False
</code></pre>
<p>Here is the current URL for this problem: <a href="http://codingbat.com/prob/p110166" rel="nofollow">http://codingbat.com/prob/p110166</a></p>
<p>Can anyone point me to what I'm doing wrong?</p>
| 2 | 2016-08-30T06:35:57Z | 39,220,413 | <p>The problem states "The array length may be less than 4." Your code currently assumes the array is at least length 4. However, if <code>i</code> is greater than the last index of the list, an <code>IndexError</code> will be thrown.</p>
<p>You should first check if <code>len(arr) < 4</code> and return <code>False</code> if so.</p>
| 1 | 2016-08-30T06:38:58Z | [
"python",
"arrays",
"list"
] |
Error:list index out of range | 39,220,365 | <p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p>
<p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4."</p>
<p>Here is my code which works if I create a list and then run it locally (on codingbat.com it is necessary to create a function but I do not create a function to test my code locally):</p>
<pre><code>arr = [14,9,28,55,66,33,789,4548]
for i in range (4):
if arr[i] == 9:
print('True')
print('False')*
</code></pre>
<p>Here is the code I'm trying to run on codingbat.com but I receive "Error:list index out of range" error:</p>
<pre><code>def array_front9(arr):
for i in range(4):
if arr[i] == 9:
return True
return False
</code></pre>
<p>Here is the solution according to codingbat.com:</p>
<pre><code>def array_front9(nums):
# First figure the end for the loop
end = len(nums)
if end > 4:
end = 4
for i in range(end): # loop over index [0, 1, 2, 3]
if nums[i] == 9:
return True
return False
</code></pre>
<p>Here is the current URL for this problem: <a href="http://codingbat.com/prob/p110166" rel="nofollow">http://codingbat.com/prob/p110166</a></p>
<p>Can anyone point me to what I'm doing wrong?</p>
| 2 | 2016-08-30T06:35:57Z | 39,220,420 | <p>You use <code>range(4)</code>. So it will always look for 4 numbers. So when there are only three numbers it will still look for a fourth one. The fourth one doesn't exist so it throws an error. </p>
<p>Instead you need to see what the lenght of the list is and then iterate over that lenght.</p>
<p>Like this:</p>
<pre><code>for i in range(len(arr)):
if arr[i] == 9:
</code></pre>
<p>Or even simpler you can iterate over a list like this:</p>
<pre><code>for list_item in arr:
if list_item == 9: # you don't even have to use the [i]
</code></pre>
| 0 | 2016-08-30T06:39:18Z | [
"python",
"arrays",
"list"
] |
Error:list index out of range | 39,220,365 | <p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p>
<p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4."</p>
<p>Here is my code which works if I create a list and then run it locally (on codingbat.com it is necessary to create a function but I do not create a function to test my code locally):</p>
<pre><code>arr = [14,9,28,55,66,33,789,4548]
for i in range (4):
if arr[i] == 9:
print('True')
print('False')*
</code></pre>
<p>Here is the code I'm trying to run on codingbat.com but I receive "Error:list index out of range" error:</p>
<pre><code>def array_front9(arr):
for i in range(4):
if arr[i] == 9:
return True
return False
</code></pre>
<p>Here is the solution according to codingbat.com:</p>
<pre><code>def array_front9(nums):
# First figure the end for the loop
end = len(nums)
if end > 4:
end = 4
for i in range(end): # loop over index [0, 1, 2, 3]
if nums[i] == 9:
return True
return False
</code></pre>
<p>Here is the current URL for this problem: <a href="http://codingbat.com/prob/p110166" rel="nofollow">http://codingbat.com/prob/p110166</a></p>
<p>Can anyone point me to what I'm doing wrong?</p>
| 2 | 2016-08-30T06:35:57Z | 39,220,467 | <p>It is given in the problem that the array length may be less than 4. Your are just iterating over an array. You should first check whether the <code>array</code> is at least of <code>length 4</code>. If the <code>array</code> is less than 4 then only iterate through the length of the <code>array</code>.</p>
<pre><code>n = 4
if len(arr) < 4:
n = len(arr)
for i in range(n):
#...Your code...
</code></pre>
| 1 | 2016-08-30T06:41:57Z | [
"python",
"arrays",
"list"
] |
Error:list index out of range | 39,220,365 | <p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p>
<p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4."</p>
<p>Here is my code which works if I create a list and then run it locally (on codingbat.com it is necessary to create a function but I do not create a function to test my code locally):</p>
<pre><code>arr = [14,9,28,55,66,33,789,4548]
for i in range (4):
if arr[i] == 9:
print('True')
print('False')*
</code></pre>
<p>Here is the code I'm trying to run on codingbat.com but I receive "Error:list index out of range" error:</p>
<pre><code>def array_front9(arr):
for i in range(4):
if arr[i] == 9:
return True
return False
</code></pre>
<p>Here is the solution according to codingbat.com:</p>
<pre><code>def array_front9(nums):
# First figure the end for the loop
end = len(nums)
if end > 4:
end = 4
for i in range(end): # loop over index [0, 1, 2, 3]
if nums[i] == 9:
return True
return False
</code></pre>
<p>Here is the current URL for this problem: <a href="http://codingbat.com/prob/p110166" rel="nofollow">http://codingbat.com/prob/p110166</a></p>
<p>Can anyone point me to what I'm doing wrong?</p>
| 2 | 2016-08-30T06:35:57Z | 39,220,686 | <p>Simply test this expression:</p>
<pre><code>9 in arr[:4]
</code></pre>
<p>I explain:</p>
<p>As others have pointed out, your array might be shorter than 4 items, in which case indexing at, say <code>3</code>, the fourth number, will raise an <code>IndexError</code>.</p>
<p>But let's use the feature that <code>slicing</code> won't raise an exception, that is:</p>
<pre><code>In [232]: a = [1, 2]
In [233]: a[:10]
Out[233]: [1, 2]
</code></pre>
<p>In the above example I took a slice from the beginning of the array up until the 10'th item, and didn't get an exception, but Python returned the entire list.</p>
<p>Thus, you could do the check as simply as:</p>
<pre><code>9 in arr[:4]
</code></pre>
<p>and that's all!</p>
| 1 | 2016-08-30T06:54:30Z | [
"python",
"arrays",
"list"
] |
Error:list index out of range | 39,220,365 | <p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p>
<p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4."</p>
<p>Here is my code which works if I create a list and then run it locally (on codingbat.com it is necessary to create a function but I do not create a function to test my code locally):</p>
<pre><code>arr = [14,9,28,55,66,33,789,4548]
for i in range (4):
if arr[i] == 9:
print('True')
print('False')*
</code></pre>
<p>Here is the code I'm trying to run on codingbat.com but I receive "Error:list index out of range" error:</p>
<pre><code>def array_front9(arr):
for i in range(4):
if arr[i] == 9:
return True
return False
</code></pre>
<p>Here is the solution according to codingbat.com:</p>
<pre><code>def array_front9(nums):
# First figure the end for the loop
end = len(nums)
if end > 4:
end = 4
for i in range(end): # loop over index [0, 1, 2, 3]
if nums[i] == 9:
return True
return False
</code></pre>
<p>Here is the current URL for this problem: <a href="http://codingbat.com/prob/p110166" rel="nofollow">http://codingbat.com/prob/p110166</a></p>
<p>Can anyone point me to what I'm doing wrong?</p>
| 2 | 2016-08-30T06:35:57Z | 39,220,778 | <p>Easier solution for this problem would be:</p>
<pre><code>if len(arr) > 4:
if 9 in arr[0:4]:
return True
else:
return False
else:
print('Array length is shorter than 4')
return False
</code></pre>
<p>If you want to check for 9, even if the list length is less than 4, then below is the solution:</p>
<pre><code>def check(arr):
max = 4 if len(arr) >= 4 else len(arr)
if 9 in arr[0:max]:
return True
else:
return False
print check(arr)
</code></pre>
| 0 | 2016-08-30T06:58:45Z | [
"python",
"arrays",
"list"
] |
Error:list index out of range | 39,220,365 | <p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p>
<p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4."</p>
<p>Here is my code which works if I create a list and then run it locally (on codingbat.com it is necessary to create a function but I do not create a function to test my code locally):</p>
<pre><code>arr = [14,9,28,55,66,33,789,4548]
for i in range (4):
if arr[i] == 9:
print('True')
print('False')*
</code></pre>
<p>Here is the code I'm trying to run on codingbat.com but I receive "Error:list index out of range" error:</p>
<pre><code>def array_front9(arr):
for i in range(4):
if arr[i] == 9:
return True
return False
</code></pre>
<p>Here is the solution according to codingbat.com:</p>
<pre><code>def array_front9(nums):
# First figure the end for the loop
end = len(nums)
if end > 4:
end = 4
for i in range(end): # loop over index [0, 1, 2, 3]
if nums[i] == 9:
return True
return False
</code></pre>
<p>Here is the current URL for this problem: <a href="http://codingbat.com/prob/p110166" rel="nofollow">http://codingbat.com/prob/p110166</a></p>
<p>Can anyone point me to what I'm doing wrong?</p>
| 2 | 2016-08-30T06:35:57Z | 39,220,846 | <p>You have to get the minimum checking length of the input list:</p>
<pre><code>def array_front9(nums):
return 9 in nums[:min(4,len(nums))]
</code></pre>
| 0 | 2016-08-30T07:01:39Z | [
"python",
"arrays",
"list"
] |
Error:list index out of range | 39,220,365 | <p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p>
<p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4."</p>
<p>Here is my code which works if I create a list and then run it locally (on codingbat.com it is necessary to create a function but I do not create a function to test my code locally):</p>
<pre><code>arr = [14,9,28,55,66,33,789,4548]
for i in range (4):
if arr[i] == 9:
print('True')
print('False')*
</code></pre>
<p>Here is the code I'm trying to run on codingbat.com but I receive "Error:list index out of range" error:</p>
<pre><code>def array_front9(arr):
for i in range(4):
if arr[i] == 9:
return True
return False
</code></pre>
<p>Here is the solution according to codingbat.com:</p>
<pre><code>def array_front9(nums):
# First figure the end for the loop
end = len(nums)
if end > 4:
end = 4
for i in range(end): # loop over index [0, 1, 2, 3]
if nums[i] == 9:
return True
return False
</code></pre>
<p>Here is the current URL for this problem: <a href="http://codingbat.com/prob/p110166" rel="nofollow">http://codingbat.com/prob/p110166</a></p>
<p>Can anyone point me to what I'm doing wrong?</p>
| 2 | 2016-08-30T06:35:57Z | 39,221,060 | <p>The problem is <em>"check the first four numbers of a list, to see if any of them is a 9"</em>.</p>
<p>Now, if the list is less than 4, then automatically the check will fail:</p>
<pre><code>if len(arr) < 4:
return false
</code></pre>
<p>Next, you need to check if the first four items contain nine. There are many ways to do this, one of the easiest is:</p>
<pre><code>for i in arr[:4]:
if i == '9':
return true
</code></pre>
<p>Combine the two:</p>
<pre><code>def check_for_nine(arr):
if len(arr) < 4:
return false
for i in arr[:4]:
if i == '9':
return true
</code></pre>
<p>The issue with your initial approach is you are forcing the length to be 4, and assuming that at minimum the array will have 4 elements. If the array has 3 elements, then your code will not work.</p>
<p>To avoid this, don't assume a specific length. If you use slicing, then you are guaranteed that you will get <em>at most 4</em> items.</p>
<p>Here is an example of this:</p>
<pre><code>>>> i = [1,2]
>>> i[:4]
[1, 2]
</code></pre>
<p>Even though <code>i</code> only has two items, the slice to 4 works and doesn't raise an error. Once <code>i</code> has more than 4 items, it will limit to the first four:</p>
<pre><code>>>> i = [1,2,3,4,5,6,7,8]
>>> i[:4]
[1, 2, 3, 4]
</code></pre>
<p>However, our problem statement specifically said that check if the first four items contain 9. If we just use the slice trick, like this:</p>
<pre><code>for i in arr[:4]:
if i == '9':
return true
</code></pre>
<p>It will return true even if we pass it an array like <code>['1','9']</code> since the slice will always work.</p>
<p>To catch this condition - we first check if the length of the list is less than 4, because if it is - it automatically fails the condition.</p>
| 0 | 2016-08-30T07:12:56Z | [
"python",
"arrays",
"list"
] |
Error:list index out of range | 39,220,365 | <p>I am a beginner in Python and programming in general and I'm trying to solve a problem on codingbat.com (the problem is called "array_front9" under the section "Warmup-2"). </p>
<p>The problem is: "Given an array of ints, return True if one of the first 4 elements in the array is a 9. The array length may be less than 4."</p>
<p>Here is my code which works if I create a list and then run it locally (on codingbat.com it is necessary to create a function but I do not create a function to test my code locally):</p>
<pre><code>arr = [14,9,28,55,66,33,789,4548]
for i in range (4):
if arr[i] == 9:
print('True')
print('False')*
</code></pre>
<p>Here is the code I'm trying to run on codingbat.com but I receive "Error:list index out of range" error:</p>
<pre><code>def array_front9(arr):
for i in range(4):
if arr[i] == 9:
return True
return False
</code></pre>
<p>Here is the solution according to codingbat.com:</p>
<pre><code>def array_front9(nums):
# First figure the end for the loop
end = len(nums)
if end > 4:
end = 4
for i in range(end): # loop over index [0, 1, 2, 3]
if nums[i] == 9:
return True
return False
</code></pre>
<p>Here is the current URL for this problem: <a href="http://codingbat.com/prob/p110166" rel="nofollow">http://codingbat.com/prob/p110166</a></p>
<p>Can anyone point me to what I'm doing wrong?</p>
| 2 | 2016-08-30T06:35:57Z | 39,221,110 | <p>Thank you for all your answers, they have been really helpful!</p>
<p>I decided to use the IF loop instead of the FOR loop, like this:</p>
<pre><code>def array_front9(arr):
if 9 in arr[0:4]:
return True
return False
</code></pre>
<p>As much as I can see, this solution works no matter what the length of the list is, and it seems like it fits the definition of the problem i.e. "no matter what the length of the list is, if any of the first four elements equals 9, return True". </p>
| 0 | 2016-08-30T07:15:31Z | [
"python",
"arrays",
"list"
] |
Rename defaultdict key in Python | 39,220,428 | <p>I have the following problem: I have a defaultdict called word_count containing words and the number how often they occur. I get this by counting the reply of the Google Speech API. However, this API gives me back things like '\303\266' for the German letter 'ö'.
Now I want to go through this dict, test if one of these things shown above is there and replace it with the right thing like this:</p>
<p>Filling the defaultdict:</p>
<pre><code>word_count = defaultdict(int)
for line in fileinput.input([file]):
line = line.strip()
words = line.split()
for word in words:
word_count[word] += 1
</code></pre>
<p>So far it works fine, I can print the dict and it gets me the words with the number.</p>
<p>Now replacing the key:</p>
<pre><code>for key,val in word_count:
if '\\303\\266' in key:
new = key.replace('\\303\\266', 'ö')
word_count[new] = word_count.pop(key)
</code></pre>
<p>Now this does not work, I guess because I cannot pop(key) as it expects an integer. How else would I do this? I tried several approaches, but nothing seems to work here.</p>
<p>Any help would be greatly appreciated!</p>
<p><strong>Solution:</strong></p>
<p>Turns out this was my fault, as I sorted the dict and thereby turned it to a list of tuples. Thanks to everyone who helped me figure this out!</p>
| -2 | 2016-08-30T06:40:05Z | 39,220,552 | <p>You can do it like so:</p>
<pre><code>word_count['ö'] = word_count[key]
</code></pre>
<p>and then:</p>
<pre><code>del word_count[key]
</code></pre>
| 0 | 2016-08-30T06:47:07Z | [
"python",
"defaultdict",
"google-speech-api"
] |
Rename defaultdict key in Python | 39,220,428 | <p>I have the following problem: I have a defaultdict called word_count containing words and the number how often they occur. I get this by counting the reply of the Google Speech API. However, this API gives me back things like '\303\266' for the German letter 'ö'.
Now I want to go through this dict, test if one of these things shown above is there and replace it with the right thing like this:</p>
<p>Filling the defaultdict:</p>
<pre><code>word_count = defaultdict(int)
for line in fileinput.input([file]):
line = line.strip()
words = line.split()
for word in words:
word_count[word] += 1
</code></pre>
<p>So far it works fine, I can print the dict and it gets me the words with the number.</p>
<p>Now replacing the key:</p>
<pre><code>for key,val in word_count:
if '\\303\\266' in key:
new = key.replace('\\303\\266', 'ö')
word_count[new] = word_count.pop(key)
</code></pre>
<p>Now this does not work, I guess because I cannot pop(key) as it expects an integer. How else would I do this? I tried several approaches, but nothing seems to work here.</p>
<p>Any help would be greatly appreciated!</p>
<p><strong>Solution:</strong></p>
<p>Turns out this was my fault, as I sorted the dict and thereby turned it to a list of tuples. Thanks to everyone who helped me figure this out!</p>
| -2 | 2016-08-30T06:40:05Z | 39,220,887 | <p>From the discussions get to know that you are treating with list of tuple instead of <code>dict</code>. So <code>list.pop</code> always expect a integer that's why you getting an error.</p>
<pre><code>TypeError: list indices must be integers, not str
</code></pre>
<p>And <code>dict</code> expect it's key. So here you have to convert the input like <code>dict</code> or pop up from list with using it's index.</p>
| 1 | 2016-08-30T07:03:48Z | [
"python",
"defaultdict",
"google-speech-api"
] |
Applying an operation on multiple columns with a fixed column in pandas | 39,220,504 | <p>I have a dataframe as shown below. The last column shows the sum of values from all the columns i.e. <code>A</code>,<code>B</code>,<code>D</code>,<code>K</code> and <code>T</code>. Please note some of the columns have <code>NaN</code> as well.</p>
<pre><code>word1,A,B,D,K,T,sum
na,,63.0,,,870.0,933.0
sva,,1.0,,3.0,695.0,699.0
a,,102.0,,1.0,493.0,596.0
sa,2.0,487.0,,2.0,15.0,506.0
su,1.0,44.0,,136.0,214.0,395.0
waw,1.0,9.0,,34.0,296.0,340.0
</code></pre>
<p>How can I calculate the entropy for each row? i.e. I should find something like following</p>
<pre><code>df['A']/df['sum']*log(df['A']/df['sum']) + df['B']/df['sum']*log(df['B']/df['sum']) + ...... + df['T']/df['sum']*log(df['T']/df['sum'])
</code></pre>
<p>The condition is that whenever the value inside the <code>log</code> becomes <code>zero</code> or <code>NaN</code>, the whole value should be treated as zero (by definition, the log will return an error as log 0 is undefined).</p>
<p>I am aware of using lambda operation to apply on individual columns. Here I am not able to think for a pure pandas solution where a fixed column <code>sum</code> is applied on different columns <code>A</code>,<code>B</code>,<code>D</code> etc.. Though I can think of a simple loopwise iteration over CSV file with hard-coded column values.</p>
| 3 | 2016-08-30T06:44:16Z | 39,220,888 | <p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.ix.html" rel="nofollow"><code>ix</code></a> for selecting columns from <code>A</code> to <code>T</code>, then divide by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a> with <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.log.html" rel="nofollow"><code>numpy.log</code></a>. Last use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sum.html" rel="nofollow"><code>sum</code></a>:</p>
<pre><code>print (df['A']/df['sum']*np.log(df['A']/df['sum']))
0 NaN
1 NaN
2 NaN
3 -0.021871
4 -0.015136
5 -0.017144
dtype: float64
print (df.ix[:,'A':'T'].div(df['sum'],axis=0)*np.log(df.ix[:,'A':'T'].div(df['sum'],axis=0)))
A B D K T
0 NaN -0.181996 NaN NaN -0.065191
1 NaN -0.009370 NaN -0.023395 -0.005706
2 NaN -0.302110 NaN -0.010722 -0.156942
3 -0.021871 -0.036835 NaN -0.021871 -0.104303
4 -0.015136 -0.244472 NaN -0.367107 -0.332057
5 -0.017144 -0.096134 NaN -0.230259 -0.120651
print((df.ix[:,'A':'T'].div(df['sum'],axis=0)*np.log(df.ix[:,'A':'T'].div(df['sum'],axis=0)))
.sum(axis=1))
0 -0.247187
1 -0.038471
2 -0.469774
3 -0.184881
4 -0.958774
5 -0.464188
dtype: float64
</code></pre>
| 4 | 2016-08-30T07:03:51Z | [
"python",
"pandas",
"dataframe",
"sum",
"multiple-columns"
] |
Applying an operation on multiple columns with a fixed column in pandas | 39,220,504 | <p>I have a dataframe as shown below. The last column shows the sum of values from all the columns i.e. <code>A</code>,<code>B</code>,<code>D</code>,<code>K</code> and <code>T</code>. Please note some of the columns have <code>NaN</code> as well.</p>
<pre><code>word1,A,B,D,K,T,sum
na,,63.0,,,870.0,933.0
sva,,1.0,,3.0,695.0,699.0
a,,102.0,,1.0,493.0,596.0
sa,2.0,487.0,,2.0,15.0,506.0
su,1.0,44.0,,136.0,214.0,395.0
waw,1.0,9.0,,34.0,296.0,340.0
</code></pre>
<p>How can I calculate the entropy for each row? i.e. I should find something like following</p>
<pre><code>df['A']/df['sum']*log(df['A']/df['sum']) + df['B']/df['sum']*log(df['B']/df['sum']) + ...... + df['T']/df['sum']*log(df['T']/df['sum'])
</code></pre>
<p>The condition is that whenever the value inside the <code>log</code> becomes <code>zero</code> or <code>NaN</code>, the whole value should be treated as zero (by definition, the log will return an error as log 0 is undefined).</p>
<p>I am aware of using lambda operation to apply on individual columns. Here I am not able to think for a pure pandas solution where a fixed column <code>sum</code> is applied on different columns <code>A</code>,<code>B</code>,<code>D</code> etc.. Though I can think of a simple loopwise iteration over CSV file with hard-coded column values.</p>
| 3 | 2016-08-30T06:44:16Z | 39,221,210 | <pre><code>df1 = df.iloc[:, :-1]
df2 = df1.div(df1.sum(1), axis=0)
df2.mul(np.log(df2)).sum(1)
word1
na -0.247187
sva -0.038471
a -0.469774
sa -0.184881
su -0.958774
waw -0.464188
dtype: float64
</code></pre>
<h3>Setup</h3>
<pre><code>from StringIO import StringIO
import pandas as pd
text = """word1,A,B,D,K,T,sum
na,,63.0,,,870.0,933.0
sva,,1.0,,3.0,695.0,699.0
a,,102.0,,1.0,493.0,596.0
sa,2.0,487.0,,2.0,15.0,506.0
su,1.0,44.0,,136.0,214.0,395.0
waw,1.0,9.0,,34.0,296.0,340.0"""
df = pd.read_csv(StringIO(text), index_col=0)
df
</code></pre>
<p><a href="http://i.stack.imgur.com/I01af.png" rel="nofollow"><img src="http://i.stack.imgur.com/I01af.png" alt="enter image description here"></a></p>
| 2 | 2016-08-30T07:21:58Z | [
"python",
"pandas",
"dataframe",
"sum",
"multiple-columns"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.