title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
Randomly parsing files in Python from the command line
38,751,610
<p>When I was programming in C I had figured out a way in order to parse command line arguments for my program in any order, but I just would have to specify what the file was. So my input was something like this: <code>./exe.out -i &lt;inputfile&gt; -o &lt;outputfile&gt; -a &lt;someotherfile&gt; etc...</code> And this could get mixed up like so: <code>./exe.out -o &lt;outputfile&gt; -i &lt;inputfile&gt; -a &lt;someotherfile&gt; etc...</code> </p> <p>Now I need to do this in python. Meaning, having a method which will handle command line arguments in the beginning of the program and return the file locations to the main program. </p> <p><strong>ex.</strong> <code>python test.py -i &lt;inputfile&gt; -o &lt;outputfile&gt; -a &lt;someotherfile&gt; etc...</code></p> <p>Can this be done? I've found a way to do it, but the order has to precise and this will <strong>not</strong> do for my project.</p>
-2
2016-08-03T18:57:21Z
38,751,654
<p>You are looking for <code>optparse</code> (before Python 2.7) or <code>argparse</code> (Python 2.7 or above).</p>
3
2016-08-03T19:00:08Z
[ "python", "parsing", "command", "arguments" ]
How do I convert Tensorflow variables to Matlab structures?
38,751,664
<p>I am trying to pass the model parameters (W &amp; b) from tensorflow to matlab as a dictionary. But when I convert it to a structure in matlab the fields are still tensor variables and I cant do the desired operations on them. Is there any way to fix that and convert them to double or matrix?</p> <p>In tensor flow:</p> <pre><code>return {'W': W, 'b': b} </code></pre> <p>In matlab:</p> <pre><code>P = py.myModelOutput(samples,labels) model.parameters = struct(P) </code></pre> <p>Then when I get a print of the structure in matlab it shows the following:</p> <pre><code>ans = W: [1x1 py.tensorflow.python.ops.variables.Variable] b: [1x1 py.tensorflow.python.ops.variables.Variable] </code></pre> <p>Trying to convert the fields to double does not help either:</p> <pre><code>double(model.parameters.W) </code></pre> <p>Error using double Conversion to double from py.tensorflow.python.ops.variables.Variable is not possible.</p>
0
2016-08-03T19:00:35Z
38,752,950
<p>Assuming in your TensorFlow program you have a <code>tf.Session</code> object called <code>sess</code>, you should modify your code to return the following:</p> <pre><code>def myModelOutput(...): # ... sess = tf.Session() # ... # Convert the `tf.Variable` objects `W` and `b` to NumPy arrays. W_val, b_val = sess.run([W, b]) sess.close() # Assumes `sess` is local to the function. return {'W': W_val, 'b': b_val} </code></pre>
0
2016-08-03T20:22:27Z
[ "python", "matlab", "data-structures", "tensorflow", "data-type-conversion" ]
Python 2.7 on OS X: TypeError: 'frozenset' object is not callable on each command
38,751,800
<p>I have this error on each my command with Python:</p> <pre> ➜ /tmp sudo easy_install pip Traceback (most recent call last): File "/usr/bin/easy_install-2.7", line 11, in load_entry_point('setuptools==1.1.6', 'console_scripts', 'easy_install')() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 357, in load_entry_point return get_distribution(dist).load_entry_point(group, name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2394, in load_entry_point return ep.load() File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/pkg_resources.py", line 2108, in load entry = __import__(self.module_name, globals(),globals(), ['__name__']) File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/__init__.py", line 11, in from setuptools.extension import Extension File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/extension.py", line 5, in from setuptools.dist import _get_unpatched File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/dist.py", line 15, in from setuptools.compat import numeric_types, basestring File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/setuptools/compat.py", line 17, in import httplib File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 80, in import mimetools File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/mimetools.py", line 6, in import tempfile File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/tempfile.py", line 35, in from random import Random as _Random File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/random.py", line 49, in import hashlib as _hashlib File "build/bdist.macosx-10.11-intel/egg/hashlib.py", line 115, in """ TypeError: 'frozenset' object is not callable </pre> <p>What can I do with this?</p>
0
2016-08-03T19:08:29Z
38,767,427
<p>Removal of this package have helped me:</p> <pre> sudo rm -rf /Library/Python/2.7/site-packages/hashlib-20081119-py2.7-macosx-10.11-intel.egg </pre>
1
2016-08-04T12:31:23Z
[ "python" ]
Python 3.5: PIL Image.fromarray producing nonsense image
38,751,865
<p>I have an RGB image. When I import this image, I convert it to HSV using <code>matplotlib.color</code> and save the resulting array in a dict. When I want to display this image, I use <code>Image.fromarray</code> with <code>mode = 'HSV'</code>. I'm not sure what I am doing wrong but when the image is displayed, I get a mess (seen below along with code). Any help is appreciated. The code snippets below are roughly what happens in order to any given set of imported images.</p> <p>RGB to HSV Code:</p> <pre><code>from skimage import io import matplotlib.colors as mpclr import glob import os from PIL import Image, ImageOps types = ("\*.tif", "\*.jpg", "\*.ppm") imagePath = [] def importAllImgs(folderPath): for ext in types: imagePath.extend(glob.glob(folderPath + ext)) im_coll = io.ImageCollection(imagePath, conserve_memory = True) im_array = [] for i in range(len(im_coll)): #CONVERSION HAPPENS HERE image = im_coll[i] fltImg = np.around((np.array(image)/255.0), decimals = 2) imgHSV = mpclr.rgb_to_hsv(fltImg) im_array.append(imgHSV) return im_array, imagePath </code></pre> <p>Storage of Data:</p> <pre><code>def organizeAllData(self, imgArrList, imgPathList): self.allImages = dict() self.imageKeys = imgPathList for i in range(len(imgPathList)): self.allImages[imgPathList[i]] = {'H': imgArrList[i][:, :, 0], 'S': imgArrList[i][:, :, 1], 'V': imgArrList[i][:, :, 2]} self.hsvValues = [] self.labelValues = [] return self.allImages </code></pre> <p>Construction of array for displaying image:</p> <pre><code>def getImage(self, imageOfInterest): H = self.allImages[imageOfInterest]['H'][:,:] S = self.allImages[imageOfInterest]['S'][:,:] V = self.allImages[imageOfInterest]['V'][:,:] imgArray = np.dstack((H,S,V)) return imgArray </code></pre> <p>Displaying of Image:</p> <pre><code> preImArray = halThrThsnd.getImage(self.imagePaths[self.imageIndex]) self.preIm = Image.fromarray(preImArray, 'HSV') </code></pre> <p>And finally, the resulting image: </p> <p><a href="http://i.stack.imgur.com/UspTv.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/UspTv.jpg" alt="enter image description here"></a></p>
1
2016-08-03T19:12:33Z
38,878,046
<p>As per user sascha's comment (see below question), I decided to normalize the libraries I'm using for HSV conversion. Once I did that, I got normal images no problem. It turns out that depending on what library you use for image conversion, you will get different HSV value ranges. Some libraries will produce a range from 0 to 1. Others will produce a range from 0 to 255. </p> <p>Tl;dr: Used the same library across all processes, got a good image. </p>
0
2016-08-10T15:43:22Z
[ "python", "image", "matplotlib", "python-imaging-library" ]
How to prevent airflow from backfilling dag runs?
38,751,872
<p>Say you have an airflow DAG that doesn't make sense to backfill, meaning that, after it's run once, running it subsequent times quickly would be completely pointless.</p> <p>For example, if you're loading data from some source that is only updated hourly into your database, backfilling, which occurs in rapid succession, would just be importing the same data again and again.</p> <p>This is especially annoying when you instantiate a new hourly task, and it runs <code>N</code> amount of times for each hour it missed, doing redundant work, before it starts running on the interval you specified.</p> <p>The only solution I can think of is something that they specifically advised against in <a href="https://pythonhosted.org/airflow/faq.html" rel="nofollow">FAQ of the docs</a></p> <blockquote> <p>We recommend against using dynamic values as start_date, especially <code>datetime.now()</code> as it can be quite confusing.</p> </blockquote> <p>Is there any way to disable backfilling for a DAG, or should I do the above?</p>
3
2016-08-03T19:12:56Z
38,885,573
<p>This appears to be an unsolved Airflow problem. I know I would really like to have exactly the same feature. Here is as far as I've gotten; it may be useful to others.</p> <p>The are UI features (at least in 1.7.1.3) which can help with this problem. If you go to the Tree view and click on a specific task (square boxes), a dialog button will come up with a 'mark success' button. Clicking 'past', then clicking 'mark success' will label all the instances of that task in DAG as successful and they will not be run. The top level DAG (circles on top) can also be labeled as successful in a similar fashion, but there doesn't appear to be way to label multiple DAG instances.</p> <p>I haven't looked into it deeply enough yet, but it may be possible to use the 'trigger_dag' subcommand to mark states of DAGs. see here: <a href="https://github.com/apache/incubator-airflow/pull/644/commits/4d30d4d79f1a18b071b585500474248e5f46d67d" rel="nofollow">https://github.com/apache/incubator-airflow/pull/644/commits/4d30d4d79f1a18b071b585500474248e5f46d67d</a></p> <p>A CLI feature to mark DAGs is in the works: <a href="http://mail-archives.apache.org/mod_mbox/airflow-commits/201606.mbox/%3CJIRA.12973462.1464369259000.37918.1465189859133@Atlassian.JIRA%3E" rel="nofollow">http://mail-archives.apache.org/mod_mbox/airflow-commits/201606.mbox/%3CJIRA.12973462.1464369259000.37918.1465189859133@Atlassian.JIRA%3E</a> <a href="https://github.com/apache/incubator-airflow/pull/1590" rel="nofollow">https://github.com/apache/incubator-airflow/pull/1590</a></p> <p>UPDATE (9/28/2016): A new operator 'LatestOnlyOperator' has been added (<a href="https://github.com/apache/incubator-airflow/pull/1752" rel="nofollow">https://github.com/apache/incubator-airflow/pull/1752</a>) which will only run the latest version of downstream tasks. Sounds very useful and hopefully it will make it into the releases soon</p>
1
2016-08-11T00:34:10Z
[ "python", "scheduled-tasks", "airflow" ]
mapping URL arguments in Python Requests redirect
38,751,932
<p>While using the <a href="http://routes.readthedocs.io/en/latest/" rel="nofollow">Routes</a> library I want to <a href="http://routes.readthedocs.io/en/latest/uni_redirect_rest.html#redirect-routes" rel="nofollow">redirect</a> certain URLs. The documentation says it can be achieved like this:</p> <pre><code>map.redirect("/legacyapp/archives/{url:.*}", "/archives/{url}") </code></pre> <p>And I am indeed able to redirect to a URL this way. However I am unable to map/parse the URL arguments from the request to the redirect. My code looks like this:</p> <pre><code>app.mapper.redirect( "/repository/status_for_installed_repository{url:.*}", "/api/repositories/check_updates/{url}" ) </code></pre> <p>and if the app is passed this:</p> <pre><code>curl -L 'FQDN/repository/status_for_installed_repository?owner=qqqqqq&amp;changeset_revision=e5f6ced3e91f&amp;name=asdsadsadas' </code></pre> <p>it redirects me to </p> <pre><code>GET /api/repositories/check_updates </code></pre> <p>but I cannot find a way how to obtain the values of <code>owner</code> <code>name</code> and <code>changeset_revision</code>.</p> <p>I expect this to be a common use case as generally you do not want to lose arguments when redirecting?</p> <p>Any help is much appreciated. Thanks.</p>
0
2016-08-03T19:16:26Z
38,773,565
<p>I ended up implementing it as follows:</p> <pre><code>def _map_redirects( app ): """ Add redirect to the Routes mapper and forward the received query string. Subsequently when the redirect is triggered in Routes middleware the request will not even reach the webapp. """ def forward_qs(environ, result): qs_dict = urlparse.parse_qs(environ['QUERY_STRING']) for qs in qs_dict: result[ qs ] = qs_dict[ qs ] return True app.mapper.redirect( "/repository/status_for_installed_repository", "/api/repositories/check_updates/", _redirect_code="301 Moved Permanently", conditions=dict( function=forward_qs ) ) return app </code></pre>
0
2016-08-04T17:11:36Z
[ "python", "routes", "url-routing", "url-redirection" ]
Color numbers in pandas dataframe
38,752,010
<p>Is there a way to print some numbers in a dataframe in a different color? So for instance if I wanted to have the 1 in the following table in red. How can I do that?</p> <pre><code>import pandas as pd A=pd.DataFrame({'A':[1,2], 'B':[3,4]}) </code></pre> <p>I found libraries like termcolor. But there I can only print normal text in various colors.</p>
1
2016-08-03T19:21:18Z
38,752,335
<p>In addition to the answer @piRSquared provided which gives great ability for granular control, it appears <code>pandas</code> has added a <a href="http://pandas.pydata.org/pandas-docs/stable/style.html" rel="nofollow">style</a> feature as of <code>0.17.1</code> for addressing this exact issue. Here is a slightly modified version of the example provided in the linked documentation.</p> <p><a href="http://i.stack.imgur.com/xDv75.png" rel="nofollow"><img src="http://i.stack.imgur.com/xDv75.png" alt="enter image description here"></a></p>
2
2016-08-03T19:42:14Z
[ "python", "python-2.7", "pandas" ]
Overwrite yaml config file in GUI (python)
38,752,011
<p>I have implemented a GUI interface using PyQt4. In my GUI interface I have a configuration tab where users can make changes to the config file (with line edits). I am able to overwrite the yaml config file in the GUI with these inputted values (I have buttons for load, save, and overwrite), but when these variables are actually being used in other modules, it reads from the original config values. This is how I am reading my config file in the modules that use the variables:</p> <pre><code>with open("config.yaml", "r") as f: config = yaml.safe_load(f) MIN_VOLTAGE = config['test1']['minVolt'] MAX_VOLTAGE = config['test1']['maxVolt'] MAX_CURR = config['test1']['maxCurr'] </code></pre> <p>My config file looks like this:</p> <pre><code>test1: maxCurr: 5 maxVolt: 5 minVolt: -5 test2: maxVolt: 8 setCurr: 3 </code></pre> <p>How will I be able to use the new config values without exiting out of the GUI?</p>
0
2016-08-03T19:21:20Z
38,766,629
<p>You probably do not update the values <code>MIN_VOLTAGE</code>. <code>MAX_VOLTAGE</code> and <code>MAX_CURR</code> after writing the YAML file, but you do not show enough code to identify the problem.</p> <p>You code loads the YAML file once (probably at application startup), and the values are populated thereafter. If you overwrite your YAML file, the values in your application will not automatically change unless you either manually modify them or reload the YAML file into those values.</p> <p>A sane approach would be to store the configuration values in a class which has a <code>save</code> and <code>load</code> method, then use the values from there and also update them there when the user changes configuration. Invoke <code>save</code> after modification, and <code>load</code> at application startup.</p>
0
2016-08-04T11:53:45Z
[ "python", "file", "pyqt4", "yaml", "config" ]
django deploy- ImproperlyConfigured: The SECRET_KEY setting must not be empty
38,752,015
<p>The project worked fine on windows pycharm.</p> <p>Now i am putting it on ubuntu14.04 and apache2.</p> <p>When i run <code>python manage.py runserver 8000</code></p> <pre><code>Traceback (most recent call last): File "manage.py", line 14, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/management/__init__.py", line 195, in fetch_command klass = load_command_class(app_name, subcommand) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/management/__init__.py", line 39, 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 "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/management/commands/runserver.py", line 16, in &lt;module&gt; from django.db.migrations.executor import MigrationExecutor File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/migrations/executor.py", line 7, in &lt;module&gt; from .loader import MigrationLoader File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/migrations/loader.py", line 10, in &lt;module&gt; from django.db.migrations.recorder import MigrationRecorder File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/migrations/recorder.py", line 12, in &lt;module&gt; class MigrationRecorder(object): File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/migrations/recorder.py", line 26, in MigrationRecorder class Migration(models.Model): File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/migrations/recorder.py", line 27, in Migration app = models.CharField(max_length=255) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/models/fields/__init__.py", line 1072, in __init__ super(CharField, self).__init__(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/models/fields/__init__.py", line 166, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/Web-Interaction-APP/settings.py", line 8, in &lt;module&gt; application = get_wsgi_application() File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/wsgi.py", line 13, in get_wsgi_application django.setup() File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 120, 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>I have also tried to change my <code>manage.py</code> and <code>wsgi.py</code>. My folder is:</p> <pre><code>Web-Interaction-APP -manage.py -seetings.py *apache(folder) -wsgi.py *project(folder) </code></pre> <p>in my manage.py:</p> <pre><code>#!/usr/bin/env python #This file runs the server for this application from command line. import os, sys #Executes the code in the following condition if the program is run directly. #(Source: http://stackoverflow.com/questions/419163/what-does-if-name-main-do) if __name__ == "__main__": #Refers to the path of this django project's settings module. #(DJANGO_SETTINGS_MODULE is an environment variable to module import path.) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.management import execute_from_command_line #Executes the django project. execute_from_command_line(sys.argv) </code></pre> <p>In my wsgi.py:</p> <pre><code>import os, sys # Calculate the path based on the location of the WSGI script. apache_configuration= os.path.dirname(__file__) project = os.path.dirname(apache_configuration) workspace = os.path.dirname(project) sys.path.append(workspace) sys.path.append(project) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Web-Interaction-APP.settings") # Add the path to 3rd party django application and to django itself. sys.path.append('/home/zhaojf1') os.environ['DJANGO_SETTINGS_MODULE'] = '10.231.52.XX.apache.override' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </code></pre>
1
2016-08-03T19:21:44Z
38,755,630
<p>This error is common when your <a href="http://stackoverflow.com/a/20646241/2532070"><code>DJANGO_SETTINGS_MODULE</code> path is incorrect</a>.</p> <p>When you run <code>python manage.py runserver 8000</code> you are using <code>manage.py</code> which is settings your <code>DJANGO_SETTINGS_MODULE</code> to <code>settings</code>. It doesn't appear that you have a <code>settings.py</code> in your root directory, so this line in <code>manage.py</code>:</p> <pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") </code></pre> <p>should become:</p> <pre><code>os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Web-Interaction-APP.settings") </code></pre> <p>as you have in your <code>wsgi.py</code> file.</p>
0
2016-08-04T00:17:59Z
[ "python", "django", "ubuntu", "deployment" ]
django deploy- ImproperlyConfigured: The SECRET_KEY setting must not be empty
38,752,015
<p>The project worked fine on windows pycharm.</p> <p>Now i am putting it on ubuntu14.04 and apache2.</p> <p>When i run <code>python manage.py runserver 8000</code></p> <pre><code>Traceback (most recent call last): File "manage.py", line 14, in &lt;module&gt; execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/management/__init__.py", line 195, in fetch_command klass = load_command_class(app_name, subcommand) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/management/__init__.py", line 39, 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 "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/management/commands/runserver.py", line 16, in &lt;module&gt; from django.db.migrations.executor import MigrationExecutor File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/migrations/executor.py", line 7, in &lt;module&gt; from .loader import MigrationLoader File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/migrations/loader.py", line 10, in &lt;module&gt; from django.db.migrations.recorder import MigrationRecorder File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/migrations/recorder.py", line 12, in &lt;module&gt; class MigrationRecorder(object): File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/migrations/recorder.py", line 26, in MigrationRecorder class Migration(models.Model): File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/migrations/recorder.py", line 27, in Migration app = models.CharField(max_length=255) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/models/fields/__init__.py", line 1072, in __init__ super(CharField, self).__init__(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/db/models/fields/__init__.py", line 166, in __init__ self.db_tablespace = db_tablespace or settings.DEFAULT_INDEX_TABLESPACE File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/var/www/Web-Interaction-APP/settings.py", line 8, in &lt;module&gt; application = get_wsgi_application() File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/core/wsgi.py", line 13, in get_wsgi_application django.setup() File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/dist-packages/Django-1.9-py2.7.egg/django/conf/__init__.py", line 120, 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>I have also tried to change my <code>manage.py</code> and <code>wsgi.py</code>. My folder is:</p> <pre><code>Web-Interaction-APP -manage.py -seetings.py *apache(folder) -wsgi.py *project(folder) </code></pre> <p>in my manage.py:</p> <pre><code>#!/usr/bin/env python #This file runs the server for this application from command line. import os, sys #Executes the code in the following condition if the program is run directly. #(Source: http://stackoverflow.com/questions/419163/what-does-if-name-main-do) if __name__ == "__main__": #Refers to the path of this django project's settings module. #(DJANGO_SETTINGS_MODULE is an environment variable to module import path.) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") from django.core.management import execute_from_command_line #Executes the django project. execute_from_command_line(sys.argv) </code></pre> <p>In my wsgi.py:</p> <pre><code>import os, sys # Calculate the path based on the location of the WSGI script. apache_configuration= os.path.dirname(__file__) project = os.path.dirname(apache_configuration) workspace = os.path.dirname(project) sys.path.append(workspace) sys.path.append(project) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Web-Interaction-APP.settings") # Add the path to 3rd party django application and to django itself. sys.path.append('/home/zhaojf1') os.environ['DJANGO_SETTINGS_MODULE'] = '10.231.52.XX.apache.override' import django.core.handlers.wsgi application = django.core.handlers.wsgi.WSGIHandler() </code></pre>
1
2016-08-03T19:21:44Z
38,755,646
<p>Maybe in your settings file, you are setting the <code>SECRET_KEY</code> using a <code>ENV</code> variable, open a shell and just:</p> <pre><code> export SECRET_KEY='test_key' </code></pre> <p>Then, try to run your server again. </p>
0
2016-08-04T00:20:32Z
[ "python", "django", "ubuntu", "deployment" ]
Communication from Python to Arduino over USB
38,752,081
<p>I am trying to communicate with an Arduino. I use python and pyserial for communication over USB. As you can see in the source code below, I am trying to send a bytearray, which contains some information for two ledstrips, to the Arduino. But the Arduino does not receive the right information. It looks like the bytearray is transformed or information is getting lost. </p> <p>I searched the whole day for a solution, but nothing has worked. Hopefully one of you can help me with this problem.</p> <p>Thanks in advance.</p> <p><strong>Python Code</strong></p> <pre><code>import sys import serial import time HEADER_BYTE_1 = 0xBA HEADER_BYTE_2 = 0xBE def main(): ser = serial.Serial('/dev/ttyUSB0', 57600) message = { 'header': [None]*2, 'colors': [None]*6, 'checksum': 0x00 } message['header'][0] = HEADER_BYTE_1 message['header'][1] = HEADER_BYTE_2 # first led message['colors'][0] = 0xFF message['colors'][1] = 0xFF message['colors'][2] = 0xFF # second led message['colors'][3] = 0x00 message['colors'][4] = 0x00 message['colors'][5] = 0x00 # create checksum for color in message['colors']: for bit in bytes(color): message['checksum'] ^= bit # write message to arduino cmd = convert_message_to_protocol(message) ser.write(cmd) print(cmd) time.sleep(5) # read response from arduino while True: response = ser.readline() print(response) def convert_message_to_protocol(message): cmd = bytearray() for header in message['header']: cmd.append(header) for color in message['colors']: cmd.append(color) cmd.append(message['checksum']) return cmd if __name__ == '__main__': main() </code></pre> <p><strong>Arduino Code</strong></p> <pre><code>const int kChannel1FirstPin = 3; const int kChannel1SecondPin = 5; const int kChannel1ThirdPin = 6; const int kChannel2FirstPin = 9; const int kChannel2SecondPin = 10; const int kChannel2ThirdPin = 11; // Protocol details (two header bytes, 6 value bytes, checksum) const int kProtocolHeaderFirstByte = 0xBA; const int kProtocolHeaderSecondByte = 0xBE; const int kProtocolHeaderLength = 2; const int kProtocolBodyLength = 6; const int kProtocolChecksumLength = 1; // Buffers and state bool appearToHaveValidMessage; byte receivedMessage[6]; void setup() { // set pins 2 through 13 as outputs: pinMode(kChannel1FirstPin, OUTPUT); pinMode(kChannel1SecondPin, OUTPUT); pinMode(kChannel1ThirdPin, OUTPUT); pinMode(kChannel2FirstPin, OUTPUT); pinMode(kChannel2SecondPin, OUTPUT); pinMode(kChannel2ThirdPin, OUTPUT); analogWrite(kChannel1FirstPin, 255); analogWrite(kChannel1SecondPin, 255); analogWrite(kChannel1ThirdPin, 255); analogWrite(kChannel2FirstPin, 255); analogWrite(kChannel2SecondPin, 255); analogWrite(kChannel2ThirdPin, 255); appearToHaveValidMessage = false; // initialize the serial communication: Serial.begin(57600); } void loop () { int availableBytes = Serial.available(); Serial.println(availableBytes); if (!appearToHaveValidMessage) { // If we haven't found a header yet, look for one. if (availableBytes &gt;= kProtocolHeaderLength) { Serial.println("right size"); // Read then peek in case we're only one byte away from the header. byte firstByte = Serial.read(); byte secondByte = Serial.peek(); if (firstByte == kProtocolHeaderFirstByte &amp;&amp; secondByte == kProtocolHeaderSecondByte) { Serial.println("Right Header"); // We have a valid header. We might have a valid message! appearToHaveValidMessage = true; // Read the second header byte out of the buffer and refresh the buffer count. Serial.read(); availableBytes = Serial.available(); } } } if (availableBytes &gt;= (kProtocolBodyLength + kProtocolChecksumLength) &amp;&amp; appearToHaveValidMessage) { // Read in the body, calculating the checksum as we go. byte calculatedChecksum = 0; for (int i = 0; i &lt; kProtocolBodyLength; i++) { receivedMessage[i] = Serial.read(); calculatedChecksum ^= receivedMessage[i]; } byte receivedChecksum = Serial.read(); if (receivedChecksum == calculatedChecksum) { // Hooray! Push the values to the output pins. analogWrite(kChannel1FirstPin, receivedMessage[0]); analogWrite(kChannel1SecondPin, receivedMessage[1]); analogWrite(kChannel1ThirdPin, receivedMessage[2]); analogWrite(kChannel2FirstPin, receivedMessage[3]); analogWrite(kChannel2SecondPin, receivedMessage[4]); analogWrite(kChannel2ThirdPin, receivedMessage[5]); Serial.print("OK"); Serial.write(byte(10)); } else { Serial.print("FAIL"); Serial.write(byte(10)); } appearToHaveValidMessage = false; } } </code></pre> <p><strong>Example</strong> </p> <p>Generated Bytes in Python: <code>b'\xba\xbe\xff\xff\xff\x00\x00\x00\x00'</code></p> <p>Received Bytes on the Arduino: <code>b'L\xc30\r\n'</code></p>
1
2016-08-03T19:26:26Z
38,763,286
<p>Changing the baudrate to 9600 has fixed the communication</p>
0
2016-08-04T09:17:55Z
[ "python", "arduino", "pyserial" ]
PUT dictionary in dictionary in Python requests
38,752,091
<p>I want to send a PUT request with the following data structure:</p> <pre><code>{ body : { version: integer, file_id: string }} </code></pre> <p>Here is the client code:</p> <pre><code>def check_id(): id = request.form['id'] res = logic.is_id_valid(id) file_uuid = request.form['file_id'] url = 'http://localhost:8050/firmwares' r = requests.put(url = url, data = {'body' : {'version': id, 'file_id': str(file_uuid)}}) </code></pre> <p>Here is the server code:</p> <pre><code>api.add_resource(resources.FirmwareNewVerUpload, '/firmwares') class FirmwareNewVerUpload(rest.Resource): def put(self): try: args = parser.parse_args() except: print traceback.format_exc() print 'data: ', str(args['body']), ' type: ', type(args['body']) return </code></pre> <p>The server prints:</p> <pre><code>data: version type: &lt;type 'unicode'&gt; </code></pre> <p>And this result is not what I want. Instead of inner dictionary I got a string with name of one dictionary key. If I change 'version' to 'ver'</p> <pre><code> r = requests.put(url = url, data = {'body' : {'ver': id, 'file_id': str(file_uuid)}}) </code></pre> <p>server prints</p> <pre><code>data: ver type: &lt;type 'unicode'&gt; </code></pre> <p>How to send a dictionary with inner dictionary?</p>
-1
2016-08-03T19:27:03Z
38,752,460
<p>In official doc you found a topic called <a href="http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests" rel="nofollow">More complicated POST requests</a></p> <blockquote> <p>There are many times that you want to send data that is not form-encoded. If you pass in a string instead of a dict, that data will be posted directly.</p> </blockquote> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; url = 'https://api.github.com/some/endpoint' &gt;&gt;&gt; payload = {'some': 'data'} &gt;&gt;&gt; r = requests.post(url, data=json.dumps(payload)) </code></pre> <p>Maybe convert your data to JSON could be a good approach.</p> <pre><code>import json def check_id(): id = request.form['id'] res = logic.is_id_valid(id) file_uuid = request.form['file_id'] url = 'http://localhost:8050/firmwares' payload = {'body' : {'version': id, 'file_id': str(file_uuid)}} r = requests.put(url=url, data=json.dumps(payload)) </code></pre>
0
2016-08-03T19:51:39Z
[ "python", "dictionary", "python-requests" ]
PUT dictionary in dictionary in Python requests
38,752,091
<p>I want to send a PUT request with the following data structure:</p> <pre><code>{ body : { version: integer, file_id: string }} </code></pre> <p>Here is the client code:</p> <pre><code>def check_id(): id = request.form['id'] res = logic.is_id_valid(id) file_uuid = request.form['file_id'] url = 'http://localhost:8050/firmwares' r = requests.put(url = url, data = {'body' : {'version': id, 'file_id': str(file_uuid)}}) </code></pre> <p>Here is the server code:</p> <pre><code>api.add_resource(resources.FirmwareNewVerUpload, '/firmwares') class FirmwareNewVerUpload(rest.Resource): def put(self): try: args = parser.parse_args() except: print traceback.format_exc() print 'data: ', str(args['body']), ' type: ', type(args['body']) return </code></pre> <p>The server prints:</p> <pre><code>data: version type: &lt;type 'unicode'&gt; </code></pre> <p>And this result is not what I want. Instead of inner dictionary I got a string with name of one dictionary key. If I change 'version' to 'ver'</p> <pre><code> r = requests.put(url = url, data = {'body' : {'ver': id, 'file_id': str(file_uuid)}}) </code></pre> <p>server prints</p> <pre><code>data: ver type: &lt;type 'unicode'&gt; </code></pre> <p>How to send a dictionary with inner dictionary?</p>
-1
2016-08-03T19:27:03Z
39,598,206
<p>Use <code>json=</code> instead of <code>data=</code> when doing <code>requests.put</code> and <code>headers = {'content-type':'application/json'}</code>:</p> <pre><code> r = requests.put(url = url, json = {'body' : {'version': id, 'file_id': str(file_uuid)}}, headers = {'content-type':'application/json'}) </code></pre>
0
2016-09-20T15:32:11Z
[ "python", "dictionary", "python-requests" ]
Finding specific Bigram using NLTK Python 3
38,752,101
<p>I have a Problem that should actually be very easy solve with NLTK. I found a solution to my problem, but there they don't use NLTK:</p> <p><a href="http://stackoverflow.com/questions/36707617/how-can-i-count-the-specific-bigram-words">how can I count the specific bigram words?</a></p> <p>Is it possible to do that with a NLTK function?</p> <p>Here is my code:</p> <pre><code>food = open("food_low.txt") lines = food.read().split(',')[:-1] raw = wordlists.words("cleaned2.txt") fdist = nltk.FreqDist(w.lower() for w in raw) with io.open('nltk1.txt', 'w', encoding="utf-8") as h: for m in lines: if fdist[m] &gt; 0: print(m + ':', fdist[m], end=' ', file = h) </code></pre> <p>I am counting how often the words from the <code>food_low.txt</code> appear in the <code>cleaned2.txt</code>. My problem is that I have some bigram words in <code>food_low.txt</code> and they are not counted. How can I make it that it also counts the bigrams?</p>
0
2016-08-03T19:27:46Z
38,760,578
<p>You could try to count unigram and bigram without NLTK and using regular expressions (<code>re</code>). Now you do not need two separate calculations, but you can do it in one go with <code>re.findall()</code>:</p> <pre><code>import re import codecs # List of words and a sentence l = ['cow', 'dog', 'hot dog', 'pet candy'] s = 'since the opening of the bla and hot dog in the hot dog cow' # Make your own fdist fdist = {} for m in l: # Find all occurrences of m in l and store the frequency in fdist[m] fdist[m] = len(re.findall(m, s)) # Write the wordcounts for each word to a file (if fdist[m] &gt; 0) with codecs.open('nltk1.txt', 'w', encoding='utf8') as out: for m in l: if fdist[m] &gt; 0: out.write('{}:\t{}\n'.format( m, fdist[m] ) ) </code></pre> <p>Content of nltk1.txt:</p> <pre><code>cow: 1 dog: 2 hot dog: 2 </code></pre> <p>Note: If you want to use NLTK, <a href="http://stackoverflow.com/a/27094326/5488275">this answer might fulfill your needs</a>.</p>
0
2016-08-04T07:04:42Z
[ "python", "count", "nltk" ]
How to run python file from django
38,752,121
<p>How I can run python file, or django file from django view. I'm trying to make like ipython notebook, but use just text editor.</p> <p>I have create view, in this view I'm simply add python(django) text.</p> <p>Then when smb requests some view, wich process this python(django) file, I should send response with result.</p> <p>For example, print result of query set.</p> <p>In create view, I've added text:</p> <pre><code>from main.models import User for i in User.objects.all() print(i) </code></pre> <p>And in view I get request and send response with result of execution of code above.</p>
-3
2016-08-03T19:29:03Z
38,753,719
<p>If I understand well you want to run some function inside of your view that is stored in and external file. If so just put the file in your app root directory and import it in your views.py</p> <pre><code>from your_app.your_file import your_method </code></pre>
1
2016-08-03T21:12:02Z
[ "python", "django" ]
Python2.7: How to split a column into multiple column based on special strings like this?
38,752,135
<p>I'm a newbie for programming and python, so I would appreciate your advice!</p> <p>I have a dataframe like this. <a href="http://i.stack.imgur.com/33lcM.png" rel="nofollow"><img src="http://i.stack.imgur.com/33lcM.png" alt="enter image description here"></a> In 'info' column, there are 7 different categories: activities, locations, groups, skills, sights, types and other. and each categories have unique values within <strong>[ ]</strong>.(ie,"activities":<strong>["Tour"]</strong>) I would like to split 'info' column into 7 different columns based on each category as shown below.</p> <p><a href="http://i.stack.imgur.com/m8L7G.png" rel="nofollow"><img src="http://i.stack.imgur.com/m8L7G.png" alt="enter image description here"></a></p> <p>I would like to allocate appropriate column names and also put corresponding unique strings within [ ] to each row.</p> <p>Is there any easy way to split dataframe like that? I was thinking to use str.split functions to split into pieces and merge everthing later. But not sure that is the best way to go and I wanted to see if there is more sophisticated way to make a dataframe like this.</p> <p>Any advice is appreciated!</p> <p>--<strong>UPDATE</strong>--</p> <p>When print(dframe['info']), it shows like this. <a href="http://i.stack.imgur.com/LN2vp.png" rel="nofollow"><img src="http://i.stack.imgur.com/LN2vp.png" alt="enter image description here"></a></p>
-2
2016-08-03T19:29:42Z
38,752,306
<p>It looks like the content of the <code>info</code> column is JSON-formatted, so you can parse that into a dict object easily:</p> <pre><code>&gt;&gt;&gt; import json &gt;&gt;&gt; s = '''{"activities": ["Tour"], "locations": ["Tokyo"], "groups": []}''' &gt;&gt;&gt; j = json.loads(s) &gt;&gt;&gt; j {u'activities': [u'Tour'], u'locations': [u'Tokyo'], u'groups': []} </code></pre> <p>Once you have the data as a dict, you can do whatever you like with it. </p>
0
2016-08-03T19:40:45Z
[ "python", "python-2.7", "pandas", "split", "multiple-columns" ]
Python2.7: How to split a column into multiple column based on special strings like this?
38,752,135
<p>I'm a newbie for programming and python, so I would appreciate your advice!</p> <p>I have a dataframe like this. <a href="http://i.stack.imgur.com/33lcM.png" rel="nofollow"><img src="http://i.stack.imgur.com/33lcM.png" alt="enter image description here"></a> In 'info' column, there are 7 different categories: activities, locations, groups, skills, sights, types and other. and each categories have unique values within <strong>[ ]</strong>.(ie,"activities":<strong>["Tour"]</strong>) I would like to split 'info' column into 7 different columns based on each category as shown below.</p> <p><a href="http://i.stack.imgur.com/m8L7G.png" rel="nofollow"><img src="http://i.stack.imgur.com/m8L7G.png" alt="enter image description here"></a></p> <p>I would like to allocate appropriate column names and also put corresponding unique strings within [ ] to each row.</p> <p>Is there any easy way to split dataframe like that? I was thinking to use str.split functions to split into pieces and merge everthing later. But not sure that is the best way to go and I wanted to see if there is more sophisticated way to make a dataframe like this.</p> <p>Any advice is appreciated!</p> <p>--<strong>UPDATE</strong>--</p> <p>When print(dframe['info']), it shows like this. <a href="http://i.stack.imgur.com/LN2vp.png" rel="nofollow"><img src="http://i.stack.imgur.com/LN2vp.png" alt="enter image description here"></a></p>
-2
2016-08-03T19:29:42Z
38,752,523
<p>Ok, here is how to do it :</p> <pre><code>import pandas as pd import ast #Initial Dataframe is df mylist = list(df['info']) mynewlist = [] for l in mylist: mynewlist.append(ast.literal_eval(l)) df_info = pd.DataFrame(mynewlist) #Add columns of decoded info to the initial dataset df_new = pd.concat([df,df_info],axis=1) #Remove the column info del df_new['info'] </code></pre>
0
2016-08-03T19:55:51Z
[ "python", "python-2.7", "pandas", "split", "multiple-columns" ]
What does self[identifier] = some_value do in this code?
38,752,193
<p>I was just trying to learn K-ary tree implementation in Python and came across this link: <a href="http://www.quesucede.com/page/show/id/python-3-tree-implementation">http://www.quesucede.com/page/show/id/python-3-tree-implementation</a></p> <p>In the tree.py file, there is a section of code like this:</p> <pre><code>class Tree: def __init__(self): self.__nodes = {} @property def nodes(self): return self.__nodes def add_node(self, identifier, parent=None): node = Node(identifier) self[identifier] = node if parent is not None: self[parent].add_child(identifier) return node # ... ... def __getitem__(self, key): return self.__nodes[key] def __setitem__(self, key, item): self.__nodes[key] = item </code></pre> <p>What is <code>self[identifier]</code>? Is it a list? This is really confusing. Can someone explain and/or point me to some documentation of using self as a list?</p>
6
2016-08-03T19:33:22Z
38,752,271
<p>In the full example code, this is the important bit:</p> <pre><code>def __getitem__(self, key): return self.__nodes[key] def __setitem__(self, key, item): self.__nodes[key] = item </code></pre> <p>These two 'magic methods', <code>__getitem__</code> and <code>__setitem__</code>, allow the class to be accessed like a list or dictionary would be, using the <code>foo[key]</code> syntax.</p> <p>So, in your case, if <code>foo</code> was a <code>Tree</code> instance, <code>foo["a"] = "b"</code> would execute <code>__setitem__</code> with <code>key</code> as <code>"a"</code> and <code>item</code> as <code>"b"</code>, consequently mapping <code>key</code> to <code>item</code> in the <code>self.__nodes</code> dictionary.</p>
3
2016-08-03T19:38:24Z
[ "python" ]
What does self[identifier] = some_value do in this code?
38,752,193
<p>I was just trying to learn K-ary tree implementation in Python and came across this link: <a href="http://www.quesucede.com/page/show/id/python-3-tree-implementation">http://www.quesucede.com/page/show/id/python-3-tree-implementation</a></p> <p>In the tree.py file, there is a section of code like this:</p> <pre><code>class Tree: def __init__(self): self.__nodes = {} @property def nodes(self): return self.__nodes def add_node(self, identifier, parent=None): node = Node(identifier) self[identifier] = node if parent is not None: self[parent].add_child(identifier) return node # ... ... def __getitem__(self, key): return self.__nodes[key] def __setitem__(self, key, item): self.__nodes[key] = item </code></pre> <p>What is <code>self[identifier]</code>? Is it a list? This is really confusing. Can someone explain and/or point me to some documentation of using self as a list?</p>
6
2016-08-03T19:33:22Z
38,752,558
<p>They are using the <code>__getitem__</code> magic method. This method is used in a class to allow its instances to use [] (indexer) operators for list indexing, dictionary lookups, or accessing ranges of values.</p> <p>In the fallowing sample, we have a list with some extra functionality like head and tail. Example taken from <a href="http://www.rafekettler.com/magicmethods.html" rel="nofollow">here</a>:</p> <pre><code>class FunctionalList: '''A class wrapping a list with some extra functional magic, like head, tail, init, last, drop, and take.''' def __init__(self, values=None): if values is None: self.values = [] else: self.values = values def __len__(self): return len(self.values) def __getitem__(self, key): # if key is of invalid type or value, the list values will raise the error return self.values[key] def __setitem__(self, key, value): self.values[key] = value def __delitem__(self, key): del self.values[key] def __iter__(self): return iter(self.values) def __reversed__(self): return FunctionalList(reversed(self.values)) def append(self, value): self.values.append(value) def head(self): # get the first element return self.values[0] def tail(self): # get all elements after the first return self.values[1:] def init(self): # get elements up to the last return self.values[:-1] def last(self): # get last element return self.values[-1] def drop(self, n): # get all elements except first n return self.values[n:] def take(self, n): # get first n elements return self.values[:n] </code></pre>
1
2016-08-03T19:58:20Z
[ "python" ]
In DRF(django-rest-framework), If model has two foreignkeyfield, is it possible to serialize?
38,752,198
<p>I made django project through DRF.</p> <p>On my struggling with DRF, I getting wonder that it is possible to serializing these models.</p> <p><strong>models.py</strong></p> <pre><code>class Post(models.Model): author = models.ForeignKey(User, related_name='related_postwriter') title = models.CharField(max_length=200, blank = False) text = models.TextField(blank = True) created_date = models.DateTimeField( default=timezone.now ) point = models.PointField(null=False, blank=True) def __str__(self): # __unicode__ on Python 2 return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post', related_name='related_comments') author = models.ForeignKey(User, related_name='related_commentwriter') text = models.TextField(max_length=500) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.text </code></pre> <p>There are two ForeignKey field in Comment model, i think it is maybe the reason serializer.py is very hard to deal with.</p> <p><strong>serializers.py</strong></p> <pre><code>class UserSerializer(serializers.ModelSerializer): posts = serializers.PrimaryKeyRelatedField(many=True, read_only=True) comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = User fields = ('id', 'username', 'email', 'posts') class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'author', 'title', 'text', 'point') def create(self, validated_data): validated_data['author'] = self.context['request'].user return super(PostSerializer, self).create(validated_data) class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'post', 'author', 'text') def create(self, validated_data): validated_data['author'] = self.context['request'].user return super(CommentSerializer, self).create(validated_data) </code></pre> <p>I thought <code>comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)</code> have to be placed in <code>class PostSerializer(serializers.ModelSerializer):</code> also, but when i placed as i thought, there comes error <code>AssertionError at /posts/ The field 'comments' was declared on serializer PostSerializer, but has not been included in the 'fields' option.</code> so when i put 'comments' in ther field like </p> <pre><code>class PostSerializer(serializers.ModelSerializer): comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Post fields = ('id', 'author', 'title', 'text', 'point', 'comments') </code></pre> <p>then, -> <code>AttributeError at /posts/ 'Post' object has no attribute 'comments'</code> is occurred.</p> <p>What is my fault? </p> <p>Because I want make android app that user can read a post and comments 'related with the post' at the same time(like almost community websites, reddit, facebook...), <strong>serializers.py</strong> i posted is not enough. <strong>serializers.py</strong> i posted is not seems to be sufficient for reflecting relation between post and comment.</p> <p>Are there problem with comment model? Or am i wrong?</p> <p>I'm new, novice at programming, Please teach me. </p> <p>Thanks for reading.</p>
0
2016-08-03T19:33:42Z
38,752,275
<p>There is nothing wrong, you are just accessing the wrong attributes. If you look at your models, you define a related name to posts:</p> <p><code>post = models.ForeignKey('blog.Post', related_name='related_comments')</code></p> <p>So, when you write your serializer, the "field" you should be accessing should be the related name instead of comments. Change the serializer to:</p> <pre><code>class PostSerializer(serializers.ModelSerializer): related_comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Post fields = ('id', 'author', 'title', 'text', 'point', 'related_comments') </code></pre>
2
2016-08-03T19:38:36Z
[ "python", "django", "django-rest-framework" ]
In DRF(django-rest-framework), If model has two foreignkeyfield, is it possible to serialize?
38,752,198
<p>I made django project through DRF.</p> <p>On my struggling with DRF, I getting wonder that it is possible to serializing these models.</p> <p><strong>models.py</strong></p> <pre><code>class Post(models.Model): author = models.ForeignKey(User, related_name='related_postwriter') title = models.CharField(max_length=200, blank = False) text = models.TextField(blank = True) created_date = models.DateTimeField( default=timezone.now ) point = models.PointField(null=False, blank=True) def __str__(self): # __unicode__ on Python 2 return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post', related_name='related_comments') author = models.ForeignKey(User, related_name='related_commentwriter') text = models.TextField(max_length=500) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.text </code></pre> <p>There are two ForeignKey field in Comment model, i think it is maybe the reason serializer.py is very hard to deal with.</p> <p><strong>serializers.py</strong></p> <pre><code>class UserSerializer(serializers.ModelSerializer): posts = serializers.PrimaryKeyRelatedField(many=True, read_only=True) comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = User fields = ('id', 'username', 'email', 'posts') class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ('id', 'author', 'title', 'text', 'point') def create(self, validated_data): validated_data['author'] = self.context['request'].user return super(PostSerializer, self).create(validated_data) class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ('id', 'post', 'author', 'text') def create(self, validated_data): validated_data['author'] = self.context['request'].user return super(CommentSerializer, self).create(validated_data) </code></pre> <p>I thought <code>comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True)</code> have to be placed in <code>class PostSerializer(serializers.ModelSerializer):</code> also, but when i placed as i thought, there comes error <code>AssertionError at /posts/ The field 'comments' was declared on serializer PostSerializer, but has not been included in the 'fields' option.</code> so when i put 'comments' in ther field like </p> <pre><code>class PostSerializer(serializers.ModelSerializer): comments = serializers.PrimaryKeyRelatedField(many=True, read_only=True) class Meta: model = Post fields = ('id', 'author', 'title', 'text', 'point', 'comments') </code></pre> <p>then, -> <code>AttributeError at /posts/ 'Post' object has no attribute 'comments'</code> is occurred.</p> <p>What is my fault? </p> <p>Because I want make android app that user can read a post and comments 'related with the post' at the same time(like almost community websites, reddit, facebook...), <strong>serializers.py</strong> i posted is not enough. <strong>serializers.py</strong> i posted is not seems to be sufficient for reflecting relation between post and comment.</p> <p>Are there problem with comment model? Or am i wrong?</p> <p>I'm new, novice at programming, Please teach me. </p> <p>Thanks for reading.</p>
0
2016-08-03T19:33:42Z
38,752,835
<p>You can use <a href="http://www.django-rest-framework.org/api-guide/relations/#nested-relationships" rel="nofollow">Nested relationships</a></p>
1
2016-08-03T20:15:31Z
[ "python", "django", "django-rest-framework" ]
remove extra newline when writing to a file
38,752,220
<p>This little script writes keywords to a file, but adds an extra newline between each keyword. How do I make it stop? I.e. instead of</p> <pre><code>Apple Banana Crayon </code></pre> <p>I want </p> <pre><code>Apple Banana Crayon </code></pre> <p>I tried Googling "listwrite" but didn't help.</p> <p>I am sure this is a very simple thing but I can't figure it out.</p> <pre><code>#!/usr/local/bin/python ################################################### # nerv3.py # Goal: Named entity recognition script to pull names/place from text # called as python nerv3.py text_path_or_file # # Inputs: # path - text file or directory containing text files # output - output file name # uuid # Outputs: # Output file written # People, Places, Others files # ################################################### #gonna need to install AlchemyAPI import AlchemyAPI import argparse import xml.etree.ElementTree as ET import collections import codecs import os #from IPython import embed #================================================= def listwrite(output_file,thelist): for item in thelist: item.encode('utf-8') output_file.write("%s\n\n" % item) #================================================= def main(): tmpdir = "/tmp/pagekicker" #personal api key saved as api_key.txt parser = argparse.ArgumentParser() parser.add_argument('path', help = "target file or directory for NER") parser.add_argument('output', help = "target file for output") parser.add_argument('uuid', help = "uuid") args = parser.parse_args() in_file = args.path out_file = args.output uuid = args.uuid folder = os.path.join(tmpdir, uuid) print folder cwd = os.getcwd() apikey_location = os.path.join(cwd, "api_key.txt") with open(in_file) as f: text = f.read() alchemyObj = AlchemyAPI.AlchemyAPI() alchemyObj.loadAPIKey(apikey_location) result = alchemyObj.TextGetRankedNamedEntities(text) root = ET.fromstring(result) place_list = ['City', 'Continent', 'Country', 'Facility', 'GeographicFeature',\ 'Region', 'StateOrCounty'] People = {} Places = {} Other = {} for entity in root.getiterator('entity'): if entity[0].text == 'Person': People[entity[3].text]=[entity[1].text, entity[2].text] elif entity[0].text in place_list: Places[entity[3].text] = [entity[1].text, entity[2].text] else: Other[entity[3].text] = [entity[1].text, entity[2].text] #print lists ordered by relevance Places_s = sorted(Places, key = Places.get, reverse = True) People_s = sorted(People, key = People.get, reverse = True) Other_s = sorted(Other, key = Other.get, reverse = True) # here is where things seem to go awry with codecs.open(out_file, mode = 'w', encoding='utf-8') as o: listwrite(o, People_s) listwrite(o, Places_s) listwrite(o, Other_s) out_file = os.path.join(folder, 'People') with codecs.open(out_file, mode= 'w', encoding='utf-8') as o: listwrite(o, People_s) out_file = os.path.join(folder, 'Places') with codecs.open(out_file, mode= 'w', encoding='utf-8') as o: listwrite(o, Places_s) out_file = os.path.join(folder, 'Other') with codecs.open(out_file, mode= 'w', encoding='utf-8') as o: listwrite(o, Other_s) #================================================= if __name__ == '__main__': main() </code></pre>
-2
2016-08-03T19:35:10Z
38,752,272
<pre><code>def listwrite(output_file,thelist): for item in thelist: item.encode('utf-8') output_file.write("%s\n\n" % item) </code></pre> <p>In the code, listwrite is defined as a function. For every <code>item</code> in <code>thelist</code>, it writes the <code>item</code>, followed by two newline characters. To remove the extra line, simply remove one of the <code>\n</code>s.</p> <pre><code>def listwrite(output_file,thelist): for item in thelist: item.encode('utf-8') output_file.write("%s\n" % item) </code></pre>
2
2016-08-03T19:38:25Z
[ "python", "newline" ]
Dynamicly add a new subplot2grid to a figure
38,752,242
<p>I have an application that have 3 figures, and dynamicaly change them. For now it's been working fine by using <code>add_subplot()</code> to the figure. But now I have to make my graphs more complex, and need to use <code>subplot2grid()</code></p> <pre><code>self.figure1 = plt.figure() self.canvas1 = FigureCanvas(self.figure1) self.graphtoolbar1 = NavigationToolbar(self.canvas1, frameGraph1) self.figure3 = plt.figure() self.canvas3 = FigureCanvas(self.figure3) self.graphtoolbar3 = NavigationToolbar(self.canvas3, frameGraph3) self.figure4 = plt.figure() self.canvas4 = FigureCanvas(self.figure4) self.graphtoolbar4 = NavigationToolbar(self.canvas4, frameGraph4) </code></pre> <p>And here's the code that adds it, and what I've got so far.</p> <pre><code>#ax = self.figure1.add_subplot(2,1,1) &lt;---- What I used to do fig = self.figure1 ax = plt.subplot2grid((4,4), (0,0), rowspan=3, colspan=4) # &lt;--- what I'm trying to do ax.hold(False) ax.plot(df['Close'], 'b-') ax.legend(loc=0) ax.set_xlabel("Date") ax.set_ylabel("Price") ax.grid(True) for tick in ax.get_xticklabels(): tick.set_rotation(20) self.canvas1.draw() </code></pre> <p>The above adds it to figure 4. Probably because that's the latest instantiated by plt. But I'd like the above to add a subplot2grid to <code>self.figure1</code>, while still having the dynamicly abilities as before.</p>
0
2016-08-03T19:36:56Z
38,752,824
<p>Looking into the source code of <code>matplotlib</code>, the <code>subplot2grid</code>-function is defined in the following way:</p> <pre><code>def subplot2grid(shape, loc, rowspan=1, colspan=1, **kwargs): """ Create a subplot in a grid. The grid is specified by *shape*, at location of *loc*, spanning *rowspan*, *colspan* cells in each direction. The index for loc is 0-based. :: subplot2grid(shape, loc, rowspan=1, colspan=1) is identical to :: gridspec=GridSpec(shape[0], shape[2]) subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan) subplot(subplotspec) """ fig = gcf() # &lt;-------- HERE s1, s2 = shape subplotspec = GridSpec(s1, s2).new_subplotspec(loc, rowspan=rowspan, colspan=colspan) a = fig.add_subplot(subplotspec, **kwargs) bbox = a.bbox byebye = [] for other in fig.axes: if other==a: continue if bbox.fully_overlaps(other.bbox): byebye.append(other) for ax in byebye: delaxes(ax) draw_if_interactive() return a </code></pre> <p>As you can see from my comment "HERE" in the code snippet, it is only using the active figure, i.e. <code>fig = gcf()</code> (gcf is short for "get current figure").</p> <p>Achieving your goal should be easily done by modifying the function slightly and put it into your script.</p> <pre><code>from matplotlib.gridspec import GridSpec from matplotlib.backends import pylab_setup _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup() def my_subplot2grid(fig, shape, loc, rowspan=1, colspan=1, **kwargs): s1, s2 = shape subplotspec = GridSpec(s1, s2).new_subplotspec(loc, rowspan=rowspan, colspan=colspan) a = fig.add_subplot(subplotspec, **kwargs) bbox = a.bbox byebye = [] for other in fig.axes: if other==a: continue if bbox.fully_overlaps(other.bbox): byebye.append(other) for ax in byebye: delaxes(ax) draw_if_interactive() return a </code></pre> <p>Now it should be possible to do your thing, with a modification to your function call as</p> <pre><code>ax = plt.my_subplot2grid(self.figure1, (4,4), (0,0), rowspan=3, colspan=4) </code></pre> <p>Hope it helps!</p>
1
2016-08-03T20:14:48Z
[ "python", "matplotlib" ]
How do I set a global variable via function call?
38,752,431
<p>I am trying to change the value of global variable <code>edl_loading</code> to <code>True</code> in function <code>edl_flashing</code> ,somehow it doesn't work?can anyone help understand why does <code>print edl_loading</code> prints <code>False</code> after call to <code>edl_flashing</code> in which I change the value to <code>True</code></p> <pre><code>def edl_flashing(): edl_loading = True print edl_loading def main (): global edl_loading edl_loading = False print edl_loading edl_flashing() print edl_loading #Why this prints as False if __name__ == '__main__': main() </code></pre> <p>OUTPUT:-</p> <pre><code>False True False </code></pre>
1
2016-08-03T19:49:10Z
38,752,484
<p>You need to use the <code>global</code> in both of your functions - <code>main</code> and <code>edl_flashing</code></p> <pre><code>def edl_flashing(): global edl_loading edl_loading = True print edl_loading </code></pre> <p>Without the global declaration in the function, the variable name is local to the function.</p> <p>The above change prints out</p> <pre><code>False True True </code></pre>
1
2016-08-03T19:53:31Z
[ "python" ]
get mean for all columns in a dataframe and create a new dataframe
38,752,444
<p>I have a dataframe with only numeric values and I want to calculate the mean for every column and create a new dataframe.<br> The original dataframe is indexed by a datetimefield. The new dataframe should be indexed by the same field as original dataframe with a value equal to last row index of original dataframe.</p> <p>Code so far</p> <pre><code>mean_series=df.mean() df_mean= pd.DataFrame(stddev_series) df_mean.rename(columns=lambda x: 'std_dev_'+ x, inplace=True) </code></pre> <p>but this gives an error</p> <pre><code>df_mean.rename(columns=lambda x: 'std_mean_'+ x, inplace=True) TypeError: ufunc 'add' did not contain a loop with signature matching types dtype('S21') dtype('S21') dtype('S21') </code></pre>
0
2016-08-03T19:50:23Z
38,752,851
<p>Your question implies that you want a new DataFrame with a single row.</p> <pre><code>In [10]: df.head(10) Out[10]: 0 1 2 3 2011-01-01 00:00:00 0.182481 0.523784 0.718124 0.063792 2011-01-01 01:00:00 0.321362 0.404686 0.481889 0.524521 2011-01-01 02:00:00 0.514426 0.735809 0.433758 0.392824 2011-01-01 03:00:00 0.616802 0.149099 0.217199 0.155990 2011-01-01 04:00:00 0.525465 0.439633 0.641974 0.270364 2011-01-01 05:00:00 0.749662 0.151958 0.200913 0.219916 2011-01-01 06:00:00 0.665164 0.396595 0.980862 0.560119 2011-01-01 07:00:00 0.797803 0.377273 0.273724 0.220965 2011-01-01 08:00:00 0.651989 0.553929 0.769008 0.545288 2011-01-01 09:00:00 0.692169 0.261194 0.400704 0.118335 In [11]: df.tail() Out[11]: 0 1 2 3 2011-01-03 19:00:00 0.247211 0.539330 0.734206 0.781125 2011-01-03 20:00:00 0.278550 0.534943 0.804949 0.137291 2011-01-03 21:00:00 0.602246 0.108791 0.987120 0.455887 2011-01-03 22:00:00 0.003097 0.436435 0.987877 0.046066 2011-01-03 23:00:00 0.604916 0.670532 0.513927 0.610775 In [12]: df.mean() Out[12]: 0 0.495307 1 0.477509 2 0.562590 3 0.447997 dtype: float64 In [13]: new_df = pd.DataFrame(df.mean().to_dict(),index=[df.index.values[-1]]) In [14]: new_df Out[14]: 0 1 2 3 2011-01-03 23:00:00 0.495307 0.477509 0.56259 0.447997 In [15]: new_df.rename(columns=lambda c: "mean_"+str(c)) Out[15]: mean_0 mean_1 mean_2 mean_3 2011-01-03 23:00:00 0.495307 0.477509 0.56259 0.447997 </code></pre>
2
2016-08-03T20:16:09Z
[ "python", "dataframe", "series" ]
CSRF token cookie vulnerabilities during security scan
38,752,546
<p>I am making a simple website for my employer using Django, and I had to run the code through a security scan to test for vulnerabilities. One of the issues is cookie vulnerabilities that I can find documentation to find for.</p> <p>The cookie vulnerabilities are raised when logging in to my website.</p> <p>Here is the error - the scan is run by OCIO-Internet-Scan</p> <blockquote> <p>CVSS: 5.0 Message: csrftoken Cookie has problem(s) <code>csrftoken =</code> <code>J4S6ZO7ssz4TUIlRNv9d95mCFomAbXO1; Host = [removed] Path = /</code></p> <ol> <li>Cookie can be cached.</li> <li>Cookie is persistent. Cookie expires at : Wed, 07 Jun 2017</li> </ol> <p>Persistent session-handling cookies: When a session-handling cookie is set persistently, it allows the cookie to be valid even after a user terminates a session. Therefore an attacker can use a session cookie stored as a text file by the browser to access restricted information. Cacheable cookies: A cachable cookie could be cached at a proxy or a gateway. It can result in serving a cookie value that is out of date or stale. An attacker may also steal such cookies if he has compromised that proxy or gateway.</p> </blockquote> <p>My question is, where exactly can I make changes to the csrftoken behavior for this? I can't find it using google, and I cannot bring the website up until this is fixed. Am I even able to change how csrf acts to accommodate these errors?</p>
2
2016-08-03T19:57:16Z
38,752,679
<p>It sounds like you want to change the <a href="https://docs.djangoproject.com/en/1.9/ref/settings/#csrf-cookie-age"><code>CSRF_COOKIE_AGE</code></a> setting to <code>None</code>:</p> <blockquote> <p>Default: <strong>31449600</strong> (approximately 1 year, in seconds)</p> <p>The age of CSRF cookies, in seconds.</p> <p>The reason for setting a long-lived expiration time is to avoid problems in the case of a user closing a browser or bookmarking a page and then loading that page from a browser cache. Without persistent cookies, the form submission would fail in this case.</p> <p>Some browsers (specifically Internet Explorer) can disallow the use of persistent cookies or can have the indexes to the cookie jar corrupted on disk, thereby causing CSRF protection checks to (sometimes intermittently) fail. <em>Change this setting to <strong>None</strong> to use session-based CSRF cookies, which keep the cookies in-memory instead of on persistent storage.</em></p> </blockquote> <p>That will cause it to be a session cookie instead of a persistent cookie. Session cookies don't have an expiration date so the browser holds them in memory for the current browser session only and then deletes them when the session is over.</p> <p>You can find info on how to change the Django setting <a href="https://docs.djangoproject.com/en/1.9/topics/settings/">here</a>.</p>
5
2016-08-03T20:05:28Z
[ "python", "django", "security", "cookies" ]
output file with names from groupby results pandas python
38,752,592
<p>i have a sample dataset:</p> <pre><code>import pandas as pd df = {'READID': [1,1,1 ,1,1 ,5,5 ,5,5], 'VG': ['LV5-F*01','LV5-F*01' ,'LV5-F*01','LV5-F*01','LV5-F*01','LV5-A*01','LV5-A*01','LV5-A*01','LV5-A*01'], 'Pro': [1,1,1,1,1,2,2,2,2]} df = pd.DataFrame(df) </code></pre> <p>it looks like :</p> <pre><code>df Out[23]: Pro READID VG 0 1 1 LV5-F*01 1 1 1 LV5-F*01 2 1 1 LV5-F*01 3 1 1 LV5-F*01 4 1 1 LV5-F*01 5 2 5 LV5-A*01 6 2 5 LV5-A*01 7 2 5 LV5-A*01 8 2 5 LV5-A*01 </code></pre> <p>This is a sample dataset, the actual dataset contains many more columns and many many more rows with different combinations for the groupby, i want to groupby the 3 columns and output individual separate files with the VG as part of its name:</p> <p>desired output:</p> <pre><code>'LV5-F*01.txt': Pro READID VG 0 1 1 LV5-F*01 1 1 1 LV5-F*01 2 1 1 LV5-F*01 3 1 1 LV5-F*01 4 1 1 LV5-F*01 'LV5-A*01.txt': Pro READID VG 5 2 5 LV5-A*01 6 2 5 LV5-A*01 7 2 5 LV5-A*01 8 2 5 LV5-A*01 </code></pre> <p>My attempt:</p> <pre><code>(df.groupby(['READID','VG','Pro']) .apply(lambda gp: gp.to_csv('{}.txt'.format(gp.VG.name), sep='\t', index=False)) ) </code></pre> <p>however, the </p> <pre><code> '{}.txt'.format(gp.VG.name) </code></pre> <p>part only produced a file named 'VG.txt' containing only 1 line which is not what i want. </p>
1
2016-08-03T20:00:19Z
38,752,660
<p>You don't need groupby, you can just select the rows you need and convert them to text file.</p> <pre><code>import pandas as pd df = {'READID': [1,1,1 ,1,1 ,5,5 ,5,5], 'VG': ['LV5-F*01','LV5-F*01' ,'LV5-F*01','LV5-F*01','LV5-F*01','LV5-A*01','LV5-A*01','LV5-A*01','LV5-A*01'], 'Pro': [1,1,1,1,1,2,2,2,2]} df = pd.DataFrame(df) with open('LV5-F*01.txt', 'w') as fil: fil.write(df[df['VG'] == 'LV5-F*01'].to_string()) with open('LV5-A*01.txt', 'w') as fil: fil.write(df[df['VG'] == 'LV5-A*01'].to_string()) </code></pre>
0
2016-08-03T20:04:23Z
[ "python", "pandas" ]
output file with names from groupby results pandas python
38,752,592
<p>i have a sample dataset:</p> <pre><code>import pandas as pd df = {'READID': [1,1,1 ,1,1 ,5,5 ,5,5], 'VG': ['LV5-F*01','LV5-F*01' ,'LV5-F*01','LV5-F*01','LV5-F*01','LV5-A*01','LV5-A*01','LV5-A*01','LV5-A*01'], 'Pro': [1,1,1,1,1,2,2,2,2]} df = pd.DataFrame(df) </code></pre> <p>it looks like :</p> <pre><code>df Out[23]: Pro READID VG 0 1 1 LV5-F*01 1 1 1 LV5-F*01 2 1 1 LV5-F*01 3 1 1 LV5-F*01 4 1 1 LV5-F*01 5 2 5 LV5-A*01 6 2 5 LV5-A*01 7 2 5 LV5-A*01 8 2 5 LV5-A*01 </code></pre> <p>This is a sample dataset, the actual dataset contains many more columns and many many more rows with different combinations for the groupby, i want to groupby the 3 columns and output individual separate files with the VG as part of its name:</p> <p>desired output:</p> <pre><code>'LV5-F*01.txt': Pro READID VG 0 1 1 LV5-F*01 1 1 1 LV5-F*01 2 1 1 LV5-F*01 3 1 1 LV5-F*01 4 1 1 LV5-F*01 'LV5-A*01.txt': Pro READID VG 5 2 5 LV5-A*01 6 2 5 LV5-A*01 7 2 5 LV5-A*01 8 2 5 LV5-A*01 </code></pre> <p>My attempt:</p> <pre><code>(df.groupby(['READID','VG','Pro']) .apply(lambda gp: gp.to_csv('{}.txt'.format(gp.VG.name), sep='\t', index=False)) ) </code></pre> <p>however, the </p> <pre><code> '{}.txt'.format(gp.VG.name) </code></pre> <p>part only produced a file named 'VG.txt' containing only 1 line which is not what i want. </p>
1
2016-08-03T20:00:19Z
38,752,953
<pre><code>g = df.groupby(['READID','VG','Pro']) for group in g: group[1].to_csv('{}.txt'.format(group[0][1]), sep='\t', index=False) </code></pre> <p>You might want to strip <code>*</code> character if it causes problems.</p> <p>Also note that you group on three keys but using only one key as the file name. It may overwrite other files with the same key.</p>
0
2016-08-03T20:22:41Z
[ "python", "pandas" ]
Merge Dataframe by regular expression or fuzzy match
38,752,653
<p>I have d1 and d2 and I want to merge the two by ID column. However, the ID and ID2 are not exactly match. Instead, ID is the first 8 digit of ID2 (sometimes it can be the first 6 digit, or sometimes it can be one or two digit different).</p> <p>I understand that I can pre-process ID2 to keep only the first 8 digit. However, I cannot handle all the situations.</p> <p>I wonder is there an advanced way to merge through regular expression for fuzzy match? say, if the first 6 digits match, then merge?</p> <pre><code>d1=pd.DataFrame({'ID':['00846U10','01381710'], 'count':[100,200]}) d2=pd.DataFrame({'ID2':['00846U101','013817101','02376R102'], 'value':[1,5,6]}) </code></pre>
2
2016-08-03T20:03:45Z
38,752,724
<p>dude,</p> <p>I have had the same problem and the only solution is to use other python packages. Have a look at <code>fuzzywuzzy</code> for instance. Its very good.</p> <p>The general idea is that, for every row in d1, you will look for the row in d2 that has the highest fuzzy matching score.</p>
1
2016-08-03T20:08:17Z
[ "python", "regex", "pandas", "merge", "fuzzy" ]
Python Tkinter GUI Calculator
38,752,665
<p>So I am currently in the process of making a GUI Calculator, but am unsure on how to write code that will perform the operations of the calculator. Right now I currently have setup the window, entry box, and calculator buttons, but none of them actually do anything at the moment. </p> <p>I am just confused on how these buttons are represented in code and so I am not sure how to write a block of code that will be able to read in these button inputs and perform addition,subtraction, etc. </p> <p>Here is my code so far </p> <pre><code>class Calculator(Frame): def __init__(self,master): Frame.__init__(self,master) self.grid() self.dataEnt = Entry(self) self.dataEnt.grid(row = 0, column = 1, columnspan = 4) labels =[['AC','%','/'], ['7','8','9','*'], ['4','5','6','-'], ['1','2','3','+'], ['0','.','=']] label = Button(self,relief = RAISED, padx = 10, text = labels[0][0]) #AC label.grid(row = 1, column = 0, columnspan = 2) label = Button(self,relief = RAISED, padx = 10, text = labels[0][1]) # % label.grid(row = 1, column = 3) label = Button(self,relief = RAISED, padx = 10, text = labels[0][2]) # / label.grid(row = 1, column = 4) for r in range(1,4): for c in range(4): #create label for row r and column c label = Button(self,relief = RAISED, padx = 10, text = labels[r][c]) # 789* 456- 123+ # place label in row r and column c label.grid(row = r+1, column = c+1) label = Button(self,relief = RAISED, padx = 10, text = labels[4][0]) #0 label.grid(row = 5, column = 0, columnspan = 2) label = Button(self,relief = RAISED, padx = 10, text = labels[4][1]) # . label.grid(row = 5, column = 3) label = Button(self,relief = RAISED, padx = 10, text = labels[4][2]) # = label.grid(row = 5, column = 4) def operations(self,num ): def main(): root = Tk() root.title('Calculator') obj = Calculator(root) root.mainloop() </code></pre> <p><a href="http://i.stack.imgur.com/Oq7sV.png" rel="nofollow">and here is what the calculator looks like so far</a></p> <p>My guess is that I need to somehow be able to read the input as a string and then have python evaluate that string as a mathematical expression but I am not sure how to go about it. </p> <p>Thanks for any help!</p>
-1
2016-08-03T20:04:34Z
38,753,030
<p>What you could do is <em>bind</em> all buttons to a method that identifies the button and append a string to a list or evaluate the expression. This list could then be displayed in the label.</p> <pre><code>def button_press(self, event): widget = event.widget text = widget["text"] if text != "AC" and text != "=": self.operations.append(text) elif text == "AC": self.operations = [] # Clear the list. elif text == "=": self.evaluate() self.label["text"] = "".join(self.operations) def evaluate(self): try: self.operations = [str(eval("".join(self.operations)))] except (ArithmeticError, SyntaxError, TypeError, NameError): self.operations = ["ERROR"] </code></pre> <p>This code cannot just be pasted in to your program, it's just to demonstrate how you could solve the problem.</p>
0
2016-08-03T20:27:27Z
[ "python", "user-interface", "tkinter", "calculator", "operator-keyword" ]
How to flatten a nested "homogeneous" list
38,752,696
<p>I have read <a href="http://stackoverflow.com/q/10823877/3001761">What is the fastest way to flatten arbitrarily nested lists in Python?</a>, which provides good answers on how to flatten arbitrarily nested lists in Python. However, a lot of the time, lists are nested to an arbitrary depth but homogeneous. A homogeneous nested list has identical structure between all list elements that are at the same depth.</p> <ul> <li>This is a homogeneous list: <code>[[0, 1], [2, 3]]</code></li> <li>This is not a homogeneous list: <code>[0, 1, [2, 3]]</code></li> </ul> <p>The best way to flatten such lists of low depth is the idiomatic list comprehension: <code>[inner for outer in seq for inner in outer]</code> This quickly becomes unwieldy for larger depths, taking up many lines to express a simple idea. Consider: <code>[more_inner inner for outer in seq for inner in outer for more_inner in inner]</code> This is hard to follow, and it is an eyesore.</p> <p>For this common special case, can we come up with a specific solution that is both readable and efficient?</p>
-3
2016-08-03T20:06:26Z
38,752,697
<p>Here is my solution:</p> <pre><code>def homo_flat( seq ): first = 0 while True: if type( seq[ first ] ) not in [ list, tuple ]: return seq else: seq = [ inner for outer in seq for inner in outer ] </code></pre>
-5
2016-08-03T20:06:26Z
[ "python", "list" ]
Convert spreadsheet to nested dictionary form for D3
38,752,756
<p>Having trouble with this one. Feel as though I've whipped through similar transformations of data, but this one is throwing me for a <em>loop</em>.</p> <p>Looking to convert a spreadsheet data into a nested JSON that will be used for a D3 visualization, seen it referred to as "<a href="https://gist.github.com/mbostock/1093025" rel="nofollow">flare.json</a>".</p> <p>The target JSON would look something like this (where, obviously, a dictionary would be just as good):</p> <pre><code>{ "name": "root", "children": [ { "name": "A1", "children": [ { "name": "A2", "children": [ { "name": "A3", "children": [ { "name": "A4", "children": [ ] } ] } ] } ] }, { "name": "B1", "children": [ { "name": "B2", "children": [ { "name": "B3", "children": [ { "name": "B4", "children": [ ] } ] } ] } ] } ] } </code></pre> <p>I'm pulling data from a spreadsheet with <a href="https://openpyxl.readthedocs.io/en/default/" rel="nofollow">openpyxl</a> that provides a root tuple that contains tuples of each column value.</p> <p>e.g.</p> <pre><code>( ('A1','A2','A3','A4'), ('B1','B2','B3','B4'), ) </code></pre> <p>I know there are 101 different ways to do this, considered using dataframes from <a href="http://pandas.pydata.org/" rel="nofollow">pandas</a>, and I'm sure <a href="https://openpyxl.readthedocs.io/en/default/" rel="nofollow">openpyxl</a> has a myriad of methods and conversions for this kind of thing. But for whatever reason, having a hard time envisioning this process today. Thanks in advance.</p>
0
2016-08-03T20:10:45Z
38,753,169
<p>This should do it:</p> <pre><code>def convert_data(data): out = {'name': 'root', 'children': []} for row in data: out['children'].append({}) current = out['children'] for value in row: current[-1]['name'] = value current[-1]['children'] = [{}] current = current[-1]['children'] return out data = (('A1','A2','A3','A4'), ('B1','B2','B3','B4')) new_structure = convert_data(data) </code></pre> <p>You can obviously use something like <a href="https://docs.python.org/3/library/json.html#json.dumps" rel="nofollow"><code>json.dumps</code></a> to output it as a JSON string.</p>
1
2016-08-03T20:36:38Z
[ "python", "d3.js", "nested-loops" ]
Return True every other weekend, return False any other day
38,752,837
<p>I'm trying to make a script that will run every other weekend, I've tried using datetime for that (a solution I found on the internet, likewise), but it always prints the entire week.</p> <pre><code>from datetime import date, timedelta reference_monday = date(2016, 1, 8) # any monday of a "week one" schedule = [[True, True, True, True, True, True, True], [True, True, True, True, True, False, False]] def check_date(d): return schedule[abs(d - reference_monday).days / 7 % 2][d.weekday()] start = date(2012, 6, 4) for w in range(6): thisweek = start + timedelta(weeks=w) print 'week of', thisweek, ':', print ','.join(str(check_date(thisweek + timedelta(days=d))) for d in range(7)) </code></pre> <p>it returns</p> <pre><code>week of 2012-06-04 : True,True,True,True,True,True,True week of 2012-06-11 : True,True,True,True,True,False,False week of 2012-06-18 : True,True,True,True,True,True,True week of 2012-06-25 : True,True,True,True,True,False,False week of 2012-07-02 : True,True,True,True,True,True,True week of 2012-07-09 : True,True,True,True,True,False,False </code></pre> <p>I would like it to return either true or false, depending on that current day.</p>
1
2016-08-03T20:15:38Z
38,752,960
<p>As stated in the comments, there are better alternatives to scheduling tasks. </p> <p>Is this what you want?</p> <pre><code>def check_date(d): return not schedule[abs(d - reference_monday).days / 7 % 2][d.weekday()] </code></pre> <p>Output</p> <pre><code>week of 2012-06-04 : False,False,False,False,False,False,False week of 2012-06-11 : False,False,False,False,False,True,True week of 2012-06-18 : False,False,False,False,False,False,False week of 2012-06-25 : False,False,False,False,False,True,True week of 2012-07-02 : False,False,False,False,False,False,False week of 2012-07-09 : False,False,False,False,False,True,True </code></pre> <blockquote> <p>I would like it to return either true or false, depending on that current day</p> </blockquote> <pre><code>start = date(2012, 6, 4) for w in range(6): thisweek = start + timedelta(weeks=w) print 'week of', thisweek, ':', # Only Saturday and Sunday run_sat = check_date(thisweek + timedelta(days=5)) run_sun = check_date(thisweek + timedelta(days=6)) print "{:5} | {:5}".format(str(run_sat), str(run_sun)) </code></pre> <p>Outputs</p> <pre><code>week of 2012-06-04 : False | False week of 2012-06-11 : True | True week of 2012-06-18 : False | False week of 2012-06-25 : True | True week of 2012-07-02 : False | False week of 2012-07-09 : True | True </code></pre>
0
2016-08-03T20:22:58Z
[ "python" ]
y axis of heat map not inverting in Python
38,752,844
<p>I'm generating 4 heat maps using subplots and want the y-axis inverted. I'm using <code>ax[i].invert_yaxis()</code> but it doesn't seem to be working. An example of the code is below:</p> <pre><code>everything = [data_y_axis, data_length, data_roundness, data_y_SDev] legend = ['title1', 'title2', 'title3', 'title4'] fig, ax = plt.subplots(nrows = 1, ncols = 4, sharex = False, sharey = True, figsize = (13,3)) ax = ax.flatten() for i, v in enumerate(everything): heatmap = ax[i].pcolor(v, cmap=plt.cm.Blues) ax[i].invert_yaxis() ax[i].xaxis.tick_top() ax[i].set_xticks(np.arange(v.shape[1])+0.5, minor=False) ax[i].set_xticklabels(column_labels, minor=False) ax[i].set_yticks(np.arange(v.shape[0])+0.5, minor=False) ax[i].set_yticklabels(row_labels, minor=False, fontproperties = titlefont) ax[i].set_xticklabels(column_labels, minor=False, fontproperties = titlefont) cb = fig.colorbar(heatmap, orientation='horizontal', pad=0.02, ax = ax[i]) cb.set_label(label = legend[i], fontproperties = titlefont) cb.outline.set_linewidth(2) </code></pre> <p>The items in <code>everything</code> are just np.arrays, all of which have the same shape of (4, 6).</p> <p>It's currently producing maps like this:<a href="http://i.stack.imgur.com/wJg78.png" rel="nofollow"><img src="http://i.stack.imgur.com/wJg78.png" alt="enter image description here"></a> and should look like this: <a href="http://i.stack.imgur.com/08URE.png" rel="nofollow"><img src="http://i.stack.imgur.com/08URE.png" alt="enter image description here"></a>.</p> <p>Have I done something obviously wrong?</p>
1
2016-08-03T20:15:56Z
38,753,354
<p>Aha. I have solved it. I removed <code>ax[i].invert_yaxis()</code> from within the <code>for</code> loop and stuck it at the end. It now works:</p> <pre><code>for i, v in enumerate(everything): heatmap = ax[i].pcolor(v, cmap=plt.cm.Blues) ax[i].xaxis.tick_top() ax[i].set_xticks(np.arange(v.shape[1])+0.5, minor=False) ax[i].set_xticklabels(column_labels, minor=False) ax[i].set_yticks(np.arange(v.shape[0])+0.5, minor=False) ax[i].set_yticklabels(row_labels, minor=False, fontproperties = titlefont) ax[i].set_xticklabels(column_labels, minor=False, fontproperties = titlefont) cb = fig.colorbar(heatmap, orientation='horizontal', pad=0.02, ax = ax[i]) cb.set_label(label = legend[i], fontproperties = titlefont) cb.outline.set_linewidth(2) ax[0].invert_yaxis() </code></pre>
0
2016-08-03T20:48:56Z
[ "python", "matplotlib", "heatmap" ]
Pandas Date Conditional Calculation
38,753,047
<p>I am trying to create a column in pandas based off of a conditional statement that calculates time between two events. I was able to work out the day calculation but when plugged into my conditional statement:</p> <pre><code>def defect_age(df): if df['Status'] == 'R': return (pd.to_datetime(df['resolved_on'], errors='coerce') - pd.to_datetime(df['submitted_on'])) / np.timedelta64(1, 'D') else: return 'null' </code></pre> <p>And later called by the column:</p> <pre><code>group_df['Age'] = group_df.apply(defect_age(group_df), axis=0) </code></pre> <p>I am getting the following error:</p> <pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p>I tried to base mine on the question asked <a href="http://stackoverflow.com/questions/27041724/using-conditional-to-generate-new-column-in-pandas-dataframe">HERE</a>...But I am not having much success. Any help is appreciated!</p>
1
2016-08-03T20:28:30Z
38,753,381
<p>Do it like this :</p> <pre><code>group_df['Age'] = group_df.apply(lambda row:defect_age(row), axis=1) </code></pre> <p>This is because you want to apply the function to each row not to the whole dataframe at once.</p> <p><code>df['Status'] == 'R'</code> will give a list of booleans if applied on a dataframe and u cant put a list of booleans in an if expression</p>
1
2016-08-03T20:50:50Z
[ "python", "datetime", "pandas", "conditional" ]
Pandas Date Conditional Calculation
38,753,047
<p>I am trying to create a column in pandas based off of a conditional statement that calculates time between two events. I was able to work out the day calculation but when plugged into my conditional statement:</p> <pre><code>def defect_age(df): if df['Status'] == 'R': return (pd.to_datetime(df['resolved_on'], errors='coerce') - pd.to_datetime(df['submitted_on'])) / np.timedelta64(1, 'D') else: return 'null' </code></pre> <p>And later called by the column:</p> <pre><code>group_df['Age'] = group_df.apply(defect_age(group_df), axis=0) </code></pre> <p>I am getting the following error:</p> <pre><code>ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). </code></pre> <p>I tried to base mine on the question asked <a href="http://stackoverflow.com/questions/27041724/using-conditional-to-generate-new-column-in-pandas-dataframe">HERE</a>...But I am not having much success. Any help is appreciated!</p>
1
2016-08-03T20:28:30Z
38,753,438
<p>Try using this definition of <code>defect_age</code></p> <pre><code>def defect_age(df): resolved = pd.to_datetime(df.resolved_on, errors='coerce') submitted = pd.to_datetime(df.submitted_on) r = (resolved - submitted) / np.timedelta64(1, 'D') return np.where(df.Status == 'R', r, np.nan) </code></pre> <p>The error was coming from <code>if df['Status'] == 'R'</code></p> <p>This would have been a series of boolean values and not a single boolean value that <code>if</code> needs. You still want to run this over the whole series at once. I hope I've given you something that does the trick.</p>
1
2016-08-03T20:54:13Z
[ "python", "datetime", "pandas", "conditional" ]
alternative to numpy.gradient
38,753,066
<p>I have been struggling to find a robust function to compute gradient for a 3D array. numpy.gradient supports up to 2nd order accuracy. Is there any alternative way to compute the gradient with a better accuracy? thanks.</p>
2
2016-08-03T20:30:06Z
38,753,582
<p>I would suggest using the symbolic library called <em>Theano</em> (<a href="http://deeplearning.net/software/theano/" rel="nofollow">http://deeplearning.net/software/theano/</a>). It is primarily designed for neural networks and deep learning stuff, yet quite nicely fits what you want. </p> <p>After installing theano, here is a simple code for computing the gradient of a 1-d vector. You can extend it to 3-d yourself.</p> <pre><code> import numpy as np import theano import theano.tensor as T x = T.dvector('x') J, updates = theano.scan(lambda i, x : (x[i+1] - x[i])/2, sequences=T.arange(x.shape[0] - 1), non_sequences=[x]) f = theano.function([x], J, updates=updates) f(np.array([1, 2, 4, 7, 11, 16], dtype='float32')) f(np.array([1, 2, 4, 7.12345, 11, 16], dtype='float32')) </code></pre>
1
2016-08-03T21:02:55Z
[ "python", "gradient", "numerical-methods" ]
alternative to numpy.gradient
38,753,066
<p>I have been struggling to find a robust function to compute gradient for a 3D array. numpy.gradient supports up to 2nd order accuracy. Is there any alternative way to compute the gradient with a better accuracy? thanks.</p>
2
2016-08-03T20:30:06Z
38,766,576
<p>Finally I found this: 4th order gradient. Wish numpy would integrate this, too...</p> <p><a href="https://gist.github.com/deeplycloudy/1b9fa46d5290314d9be02a5156b48741" rel="nofollow">https://gist.github.com/deeplycloudy/1b9fa46d5290314d9be02a5156b48741</a></p> <pre><code>def gradientO4(f, *varargs): """Calculate the fourth-order-accurate gradient of an N-dimensional scalar function. Uses central differences on the interior and first differences on boundaries to give the same shape. Inputs: f -- An N-dimensional array giving samples of a scalar function varargs -- 0, 1, or N scalars giving the sample distances in each direction Outputs: N arrays of the same shape as f giving the derivative of f with respect to each dimension. """ N = len(f.shape) # number of dimensions n = len(varargs) if n == 0: dx = [1.0]*N elif n == 1: dx = [varargs[0]]*N elif n == N: dx = list(varargs) else: raise SyntaxError, "invalid number of arguments" # use central differences on interior and first differences on endpoints #print dx outvals = [] # create slice objects --- initially all are [:, :, ..., :] slice0 = [slice(None)]*N slice1 = [slice(None)]*N slice2 = [slice(None)]*N slice3 = [slice(None)]*N slice4 = [slice(None)]*N otype = f.dtype.char if otype not in ['f', 'd', 'F', 'D']: otype = 'd' for axis in range(N): # select out appropriate parts for this dimension out = np.zeros(f.shape, f.dtype.char) slice0[axis] = slice(2, -2) slice1[axis] = slice(None, -4) slice2[axis] = slice(1, -3) slice3[axis] = slice(3, -1) slice4[axis] = slice(4, None) # 1D equivalent -- out[2:-2] = (f[:4] - 8*f[1:-3] + 8*f[3:-1] - f[4:])/12.0 out[slice0] = (f[slice1] - 8.0*f[slice2] + 8.0*f[slice3] - f[slice4])/12.0 slice0[axis] = slice(None, 2) slice1[axis] = slice(1, 3) slice2[axis] = slice(None, 2) # 1D equivalent -- out[0:2] = (f[1:3] - f[0:2]) out[slice0] = (f[slice1] - f[slice2]) slice0[axis] = slice(-2, None) slice1[axis] = slice(-2, None) slice2[axis] = slice(-3, -1) ## 1D equivalent -- out[-2:] = (f[-2:] - f[-3:-1]) out[slice0] = (f[slice1] - f[slice2]) # divide by step size outvals.append(out / dx[axis]) # reset the slice object in this dimension to ":" slice0[axis] = slice(None) slice1[axis] = slice(None) slice2[axis] = slice(None) slice3[axis] = slice(None) slice4[axis] = slice(None) if N == 1: return outvals[0] else: return outvals </code></pre>
0
2016-08-04T11:50:40Z
[ "python", "gradient", "numerical-methods" ]
PyQt - Animations without redrawing everything?
38,753,131
<p>So I'm trying to learn animations in PyQt and throughout all the examples I can find online, they all seem to use the <code>self.update()</code> or <code>self.repaint()</code> methods to increment the animations. This means basically the code has to erase then redraw the entire widget for every frame, even though much of what I intend to animate is static.</p> <p>For example the code below, this generates a circular progress pie. The important bit is the <code>paint()</code> method under <code>ProgressMeter</code> (first class): for every frame in the animation this example paints the background, the actual progress pie, and the percentage indicator. </p> <p>If I change the code to something like:</p> <pre><code>if self.angle &gt; 120: # do not draw background </code></pre> <p>then after 120 frames, the background does not get drawn anymore.</p> <p>This seems terribly inefficient because (logically) the background should only be drawn once, no? </p> <p>What would you recommend for animations like these?</p> <p>Addendum: I have lurked a lot on this site to steal examples and code, but haven't posted for a long time. Please let me know about proper etiquette etc if I am not following it properly.</p> <pre><code>import sys from PyQt4 import QtGui, QtCore class ProgressMeter(QtGui.QGraphicsItem): def __init__(self, parent): super(ProgressMeter, self).__init__() self.parent = parent self.angle = 0 self.per = 0 def boundingRect(self): return QtCore.QRectF(0, 0, self.parent.width(), self.parent.height()) def increment(self): self.angle += 1 self.per = int(self.angle / 3.6) if self.angle &gt; 360: return False else: return True def paint(self, painter, option, widget): self.drawBackground(painter, widget) self.drawMeter(painter, widget) self.drawText(painter) def drawBackground(self, painter, widget): painter.setRenderHint(QtGui.QPainter.Antialiasing) painter.setPen(QtCore.Qt.NoPen) p1 = QtCore.QPointF(80, 80) g = QtGui.QRadialGradient(p1 * 0.2, 80 * 1.1) g.setColorAt(0.0, widget.palette().light().color()) g.setColorAt(1.0, widget.palette().dark().color()) painter.setBrush(g) painter.drawEllipse(0, 0, 80, 80) p2 = QtCore.QPointF(40, 40) g = QtGui.QRadialGradient(p2, 70 * 1.3) g.setColorAt(0.0, widget.palette().midlight().color()) g.setColorAt(1.0, widget.palette().dark().color()) painter.setBrush(g) painter.drawEllipse(7.5, 7.5, 65, 65) def drawMeter(self, painter, widget): painter.setPen(QtCore.Qt.NoPen) painter.setBrush(widget.palette().highlight().color()) painter.drawPie(7.5, 7.5, 65, 65, 0, -self.angle * 16) def drawText(self, painter): text = "%d%%" % self.per font = painter.font() font.setPixelSize(11) painter.setFont(font) brush = QtGui.QBrush(QtGui.QColor("#000000")) pen = QtGui.QPen(brush, 1) painter.setPen(pen) # size = painter.fontMetrics().size(QtCore.Qt.TextSingleLine, text) painter.drawText(0, 0, 80, 80, QtCore.Qt.AlignCenter, text) class MyView(QtGui.QGraphicsView): def __init__(self): super(MyView, self).__init__() self.initView() self.setupScene() self.setupAnimation() self.setGeometry(300, 150, 250, 250) def initView(self): self.setWindowTitle("Progress meter") self.setRenderHint(QtGui.QPainter.Antialiasing) policy = QtCore.Qt.ScrollBarAlwaysOff self.setVerticalScrollBarPolicy(policy) self.setHorizontalScrollBarPolicy(policy) self.setBackgroundBrush(self.palette().window()) self.pm = ProgressMeter(self) self.pm.setPos(55, 55) def setupScene(self): self.scene = QtGui.QGraphicsScene(self) self.scene.setSceneRect(0, 0, 250, 250) self.scene.addItem(self.pm) self.setScene(self.scene) def setupAnimation(self): self.timer = QtCore.QTimeLine() self.timer.setLoopCount(0) self.timer.setFrameRange(0, 100) self.animation = QtGui.QGraphicsItemAnimation() self.animation.setItem(self.pm) self.animation.setTimeLine(self.timer) self.timer.frameChanged[int].connect(self.doStep) self.timer.start() def doStep(self, i): if not self.pm.increment(): self.timer.stop() self.pm.update() app = QtGui.QApplication([]) view = MyView() view.show() sys.exit(app.exec_()) </code></pre>
0
2016-08-03T20:34:20Z
38,765,868
<p>The Qt's documentation about QWidget repaint slot says:</p> <p><em>Repaints the widget directly by calling paintEvent() immediately, unless updates are disabled or the widget is hidden. We suggest only using repaint() if you need an immediate repaint, for example during animation. In almost all circumstances update() is better, as it permits Qt to optimize for speed and minimize flicker. Warning: If you call repaint() in a function which may itself be called from paintEvent(), you may get infinite recursion. The update() function never causes recursion.</em></p> <p>That should give you an answer about when to use or not repaint or update slots.</p> <p>About making animations I'd suggest you also to take a look to the <a href="http://doc.qt.io/qt-4.8/animation-overview.html" rel="nofollow">Qt4's animation framework</a> or <a href="http://doc.qt.io/qt-5/animation-overview.html" rel="nofollow">Qt5's animation framework</a>, which is a really powerful way to animate widgets on Qt.</p>
0
2016-08-04T11:16:41Z
[ "python", "qt", "user-interface", "animation", "pyqt" ]
How to search for text in Beautiful Soup
38,753,155
<p>Im trying to create a script that checks the stock of items on a website, im trying to locate every line that has "ATS" in it including the number after the colon. I then want to print all the values of "ATS" (one value for each size) Here is the script that I have so far:</p> <pre><code>import requests from bs4 import BeautifulSoup prodpage=requests.get('http://www.adidas.com/on/demandware.store/Sites-adidas-US-Site/en_US/Product-GetVariants?pid=S32145', headers={'User-Agent': 'Mozilla/5.0'} ) soup = BeautifulSoup(prodpage.text) print (soup) </code></pre> <p><strong>which returns this:</strong></p> <pre><code>{"id": "S32145_590", "attributes": { "size":"7" }, "articleNo": "S32145", "onlineFrom": 1.4667516E12, "customBadges": "~", "pricing": {"standard": "140.0", "sale": "140.0", "isPromoPrice": false, "quantities": [ {"unit": "PIECE", "value": "1.0"} ]} , "avStatusQuantity": 1.0, "avStatus": "IN_STOCK", "inStock": true, "avLevels": {"IN_STOCK": 1.0, "PREORDER": 0.0, "BACKORDER": 0.0, "NOT_AVAILABLE": 0.0, "PREVIEW": 0.0}, "ATS": 7.0, "inStockDate": "" }, </code></pre>
1
2016-08-03T20:35:35Z
38,753,299
<p>I think BeautifulSoup is not the optimal way to go. It looks more like json-formated data. BeautifulSoup is mainly a parser for HTML/XML. So my suggestion is to go for</p> <pre><code>import requests import json prodpage=requests.get('http://www.adidas.com/on/demandware.store/Sites-adidas-US-Site/en_US/Product-GetVariants?pid=S32145', headers={'User-Agent': 'Mozilla/5.0'} ) data = json.loads(prodpage.text) </code></pre> <p>and then looking for ATS in the dict structure i.e.</p> <pre><code>for variant in data['variations']['variants']: print(variant['ATS']) </code></pre> <p>This returns for me</p> <pre><code>0 0 12.0 0 8.0 0 7.0 0.0 6.0 0.0 17.0 12.0 18.0 2.0 9.0 3.0 7.0 0 7.0 0 5.0 </code></pre>
0
2016-08-03T20:45:44Z
[ "python", "beautifulsoup", "bs4" ]
selenium webdriver importing Options giving me an ImportError
38,753,173
<p>Link to the original code I'm trying to implement into my code.</p> <p><a href="http://stackoverflow.com/questions/16800689/running-selenium-webdriver-using-python-with-extensions-crx-files">Running Selenium WebDriver using Python with extensions (.crx files)</a></p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options chop = webdriver.ChromeOptions() chop.add_extension('Adblock-Plus_v1.4.1.crx') driver = webdriver.Chrome(chrome_options = chop) </code></pre> <p>I tried incorporating the code, but the 2nd line,</p> <pre><code>from selenium.webdriver.chrome.options import Options </code></pre> <p>is tossing out an error</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; from selenium.webdriver.chrome.options import Options ImportError: No module named options </code></pre> <p>I updated selenium, updated chromedriver, and this problem doesn't go away. I checked stackoverflow and nothing seems to be related to my problem where the module is found.</p>
1
2016-08-03T20:36:54Z
38,753,490
<p>Seems like there is an issue with below statement:-</p> <pre><code>chop = webdriver.ChromeOptions() </code></pre> <p>Try:-</p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options chop = Options() chop.add_extension('Adblock-Plus_v1.4.1.crx') driver = webdriver.Chrome(chrome_options=chop) </code></pre>
0
2016-08-03T20:57:04Z
[ "python", "selenium", "selenium-webdriver", "google-chrome-extension", "selenium-chromedriver" ]
selenium webdriver importing Options giving me an ImportError
38,753,173
<p>Link to the original code I'm trying to implement into my code.</p> <p><a href="http://stackoverflow.com/questions/16800689/running-selenium-webdriver-using-python-with-extensions-crx-files">Running Selenium WebDriver using Python with extensions (.crx files)</a></p> <pre><code>from selenium import webdriver from selenium.webdriver.chrome.options import Options chop = webdriver.ChromeOptions() chop.add_extension('Adblock-Plus_v1.4.1.crx') driver = webdriver.Chrome(chrome_options = chop) </code></pre> <p>I tried incorporating the code, but the 2nd line,</p> <pre><code>from selenium.webdriver.chrome.options import Options </code></pre> <p>is tossing out an error</p> <pre><code>Traceback (most recent call last): File "&lt;pyshell#6&gt;", line 1, in &lt;module&gt; from selenium.webdriver.chrome.options import Options ImportError: No module named options </code></pre> <p>I updated selenium, updated chromedriver, and this problem doesn't go away. I checked stackoverflow and nothing seems to be related to my problem where the module is found.</p>
1
2016-08-03T20:36:54Z
38,755,825
<p>I fixed the problem, there was no options.py in the selenium2.7 version for some unusual reason.</p> <p>All I did was update using terminal for mac osx, but you can't just update it, you have to delete all the pre existing paths first. So go find where your selenium is installed using</p> <pre><code>import sys print sys.path </code></pre> <p>Find your selenium path, cd into the path using terminal and delete every folder or file with selenium attached to it.</p> <p>In your terminal, type</p> <pre><code>sudo easy_install selenium </code></pre> <p>The problem I had where this problem didn't go away was I called sudo easy_install without deleting the folder. For some reason, the hickup was gone after I deleted everything and did a fresh install.</p>
1
2016-08-04T00:47:30Z
[ "python", "selenium", "selenium-webdriver", "google-chrome-extension", "selenium-chromedriver" ]
Django: clearing sessions in django_session table
38,753,183
<p>I am working on sessions in Django.</p> <p>By default django stores sessions in django_session, I found out there is no way to purge sessions.</p> <p>though clearsession can be used to delete rows. It is also recommended to run this as a cron job.</p> <p>But doing this means logging out all logged-in users..right? (am not sure)</p> <p>Is this the right practice?</p>
0
2016-08-03T20:37:54Z
38,753,254
<p>The Django <a href="https://docs.djangoproject.com/en/dev/topics/http/sessions/#clearing-the-session-store" rel="nofollow">documentation</a> states (emphasis from me):</p> <blockquote> <h1>Clearing the session store</h1> <p>As users create new sessions on your website, session data can accumulate in your session store. If you’re using the database backend, the django_session database table will grow. If you’re using the file backend, your temporary directory will contain an increasing number of files.</p> <p>To understand this problem, consider what happens with the database backend. When a user logs in, Django adds a row to the django_session database table. Django updates this row each time the session data changes. If the user logs out manually, Django deletes the row. But if the user does not log out, the row never gets deleted. A similar process happens with the file backend.</p> <p>Django does not provide automatic purging of expired sessions. Therefore, <strong>it’s your job to purge expired sessions</strong> on a regular basis. Django provides a clean-up management command for this purpose: <code>clearsessions</code>. It’s recommended to call this command on a regular basis, for example as <strong>a daily cron job</strong>.</p> <p>Note that the cache backend isn’t vulnerable to this problem, because caches automatically delete stale data. Neither is the cookie backend, because the session data is stored by the users’ browsers.</p> </blockquote> <p>Found this link in <a href="http://stackoverflow.com/a/7296233/1218980">Abid A's answer</a>.</p> <h1>The <a href="https://docs.djangoproject.com/ja/1.9/ref/django-admin/#django-contrib-sessions" rel="nofollow"><code>clearsessions</code></a> command</h1> <blockquote> <p>Can be run as a cron job or directly to clean out expired sessions.</p> </blockquote> <p>So it won't log off every user.</p> <p>As mentioned by Kevin Christopher Henry in a <a href="http://stackoverflow.com/questions/38753183/django-clearing-sessions-in-django-session-table/38753254?noredirect=1#comment64882372_38753183">comment</a> and in the other <a href="http://stackoverflow.com/a/37221549/1218980">possible duplicate</a> of your question <a href="http://stackoverflow.com/questions/38753183/django-clearing-sessions-in-django-session-table/38753254?noredirect=1#comment64884597_38753183">flagged by e4c5</a>.</p>
1
2016-08-03T20:42:50Z
[ "python", "django" ]
How can I remove rows from a numpy array that have NaN as the first element?
38,753,198
<p>I have a numpy array that looks like this:</p> <pre><code> [[nan 0 0 ..., 0.0 0.053526738 0.068421053] [nan 0 0 ..., 0.0 0.059653990999999996 0.068421053] [nan 0 0 ..., 1.0 0.912542592 0.068421053] ..., [1 0 0 ..., 0.0 0.126523399 0.193548387] [nan 0 0 ..., 0.0 0.034388807 0.068421053] [4 0 0 ..., 0.0 0.02250561 0.068421053]] </code></pre> <p>How do I remove all rows from the array where nan is the first element?</p>
0
2016-08-03T20:39:09Z
38,753,885
<p>If x is the original array, the following puts the valid rows into y:</p> <pre><code>y = x[~np.isnan(x[:, 0])] </code></pre>
1
2016-08-03T21:23:39Z
[ "python", "numpy" ]
how to plot a list of byte data with matplotlib
38,753,205
<p>I've got a bunch of data that I read in from a telnet machine...It's x, y data, but it's just comma separated like <code>x1,y1,x2,y2,x3,y3,...</code></p> <p>Here's a sample:</p> <pre><code>In[28] data[1:500] Out[28] b'3.00000000E+007,-5.26880000E+001,+3.09700000E+007,-5.75940000E+001,+3.19400000E+007,-5.56250000E+001,+3.29100000E+007,-5.69380000E+001,+3.38800000E+007,-5.40630000E+001,+3.48500000E+007,-5.36560000E+001,+3.58200000E+007,-5.67190000E+001,+3.67900000E+007,-5.51720000E+001,+3.77600000E+007,-5.99840000E+001,+3.87300000E+007,-5.58910000E+001,+3.97000000E+007,-5.35160000E+001,+4.06700000E+007,-5.48130000E+001,+4.16400000E+007,-5.52810000E+001,+4.26100000E+007,-5.64690000E+001,+4.35800000E+007,-5.3938' </code></pre> <p>I want to plot this as a line graph with matplot lib. I've tried the <code>struct</code> package for converting this into a list of doubles instead of bytes, but I ran into so many problems with that...Then there's the issue of what to do with the scientific notation...I want to obviously perserve the magnitude that it's trying to convey, but I can't just do that by naively swapping the byte encodings to what they would mean with a double encoding.</p> <p>I'm trying all sorts of things that I would normally try with C, but I can't help but think there's a better way with Python!</p> <p>I think I need to get the <code>x's</code> and <code>y's</code> into a numpy array and do so without losing any of the exponential notation...</p> <p>Any ideas?</p>
1
2016-08-03T20:39:46Z
38,753,409
<p>to read your items, two at a time (x1, y1), try this: <a href="http://stackoverflow.com/questions/16789776/iterating-over-two-values-of-a-list-at-a-time-in-python">iterating over two values of a list at a time in python</a></p> <p>and then (divide and conquer style), deal with the scientific notation separately.</p> <p>Once you've got two lists of numbers, then the matplotlib documentation can take it from there. </p> <p>That may not be a complete answer, but it should get you a start.</p>
1
2016-08-03T20:52:39Z
[ "python", "list", "numpy", "matplotlib", "bytearray" ]
how to plot a list of byte data with matplotlib
38,753,205
<p>I've got a bunch of data that I read in from a telnet machine...It's x, y data, but it's just comma separated like <code>x1,y1,x2,y2,x3,y3,...</code></p> <p>Here's a sample:</p> <pre><code>In[28] data[1:500] Out[28] b'3.00000000E+007,-5.26880000E+001,+3.09700000E+007,-5.75940000E+001,+3.19400000E+007,-5.56250000E+001,+3.29100000E+007,-5.69380000E+001,+3.38800000E+007,-5.40630000E+001,+3.48500000E+007,-5.36560000E+001,+3.58200000E+007,-5.67190000E+001,+3.67900000E+007,-5.51720000E+001,+3.77600000E+007,-5.99840000E+001,+3.87300000E+007,-5.58910000E+001,+3.97000000E+007,-5.35160000E+001,+4.06700000E+007,-5.48130000E+001,+4.16400000E+007,-5.52810000E+001,+4.26100000E+007,-5.64690000E+001,+4.35800000E+007,-5.3938' </code></pre> <p>I want to plot this as a line graph with matplot lib. I've tried the <code>struct</code> package for converting this into a list of doubles instead of bytes, but I ran into so many problems with that...Then there's the issue of what to do with the scientific notation...I want to obviously perserve the magnitude that it's trying to convey, but I can't just do that by naively swapping the byte encodings to what they would mean with a double encoding.</p> <p>I'm trying all sorts of things that I would normally try with C, but I can't help but think there's a better way with Python!</p> <p>I think I need to get the <code>x's</code> and <code>y's</code> into a numpy array and do so without losing any of the exponential notation...</p> <p>Any ideas?</p>
1
2016-08-03T20:39:46Z
38,753,491
<p>First convert your data to numbers with for example:</p> <pre><code>data = b'3.00000000E+007,-5.26880000E+001,+3.09700000E+007,-5.75940000E+001' numbers = map(float, data.split(',')) </code></pre> <p>Now slice the array to get x and y-data seperately and plot it with matplotlib</p> <pre><code>x = numbers[::2] y = numbers[1::2] import matplotlib.pyplot as plt plt.plot(x, y) plt.show() </code></pre>
4
2016-08-03T20:57:08Z
[ "python", "list", "numpy", "matplotlib", "bytearray" ]
Beautifulsoup HTML table parsing--only able to get the last row?
38,753,246
<p>I have a simple HTML table to parse but somehow Beautifulsoup is only able to get me results from the last row. I'm wondering if anyone would take a look at that and see what's wrong. So I already created the rows object from the HTML table:</p> <pre><code> &lt;table class='participants-table'&gt; &lt;thead&gt; &lt;tr&gt; &lt;th data-field="name" class="sort-direction-toggle name"&gt;Name&lt;/th&gt; &lt;th data-field="type" class="sort-direction-toggle type active-sort asc"&gt;Type&lt;/th&gt; &lt;th data-field="sector" class="sort-direction-toggle sector"&gt;Sector&lt;/th&gt; &lt;th data-field="country" class="sort-direction-toggle country"&gt;Country&lt;/th&gt; &lt;th data-field="joined_on" class="sort-direction-toggle joined-on"&gt;Joined On&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;th class='name'&gt;&lt;a href="/what-is-gc/participants/4479-Grontmij"&gt;Grontmij&lt;/a&gt;&lt;/th&gt; &lt;td class='type'&gt;Company&lt;/td&gt; &lt;td class='sector'&gt;General Industrials&lt;/td&gt; &lt;td class='country'&gt;Netherlands&lt;/td&gt; &lt;td class='joined-on'&gt;2000-09-20&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th class='name'&gt;&lt;a href="/what-is-gc/participants/4492-Groupe-Bial"&gt;Groupe Bial&lt;/a&gt;&lt;/th&gt; &lt;td class='type'&gt;Company&lt;/td&gt; &lt;td class='sector'&gt;Pharmaceuticals &amp;amp; Biotechnology&lt;/td&gt; &lt;td class='country'&gt;Portugal&lt;/td&gt; &lt;td class='joined-on'&gt;2004-02-19&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I use the following codes to get the rows: </p> <pre><code>table=soup.find_all("table", class_="participants-table") table1=table[0] rows=table1.find_all('tr') rows=rows[1:] </code></pre> <p>This gets:</p> <pre><code>rows=[&lt;tr&gt; &lt;th class="name"&gt;&lt;a href="/what-is-gc/participants/4479-Grontmij"&gt;Grontmij&lt;/a&gt;&lt;/th&gt; &lt;td class="type"&gt;Company&lt;/td&gt; &lt;td class="sector"&gt;General Industrials&lt;/td&gt; &lt;td class="country"&gt;Netherlands&lt;/td&gt; &lt;td class="joined-on"&gt;2000-09-20&lt;/td&gt; &lt;/tr&gt;, &lt;tr&gt; &lt;th class="name"&gt;&lt;a href="/what-is-gc/participants/4492-Groupe-Bial"&gt;Groupe Bial&lt;/a&gt;&lt;/th&gt; &lt;td class="type"&gt;Company&lt;/td&gt; &lt;td class="sector"&gt;Pharmaceuticals &amp;amp; Biotechnology&lt;/td&gt; &lt;td class="country"&gt;Portugal&lt;/td&gt; &lt;td class="joined-on"&gt;2004-02-19&lt;/td&gt; &lt;/tr&gt;] </code></pre> <p>As expected, it looks like. However, if I continue:</p> <pre><code>for row in rows: cells = row.find_all('th') </code></pre> <p>I'm only able to get the last entry! </p> <pre><code>cells=[&lt;th class="name"&gt;&lt;a href="/what-is-gc/participants/4492-Groupe-Bial"&gt;Groupe Bial&lt;/a&gt;&lt;/th&gt;] </code></pre> <p>What is going on? This is my first time using beautifulsoup, and what I'd like to do is to export this table into CSV. Any help is greatly appreciated! Thanks</p>
2
2016-08-03T20:42:11Z
38,753,740
<p>You need to extend if you want all the th tags in a single list, you just keep reassigning <code>cells = row.find_all('th')</code> so when your print cells outside the loop you will only see what it was last assigned to i.e the last th in the last tr:</p> <pre><code>cells = [] for row in rows: cells.extend(row.find_all('th')) </code></pre> <p>Also since there is only one table you can just use <em>find</em>:</p> <pre><code>soup = BeautifulSoup(html) table = soup.find("table", class_="participants-table") </code></pre> <p>If you want to skip the thead row you can use a <em>css selector</em>:</p> <pre><code>from bs4 import BeautifulSoup soup = BeautifulSoup(html) rows = soup.select("table.participants-table thead ~ tr") cells = [tr.th for tr in rows] print(cells) </code></pre> <p>cells will give you:</p> <pre><code>[&lt;th class="name"&gt;&lt;a href="/what-is-gc/participants/4479-Grontmij"&gt;Grontmij&lt;/a&gt;&lt;/th&gt;, &lt;th class="name"&gt;&lt;a href="/what-is-gc/participants/4492-Groupe-Bial"&gt;Groupe Bial&lt;/a&gt;&lt;/th&gt;] </code></pre> <p>To write the whole table to csv:</p> <pre><code>import csv soup = BeautifulSoup(html, "html.parser") rows = soup.select("table.participants-table tr") with open("data.csv", "w") as out: wr = csv.writer(out) wr.writerow([th.text for th in rows[0].find_all("th")] + ["URL"]) for row in rows[1:]: wr.writerow([tag.text for tag in row.find_all()] + [row.th.a["href"]]) </code></pre> <p>which for you sample will give you:</p> <pre><code>Name,Type,Sector,Country,Joined On,URL Grontmij,Company,General Industrials,Netherlands,2000-09-20,/what-is-gc/participants/4479-Grontmij Groupe Bial,Company,Pharmaceuticals &amp; Biotechnology,Portugal,2004-02-19,/what-is-gc/participants/4492-Groupe-Bial </code></pre>
1
2016-08-03T21:13:32Z
[ "python", "html", "parsing", "beautifulsoup" ]
await asyncio.wait(coroutines) invalid syntax
38,753,312
<p>I have a python program that uses <code>asyncio</code> and <code>await</code> modules. This is an example program that I have taken from <a href="http://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/" rel="nofollow">here</a>. </p> <pre><code>import asyncio import os import urllib.request import await @asyncio.coroutine def download_coroutine(url): """ A coroutine to download the specified url """ request = urllib.request.urlopen(url) filename = os.path.basename(url) with open(filename, 'wb') as file_handle: while True: chunk = request.read(1024) if not chunk: break file_handle.write(chunk) msg = 'Finished downloading {filename}'.format(filename=filename) return msg @asyncio.coroutine def main(urls): """ Creates a group of coroutines and waits for them to finish """ coroutines = [download_coroutine(url) for url in urls] completed, pending = await asyncio.wait(coroutines) for item in completed: print(item.result()) if __name__ == '__main__': urls = ["http://www.irs.gov/pub/irs-pdf/f1040.pdf", "http://www.irs.gov/pub/irs-pdf/f1040a.pdf", "http://www.irs.gov/pub/irs-pdf/f1040ez.pdf", "http://www.irs.gov/pub/irs-pdf/f1040es.pdf", "http://www.irs.gov/pub/irs-pdf/f1040sb.pdf"] event_loop = asyncio.get_event_loop() try: event_loop.run_until_complete(main(urls)) finally: event_loop.close() </code></pre> <p>I am using <code>python 3.5.1</code>.</p> <pre><code>C:\Anaconda3\python.exe "C:\Users\XXXXXXS\AppData\Roaming\JetBrains\PyCharm Community Edition 2016.1\helpers\pydev\pydevconsole.py" 49950 49951 Python 3.5.1 |Anaconda 2.4.0 (64-bit)| (default, Jun 15 2016, 15:29:36) [MSC v.1900 64 bit (AMD64)] Type "copyright", "credits" or "license" for more information. </code></pre> <p>When I try to run it I get the following error.</p> <pre><code> File "C:/Cubic/playpen/python/concepts/advanced/coroutines.py", line 29 completed, pending = await asyncio.wait(coroutines) ^ SyntaxError: invalid syntax </code></pre> <p>I have both asyncio and await installed.</p> <p>I have tried the same thing and I don't get any syntax error either.</p> <pre><code>C:\playpen\python&gt;python Python 3.5.1 |Anaconda 2.4.0 (64-bit)| (default, Jun 15 2016, 15:29:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; async def foo(): ... await bar ... </code></pre>
1
2016-08-03T20:46:31Z
38,753,417
<p>Your article says:</p> <blockquote> <p>The async and await keywords were added in Python 3.5 to define a native coroutine and make them a distinct type when compared with a generator based coroutine. If you’d like an in-depth description of async and await, you will want to check out PEP 492.</p> </blockquote> <p>This means those kws are not valid in Python 3.4.</p> <p>I installed right now python 3.5 and tried the <code>python</code> interpreter</p> <pre><code>foo@foo-host:~$ python3.5 Python 3.5.0+ (default, Oct 11 2015, 09:05:38) [GCC 5.2.1 20151010] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; async def foo(): ... await bar ... &gt;&gt;&gt; </code></pre> <p>Got no syntax error.</p>
1
2016-08-03T20:53:10Z
[ "python", "coroutine", "python-asyncio" ]
await asyncio.wait(coroutines) invalid syntax
38,753,312
<p>I have a python program that uses <code>asyncio</code> and <code>await</code> modules. This is an example program that I have taken from <a href="http://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/" rel="nofollow">here</a>. </p> <pre><code>import asyncio import os import urllib.request import await @asyncio.coroutine def download_coroutine(url): """ A coroutine to download the specified url """ request = urllib.request.urlopen(url) filename = os.path.basename(url) with open(filename, 'wb') as file_handle: while True: chunk = request.read(1024) if not chunk: break file_handle.write(chunk) msg = 'Finished downloading {filename}'.format(filename=filename) return msg @asyncio.coroutine def main(urls): """ Creates a group of coroutines and waits for them to finish """ coroutines = [download_coroutine(url) for url in urls] completed, pending = await asyncio.wait(coroutines) for item in completed: print(item.result()) if __name__ == '__main__': urls = ["http://www.irs.gov/pub/irs-pdf/f1040.pdf", "http://www.irs.gov/pub/irs-pdf/f1040a.pdf", "http://www.irs.gov/pub/irs-pdf/f1040ez.pdf", "http://www.irs.gov/pub/irs-pdf/f1040es.pdf", "http://www.irs.gov/pub/irs-pdf/f1040sb.pdf"] event_loop = asyncio.get_event_loop() try: event_loop.run_until_complete(main(urls)) finally: event_loop.close() </code></pre> <p>I am using <code>python 3.5.1</code>.</p> <pre><code>C:\Anaconda3\python.exe "C:\Users\XXXXXXS\AppData\Roaming\JetBrains\PyCharm Community Edition 2016.1\helpers\pydev\pydevconsole.py" 49950 49951 Python 3.5.1 |Anaconda 2.4.0 (64-bit)| (default, Jun 15 2016, 15:29:36) [MSC v.1900 64 bit (AMD64)] Type "copyright", "credits" or "license" for more information. </code></pre> <p>When I try to run it I get the following error.</p> <pre><code> File "C:/Cubic/playpen/python/concepts/advanced/coroutines.py", line 29 completed, pending = await asyncio.wait(coroutines) ^ SyntaxError: invalid syntax </code></pre> <p>I have both asyncio and await installed.</p> <p>I have tried the same thing and I don't get any syntax error either.</p> <pre><code>C:\playpen\python&gt;python Python 3.5.1 |Anaconda 2.4.0 (64-bit)| (default, Jun 15 2016, 15:29:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; async def foo(): ... await bar ... </code></pre>
1
2016-08-03T20:46:31Z
38,755,741
<p><code>await</code> will raise a <code>SyntaxError</code> when used anywhere other than inside of a function defined using the <code>async</code> keyword, regardless of whether or not it has been made a coroutine using the <code>@asyncio.coroutine</code> decorator.</p> <pre><code>import asyncio async def test(): pass async def foo(): await test() # No exception raised. @asyncio.coroutine def bar(): await test() # Exception raised. </code></pre>
1
2016-08-04T00:35:11Z
[ "python", "coroutine", "python-asyncio" ]
await asyncio.wait(coroutines) invalid syntax
38,753,312
<p>I have a python program that uses <code>asyncio</code> and <code>await</code> modules. This is an example program that I have taken from <a href="http://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/" rel="nofollow">here</a>. </p> <pre><code>import asyncio import os import urllib.request import await @asyncio.coroutine def download_coroutine(url): """ A coroutine to download the specified url """ request = urllib.request.urlopen(url) filename = os.path.basename(url) with open(filename, 'wb') as file_handle: while True: chunk = request.read(1024) if not chunk: break file_handle.write(chunk) msg = 'Finished downloading {filename}'.format(filename=filename) return msg @asyncio.coroutine def main(urls): """ Creates a group of coroutines and waits for them to finish """ coroutines = [download_coroutine(url) for url in urls] completed, pending = await asyncio.wait(coroutines) for item in completed: print(item.result()) if __name__ == '__main__': urls = ["http://www.irs.gov/pub/irs-pdf/f1040.pdf", "http://www.irs.gov/pub/irs-pdf/f1040a.pdf", "http://www.irs.gov/pub/irs-pdf/f1040ez.pdf", "http://www.irs.gov/pub/irs-pdf/f1040es.pdf", "http://www.irs.gov/pub/irs-pdf/f1040sb.pdf"] event_loop = asyncio.get_event_loop() try: event_loop.run_until_complete(main(urls)) finally: event_loop.close() </code></pre> <p>I am using <code>python 3.5.1</code>.</p> <pre><code>C:\Anaconda3\python.exe "C:\Users\XXXXXXS\AppData\Roaming\JetBrains\PyCharm Community Edition 2016.1\helpers\pydev\pydevconsole.py" 49950 49951 Python 3.5.1 |Anaconda 2.4.0 (64-bit)| (default, Jun 15 2016, 15:29:36) [MSC v.1900 64 bit (AMD64)] Type "copyright", "credits" or "license" for more information. </code></pre> <p>When I try to run it I get the following error.</p> <pre><code> File "C:/Cubic/playpen/python/concepts/advanced/coroutines.py", line 29 completed, pending = await asyncio.wait(coroutines) ^ SyntaxError: invalid syntax </code></pre> <p>I have both asyncio and await installed.</p> <p>I have tried the same thing and I don't get any syntax error either.</p> <pre><code>C:\playpen\python&gt;python Python 3.5.1 |Anaconda 2.4.0 (64-bit)| (default, Jun 15 2016, 15:29:36) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; async def foo(): ... await bar ... </code></pre>
1
2016-08-03T20:46:31Z
39,302,678
<p>You have two different issues here. </p> <ol> <li><p>As mentioned by <a href="http://stackoverflow.com/users/978961/dirn">dirn</a> in his comment, you should not be importing <code>await</code>. <code>await</code> is a built in keyword in Python 3.5. So, remove <code>import await</code>.</p></li> <li><p>You've mixed the <code>@asyncio.coroutine</code> decorator and <code>await</code> keyword (as <a href="http://stackoverflow.com/users/6119465/2cubed">2Cubed</a> mentions). Instead of the decorator, use <code>async def</code> as shown in the <a href="http://www.blog.pythonlibrary.org/2016/07/26/python-3-an-intro-to-asyncio/" rel="nofollow">example</a> you linked to. In other words, instead of:</p></li> </ol> <p><code>@asyncio.coroutine def download_coroutine(url): </code></p> <p>use:</p> <p><code>async def download_coroutine(url): </code></p> <p>Do the same for <code>main</code>.</p> <p>If you make these changes, your code should run under Python 3.5.</p>
1
2016-09-03T02:23:13Z
[ "python", "coroutine", "python-asyncio" ]
Why is my Django form template removing all data after a space?
38,753,345
<p>I am using a Django Form to validate a specific sign up page. The Form is set up as so:</p> <pre><code>class MemberForm(forms.Form): email = forms.EmailField(label='Email', required=True) password = forms.RegexField(label='Password', widget=forms.PasswordInput, required=True, regex=r'^(?=.*[A-Za-z])(?=.*\d)[\S]{8,}$') confirm_password = forms.CharField(label='Confirm Password', widget=forms.PasswordInput, required=True) full_name = forms.CharField(label='Full Name', required=True) pref_name = forms.CharField(label='Preferred Name', required=False) phone = forms.RegexField(label='Phone', regex=r'^\+?1?\d{9,15}$', required=True) address = forms.CharField(label='Address', required=True) city = forms.CharField(label='City', required=True) provinces = forms.ChoiceField(label='Provinces', choices=PROVINCE_CHOICES, required=True) postal_code = forms.RegexField(label='Postal Code', regex=r'^([A-Z][0-9][A-Z]\s[0-9][A-Z][0-9])$') dob = forms.DateField(label='Birthday', required=True) occupation = forms.CharField(label='Occupation', required=True) </code></pre> <p>Everything is working fine in this regard, the form accepts everything it should and rejects everything it should. If the form is invalid, I render it again. This is all done in the following view:</p> <pre><code>def create_member(request): form = forms.MemberForm(request.POST or None) if request.method == 'POST': if form.is_valid(): #redirect provinces = Provinces.objects.all() return render(request, 'party/adminCreateAccount2.html', {'form': form, 'provinces': provinces, 'today': str(now_date())}) </code></pre> <p>So, if the form is not valid, I simply stay on the page and reuse the current form. However, when the form reloads, for some reason, all data that has a space will erase everything after the space when it is shown. </p> <p>For example, if I use 'Test Test' as my full name, then leave everything else blank, when the page reloads, I will only see 'Test'.</p> <p>My form is displayed using the following custom template:</p> <pre><code>{% for field in form %} &lt;div class="form-row grp-row grp-cells-1 {{ field.html_name }}"&gt; &lt;div class="field-box l-2c-fluid l-d-4"&gt; &lt;div class="c-1"&gt; &lt;label {% if field.field.required %} class="required" {% endif %} for={{ field.html_name }}&gt;{{ field.label }}&lt;/label&gt; &lt;/div&gt; &lt;div class="c-2"&gt; &lt;input class="vTextField" type="text" name={{ field.html_name }} id={{ field.html_name }} value={{ field.data|default_if_none:"" }}&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endfor %} </code></pre> <p>I tried outputting <code>{{ field.data|default_if_none:"" }}</code> right beside the input and it displayed the entire string ('Test test' in our example) so I am completely stumped because I know the correct data is getting passed through. Any idea why its being changed for the input value?</p>
0
2016-08-03T20:48:36Z
38,754,218
<p>Django is not doing this, your browser is. You need to put the value variable in quotes:</p> <pre><code>value="{{ field.data|default_if_none:"" }}" </code></pre> <p>But really, your shouldn't output fields like this: use Django to do it properly, with just <code>{{ field }}</code>.</p>
0
2016-08-03T21:50:20Z
[ "python", "html", "django", "django-forms", "django-templates" ]
Django and read-only database connections
38,753,431
<p>Assume a Django application which is supposed to use two MySQL databases:</p> <ul> <li><code>default</code> - for storing data represented by models <code>A</code> and <code>B</code> (read-write access)</li> <li><code>support</code> - for importing data represented by models <code>C</code> and <code>D</code> (read-only access)</li> </ul> <p>The <code>support</code> database is a part of an external application and <strong>cannot</strong> be modified.</p> <p>Since the Django application uses the built-in ORM for models <code>A</code> and <code>B</code> I figured it should use the very same ORM for models <code>C</code> and <code>D</code>, even though they map to tables in an external database (<code>support</code>.)</p> <p>In order to achieve that I defined the models <code>C</code> and <code>D</code> as follows:</p> <pre class="lang-python prettyprint-override"><code>from django.db import models class ExternalModel(models.Model): class Meta: managed = False abstract = True class ModelC(ExternalModel): some_field = models.TextField(db_column='some_field') class Meta(ExternalModel.Meta): db_table = 'some_table_c' class ModelD(ExternalModel): some_other_field = models.TextField(db_column='some_other_field') class Meta(ExternalModel.Meta): db_table = 'some_table_d' </code></pre> <p>Then I defined a database router:</p> <pre class="lang-python prettyprint-override"><code>from myapp.myapp.models import ExternalModel class DatabaseRouter(object): def db_for_read(self, model, **hints): if issubclass(model, ExternalModel): return 'support' return 'default' def db_for_write(self, model, **hints): if issubclass(model, ExternalModel): return None return 'default' def allow_relation(self, obj1, obj2, **hints): return (isinstance(obj1, ExternalModel) == isinstance(obj2, ExternalModel)) def allow_migrate(self, db, app_label, model_name=None, **hints): return (db == 'default') </code></pre> <p>And finally adjusted <code>settings.py</code>:</p> <pre class="lang-python prettyprint-override"><code># (...) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': os.path.join(BASE_DIR, 'resources', 'default.cnf'), }, }, 'support': { 'ENGINE': 'django.db.backends.mysql', 'OPTIONS': { 'read_default_file': os.path.join(BASE_DIR, 'resources', 'support.cnf'), }, }, } DATABASE_ROUTERS = ['myapp.database_router.DatabaseRouter'] # (...) </code></pre> <p>The user specified in <code>support.conf</code> for the <code>support</code> database has been assigned read-only privileges.</p> <p>But when I run <code>python manage.py makemigrations</code> it fails with the following output:</p> <pre class="lang-none prettyprint-override"><code> Traceback (most recent call last): File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 112, in execute return self.cursor.execute(query, args) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 226, in execute self.errorhandler(self, exc, value) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorvalue File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 217, in execute res = self._query(query) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 378, in _query rowcount = self._do_query(q) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 341, in _do_query db.query(q) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1142, "CREATE command denied to user 'somedbuser'@'somehost' for table 'django_migrations'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 57, in ensure_schema editor.create_model(self.Migration) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 295, in create_model self.execute(sql, params or None) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 112, in execute cursor.execute(sql, params) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/utils.py", line 62, in execute return self.cursor.execute(sql) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 112, in execute return self.cursor.execute(query, args) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 226, in execute self.errorhandler(self, exc, value) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler raise errorvalue File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 217, in execute res = self._query(query) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 378, in _query rowcount = self._do_query(q) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/cursors.py", line 341, in _do_query db.query(q) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/MySQLdb/connections.py", line 280, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (1142, "CREATE command denied to user 'somedbuser'@'somehost' for table 'django_migrations'") During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/core/management/commands/makemigrations.py", line 100, in handle loader.check_consistent_history(connection) File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/loader.py", line 276, in check_consistent_history applied = recorder.applied_migrations() File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 65, in applied_migrations self.ensure_schema() File "/Users/username/Development/stuff/myapp/lib/python3.5/site-packages/django/db/migrations/recorder.py", line 59, in ensure_schema raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1142, "CREATE command denied to user 'somedbuser'@'somehost' for table 'django_migrations'")) </code></pre> <p>It appears that Django tries to create the <code>django_migrations</code> table in the read-only database <code>support</code> nevertheless.</p> <p>Is there any clean way to prevent the migrations mechanism from attempting that? Or do I have to employ another ORM library for this read-only access to the <code>support</code> database?</p>
1
2016-08-03T20:54:03Z
39,598,235
<p>Had the same problem. Django is trying to create the 'django_migrations' table in all DBs. This happens even if there are no models associated with the read-only DB and all routers are pointing a different DB.</p> <p>I also ended up using peewee.</p>
0
2016-09-20T15:33:34Z
[ "python", "mysql", "django", "database" ]
How do you negate an annotated field in django?
38,753,458
<p>I have an annotated queryset in which I am annotating the sum of numbers. However, I want the result to be the negative of that sum. I can't seem to do it like this:</p> <p><code>Model.objects.all().annotate(total=-Sum('qty'))</code></p>
1
2016-08-03T20:55:27Z
38,753,749
<p>F objects, of course!</p> <p><code>Model.objects.all().annotate(total=Sum(F('qty')*-1))</code></p>
0
2016-08-03T21:14:01Z
[ "python", "django" ]
How do you negate an annotated field in django?
38,753,458
<p>I have an annotated queryset in which I am annotating the sum of numbers. However, I want the result to be the negative of that sum. I can't seem to do it like this:</p> <p><code>Model.objects.all().annotate(total=-Sum('qty'))</code></p>
1
2016-08-03T20:55:27Z
38,753,772
<p>I know it sounds crazy, but try this:</p> <pre><code>Model.objects.all().annotate(total=0-Sum('qty')) </code></pre> <p>The unary operator <code>-</code> seems unsupported, but the binary operator works. </p>
0
2016-08-03T21:15:48Z
[ "python", "django" ]
Pandas: drop rows based on duplicated values in a list
38,753,515
<p>I would like to drop rows within my dataframe based on if a piece of a string is duplicated within that string. For example, if the string is jkl-ghi-jkl, I would drop this row because jkl is repeated twice. I figured that creating a list and checking the list for duplicates would be the ideal approach.</p> <p>My dataframe for this example consist of 1 column and two data points:</p> <pre><code> df1 = pd.DataFrame({'Col1' : ['abc-def-ghi-jkl', 'jkl-ghi-jkl-mno'],}) </code></pre> <p>My first step I take is to apply a split to my data, and split of "-"</p> <pre><code> List = df1['Col1].str.split('-') List </code></pre> <p>Which is yields the output:</p> <pre><code> 0 [abc, def, ghi, jkl] 1 [jkl, ghi, jkl, mno] Name: Col1, dtype: object </code></pre> <p>My second step I take is to convert my output into lists:</p> <pre><code> List = List.tolist() </code></pre> <p>Which yields:</p> <pre><code> [['abc', 'def', 'ghi', 'jkl'], ['jkl', 'ghi', 'jkl', 'mno']] </code></pre> <p>My last step I wish to accomplish is to compare a full list with a distinct list of unique values:</p> <pre><code> len(List) &gt; len(set(List)) </code></pre> <p>Which yields the error:</p> <pre><code> TypeError: unhashable type: 'list' </code></pre> <p>I am aware that my .tolist() creates a list of 2 series. Is there a way to convert these series into a list in order to test for duplicates? I wish to use this piece of code:</p> <pre><code> len(List) &gt; len(set(List) </code></pre> <p>with a drop in order to drop all rows with a duplicated value within each cell. </p> <p>Is this the correct way of approaching, or is there a simpler way?</p> <p>My end output should look like:</p> <pre><code> Col1 abc-def-ghi-jkl </code></pre> <p>Because string jkl-ghi-jkl-mno gets dropped due to "jkl" repeating twice</p>
6
2016-08-03T20:59:07Z
38,753,716
<p>You can combine <code>str.split</code> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow"><code>duplicated</code></a> to get a Boolean indexer:</p> <pre><code># Get a Boolean indexer for duplicates. dupe_rows = df1['Col1'].str.split('-', expand=True) dupe_rows = dupe_rows.apply(lambda row: row.duplicated().any(), axis=1) # Remove the duplicates. df1 = df1[~dupe_rows] </code></pre> <p><strong>Edit</strong></p> <p>Another option is to use <a href="http://toolz.readthedocs.io/en/latest/api.html#toolz.itertoolz.isdistinct" rel="nofollow"><code>toolz.isdistinct</code></a> in a similar manner as the other answers:</p> <pre><code>import toolz df1[df1.Col1.str.split('-').apply(toolz.isdistinct)] </code></pre>
4
2016-08-03T21:11:56Z
[ "python", "pandas" ]
Pandas: drop rows based on duplicated values in a list
38,753,515
<p>I would like to drop rows within my dataframe based on if a piece of a string is duplicated within that string. For example, if the string is jkl-ghi-jkl, I would drop this row because jkl is repeated twice. I figured that creating a list and checking the list for duplicates would be the ideal approach.</p> <p>My dataframe for this example consist of 1 column and two data points:</p> <pre><code> df1 = pd.DataFrame({'Col1' : ['abc-def-ghi-jkl', 'jkl-ghi-jkl-mno'],}) </code></pre> <p>My first step I take is to apply a split to my data, and split of "-"</p> <pre><code> List = df1['Col1].str.split('-') List </code></pre> <p>Which is yields the output:</p> <pre><code> 0 [abc, def, ghi, jkl] 1 [jkl, ghi, jkl, mno] Name: Col1, dtype: object </code></pre> <p>My second step I take is to convert my output into lists:</p> <pre><code> List = List.tolist() </code></pre> <p>Which yields:</p> <pre><code> [['abc', 'def', 'ghi', 'jkl'], ['jkl', 'ghi', 'jkl', 'mno']] </code></pre> <p>My last step I wish to accomplish is to compare a full list with a distinct list of unique values:</p> <pre><code> len(List) &gt; len(set(List)) </code></pre> <p>Which yields the error:</p> <pre><code> TypeError: unhashable type: 'list' </code></pre> <p>I am aware that my .tolist() creates a list of 2 series. Is there a way to convert these series into a list in order to test for duplicates? I wish to use this piece of code:</p> <pre><code> len(List) &gt; len(set(List) </code></pre> <p>with a drop in order to drop all rows with a duplicated value within each cell. </p> <p>Is this the correct way of approaching, or is there a simpler way?</p> <p>My end output should look like:</p> <pre><code> Col1 abc-def-ghi-jkl </code></pre> <p>Because string jkl-ghi-jkl-mno gets dropped due to "jkl" repeating twice</p>
6
2016-08-03T20:59:07Z
38,753,754
<p><code>split</code> <code>'Col1'</code> and apply a repeat checker using an efficient <code>numpy</code> algorithm.</p> <pre><code>def nerpt(lst): ti = np.triu_indices(len(lst), 1) a = np.array(lst) return (a[ti[0]] == a[ti[1]]).any() df1[~df1.Col1.str.split('-').apply(nerpt)] </code></pre> <p><a href="http://i.stack.imgur.com/WnDn8.png" rel="nofollow"><img src="http://i.stack.imgur.com/WnDn8.png" alt="enter image description here"></a></p> <hr> <h3>Timings</h3> <p>Pretty clear using <code>set</code> is most efficient. This is reflective of @Luis's answer</p> <p>Using <code>pd.concat([df1 for _ in range(10000)])</code></p> <pre><code>rpt1 = lambda lst: not pd.Index(lst).is_unique rpt2 = lambda lst: len(lst) != len(set(lst)) rpt3 = nerpt </code></pre> <p><a href="http://i.stack.imgur.com/H3Y9E.png" rel="nofollow"><img src="http://i.stack.imgur.com/H3Y9E.png" alt="enter image description here"></a></p>
4
2016-08-03T21:15:02Z
[ "python", "pandas" ]
Pandas: drop rows based on duplicated values in a list
38,753,515
<p>I would like to drop rows within my dataframe based on if a piece of a string is duplicated within that string. For example, if the string is jkl-ghi-jkl, I would drop this row because jkl is repeated twice. I figured that creating a list and checking the list for duplicates would be the ideal approach.</p> <p>My dataframe for this example consist of 1 column and two data points:</p> <pre><code> df1 = pd.DataFrame({'Col1' : ['abc-def-ghi-jkl', 'jkl-ghi-jkl-mno'],}) </code></pre> <p>My first step I take is to apply a split to my data, and split of "-"</p> <pre><code> List = df1['Col1].str.split('-') List </code></pre> <p>Which is yields the output:</p> <pre><code> 0 [abc, def, ghi, jkl] 1 [jkl, ghi, jkl, mno] Name: Col1, dtype: object </code></pre> <p>My second step I take is to convert my output into lists:</p> <pre><code> List = List.tolist() </code></pre> <p>Which yields:</p> <pre><code> [['abc', 'def', 'ghi', 'jkl'], ['jkl', 'ghi', 'jkl', 'mno']] </code></pre> <p>My last step I wish to accomplish is to compare a full list with a distinct list of unique values:</p> <pre><code> len(List) &gt; len(set(List)) </code></pre> <p>Which yields the error:</p> <pre><code> TypeError: unhashable type: 'list' </code></pre> <p>I am aware that my .tolist() creates a list of 2 series. Is there a way to convert these series into a list in order to test for duplicates? I wish to use this piece of code:</p> <pre><code> len(List) &gt; len(set(List) </code></pre> <p>with a drop in order to drop all rows with a duplicated value within each cell. </p> <p>Is this the correct way of approaching, or is there a simpler way?</p> <p>My end output should look like:</p> <pre><code> Col1 abc-def-ghi-jkl </code></pre> <p>Because string jkl-ghi-jkl-mno gets dropped due to "jkl" repeating twice</p>
6
2016-08-03T20:59:07Z
38,753,833
<p>Here is another option, using <code>set</code> and <code>len</code>:</p> <pre><code>df1 = pd.DataFrame({'Col1' : ['abc-def-ghi-jkl', 'jkl-ghi-jkl-mno'],}) df1['length'] = df1['Col1'].str.split('-').apply(set).apply(len) print( df1 ) Col1 length 0 abc-def-ghi-jkl 4 1 jkl-ghi-jkl-mno 3 df1 = df1.loc[ df1['length'] &lt; 4 ] print(df1) Col1 length 1 jkl-ghi-jkl-mno 3 </code></pre>
4
2016-08-03T21:19:38Z
[ "python", "pandas" ]
Pandas: drop rows based on duplicated values in a list
38,753,515
<p>I would like to drop rows within my dataframe based on if a piece of a string is duplicated within that string. For example, if the string is jkl-ghi-jkl, I would drop this row because jkl is repeated twice. I figured that creating a list and checking the list for duplicates would be the ideal approach.</p> <p>My dataframe for this example consist of 1 column and two data points:</p> <pre><code> df1 = pd.DataFrame({'Col1' : ['abc-def-ghi-jkl', 'jkl-ghi-jkl-mno'],}) </code></pre> <p>My first step I take is to apply a split to my data, and split of "-"</p> <pre><code> List = df1['Col1].str.split('-') List </code></pre> <p>Which is yields the output:</p> <pre><code> 0 [abc, def, ghi, jkl] 1 [jkl, ghi, jkl, mno] Name: Col1, dtype: object </code></pre> <p>My second step I take is to convert my output into lists:</p> <pre><code> List = List.tolist() </code></pre> <p>Which yields:</p> <pre><code> [['abc', 'def', 'ghi', 'jkl'], ['jkl', 'ghi', 'jkl', 'mno']] </code></pre> <p>My last step I wish to accomplish is to compare a full list with a distinct list of unique values:</p> <pre><code> len(List) &gt; len(set(List)) </code></pre> <p>Which yields the error:</p> <pre><code> TypeError: unhashable type: 'list' </code></pre> <p>I am aware that my .tolist() creates a list of 2 series. Is there a way to convert these series into a list in order to test for duplicates? I wish to use this piece of code:</p> <pre><code> len(List) &gt; len(set(List) </code></pre> <p>with a drop in order to drop all rows with a duplicated value within each cell. </p> <p>Is this the correct way of approaching, or is there a simpler way?</p> <p>My end output should look like:</p> <pre><code> Col1 abc-def-ghi-jkl </code></pre> <p>Because string jkl-ghi-jkl-mno gets dropped due to "jkl" repeating twice</p>
6
2016-08-03T20:59:07Z
38,754,134
<p>I went the same route you did, but instead kept everything in one dataframe; used <code>apply()</code> and indexed to get what I needed:</p> <pre><code>[in]: gf1 = df1 gf1['Col2'] = gf1['Col1'].str.split('-') #keep lists in same DF gf1['Col3'] = gf1['Col2'].apply(set).apply(len) == gf1['Col2'].apply(len) df1 = gf1['Col1'].loc[gf1['Col3'] == True] df1 [Out]: 0 abc-def-ghi-jkl Name: Col1, dtype: object </code></pre>
1
2016-08-03T21:44:03Z
[ "python", "pandas" ]
double read calls in python fuse leading to EINVAL
38,753,522
<p>I am having trouble with python-fuse. Here is a standalone example of the issue: <a href="https://gist.github.com/ensonic/87e4108a7be64412d1c5a553b7e01f88" rel="nofollow">https://gist.github.com/ensonic/87e4108a7be64412d1c5a553b7e01f88</a></p> <p>When mounting the fake-in-memory file system, I can list the contents , but I can read the files:</p> <pre><code>&gt; ls -al ~/temp/mount/ total 1 -r--r--r-- 1 user group 34 Aug 3 22:44 test.txt &gt; cat ~/temp/mount/test.txt cat: /home/user/temp/mount/test.txt: Invalid argument </code></pre> <p>When I run the fuse fs in the forground (-d), I get this debug info:</p> <pre><code>LOOKUP /test.txt getattr /test.txt NODEID: 2 unique: 120, success, outsize: 144 unique: 121, opcode: OPEN (14), nodeid: 2, insize: 48, pid: 10342 open flags: 0x8000 /test.txt open[0] flags: 0x8000 /test.txt unique: 121, success, outsize: 32 unique: 122, opcode: READ (15), nodeid: 2, insize: 80, pid: 10342 read[0] 4096 bytes from 0 flags: 0x8000 unique: 122, error: -22 (Invalid argument), outsize: 16 unique: 123, opcode: READ (15), nodeid: 2, insize: 80, pid: 10342 read[0] 4096 bytes from 0 flags: 0x8000 unique: 123, error: -22 (Invalid argument), outsize: 16 unique: 124, opcode: FLUSH (25), nodeid: 2, insize: 64, pid: 10342 unique: 124, error: -38 (Function not implemented), outsize: 16 unique: 125, opcode: RELEASE (18), nodeid: 2, insize: 64, pid: 0 release[0] flags: 0x8000 unique: 125, success, outsize: 16 </code></pre> <p>and my logfile has:</p> <pre><code>INFO:fakefs:open fake file /test.txt INFO:fakefs:read from /test.txt, offs 0, size 4096, len 34 INFO:fakefs:read remainder INFO:fakefs:read() = 34 bytes INFO:fakefs:read from /test.txt, offs 0, size 4096, len 34 INFO:fakefs:read remainder INFO:fakefs:read() = 34 bytes INFO:fakefs:released(/test.txt) = 0 </code></pre> <p>What I wonder is: 1) why is the read done twice (read[0] 4096 bytes from 0 flags: 0x8000) 2) why does it return EINVAL? I return the data - there is no single EINVAL in my code.</p> <p>In the actual example I am implementing the rest of the fs functions too, this is not the issue.</p>
1
2016-08-03T20:59:17Z
38,762,579
<p>Turns out it is related to the tricky handling of encoding in python 2 (there is no python-fuse for py3).</p> <p>Returning bytes(buf) in read() fixes it. The fuse code uses EINVAL also when things look wrong it received from the python side.</p>
0
2016-08-04T08:46:09Z
[ "python", "fuse" ]
Using os.system() in Python is open a program, can't see window of launched program
38,753,553
<p>I am trying to launch a program/GUI from within a python code.</p> <p>From the terminal, I can get the program to launch by simply typing the program name. A few lines get outputted to the terminal, and then a separate window opens with the GUI. </p> <p>I tried to emulate this in python by running</p> <pre><code>os.system("&lt;program name&gt;") </code></pre> <p>The typical output lines, as mentioned above, get printed to the console, but no window opens up with the GUI.</p> <p>Can os.system() be used to execute programs that have their own separate window?</p>
1
2016-08-03T21:01:07Z
38,753,764
<p>Here is a solution using <code>subprocess</code></p> <pre><code>import subprocess subprocess.Popen("notepad.exe") </code></pre> <p>Or if you want to run a python program with a specific interpreter:</p> <pre><code>subprocess.Popen('{0} {1}'.format(PythonInterpreterPath,PythonFilePath.py)) </code></pre>
0
2016-08-03T21:15:29Z
[ "python", "os.system" ]
Using os.system() in Python is open a program, can't see window of launched program
38,753,553
<p>I am trying to launch a program/GUI from within a python code.</p> <p>From the terminal, I can get the program to launch by simply typing the program name. A few lines get outputted to the terminal, and then a separate window opens with the GUI. </p> <p>I tried to emulate this in python by running</p> <pre><code>os.system("&lt;program name&gt;") </code></pre> <p>The typical output lines, as mentioned above, get printed to the console, but no window opens up with the GUI.</p> <p>Can os.system() be used to execute programs that have their own separate window?</p>
1
2016-08-03T21:01:07Z
38,753,886
<p>From the <a href="https://docs.python.org/3/library/os.html#os.system" rel="nofollow">Python manual</a>:</p> <blockquote> <p>[<a href="https://docs.python.org/3/library/os.html#os.system" rel="nofollow"><code>os.system</code></a>] is implemented by calling the Standard C function <a href="http://linux.die.net/man/3/system" rel="nofollow"><code>system()</code></a></p> </blockquote> <p>That being said, you shouldn't have any problems launching a GUI application with <a href="https://docs.python.org/3/library/os.html#os.system" rel="nofollow"><code>os.system</code></a>. I've just tried it myself and it works fine.</p> <p>It also mentions in the manual that:</p> <blockquote> <p>The <a href="https://docs.python.org/3/library/subprocess.html" rel="nofollow">subprocess</a> module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.</p> </blockquote> <p>Maybe that's worth a try. Do any other GUI applications work when you spawn them with <a href="https://docs.python.org/3/library/os.html#os.system" rel="nofollow"><code>os.system</code></a>?</p>
1
2016-08-03T21:23:40Z
[ "python", "os.system" ]
What does "TypeError : (1,2,3) is not JSON serializable" mean?
38,753,599
<p>I'm trying to pull an array from Objective-C into my Python code, and when I do, I get the following error:</p> <pre><code>TypeError: ( 5850, 5500, 5170, 2500, 2400, 2400, 2400, 2500, 5170, 5500, 5850 ) is not JSON serializable </code></pre> <p>I've tried to put a dict() method around my Objective-C wrapper call to turn it into a dictionary, and that doesn't work either (and probably isn't what I want anyways, as I want a Python array object containing these values). How do I fix this error? I did some searching, and most past questions ask about DJango methods giving a similar issue, but isn't quite what I need.</p>
-1
2016-08-03T21:03:43Z
38,753,654
<p>A <code>dict()</code> object or in this case, a JSON object requires a key followed by a value.</p> <p>Thus, you are getting a <code>TypeError</code> as you are trying to convert an array to JSON. Adding some keys to this array will fix the error.</p> <p>Sample Code:</p> <pre><code>json_payload = { '0': 5850, '1': 5500, '2': 5170, '3': 2500, '4': 2400, '5': 2400, '6': 2400, } </code></pre> <p>If instead you wish to create a python <code>list</code> object, try this:</p> <pre><code>nums = [ 5850, 5500, 5170, 2500, 2400, 2400, 2400] </code></pre> <p><code>nums</code> can then be sent as a json object.</p>
-1
2016-08-03T21:07:58Z
[ "python", "objective-c", "arrays", "json" ]
What does "TypeError : (1,2,3) is not JSON serializable" mean?
38,753,599
<p>I'm trying to pull an array from Objective-C into my Python code, and when I do, I get the following error:</p> <pre><code>TypeError: ( 5850, 5500, 5170, 2500, 2400, 2400, 2400, 2500, 5170, 5500, 5850 ) is not JSON serializable </code></pre> <p>I've tried to put a dict() method around my Objective-C wrapper call to turn it into a dictionary, and that doesn't work either (and probably isn't what I want anyways, as I want a Python array object containing these values). How do I fix this error? I did some searching, and most past questions ask about DJango methods giving a similar issue, but isn't quite what I need.</p>
-1
2016-08-03T21:03:43Z
38,753,776
<p>You want a Python array object, i.e. a <code>list()</code> object. There's no sense in using a <code>dict()</code>, unless you want a dictionary.</p> <p>Use <code>list(1,2,3..,n)</code> or <code>[1, 2, 3..., n ]</code>to make a Python list object. You'll then access elements by their respective indices.</p> <p>A Python <code>list()</code> object qualifies as a JSON array/object.</p>
2
2016-08-03T21:15:57Z
[ "python", "objective-c", "arrays", "json" ]
How to Modify the Dataframe so Each Row Stores All the Data of its Duplicate Rows?
38,753,631
<p>I have this dataframe with three columns (<code>ID</code>,<code>key</code>, and <code>word</code>)</p> <pre><code> ID key word 0 1 A Apple 1 1 B Bug 2 2 C Cat 3 3 D Dog 4 3 E Exogenous 5 3 E Egg </code></pre> <p>I want to create additional <code>key</code> and <code>word</code> columns -as necessary- to store the data in the <code>key</code> and <code>word</code> columns when there are rows with duplicate <code>IDs</code></p> <p>This is a snippet of the output</p> <pre><code> ID key_0 key_1 word_0 word_1 0 1 A B Apple Bug </code></pre> <p><strong>Note:</strong> in the output above, the <code>ID</code>#<code>1</code> appeared twice in the dataframe, so the <code>"key"</code> value <code>"B"</code> associated with the duplicate <code>ID</code> will be stored in the new column <code>"key_1"</code>. The word <code>Bug</code> found in the duplicate <code>ID</code>#<code>1</code> will be stored in the new column <code>word_1</code> as well. </p> <p>The complete output should like the following: </p> <pre><code> ID key_0 key_1 key_2 word_0 word_1 word_2 0 1 A B NaN Apple Bug NaN 1 2 C NaN NaN Cat NaN NaN 2 3 D E E Dog Exogenous Egg </code></pre> <p>Notice in the complete output, the <code>ID</code>#<code>3</code> has repeated three times. The <code>key</code> of the second repeat <code>"E"</code> will be stored under the <code>"key_1"</code> column and the third repeat <code>"E"</code> will be stored in the new column <code>"key_2"</code>. This applies to the words <code>"Exogenous"</code> and <code>"Egg"</code> in the same mannar.</p> <p>I found <a href="http://stackoverflow.com/a/38734358/1974919">Alex's</a> solution useful, but it only works for the <code>key</code> column:</p> <pre><code>df.groupby('ID')['key'].apply( lambda s: pd.Series(s.values, index=['key_%s' % i for i in range(s.shape[0])])).unstack(-1) </code></pre> <p>Any idea how can I make the lambda function works for both the <code>key</code> and <code>word</code> columns? </p> <p>Thank you,</p>
1
2016-08-03T21:06:08Z
38,753,767
<p>You can use concat after using Alex's solution :</p> <pre><code>df1 = df.groupby('ID')['key'].apply( lambda s: pd.Series(s.values, index=['key_%s' % i for i in range(s.shape[0])])).unstack(-1) df2 = df.groupby('ID')['word'].apply( lambda s: pd.Series(s.values, index=['word_%s' % i for i in range(s.shape[0])])).unstack(-1) df3 = pd.DataFrame({'ID':df['ID'].unique()}) df_new = pd.concat([df1,df2,df3],axis=1) </code></pre>
0
2016-08-03T21:15:39Z
[ "python", "pandas", "dataframe", "format", "series" ]
How to Modify the Dataframe so Each Row Stores All the Data of its Duplicate Rows?
38,753,631
<p>I have this dataframe with three columns (<code>ID</code>,<code>key</code>, and <code>word</code>)</p> <pre><code> ID key word 0 1 A Apple 1 1 B Bug 2 2 C Cat 3 3 D Dog 4 3 E Exogenous 5 3 E Egg </code></pre> <p>I want to create additional <code>key</code> and <code>word</code> columns -as necessary- to store the data in the <code>key</code> and <code>word</code> columns when there are rows with duplicate <code>IDs</code></p> <p>This is a snippet of the output</p> <pre><code> ID key_0 key_1 word_0 word_1 0 1 A B Apple Bug </code></pre> <p><strong>Note:</strong> in the output above, the <code>ID</code>#<code>1</code> appeared twice in the dataframe, so the <code>"key"</code> value <code>"B"</code> associated with the duplicate <code>ID</code> will be stored in the new column <code>"key_1"</code>. The word <code>Bug</code> found in the duplicate <code>ID</code>#<code>1</code> will be stored in the new column <code>word_1</code> as well. </p> <p>The complete output should like the following: </p> <pre><code> ID key_0 key_1 key_2 word_0 word_1 word_2 0 1 A B NaN Apple Bug NaN 1 2 C NaN NaN Cat NaN NaN 2 3 D E E Dog Exogenous Egg </code></pre> <p>Notice in the complete output, the <code>ID</code>#<code>3</code> has repeated three times. The <code>key</code> of the second repeat <code>"E"</code> will be stored under the <code>"key_1"</code> column and the third repeat <code>"E"</code> will be stored in the new column <code>"key_2"</code>. This applies to the words <code>"Exogenous"</code> and <code>"Egg"</code> in the same mannar.</p> <p>I found <a href="http://stackoverflow.com/a/38734358/1974919">Alex's</a> solution useful, but it only works for the <code>key</code> column:</p> <pre><code>df.groupby('ID')['key'].apply( lambda s: pd.Series(s.values, index=['key_%s' % i for i in range(s.shape[0])])).unstack(-1) </code></pre> <p>Any idea how can I make the lambda function works for both the <code>key</code> and <code>word</code> columns? </p> <p>Thank you,</p>
1
2016-08-03T21:06:08Z
38,754,244
<pre><code>df2 = df.set_index('ID').groupby(level=0).apply(lambda df: df.reset_index(drop=True)).unstack() df2.columns = df2.columns.set_levels((df2.columns.levels[1]).astype(str), level=1) df2.columns = df2.columns.to_series().str.join('_') df2 </code></pre> <p><a href="http://i.stack.imgur.com/w3bvQ.png" rel="nofollow"><img src="http://i.stack.imgur.com/w3bvQ.png" alt="enter image description here"></a></p>
1
2016-08-03T21:52:04Z
[ "python", "pandas", "dataframe", "format", "series" ]
How to Modify the Dataframe so Each Row Stores All the Data of its Duplicate Rows?
38,753,631
<p>I have this dataframe with three columns (<code>ID</code>,<code>key</code>, and <code>word</code>)</p> <pre><code> ID key word 0 1 A Apple 1 1 B Bug 2 2 C Cat 3 3 D Dog 4 3 E Exogenous 5 3 E Egg </code></pre> <p>I want to create additional <code>key</code> and <code>word</code> columns -as necessary- to store the data in the <code>key</code> and <code>word</code> columns when there are rows with duplicate <code>IDs</code></p> <p>This is a snippet of the output</p> <pre><code> ID key_0 key_1 word_0 word_1 0 1 A B Apple Bug </code></pre> <p><strong>Note:</strong> in the output above, the <code>ID</code>#<code>1</code> appeared twice in the dataframe, so the <code>"key"</code> value <code>"B"</code> associated with the duplicate <code>ID</code> will be stored in the new column <code>"key_1"</code>. The word <code>Bug</code> found in the duplicate <code>ID</code>#<code>1</code> will be stored in the new column <code>word_1</code> as well. </p> <p>The complete output should like the following: </p> <pre><code> ID key_0 key_1 key_2 word_0 word_1 word_2 0 1 A B NaN Apple Bug NaN 1 2 C NaN NaN Cat NaN NaN 2 3 D E E Dog Exogenous Egg </code></pre> <p>Notice in the complete output, the <code>ID</code>#<code>3</code> has repeated three times. The <code>key</code> of the second repeat <code>"E"</code> will be stored under the <code>"key_1"</code> column and the third repeat <code>"E"</code> will be stored in the new column <code>"key_2"</code>. This applies to the words <code>"Exogenous"</code> and <code>"Egg"</code> in the same mannar.</p> <p>I found <a href="http://stackoverflow.com/a/38734358/1974919">Alex's</a> solution useful, but it only works for the <code>key</code> column:</p> <pre><code>df.groupby('ID')['key'].apply( lambda s: pd.Series(s.values, index=['key_%s' % i for i in range(s.shape[0])])).unstack(-1) </code></pre> <p>Any idea how can I make the lambda function works for both the <code>key</code> and <code>word</code> columns? </p> <p>Thank you,</p>
1
2016-08-03T21:06:08Z
38,759,655
<p>Another solution with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a>:</p> <pre><code>df['cols'] = df.groupby('ID')['ID'].cumcount().astype(str) df1 = df.pivot_table(index='ID', columns='cols', values=['key','word'], aggfunc=''.join) df1.columns = ['_'.join(col) for col in df1.columns] print (df1) key_0 key_1 key_2 word_0 word_1 word_2 ID 1 A B None Apple Bug None 2 C None None Cat None None 3 D E E Dog Exogenous Egg </code></pre>
0
2016-08-04T06:09:39Z
[ "python", "pandas", "dataframe", "format", "series" ]
inserting numpy integer types into sqlite with python3
38,753,737
<p>What is the correct way to insert the values of numpy integer objects into databases in python 3? In python 2.7 numpy numeric datatypes insert cleanly into sqlite, but they don't in python 3</p> <pre><code>import numpy as np import sqlite3 conn = sqlite3.connect(":memory:") conn.execute("CREATE TABLE foo (id INTEGER NOT NULL, primary key (id))") conn.execute("insert into foo values(?)", (np.int64(100),)) # &lt;-- Fails in 3 </code></pre> <p>The np.float types seem to still work just fine in both 2 and 3.</p> <pre><code> conn.execute("insert into foo values(?)", (np.float64(101),)) </code></pre> <p>In python 2, the numpy scalar integer datatypes are no longer instances of int, even converting integer-valued floating point numbers to ints.</p> <pre><code> isinstance(np.int64(1), int) # &lt;- true for 2, false for python 3 </code></pre> <p>Is this why the dbapi no longer works seamlessly with numpy?</p>
4
2016-08-03T21:13:24Z
39,106,289
<p>According to sqlite3 docs:</p> <blockquote> <p>To use other Python types with SQLite, you must adapt them to one of the sqlite3 module’s supported types for SQLite: one of NoneType, int, float, str, bytes.</p> </blockquote> <p>So you can <strong>adapt</strong> <em>np.int64</em> type. You should do something like this:</p> <pre><code>import numpy as np import sqlite3 sqlite3.register_adapter(np.int64, lambda val: int(val)) conn = sqlite3.connect(":memory:") conn.execute("CREATE TABLE foo (id INTEGER NOT NULL, primary key (id))") conn.execute("insert into foo values(?)", (np.int64(100),)) </code></pre> <p><a href="https://docs.python.org/3.5/library/sqlite3.html#registering-an-adapter-callable" rel="nofollow">Docs</a></p>
1
2016-08-23T16:21:51Z
[ "python", "sqlite", "python-3.x", "numpy", "python-db-api" ]
Scrapy merge subsite-item with site-item
38,753,743
<p>Im trying to <strong>scrape details from a subsite and merge with the details scraped with site</strong>. I've been researching through stackoverflow, as well as documentation. However, I still cant get my code to work. It seems that my function to extract additional details from the subsite does not work. If anyone could take a look I would be very grateful.</p> <pre><code># -*- coding: utf-8 -*- from scrapy.spiders import Spider from scrapy.selector import Selector from scrapeInfo.items import infoItem import pyodbc class scrapeInfo(Spider): name = "info" allowed_domains = ["http://www.nevermind.com"] start_urls = [] def start_requests(self): #Get infoID and Type from database self.conn = pyodbc.connect('DRIVER={SQL Server};SERVER=server;DATABASE=dbname;UID=user;PWD=password') self.cursor = self.conn.cursor() self.cursor.execute("SELECT InfoID, category FROM dbo.StageItem") rows = self.cursor.fetchall() for row in rows: url = 'http://www.nevermind.com/info/' InfoID = row[0] category = row[1] yield self.make_requests_from_url(url+InfoID, InfoID, category, self.parse) def make_requests_from_url(self, url, InfoID, category, callback): request = Request(url, callback) request.meta['InfoID'] = InfoID request.meta['category'] = category return request def parse(self, response): hxs = Selector(response) infodata = hxs.xpath('div[2]/div[2]') # input item path itemPool = [] InfoID = response.meta['InfoID'] category = response.meta['category'] for info in infodata: item = infoItem() item_cur, item_hist = InfoItemSubSite() # Stem Details item['id'] = InfoID item['field'] = info.xpath('tr[1]/td[2]/p/b/text()').extract() item['field2'] = info.xpath('tr[2]/td[2]/p/b/text()').extract() item['field3'] = info.xpath('tr[3]/td[2]/p/b/text()').extract() item_cur['field4'] = info.xpath('tr[4]/td[2]/p/b/text()').extract() item_cur['field5'] = info.xpath('tr[5]/td[2]/p/b/text()').extract() item_cur['field6'] = info.xpath('tr[6]/td[2]/p/b/@href').extract() # Extract additional information about item_cur from refering site # This part does not work if item_cur['field6'] = info.xpath('tr[6]/td[2]/p/b/@href').extract(): url = 'http://www.nevermind.com/info/sub/' + item_cur['field6'] = info.xpath('tr[6]/td[2]/p/b/@href').extract()[0] request = Request(url, housingtype, self.parse_item_sub) request.meta['category'] = category yield self.parse_item_sub(url, category) item_his['field5'] = info.xpath('tr[5]/td[2]/p/b/text()').extract() item_his['field6'] = info.xpath('tr[6]/td[2]/p/b/text()').extract() item_his['field7'] = info.xpath('tr[7]/td[2]/p/b/@href').extract() item['subsite_dic'] = [dict(item_cur), dict(item_his)] itemPool.append(item) yield item pass # Function to extract additional info from the subsite, and return it to the original item. def parse_item_sub(self, response, category): hxs = Selector(response) subsite = hxs.xpath('div/div[2]') # input base path category = response.meta['category'] for i in subsite: item = InfoItemSubSite() if (category == 'first'): item['subsite_field1'] = i.xpath('/td[2]/span/@title').extract() item['subsite_field2'] = i.xpath('/tr[4]/td[2]/text()').extract() item['subsite_field3'] = i.xpath('/div[5]/a[1]/@href').extract() else: item['subsite_field1'] = i.xpath('/tr[10]/td[3]/span/@title').extract() item['subsite_field2'] = i.xpath('/tr[4]/td[1]/text()').extract() item['subsite_field3'] = i.xpath('/div[7]/a[1]/@href').extract() return item pass </code></pre> <p>I've been looking at these examples together with a lot of other examples (stackoverflow is great for that!), as well as scrapy documentation, but still unable to understand how I get details send from one function and merged with the scraped items from the original function.</p> <p><a href="http://stackoverflow.com/questions/8467700/how-do-i-merge-results-from-target-page-to-current-page-in-scrapy">how do i merge results from target page to current page in scrapy?</a> <a href="http://stackoverflow.com/questions/13910357/how-can-i-use-multiple-requests-and-pass-items-in-between-them-in-scrapy-python/25571270#25571270">How can i use multiple requests and pass items in between them in scrapy python</a></p>
0
2016-08-03T21:13:43Z
38,753,888
<p>What you are looking here is called request chaining. Your problem is - yield one item from several requests. A solution to this is to chain requests while carrying your item in requests <code>meta</code> attribute.<br> Example:</p> <pre><code>def parse(self, response): item = MyItem() item['name'] = response.xpath("//div[@id='name']/text()").extract() more_page = # some page that offers more details # go to more page and take your item with you. yield Request(more_page, self.parse_more, meta={'item':item}) def parse_more(self, response): # get your item from the meta item = response.meta['item'] # fill it in with more data and yield! item['last_name'] = response.xpath("//div[@id='lastname']/text()").extract() yield item </code></pre>
1
2016-08-03T21:23:52Z
[ "python", "function", "merge", "scrapy" ]
Write to Excel File with Pandas Module
38,753,750
<p>How could I write a list of items <code>[1,2,3,4,5]</code> to an excel file in a specific tab starting at a specific row and column location using the <code>Pandas</code> module? Does it involve the <code>pandas.DataFrame.to_excel</code> function, and do I need to convert my <code>list</code> into a <code>dataframe</code> before writing it to the excel file?</p> <p>Would I make the list into a series first, and then convert the series into a dataframe, and then write the dataframe to the excel file?</p>
0
2016-08-03T21:14:17Z
38,757,389
<p>Yes you will need to use 'to_excel'. The one line code below creates a list, converts it to a series, then converts it to a dataframe and creates and excel file</p> <pre><code>pd.Series([ i for i in range(10)]).to_frame().to_excel('test.xlsx') </code></pre>
0
2016-08-04T02:07:49Z
[ "python", "excel", "pandas" ]
python matplotlib plotting many subfigures with the same parameters
38,753,766
<p>My plot is like the following </p> <pre><code>fig = plt.figure(figsize=(7,3)) ax1 = fig.add_subplot(1,3,1) ax2 = fig.add_subplot(1,3,2) ax3 = fig.add_subplot(1,3,3) ax1.scatter(x11, y11, s=50, alpha=0.5, c='orange', marker='o') ax1.scatter(x12, y12, s=50, alpha=0.5, c='blue', marker='s') ax2.scatter(x21, y21, s=50, alpha=0.5, c='orange', marker='o') ax2.scatter(x22, y22, s=50, alpha=0.5, c='blue', marker='s') ax3.scatter(x31, y31, s=50, alpha=0.5, c='orange', marker='o') ax3.scatter(x32, y32, s=50, alpha=0.5, c='blue', marker='s') </code></pre> <p>It seems kinda redundant to set <code>s=50, alpha=0.5</code> over and over. Is there a way to set them once for all? Also for color and marker, is there a way to write them in one place so it's easier to modify?</p>
2
2016-08-03T21:15:30Z
38,753,925
<p>You could do this:</p> <pre><code>fig = plt.figure(figsize=(7,3)) ax1 = fig.add_subplot(1,3,1) ax2 = fig.add_subplot(1,3,2) ax3 = fig.add_subplot(1,3,3) xs = [x11, x12, x21, x22, x31, x32] ys = [y11, y12, y21, y22, y31, y32] cs = ['orange', 'blue'] ms = 'os' for j in xrange(len(xs)): ax1.scatter(xs[j], ys[j], s=50, alpha=0.5, c=cs[j % 2], marker=ms[j % 2]) </code></pre>
3
2016-08-03T21:26:43Z
[ "python", "matplotlib", "plot" ]
python matplotlib plotting many subfigures with the same parameters
38,753,766
<p>My plot is like the following </p> <pre><code>fig = plt.figure(figsize=(7,3)) ax1 = fig.add_subplot(1,3,1) ax2 = fig.add_subplot(1,3,2) ax3 = fig.add_subplot(1,3,3) ax1.scatter(x11, y11, s=50, alpha=0.5, c='orange', marker='o') ax1.scatter(x12, y12, s=50, alpha=0.5, c='blue', marker='s') ax2.scatter(x21, y21, s=50, alpha=0.5, c='orange', marker='o') ax2.scatter(x22, y22, s=50, alpha=0.5, c='blue', marker='s') ax3.scatter(x31, y31, s=50, alpha=0.5, c='orange', marker='o') ax3.scatter(x32, y32, s=50, alpha=0.5, c='blue', marker='s') </code></pre> <p>It seems kinda redundant to set <code>s=50, alpha=0.5</code> over and over. Is there a way to set them once for all? Also for color and marker, is there a way to write them in one place so it's easier to modify?</p>
2
2016-08-03T21:15:30Z
38,760,016
<p>I like organizing the data and styles, and then using that to organize the plotting. Generating some random data to make a runnable example: </p> <pre><code>import matplotlib.pyplot as plt from numpy.random import random fig, axs = plt.subplots(3, figsize=(7,3)) #axs is an array of axes orange_styles = {'c':"orange", 'marker':'o'} blue_styles = {'c':"blue", 'marker':'s'} pts = [] for i in range(12): pts.append(random(4)) orange_x = pts[0:3] # organized data is lists of lists orange_y = pts[3:6] blue_x = pts[6:10] blue_y = pts[10:12] for ax, x, y in zip(axs, orange_x, orange_y): #all the orange cases ax.scatter(x, y, s=50, alpha=0.5, **orange_styles) # **kwds for ax, x, y in zip(axs, blue_x, blue_y): ax.scatter(x, y, s=50, alpha=0.5, **blue_styles) </code></pre>
1
2016-08-04T06:33:05Z
[ "python", "matplotlib", "plot" ]
Mypy Python 2 insist on unicode value not string value
38,753,817
<p>Python 2 will implicitly convert <code>str</code> to <code>unicode</code> in some circumstances. This conversion will sometimes throw a <code>UnicodeError</code> depending on what you try to do with the resulting value. I don't know the exact semantics, but it's something I'd like to avoid.</p> <p>Is it possible to use another type besides <code>unicode</code> or a command-line argument similar to <code>--strict-optional</code> (<a href="http://mypy-lang.blogspot.co.uk/2016/07/mypy-043-released.html" rel="nofollow">http://mypy-lang.blogspot.co.uk/2016/07/mypy-043-released.html</a>) to cause programs using this implicit conversion to fail to type check?</p> <pre><code>def returns_string_not_unicode(): # type: () -&gt; str return u"a" def returns_unicode_not_string(): # type: () -&gt; unicode return "a" </code></pre> <p>In this example, only the function <code>returns_string_not_unicode</code> fails to type check.</p> <pre><code>$ mypy --py2 unicode.py unicode.py: note: In function "returns_string_not_unicode": unicode.py:3: error: Incompatible return value type (got "unicode", expected "str") </code></pre> <p>I would like both of them to fail to typecheck.</p> <p>EDIT:</p> <p><code>type: () -&gt; byte</code> seems to be treated the same way as <code>str</code></p> <pre><code>def returns_string_not_unicode(): # type: () -&gt; bytes return u"a" </code></pre>
2
2016-08-03T21:18:24Z
38,775,762
<p>This is, unfortunately, an ongoing and currently unresolved issue -- see <a href="https://github.com/python/mypy/issues/1141" rel="nofollow">https://github.com/python/mypy/issues/1141</a> and <a href="https://github.com/python/typing/issues/208" rel="nofollow">https://github.com/python/typing/issues/208</a>.</p> <p>A partial fix is to use <code>typing.Text</code> which is (unfortunately) currently undocumented (I'll work on fixing that though). It's aliased to <code>str</code> in Python 3 and to <code>unicode</code> in Python 2. It won't resolve your actual issue or cause the second function to fail to typecheck, but it <em>does</em> make it a bit easier to write types compatible with both Python 2 and Python 3.</p> <p>In the meantime, you can hack together a partial workaround by using the recently-implemented <a href="https://docs.python.org/3/library/typing.html#newtype" rel="nofollow"><code>NewType</code> feature</a> -- it lets you define a psuedo-subclass with minimal runtime cost, which you can use to approximate the functionality you're looking for:</p> <pre><code>from typing import NewType, Text # Tell mypy to treat 'Unicode' as a subtype of `Text`, which is # aliased to 'unicode' in Python 2 and 'str' (aka unicode) in Python 3 Unicode = NewType('Unicode', Text) def unicode_not_str(a: Unicode) -&gt; Unicode: return a # my_unicode is still the original string at runtime, but Mypy # treats it as having a distinct type from `str` and `unicode`. my_unicode = Unicode(u"some string") unicode_not_str(my_unicode) # typechecks unicode_not_str("foo") # fails unicode_not_str(u"foo") # fails, unfortunately unicode_not_str(Unicode("bar")) # works, unfortunately </code></pre> <p>It's not perfect, but if you're principled about when you elevate a string into being treated as being of your custom <code>Unicode</code> type, you can get something approximating the type safety you're looking for with minimal runtime cost until the bytes/str/unicode issue is settled.</p> <p><s>Note that you'll need to install mypy from the master branch on Github to use <code>NewType</code>.</s></p> <p>Note that NewType was added as of <a href="http://mypy-lang.blogspot.co.uk/2016/08/mypy-044-released.html" rel="nofollow">mypy version 0.4.4</a>.</p>
1
2016-08-04T19:24:12Z
[ "python", "python-2.7", "mypy" ]
How to identify consecutive dates
38,753,823
<p>I would like to identify dates in a dataframe which are consecutive, that is there exists either an immediate predecessor or successor. I would then like to mark which dates are and are not consecutive in a new column. Additionally I would like to do this operation within particular subsets of my data. </p> <p>First I create a new variable where I'd identify True of False for Consecutive Days.</p> <pre><code>weatherFile['CONSECUTIVE_DAY'] = 'NA' </code></pre> <p>I've converted dates into datetime objects then to ordinal ones:</p> <pre><code>weatherFile['DATE_OBJ'] = [datetime.strptime(d, '%Y%m%d') for d in weatherFile['DATE']] weatherFile['DATE_INT'] = list([d.toordinal() for d in weatherFile['DATE_OBJ']]) </code></pre> <p>Now I would like to identify consecutive dates in the following groups:</p> <pre><code>weatherFile.groupby(['COUNTY_GEOID_YEAR', 'TEMPBIN']) </code></pre> <p>I am thinking to loop through the groups and applying an operation that will identify which days are consecutive and which are not, within unique county, tempbin subsets. </p> <p>I'm rather new to programming and python, is this a good approach so far, if so how can I progress?</p> <p>Thank you - Let me know if I should provide additional information. </p> <p>Update:</p> <p>Using @karakfa advice I tried the following:</p> <pre><code>weatherFile.groupby(['COUNTY_GEOID_YEAR', 'TEMPBIN']) weatherFile['DISTANCE'] = weatherFile[1:, 'DATE_INT'] - weatherFile[:-1,'DATE_INT'] weatherFile['CONSECUTIVE?'] = np.logical_or(np.insert((weatherFile['DISTANCE']),0,0) == 1, np.append((weatherFile['DISTANCE']),0) == 1) </code></pre> <p>This resulting in a TypeError: unhashable type. Traceback happened in the second line. weatherFile['DATE_INT'] is dtype: int64. </p>
3
2016-08-03T21:18:51Z
38,754,106
<p>Once you have the ordinal numbers it's a trivial task, here I'm using numpy arrays to propose one alternative</p> <pre><code>a=np.array([1,2,4,6,7,10,12,13,14,20]) d=a[1:]-a[:-1] # compute delta ind=np.logical_or(np.insert(d,0,0)==1,np.append(d,0)==1) # at least one side matches a[ind] # get matching entries </code></pre> <p>gives you the numbers where there is a consecutive number</p> <pre><code>array([ 1, 2, 6, 7, 12, 13, 14]) </code></pre> <p>namely 4, 10 and 20 are removed.</p>
1
2016-08-03T21:41:41Z
[ "python", "datetime", "pandas" ]
How to identify consecutive dates
38,753,823
<p>I would like to identify dates in a dataframe which are consecutive, that is there exists either an immediate predecessor or successor. I would then like to mark which dates are and are not consecutive in a new column. Additionally I would like to do this operation within particular subsets of my data. </p> <p>First I create a new variable where I'd identify True of False for Consecutive Days.</p> <pre><code>weatherFile['CONSECUTIVE_DAY'] = 'NA' </code></pre> <p>I've converted dates into datetime objects then to ordinal ones:</p> <pre><code>weatherFile['DATE_OBJ'] = [datetime.strptime(d, '%Y%m%d') for d in weatherFile['DATE']] weatherFile['DATE_INT'] = list([d.toordinal() for d in weatherFile['DATE_OBJ']]) </code></pre> <p>Now I would like to identify consecutive dates in the following groups:</p> <pre><code>weatherFile.groupby(['COUNTY_GEOID_YEAR', 'TEMPBIN']) </code></pre> <p>I am thinking to loop through the groups and applying an operation that will identify which days are consecutive and which are not, within unique county, tempbin subsets. </p> <p>I'm rather new to programming and python, is this a good approach so far, if so how can I progress?</p> <p>Thank you - Let me know if I should provide additional information. </p> <p>Update:</p> <p>Using @karakfa advice I tried the following:</p> <pre><code>weatherFile.groupby(['COUNTY_GEOID_YEAR', 'TEMPBIN']) weatherFile['DISTANCE'] = weatherFile[1:, 'DATE_INT'] - weatherFile[:-1,'DATE_INT'] weatherFile['CONSECUTIVE?'] = np.logical_or(np.insert((weatherFile['DISTANCE']),0,0) == 1, np.append((weatherFile['DISTANCE']),0) == 1) </code></pre> <p>This resulting in a TypeError: unhashable type. Traceback happened in the second line. weatherFile['DATE_INT'] is dtype: int64. </p>
3
2016-08-03T21:18:51Z
38,754,698
<p>You can use .shift(-1) or .shift(1) to compare consecutive entries:</p> <pre><code>df.loc[df['DATE_INT'].shift(-1) - df['DATE_INT'] == 1, 'CONSECUTIVE_DAY'] = True </code></pre> <p>Will set CONSECUTIVE_DAY to TRUE if the previous entry is the previous day</p> <pre><code>df.loc[(df['DATE_INT'].shift(-1) - df['DATE_INT'] == 1) | (df['DATE_INT'].shift(1) - df['DATE_INT'] == -1), 'CONSECUTIVE_DAY'] = True </code></pre> <p>Will set CONSECUTIVE_DAY to TRUE if the entry is preceeded by or followed by a consecutive date.</p>
2
2016-08-03T22:29:45Z
[ "python", "datetime", "pandas" ]
Sharing Global variables in python
38,753,914
<p>I have 2 files a.py and b.py as follows:</p> <p>a.py</p> <pre><code>import b.py Test="abc" def main(args): global Test if args.target=="this": Test="klm" b.fun() #rest of the body which I intend to execute only once #hence I cannot call main() again if __name__ == "__main__": #some arguments are parsed args = parser.parse_args() main(args) </code></pre> <p>b.py</p> <pre><code>import a print a.Test </code></pre> <p>EDIT: Output:</p> <pre><code>python a.py abc </code></pre> <p>So basically my question is why is the Test variable not getting updated in b.py and how can I make this work? Thanks.</p>
-1
2016-08-03T21:25:53Z
38,754,017
<pre><code>import a a.main() print a.Test a.Test = "new Value" print a.Text </code></pre> <p>You never invoke the main function. When you import a module, <code>__name__</code> is not <code>"__main__"</code>, so your main() never runs. When you run a.py directly it will run main()</p>
1
2016-08-03T21:34:20Z
[ "python", "python-2.7", "variables", "global-variables", "global" ]
Sharing Global variables in python
38,753,914
<p>I have 2 files a.py and b.py as follows:</p> <p>a.py</p> <pre><code>import b.py Test="abc" def main(args): global Test if args.target=="this": Test="klm" b.fun() #rest of the body which I intend to execute only once #hence I cannot call main() again if __name__ == "__main__": #some arguments are parsed args = parser.parse_args() main(args) </code></pre> <p>b.py</p> <pre><code>import a print a.Test </code></pre> <p>EDIT: Output:</p> <pre><code>python a.py abc </code></pre> <p>So basically my question is why is the Test variable not getting updated in b.py and how can I make this work? Thanks.</p>
-1
2016-08-03T21:25:53Z
38,754,246
<h2>Added due to question edit:</h2> <p>You need to consider the ordering of the imports execution. Consider these working files.</p> <p>a.py</p> <pre><code>print("Entering a") import argparse import b Test="abc" print("Id of Test: ", id(Test)) def main(args): global Test if args.target=="this": Test="klm" b.fun() #rest of the body which I intend to execute only once #hence I cannot call main() again if __name__ == "__main__": #some arguments are parsed print('Entering main') parser = argparse.ArgumentParser() parser.add_argument('--target', dest='target', type=str) args = parser.parse_args() main(args) </code></pre> <p>b.py</p> <pre><code>print("Entering b") import a print a.Test def fun(): pass </code></pre> <p>The console produces the following:</p> <pre><code>$ python a.py Entering a Entering b Entering a ('Id of Test: ', 40012016L) abc ('Id of Test: ', 40012016L) Entering main </code></pre> <p>The problem is, when you import a python module/file, you will immediately execute all the statements in that module. As such, you have a problem with your dependencies (aka imports), because b is importing a before the value of Test is 'corrected' and then immediately acting on this.</p> <p>Consider two changes. First, introduce a third file <code>config.py</code> that contains this configuration information and that b does not import a. Second, move all your statements that require this config in b into functions that are called/bootstrapped by a, as obviously intended.</p> <h2>Previous answer:</h2> <p>I have a solution demonstrating the issue, by only modifying b.py</p> <pre><code>def fun(): # Added because your main calls this. An error? pass from a import Test, main import a print Test # prints 'abc' print a.Test # prints 'abc' main() print Test # prints 'abc' print a.Test # prints 'klm' </code></pre> <p>Within the python interpretor, I can produce the following:</p> <pre><code>&gt;&gt;&gt; import b abc abc abc klm </code></pre> <p>In your code, you create a new variable called <code>Test</code> with the command <code>from a import Test</code> that points to the original string object. You actually want to access the <code>Test</code> variable owned by the module <code>a</code>.</p>
0
2016-08-03T21:52:21Z
[ "python", "python-2.7", "variables", "global-variables", "global" ]
Sharing Global variables in python
38,753,914
<p>I have 2 files a.py and b.py as follows:</p> <p>a.py</p> <pre><code>import b.py Test="abc" def main(args): global Test if args.target=="this": Test="klm" b.fun() #rest of the body which I intend to execute only once #hence I cannot call main() again if __name__ == "__main__": #some arguments are parsed args = parser.parse_args() main(args) </code></pre> <p>b.py</p> <pre><code>import a print a.Test </code></pre> <p>EDIT: Output:</p> <pre><code>python a.py abc </code></pre> <p>So basically my question is why is the Test variable not getting updated in b.py and how can I make this work? Thanks.</p>
-1
2016-08-03T21:25:53Z
38,754,333
<p>In a.py you run main in the if statement:</p> <pre><code>if __name__ == "__main__": main() </code></pre> <p>Only executes main() if that is the main script. When you import the module all the code in the if block is not run because it is not the main script. To have the main method be called remove the if statement or just call main in b.py.</p>
0
2016-08-03T21:58:53Z
[ "python", "python-2.7", "variables", "global-variables", "global" ]
sliceplot for bound material in yt without showing unbound
38,753,964
<p>I am trying to mask out the bound density of a system with the masking field </p> <pre><code>@derived_field(name = "bound_density", units = "g/cm**3") def _get_ejected_density(field, data): E = 0.5* data["cell_mass"]* (data["velx"]**2+data["vely"]**2+data["velz"]**2)+ data["gpot"]*data["cell_mass"] return ((np.array(E)&lt;0)*1)*data["density"] </code></pre> <p>It also returns the unbound density with the white color bars along with the bound density, but I don't want to show the unbound things here. </p> <p>I was wondering if there is a way I can only show the bound material in this plot. Also another solution would be setting the unbound density color bar matching to the floor bar, hence 1.0e0, so that while the plot still shows the unbound density, it exactly matches the lowest density color bar in the plot and thus cannot be distinguished.</p> <p><a href="http://i.stack.imgur.com/0AtCH.png" rel="nofollow"><img src="http://i.stack.imgur.com/0AtCH.png" alt="enter image description here"></a></p>
2
2016-08-03T21:29:50Z
38,754,068
<p>Here's an example that shows how to manipulate the colorbar so the background color matches the color at the bottom of the colorbar:</p> <p><a href="https://gist.github.com/4d07fc6475becd18b793e15ae2f00dff" rel="nofollow">https://gist.github.com/4d07fc6475becd18b793e15ae2f00dff</a></p>
1
2016-08-03T21:38:57Z
[ "python", "background-color", "yt-project" ]
python3.4 import visa fails, this worked under python3.5
38,754,007
<p>OK, I loaded Python 3.5 PYVISA, and set up my path variables in Windows, and import visa worked! Yay!</p> <p>Now I want to create an executable, using cx_Freeze. I try running it, and it says it wants to see Python 3.4.</p> <p>OK, I load Python 3.4. I add python34 paths to Windows and start up idle, load my script, and try to import visa, no module named visa.</p> <p>What do I have to do to get the script to run under Python 3.4?</p> <p>thank you</p>
0
2016-08-03T21:33:20Z
38,754,231
<p>If you have installed pyvisa by using below command:</p> <pre><code>pip install pyvisa </code></pre> <p>Then it gets installed in site packages of python 3.5 (or) site packages of that specific python version (whichever python that is serving at that point of time)</p> <p>If you want that to be available for all python versions, install it to separate folder and add that path as value to PYTHONPATH (system variable). If there is no such variable, create one. Command to install it to separate folder is:</p> <pre><code>pip install pyvisa -t c:\external </code></pre> <p>(Or)</p> <p>Re-install it using pip from specific python version</p> <pre><code>C:\Python34\python.exe -m pip install pyvisa </code></pre>
2
2016-08-03T21:51:17Z
[ "python", "visa" ]
python regex: escape illegal characters only if it's not escaped already
38,754,038
<p>Right now I'm taking in files as string and formatting them into json. The file contains \r, \n characters that I want to escape, but there are json objects in the files which already has those illegal characters escaped, like \\r and \\n. So right now I want to replace \r \n characters with \\r \\n only if it's not preceded by one \</p> <p>I have tried this below.. but I'm not sure why it doesn't work</p> <pre><code>re.sub(r'[^\][\n]', r'\\\\n', s) </code></pre> <p>any suggestion would be appreciated!</p>
0
2016-08-03T21:36:31Z
38,754,114
<p>You could do it like this using RegEx:</p> <pre><code>import re data = 'Hello\r\nWorld\\r\\n' print(data) print('-'*20) data = re.sub(r'([^\\])\r', '\\1\\\\r', data) data = re.sub(r'([^\\])\n', '\\1\\\\n', data) print(data) </code></pre> <p><strong>Outputs:</strong></p> <pre><code>Hello World\r\n -------------------- Hello\r\nWorld\r\n </code></pre> <p>Or, a slightly different approach would be to do it like this:</p> <pre><code>data = 'Hello\r\nWorld\\r\\n' print(data) print('-'*20) data = data.replace('\r', '\\r') data = data.replace('\n', '\\n') print(data) </code></pre> <p><strong>Outputs:</strong></p> <pre><code>Hello World\r\n -------------------- Hello\r\nWorld\r\n </code></pre>
3
2016-08-03T21:42:30Z
[ "python", "json", "regex" ]
Python Split Unless Next Character Is Something
38,754,072
<p>I am using Python 3.5, and I would like to split a string by the character <code>\n</code>, or new line. however if the line starts with a underscore, for example, it should put that line with the one above it. I need the solution to work for all characters, not just underscore. It should work like this:</p> <pre><code>a = '''red yellow green _surprise! blue''' print(a.split('\n') </code></pre> <p>and should result in:</p> <pre><code>['red', 'yellow', 'green\n_surprise', 'blue'] </code></pre> <p>Thanks for any help!</p>
-3
2016-08-03T21:39:08Z
38,754,167
<p>You can repalce <code>\n_</code> with some characters and then split the string with delimiter <code>\n</code></p> <pre><code>&gt;&gt;&gt; a = '''red ... yellow ... green ... _surprise! ... blue''' &gt;&gt;&gt; a 'red\nyellow\ngreen\n_surprise!\nblue' </code></pre> <p>Either:</p> <pre><code>&gt;&gt;&gt; [x.replace("###", "\n_") for x in a.replace("\n_", "###").split()] ['red', 'yellow', 'green\n_surprise!', 'blue'] </code></pre> <p>Or:</p> <pre><code>&gt;&gt;&gt; [x.replace("###", "\n_") for x in a.replace("\n_", "###").splitlines()] ['red', 'yellow', 'green\n_surprise!', 'blue'] </code></pre>
0
2016-08-03T21:47:02Z
[ "python", "python-3.x", "split" ]
Python Split Unless Next Character Is Something
38,754,072
<p>I am using Python 3.5, and I would like to split a string by the character <code>\n</code>, or new line. however if the line starts with a underscore, for example, it should put that line with the one above it. I need the solution to work for all characters, not just underscore. It should work like this:</p> <pre><code>a = '''red yellow green _surprise! blue''' print(a.split('\n') </code></pre> <p>and should result in:</p> <pre><code>['red', 'yellow', 'green\n_surprise', 'blue'] </code></pre> <p>Thanks for any help!</p>
-3
2016-08-03T21:39:08Z
38,754,180
<p>It's pretty easy using regular expressions:</p> <pre><code>import re re.split('\n(?!_)', a) # ['red', 'yellow', 'green\n_surprise!', 'blue'] </code></pre> <p>This regex litterally means <code>split by \n not followed by _</code>.</p>
2
2016-08-03T21:47:54Z
[ "python", "python-3.x", "split" ]
How do I subset a 2D grid from another 2D grid in python?
38,754,079
<p>I have gridded data over the contiguous United States and I'm trying to select a chunk of it over a specific area.</p> <pre><code>import numpy as np from netCDF4 import Dataset import matplotlib.pyplot as plt filename = '/Users/me/myfile.nc' full_data = Dataset(filename,'r') latitudes = full_data.variables['latitude'][0,:,:] longitudes = full_data.variables['longitude'][0,:,:] temperature = full_data.variables['temperature'][0,:,:] </code></pre> <p>All three variables are 2-dimensional matrices of shape (337,451). I'm trying to do the following to get a sub-selection of the data over a specific region.</p> <pre><code>index = (latitudes&gt;=44.0)&amp;(latitudes&lt;=45.0)&amp;(longitudes&gt;=-91.0)&amp;(longitudes&lt;=-89.0) temp_subset = temperature[index] lat_subset = latitudes[index] lon_subset = longitudes[index] </code></pre> <p>I would expect all three of these variables to be 2-dimensional, but instead they all return a flattened array with a shape of (102,). I've tried another approach:</p> <pre><code>index2 = np.where((latitudes&gt;=44.0)&amp;(latitudes&lt;=45.0)&amp;(longitudes&gt;=-91.0)&amp;(longitudes&lt;=-89.0)) temp = temperatures[index2[0],:] temp2 = temp[:,index2[1]] plt.imshow(temp2,origin='lower') plt.colobar() </code></pre> <p>But my data looks quite incorrect. Is there a better way to get a 2D subset grid from a larger grid?</p> <p><a href="http://i.stack.imgur.com/smavb.png" rel="nofollow"><img src="http://i.stack.imgur.com/smavb.png" alt="enter image description here"></a></p>
0
2016-08-03T21:39:28Z
38,754,255
<p>Edub,</p> <p>I suggest looking on at numpy's matrix indexing documentation, specifically <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#other-indexing-options" rel="nofollow">http://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#other-indexing-options</a> . Currently, you are providing two dimensions for indexing, but no slicing information (resulting in only receiving one dimensional results). I hope this proves useful!</p>
0
2016-08-03T21:53:04Z
[ "python", "arrays", "indexing" ]
IPython: How to show the same plot in different cells?
38,754,107
<p>I'm still new to IPython Notebooks, Jupyter, and Python in general.</p> <p>I'm creating a scatter plot in a Jupyter notebook using the following code:</p> <pre><code>import numpy as np import matplotlib.pyplot as plt n = 1024 X = np.random.normal(0, 1, n) Y = np.random.normal(0, 1, n) plt.axes([0.025, 0.025, 0.95, 0.95]) plt.scatter(X, Y, s=50) plt.show() </code></pre> <p>My question is, how can I get a reference to the plot object so I can use it in a different cell later on in the notebook? Additionally, I may need to modify the plot before showing it again.</p> <p>Also, I have <code>%matplotlib inline</code> at the top of my notebook.</p> <p>Here are some info about my environment:</p> <ul> <li><strong>Python:</strong> 3.5.2 64bit [MSC v.1900 64 bit (AMD64)]</li> <li><strong>IPython:</strong> 4.2.0</li> <li><strong>numpy:</strong> 1.11.1</li> <li><strong>scipy:</strong> 0.17.1</li> <li><strong>matplotlib:</strong> 1.5.1</li> <li><strong>sympy:</strong> 1.0</li> <li><strong>OS:</strong> Windows 7 6.1.7601 SP1</li> </ul>
3
2016-08-03T21:41:59Z
38,768,002
<p>Try the object-oriented interface of matplotlib - <a href="http://matplotlib.org/api/figure_api.html#matplotlib.figure.Figure" rel="nofollow">matplotlib.figure</a>; you can use the reference of the Figure object created, as required. </p> <ul> <li>Create a figure object - <code>fig = plt.figure()</code></li> <li>Add axes to it - <code>ax = fig.add_axes([0.025, 0.025, 0.95, 0.95])</code></li> <li>Plot on the axis created - <code>ax.plot(X, Y)</code></li> </ul>
0
2016-08-04T12:57:11Z
[ "python", "matplotlib", "ipython-notebook", "jupyter-notebook" ]
Making .next() compatible with both python 2 and 3
38,754,118
<p>I have written code in python 2.7 that I want to make it compatible with Python 3.x. So far I have tried the <code>futurize</code> and <code>modernize</code> python packages as well as <code>2to3</code>, and everything seems fine.</p> <p>But I'm stuck with python 2.7's <code>.next()</code> method. And I get warning with both the <code>futurize</code> and <code>2to3</code> packages, like: </p> <pre><code>RefactoringTool: Line 34: Calls to builtin next() possibly shadowed by global binding </code></pre> <p>And when I run actual code in python 3.x it gives me this warning:</p> <pre><code>AttributeError: 'itertools._grouper' object has no attribute 'next' </code></pre> <p>The relevant code in python 2.7 is as follows:</p> <pre><code>with open('file.txt', 'rU') as f: l = f.readlines()[2:] up = (x[1] for x in groupby(l, lambda line: line[0] == "&gt;")) for u in up: head = u.next()[1:].strip() q = "".join(s.strip() for s in u.next()) # do something </code></pre>
0
2016-08-03T21:42:55Z
38,761,356
<p>Don't call the <code>.next()</code> method directly. Use the <a href="https://docs.python.org/2/library/functions.html#next" rel="nofollow"><code>next()</code> <em>function</em></a> on an iterator instead:</p> <pre><code>for u in up: head = next(u)[1:].strip() q = "".join(s.strip() for s in next(u)) </code></pre> <p>The <code>next()</code> function will invoke the correct hook on both Python 2 and 3.</p> <p>However, the error message you see from <code>futurize</code> indicates that you may <em>also</em> have bound the name <code>next</code> elsewhere in your code.</p> <p>If you have something like:</p> <pre><code>next = some_expression </code></pre> <p>or</p> <pre><code>def next(...): # some function </code></pre> <p>as a global, then you are <em>shadowing</em> the built-in <code>next()</code> function. Rename any other use of <code>next</code> as a global in that module to avoid issues.</p> <p>For example, the following demo code throws the message you see:</p> <pre><code>$ cat demo.py def next(): pass n = g.next() $ bin/futurize demo.py RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: Refactored demo.py --- demo.py (original) +++ demo.py (refactored) @@ -1,2 +1,2 @@ def next(): pass -n = g.next() +n = g.__next__() RefactoringTool: Files that need to be modified: RefactoringTool: demo.py RefactoringTool: Warnings/messages while refactoring: RefactoringTool: ### In file demo.py ### RefactoringTool: Line 1: Calls to builtin next() possibly shadowed by global binding RefactoringTool: ### In file demo.py ### RefactoringTool: Line 1: Calls to builtin next() possibly shadowed by global binding </code></pre> <p>Note how the tool then used <code>g.__next__()</code> instead of <code>g.next()</code>, to avoid using <code>next()</code> as a function.</p> <p>Removing the <code>next</code> function from that code results in:</p> <pre><code>$ cat demo.py # def next(): pass n = g.next() $ bin/futurize demo.py RefactoringTool: Skipping optional fixer: idioms RefactoringTool: Skipping optional fixer: ws_comma RefactoringTool: Refactored demo.py --- demo.py (original) +++ demo.py (refactored) @@ -1,2 +1,2 @@ # def next(): pass -n = g.next() +n = next(g) RefactoringTool: Files that need to be modified: RefactoringTool: demo.py </code></pre>
2
2016-08-04T07:44:02Z
[ "python", "python-2.7", "iterator" ]
Pandas Interpolate dataframe with new length
38,754,132
<p>I have a dataframe with columns of Datetime, lat, lon, z. I am reading the data in from a csv file so setting the period for the datetimes do not work. The times are in 6 hour intervals but I want to linearly interpolate the data to hourly intervals. </p> <p>Go from</p> <pre><code> 'A' 'B' 'C' 'D' 0 2010-09-13 18:00:00 16.3 -78.5 1 1 2010-09-14 00:00:00 16.6 -79.8 6 2 2010-09-14 06:00:00 17.0 -81.1 12 </code></pre> <p>To</p> <pre><code> 'A' 'B' 'C' 'D' 1 2010-09-13 18:00:00 16.3 -78.5 1 2 2010-09-13 19:00:00 16.35 -78.7 2 3 2010-09-13 20:00:00 16.4 -78.9 3 4 2010-09-13 21:00:00 16.45 -79.1 4 5 2010-09-13 22:00:00 16.5 -79.3 5 .... </code></pre> <p>I have tried using the interpolate command but there are no arguments for a new length of the dataframe. </p> <pre><code>df.interpolate(method='linear') </code></pre> <p>I was thinking that I could use .loc to include 5 rows of NANs between each line in the data frame and then use the interpolation function but that seems like a bad workaround.</p> <p><strong>Solution</strong> Using DatetimeIndex eliminates the association with the other columns if your initial column was not imported as datetime.</p> <pre><code>i = pd.DatetimeIndex(start=df['A'].min(), end=df['A'].max(), freq='H') df = df.reindex(i).interpolate() print(df) </code></pre> <p>Gives the correct answer.</p>
3
2016-08-03T21:43:58Z
38,755,716
<pre><code>i = pd.DatetimeIndex(start=df.index.min(), end=df.index.max(), freq='H') df = df.reindex(i).interpolate() print(df) </code></pre> <p>outputs</p> <pre><code>2010-09-13 18:00:00 16.300000 -78.500000 2010-09-13 19:00:00 16.350000 -78.716667 2010-09-13 20:00:00 16.400000 -78.933333 2010-09-13 21:00:00 16.450000 -79.150000 2010-09-13 22:00:00 16.500000 -79.366667 </code></pre> <ol> <li><p>Create a new index with the desired frequency using <code>DatetimeIndex</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.html" rel="nofollow">docs</a>).</p></li> <li><p><code>reindex</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow">docs</a>) with this new index. By default values for new indices will be <code>np.nan</code>.</p></li> <li><p><code>interpolate</code> (<a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.interpolate.html" rel="nofollow">docs</a>) to fill in these missing values. You can supply the <code>method</code> kwarg to determine how interpolation is done.</p></li> </ol>
1
2016-08-04T00:30:37Z
[ "python", "pandas", "linear-interpolation" ]
Embedded Cython UCS2 UCS4 issue
38,754,156
<p>I have some python code I am trying to embed within c++ code using the cython api construct. For testing purposes I have been working off of: <a href="https://stackoverflow.com/questions/34480973/example-program-of-cython-as-python-to-c-converter">Example program of Cython as Python to C Converter</a></p> <p>With the slightly modified code:</p> <pre><code>#foo.pyx cdef public foo(double* x): x[0] = 0.0 //file.cpp #include "Python.h" #include "foo.h" #include &lt;iostream&gt; int main(int argc, const char * argv[]) { double arr[2] = {1,2}; foo(arr); std::cout &lt;&lt; arr[0] &lt;&lt; std::endl; std::cout &lt;&lt; arr[1] &lt;&lt; std::endl; } </code></pre> <p>After running</p> <pre><code>cython foo.pyx </code></pre> <p>I attempt to compile receiving the error message:</p> <pre><code>foo.c:(.text+0x387): undefined reference to 'PyUnicodeUCS4_DecodeUTF8' </code></pre> <p>I have seen other questions regarding the matter, such as <a href="https://stackoverflow.com/questions/19888104/an-ucs2-ucs4-incompatibility-import-failure-of-a-cythnized-pure-python-module">An UCS2-UCS4 incompatibility import failure of a Cythnized pure-Python module</a>, and when I run:</p> <pre><code>import sys; sys.maxunicode </code></pre> <p>I get 1114111 which is in line with UCS4. So what I am wondering is how to I resolve this undefined reference, when my python version seems to be line with the proper UCS there, but not elsewhere.</p>
0
2016-08-03T21:45:55Z
38,778,201
<p>It turns out I had two different installations of python on my system and I was linking the wrong one.</p>
0
2016-08-04T22:08:33Z
[ "python", "c++", "cython", "ucs2", "ucs-4" ]
Sort CSV data with Python
38,754,163
<p>I have a CSV that have this example format (there will be many rows like this format):</p> <pre><code>1131,01/06/15,PROFI ROM FOOD SRL,290.7,, 1131,,,,, 3811861,01/12/15,CENTRUL TERITORIAL DE CALCUL,141.36,, 3811861,,ELECTRONIC SA,,, 49171,01/15/15,AUTOGLOBUS 2000 SRL,"1,138.10",, 49171,,,,, 2024194PJ,01/08/15,SOCIETATEA NATIONALA DE,"2,088.17",, 2024194PJ,,RADIOCOMUNICATII SA,,, </code></pre> <p>My desired output after the sort should by like this :</p> <pre><code>1131,01/06/15,PROFI ROM FOOD SRL,290.7,, 3811861,01/12/15,CENTRUL TERITORIAL DE CALCUL ELECTRONIC SA,141.36,, 49171,01/15/15,AUTOGLOBUS 2000 SRL,"1,138.10",, 2024194PJ,01/08/15,SOCIETATEA NATIONALA DE RADIOCOMUNICATII SA,"2,088.17",, </code></pre> <p>When script is detecting a row with a number and nothing after that like this (1131,,,,,) it should delete that row, when he detects a number 2 spaces(can be more than 2 sometime, but usually 2) like this (3811861,,ELECTRONIC SA,,,) he should get that string (ELECTRONIC SA) and append it to above row at index 2 like this (CENTRUL TERITORIAL DE CALCUL ELECTRONIC SA).</p> <p>What I'm thinking is that I should make a list of lists for each row, do a for loop and append what I need (maybe a regex sort?) and ignore the rows that I don't need, but I don't know how exactly is the best way to do it? Can anyone help with a easy script, thanks a lot for your time! </p>
-1
2016-08-03T21:46:31Z
38,755,048
<p>You should look at the built-in <a href="https://docs.python.org/2/library/csv.html" rel="nofollow">csv module</a> to load the csv data, and then just loop through the lines and filter out the ones you want.</p>
-1
2016-08-03T23:08:08Z
[ "python", "csv" ]
Python keyboard events without GUI (non-blocking)
38,754,175
<p>I am trying to find a way to get KeyDown and KeyUp events in Python. With Pygame, this is easily done with <code>pygame.KEYDOWN</code> and <code>pygame.KEYUP</code>, but I am trying to find a way to do it without using a GUI.</p> <p>Ideally, I would like to be able to define a function <code>isKeyDown(key)</code>, which would return <code>True</code> if <code>key</code> is currently being held down, or return <code>False</code> if it isn't, but either way, it would move on with the code (it would be non-blocking). For example:</p> <pre><code>while True: if not isKeyDown("a"): #If 'a' isn't currently being pressed print ("You are not pressing 'a'") elif isKeyDown("a"): #If 'a' is being held down when this is run print ("You are pressing 'a'") print ("This is the end of this program") break </code></pre> <p>I've tried <code>msvcrt.getch()</code>, but that has two problems:</p> <p>1) It stops the program until something is pressed, and</p> <p>2) It doesn't really tell you if the key is being held down; it simply returns if the key is being pressed at the time. This can sometimes coincide since Windows repeats key presses when they are held down, but it is unlikely to happen when the <code>while</code> loop is being run at maximum speed.</p> <p>I've also used <code>msvcrt.kbhit()</code>, but it sets itself to <code>1</code> if any key has been pressed and not read by <code>msvcrt.getch()</code>, and so that still runs into the problems of <code>msvcrt.getch()</code> and doesn't really return whether a key is actually currently being held down.</p> <p>I am using Windows, so the <code>curses</code> module that many people have used to answer similar questions isn't available.</p> <p>Is there a way to define such a <code>isKeyDown()</code> function in Windows without a GUI, preferably only using built-in modules? If this is not possible with the built-in Python modules, third-party modules would be okay, as long as they don't require a GUI.</p> <p>Even using Pygame or Tkinter would be fine, as long as a way to turn off their GUIs.</p> <p>If this is not possible, please tell me why, so I can stop looking for a solution (I have been trying to do little else for the past few days).</p> <p>I am using Python 3.5.2 on a 64-bit Windows 10 laptop.</p>
0
2016-08-03T21:47:36Z
38,754,863
<p>It looks like what you want to do is get <a href="https://pypi.python.org/pypi/pyHook" rel="nofollow">pyhook</a>. I believe it depends on the <a href="https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/" rel="nofollow">pywin32</a> library.</p> <p>Basically what you want to do is look for creating a keylogger. That will give you non-blocking keyboard events. Of course you may want to use the win32 api to make sure that when the key is pressed it's <em>your</em> window that's in focus, if that matters to you.</p> <p>I don't have my windows box accessible, or I'd be able to give you more code samples, but that should at least point you in the right direction.</p>
0
2016-08-03T22:47:18Z
[ "python", "windows", "python-3.x" ]
Changing Edges to match angles
38,754,184
<p>I'm scripting in python and I'm very new to this, and don't have a lot of experience with vector math, I can get dot product, length, and angle of two vectors, and I've managed to get the angle of difference between the two points (an edge), but I'm not sure about the math/process of actually modifying the second set of points to match the angle of the first. What I'm trying to do is rotate the second set of points to match the first set, regardless of its current location. For example:</p> <pre><code>#python import math def dot (v1, v2): return (v1[0]*v2[0] + v1[1]*v2[1]) def length (v): return math.sqrt(dot(v,v)) def normalize (v): r = [0.0] * 2 v_len = length (v) if v_len &gt; 0.0: v_invLen = 1.0 / v_len r[0] = v[0] * v_invLen r[1] = v[1] * v_invLen return r def direction (v1, v2): return (v2[0]-v1[0], v2[1]-v1[1]) def angle(dotProduct): return math.degrees(math.acos(dotProduct)) p1,p2 = (0,0),(0,1) &lt;--- first edge p3,p4 = (0,0),(2,2) &lt;--- second edge dir = direction(p1,p2) dir2 = direction(p3,p4) dir_n = normalize(dir) dir2_n = normalize(dir2) dotProduct = dot(dir_n, dir2_n) ang1 = math.degrees(math.acos(dotProduct)) print ang1 </code></pre> <p>This gives me a 45 degree angle, what I'm trying to do is now rotate the second edge p2 to match the angle of p1 regardless of its location in world space so p1 might be (1,1),(-2,-2) and p2 might be (-1,1),(-3,3) with a 90 degree rotation required </p>
1
2016-08-03T21:48:09Z
38,754,866
<p>Define a new function called rotate:</p> <pre><code>def rotate(v,ang): result =[v[0]*math.cos(ang)-v[1]*math.sin(ang),v[0]*math.sin(ang)+v[1]*math.cos(ang)] return result # So to rotate a given vector,lets take your example p1,p2 = (1,1),(-2,-2) p3,p4 = (-1,1),(-3,3) p1,p2 = (1,1),(-2,-2) p3,p4 = (-1,1),(-3,3) dir = direction(p1,p2) dir2 = direction(p3,p4) dir_n = normalize(dir) print ("Direction1") print (dir_n) dir2_n = normalize(dir2) print ("Direction2") print (dir2_n) dotProduct = dot(dir_n, dir2_n) ang1 = math.degrees(math.acos(dotProduct)) #Rotate dir2_n in direction of dir_n new_vec = rotate(dir2_n,math.radians(ang1)) print ("rotated_vector") print (new_vec) Output: Direction1 [-0.7071067811865476, -0.7071067811865476] Direction2 [-0.7071067811865475, 0.7071067811865475] rotated_vector [-0.7071067811865475, -0.7071067811865475] </code></pre> <p>Rotated vector should be the same as dir_1. Let me know if this solves your problem</p>
0
2016-08-03T22:47:36Z
[ "python", "math", "rotation" ]
drawing gaussian random variables using scipy erfinv
38,754,423
<p>I would like to draw <em>npts</em> random variables distributed as a gaussian with mean <em>mu</em> and dispersion <em>sigma</em>. I know how to do this in Numpy:</p> <pre><code>x = np.random.normal(loc=mu, scale=sigma, size=npts) print(np.std(x), np.mean(x)) 0.1998, 0.3997 </code></pre> <p>This should also be possible to do using scipy.special.erfinv via inverse transforms, beginning from a uniform distribution:</p> <pre><code>u = np.random.uniform(0, 1, npts) </code></pre> <p>However, I can't figure out how to get the scaling correct. Has anyone done this before?</p>
0
2016-08-03T22:05:57Z
38,754,558
<p>The best approach would probably be an own implementation of highly-optimized gaussian-samplers like:</p> <ul> <li><a href="https://en.wikipedia.org/wiki/Marsaglia_polar_method" rel="nofollow">polar-method</a></li> <li><a href="https://en.wikipedia.org/wiki/Ziggurat_algorithm" rel="nofollow">ziggurat</a></li> <li><a href="https://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform" rel="nofollow">box-muller</a></li> </ul> <p>But here is something simple (which i saw a long time ago <a href="https://pythonhosted.org/pyDOE/randomized.html" rel="nofollow">here</a>). This will be less efficient than the approaches above (as it's using the quantile function / percent point function which has no closed-form representation for the normal-distribution and will be approximated):</p> <pre><code>import numpy as np from scipy.stats.distributions import norm uniform_samples = np.random.rand(100000) gaussian_samples = norm(loc=0, scale=1).ppf(uniform_samples) </code></pre>
2
2016-08-03T22:16:18Z
[ "python", "numpy", "random", "scipy", "scientific-computing" ]
drawing gaussian random variables using scipy erfinv
38,754,423
<p>I would like to draw <em>npts</em> random variables distributed as a gaussian with mean <em>mu</em> and dispersion <em>sigma</em>. I know how to do this in Numpy:</p> <pre><code>x = np.random.normal(loc=mu, scale=sigma, size=npts) print(np.std(x), np.mean(x)) 0.1998, 0.3997 </code></pre> <p>This should also be possible to do using scipy.special.erfinv via inverse transforms, beginning from a uniform distribution:</p> <pre><code>u = np.random.uniform(0, 1, npts) </code></pre> <p>However, I can't figure out how to get the scaling correct. Has anyone done this before?</p>
0
2016-08-03T22:05:57Z
38,754,777
<p>Try this:</p> <pre><code>mean = 100 sigma = 7 x = mean + 2**0.5 * sigma * erfinv(np.random.uniform(size=10**5) * 2 - 1) x.mean(), x.std() Out: (99.965915366042381, 7.0062395839075107) </code></pre> <p><a href="http://i.stack.imgur.com/t3ow5.png" rel="nofollow"><img src="http://i.stack.imgur.com/t3ow5.png" alt="enter image description here"></a></p> <p>The conversion from erf to normal distribution is from <a href="http://www.johndcook.com/blog/2008/03/15/error-function-and-the-normal-distribution/" rel="nofollow">John D. Cook's blog</a>.</p>
4
2016-08-03T22:37:59Z
[ "python", "numpy", "random", "scipy", "scientific-computing" ]
pip.main() resetting logging settings in python
38,754,432
<p>It seems that if I call <code>pip.main()</code> in my code my logging settings get reset.</p> <p>Working example:</p> <pre><code>import logging import pip logger = logging.getLogger() logger.setLevel(logging.DEBUG) logging.debug("Test") # prints 'DEBUG:root:Test' pip.main(["install", "requests"]) # prints pip output logging.debug("Test") # doesn't print anything </code></pre> <p>Any ideas how I can avoid this?</p>
0
2016-08-03T22:06:31Z
38,774,175
<p>The <code>install</code> command of <code>pip</code> overwrites the logging configuration. You need to reset the configuration yourself afterwards, e.g. by doing</p> <pre><code>logger.setLevel(logging.DEBUG) </code></pre> <p>again after the <code>pip.main()</code> call. Note that you may also have to add handlers, if the ones added by <code>pip</code> aren't what you want.</p>
0
2016-08-04T17:49:06Z
[ "python", "logging", "pip" ]
pip.main() resetting logging settings in python
38,754,432
<p>It seems that if I call <code>pip.main()</code> in my code my logging settings get reset.</p> <p>Working example:</p> <pre><code>import logging import pip logger = logging.getLogger() logger.setLevel(logging.DEBUG) logging.debug("Test") # prints 'DEBUG:root:Test' pip.main(["install", "requests"]) # prints pip output logging.debug("Test") # doesn't print anything </code></pre> <p>Any ideas how I can avoid this?</p>
0
2016-08-03T22:06:31Z
38,777,502
<p>It turns out that this is a <a href="https://github.com/pypa/pip/issues/3043#issuecomment-237476013" rel="nofollow">known issue</a> in the <a href="https://github.com/pypa/pip" rel="nofollow">pip module</a>. </p> <p>This is because when pip was created it was not intended to be imported into other programs, therefore considerations like changing root logging config were not thought about.</p> <p>The work around suggested by the project maintainers is to use the <code>subprocess</code> module to call pip itself. They are open to pull requests to resolve this but it would require a large amount of work on the project.</p> <p>Therefore my code now looks like</p> <pre><code>import logging import subprocess logger = logging.getLogger() logger.setLevel(logging.DEBUG) logging.debug("Test") # prints 'DEBUG:root:Test' process = subprocess.Popen(["pip", "install", "requests"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) process.wait() # prints pip output logging.debug("Test") # prints 'DEBUG:root:Test' </code></pre>
0
2016-08-04T21:13:38Z
[ "python", "logging", "pip" ]
Program output is not as expected - Searching for int values in a list of tuples
38,754,478
<p>I am coding a function which takes a search enquiry for a list of tuples (Employee records) and then outputs based on the enquiry parameters. For example, in my problem I am searching a salary range with a minimum of 30000 and a maximum of 100000, I would expect this to output the names of staff members within this salary range, however it instead give the output of no results found, which is incorrect as there are many staff members within this salary range.</p> <p>As a comparison, a minimum of 0 and a maximum of 100000 would output all of the records which is correct, however when putting the minimum above 30000 it always outputs no result found which is infact correct as there are many staff salaries in the list of tuples which are over 30000.</p> <p>Below is the part of the code which I believe is causing the problem (Not posting the whole code as this is a coursework project and I dont want to encourage plagiarism on my work):</p> <p>This should actually output results as there are employees within this salary range, but it is apparent that something is wrong in the code, and I cannot see what this is!</p> <p>I hope someone can help, this has been bothering me for a while and I really cant seem to find the solution to this! </p>
0
2016-08-03T22:09:51Z
38,754,582
<p>I think your program exits after the first tuple is processed. Is the first tuple outside of the salary range? If so, it skips the if statement and goes to the elif. querFound is still false and x is still 0, so it prints and exits.</p> <hr> <p>My suggestion is to replace your entire while loop with this for loop:</p> <pre><code>for t in editTup: sal = int(t[2]) if sal &gt; salMin and sal &lt; salMax: print(t[4] + " " + t[3]) querFound = True if not querFound: print('No results found') </code></pre>
1
2016-08-03T22:19:03Z
[ "python", "list", "python-3.x", "indexing", "tuples" ]
Efficient data sampling with sparse timestamps on a pre-defined date range
38,754,493
<p>Consider a dataframe with sparse temporal data. The timestamps can be very old (e.g. years ago) or very recent.</p> <p>As an example, let's take the following dataframe:</p> <pre><code> tstamp item_id budget 2016-07-01 14:56:51.882649 0Szr8SuNbY 5000.00 2016-07-20 14:57:23.856878 0Szr8SuNbY 5700.00 2016-07-17 16:32:27.838435 0Lzu1xOM87 303.51 2016-07-30 21:50:03.655102 0Lzu1xOM87 94.79 2016-08-01 14:56:31.081140 0HzuoujTsN 100.00 </code></pre> <p>Say we need to <strong>resample</strong> this dataframe <strong>for each <code>item_id</code></strong> so that we get a <strong>dense</strong> dataframe that has one data point for every day for a <strong>pre-defined date range</strong>, using a <strong>forward fill</strong>.</p> <p>In other words, if I resample the above for the time interval </p> <pre><code>pd.date_range(date(2016,7,15), date(2016,7,31) </code></pre> <p>I should get:</p> <pre><code> date item_id budget 2016-07-15 0Szr8SuNbY 5000.00 2016-07-16 0Szr8SuNbY 5000.00 2016-07-17 0Szr8SuNbY 5000.00 ... 2016-07-31 0Szr8SuNbY 5000.00 2016-07-15 0Lzu1xOM87 NaN 2016-07-16 0Lzu1xOM87 NaN 2016-07-17 0Lzu1xOM87 303.51 ... 2016-07-31 0Lzu1xOM87 94.79 2016-07-15 0HzuoujTsN NaN 2016-07-16 0HzuoujTsN NaN 2016-07-17 0HzuoujTsN NaN ... 2016-07-31 0HzuoujTsN NaN </code></pre> <p>Note that the original dataframe contains sparse timestamps and a potentially very <strong>high number</strong> of unique <code>item_id</code>s. In other words, I am hoping to find a <strong>computational efficient</strong> way of resampling this data with daily frequency on a pre-defined time period of consideration.</p> <p>What's the best we can do in Pandas, numpy, or Python in general?</p>
0
2016-08-03T22:10:33Z
38,754,772
<p>You can do a <code>groupby</code> on <code>'item_id'</code> and call <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> on each group:</p> <pre><code># Define the new time interval. new_dates = pd.date_range('2016-07-15', '2016-07-31', name='date') # Set the current time stamp as the index and perform the groupby. df = df.set_index(['tstamp']) df = df.groupby('item_id').apply(lambda grp: grp['budget'].reindex(new_dates, method='ffill').to_frame()) # Reset the index to remove 'item_id' and 'date' from the index. df = df.reset_index() </code></pre> <p>Another option is to <code>pivot</code>, <code>reindex</code>, and <code>unstack</code>:</p> <pre><code># Define the new time interval. new_dates = pd.date_range('2016-07-15', '2016-07-31', name='date') # Pivot to have 'item_id' columns with 'budget' values. df = df.pivot(index='tstamp', columns='item_id', values='budget').ffill() # Reindex with the new dates. df = df.reindex(new_dates, method='ffill') # Unstack and reset the index to return to the original format. df = df.unstack().reset_index().rename(columns={0:'budget'}) </code></pre>
1
2016-08-03T22:37:19Z
[ "python", "pandas", "numpy", "resampling" ]
AWS Unable to import module 'app' : no module named Pymysql
38,754,595
<p>I am using the AWS Console and trying to add data to a MySQL table using a Lambda function. Whenever I try to test the function, I get the following error: </p> <blockquote> <p>Unable to import module 'app' : no module named pymysql</p> </blockquote> <p>Its acting like pymysql is not in the path. I went into the microEC2 instance and pip'ed pymysql. But it still doesn't work. I have tried zipping my code into a file and uploading and also copying and pasting the code into the console and running it. Neither works. Any help would be greatly appreciated.</p> <p>Here is a code snippet:</p> <pre><code>import sys import logging import pymysql def main(event, context): </code></pre>
0
2016-08-03T22:19:56Z
38,754,838
<p>You must package all your project dependency in your deployment.</p> <ol> <li>Copy from your virtual environment the package PyMysql, to the root of directory where your code lives. </li> <li><p>Create a zip, and upload it to lambda function</p> <p>See the <a href="http://docs.aws.amazon.com/es_es/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html" rel="nofollow">docs</a></p></li> </ol>
0
2016-08-03T22:44:39Z
[ "python", "amazon-web-services", "import", "pymysql" ]
Separating multiple query results
38,754,667
<p>I am running multiple (about 60) queries in impala using impala shell from a file and outputting to a file. I am using :</p> <pre><code>impala-shell -q "query_here; query_here; etc;" -o output_path.csv -B --output_delimiter=',' </code></pre> <p>The issue is that they are not separated between queries, so query 2 would be directly appended as a new row right onto the bottom of query 1. I need to separate the results to math them up with each query, however I do not know where each query's results are done and another begins because it is a continuous CSV file.</p> <p>Is there a way to run multiple queries like this and leave some type of space or delimiter between query results or any way to separate the results by which query they came from? </p> <p>Thanks.</p>
0
2016-08-03T22:26:42Z
39,276,579
<p>You could insert your own separators by issuing some extra queries, for example <code>select '-----';</code> between the real queries.</p> <p>Writing results of individual queries to local files is not yet possible, but there is already a feature request for it (<a href="https://issues.cloudera.org/browse/IMPALA-2073" rel="nofollow">IMPALA-2073</a>). You can, however, easily save query results into HDFS as CSV files. You just have to create a new table to store the results specifying <code>row format delimited fields terminated by ','</code>, then use <code>insert into table [...] select [...]</code> to populate it. Please refer to the documentation sections <a href="http://www.cloudera.com/documentation/enterprise/latest/topics/impala_txtfile.html" rel="nofollow">Using Text Data Files with Impala Tables</a> and <a href="http://www.cloudera.com/documentation/enterprise/latest/topics/impala_insert.html" rel="nofollow">INSERT Statement</a> for details.</p> <p>One comment suggested running the individual queries as separate commands and saving their results into separate CSV files. If you choose this solution, please be aware that DDL statements like <code>create table</code> are only guaranteed to take immediate effect in the connection in which they were issued. This means that creating a table and then immediately querying it in another impala shell is prone to failure. Even if you find that it works correctly, it may fail the next time you run it. On the other hand, running such queries one after the other in the same shell is always okay.</p>
0
2016-09-01T16:27:39Z
[ "python", "sql", "impala" ]
Plane fitting in a 3d point cloud
38,754,668
<p>I am trying to find planes in a 3d point cloud, using the regression formula <a href="https://en.wikipedia.org/wiki/Plane_(geometry)" rel="nofollow">Z= a<em>X + b</em>Y +C</a> </p> <p>I implemented least squares and ransac solutions, but the 3 parameters equation limits the plane fitting to 2.5D- the formula can not be applied on planes parallel to the Z-axis.</p> <p>My question is <strong>how can I generalize the plane fitting to full 3d</strong>? I want to add the fourth parameter in order to get the full equation a<em>X +b</em>Y +c*Z + d how can I avoid the trivial (0,0,0,0) solution?</p> <p>Thanks!</p> <p>The Code I'm using:</p> <pre><code>from sklearn import linear_model def local_regression_plane_ransac(neighborhood): """ Computes parameters for a local regression plane using RANSAC """ XY = neighborhood[:,:2] Z = neighborhood[:,2] ransac = linear_model.RANSACRegressor( linear_model.LinearRegression(), residual_threshold=0.1 ) ransac.fit(XY, Z) inlier_mask = ransac.inlier_mask_ coeff = model_ransac.estimator_.coef_ intercept = model_ransac.estimator_.intercept_ </code></pre>
3
2016-08-03T22:26:59Z
38,770,513
<p>I think that you could easily use <a href="https://en.wikipedia.org/wiki/Principal_component_analysis" rel="nofollow">PCA</a> to fit the plane to the 3D points instead of regression.</p> <p>Here is a simple PCA implementation:</p> <pre><code>def PCA(data, correlation = False, sort = True): """ Applies Principal Component Analysis to the data Parameters ---------- data: array The array containing the data. The array must have NxM dimensions, where each of the N rows represents a different individual record and each of the M columns represents a different variable recorded for that individual record. array([ [V11, ... , V1m], ..., [Vn1, ... , Vnm]]) correlation(Optional) : bool Set the type of matrix to be computed (see Notes): If True compute the correlation matrix. If False(Default) compute the covariance matrix. sort(Optional) : bool Set the order that the eigenvalues/vectors will have If True(Default) they will be sorted (from higher value to less). If False they won't. Returns ------- eigenvalues: (1,M) array The eigenvalues of the corresponding matrix. eigenvector: (M,M) array The eigenvectors of the corresponding matrix. Notes ----- The correlation matrix is a better choice when there are different magnitudes representing the M variables. Use covariance matrix in other cases. """ mean = np.mean(data, axis=0) data_adjust = data - mean #: the data is transposed due to np.cov/corrcoef syntax if correlation: matrix = np.corrcoef(data_adjust.T) else: matrix = np.cov(data_adjust.T) eigenvalues, eigenvectors = np.linalg.eig(matrix) if sort: #: sort eigenvalues and eigenvectors sort = eigenvalues.argsort()[::-1] eigenvalues = eigenvalues[sort] eigenvectors = eigenvectors[:,sort] return eigenvalues, eigenvectors </code></pre> <p>And here is how you could fit the points to a plane:</p> <pre><code>def best_fitting_plane(points, equation=False): """ Computes the best fitting plane of the given points Parameters ---------- points: array The x,y,z coordinates corresponding to the points from which we want to define the best fitting plane. Expected format: array([ [x1,y1,z1], ..., [xn,yn,zn]]) equation(Optional) : bool Set the oputput plane format: If True return the a,b,c,d coefficients of the plane. If False(Default) return 1 Point and 1 Normal vector. Returns ------- a, b, c, d : float The coefficients solving the plane equation. or point, normal: array The plane defined by 1 Point and 1 Normal vector. With format: array([Px,Py,Pz]), array([Nx,Ny,Nz]) """ w, v = PCA(points) #: the normal of the plane is the last eigenvector normal = v[:,2] #: get a point from the plane point = np.mean(points, axis=0) if equation: a, b, c = normal d = -(np.dot(normal, point)) return a, b, c, d else: return point, normal </code></pre> <p>However as this method is sensitive to outliers you could use <a href="https://en.wikipedia.org/wiki/RANSAC" rel="nofollow">RANSAC</a> to make the fit robust to outliers.</p> <p>There is a Python implementation of ransac <a href="http://scipy.github.io/old-wiki/pages/Cookbook/RANSAC" rel="nofollow">here</a>.</p> <p>And you should only need to define a Plane Model class in order to use it for fitting planes to 3D points.</p> <p>In any case if you can clean the 3D points from outliers (maybe you could use a KD-Tree S.O.R filter to that) you should get pretty good results with PCA.</p> <p>Here is an implementation of an <a href="http://pointclouds.org/documentation/tutorials/statistical_outlier.php" rel="nofollow">S.O.R</a>:</p> <pre><code>def statistical_outilier_removal(kdtree, k=8, z_max=2 ): """ Compute a Statistical Outlier Removal filter on the given KDTree. Parameters ---------- kdtree: scipy's KDTree instance The KDTree's structure which will be used to compute the filter. k(Optional): int The number of nearest neighbors wich will be used to estimate the mean distance from each point to his nearest neighbors. Default : 8 z_max(Optional): int The maximum Z score wich determines if the point is an outlier or not. Returns ------- sor_filter : boolean array The boolean mask indicating wherever a point should be keeped or not. The size of the boolean mask will be the same as the number of points in the KDTree. Notes ----- The 2 optional parameters (k and z_max) should be used in order to adjust the filter to the desired result. A HIGHER 'k' value will result(normally) in a HIGHER number of points trimmed. A LOWER 'z_max' value will result(normally) in a HIGHER number of points trimmed. """ distances, i = kdtree.query(kdtree.data, k=k, n_jobs=-1) z_distances = stats.zscore(np.mean(distances, axis=1)) sor_filter = abs(z_distances) &lt; z_max return sor_filter </code></pre> <p>You could feed the function with a KDtree of your 3D points computed maybe using <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html" rel="nofollow">this implementation</a></p>
2
2016-08-04T14:42:05Z
[ "python", "3d", "geometry", "computer-vision", "point-clouds" ]
SQLAlchemy : random Unique integer?
38,754,816
<p>I can do this to set column type to be unique string :</p> <pre><code> uuid = Column(String, default=lambda: str(uuid.uuid4()), unique=True) </code></pre> <p>but I want to generate <strong>random-unique-integer</strong>, not random-unique-string.</p> <p>any idea how to do that ?</p> <hr> <p>uuid.uuid4().int</p> <p>thanks. If I can respecify :) is there a way to fit it into DB Integer type.</p>
1
2016-08-03T22:42:06Z
38,755,193
<pre><code>from random import randint def random_integer(): min_ = 100 max_ = 1000000000 rand = randint(min_, max_) # possibility of same random number is very low. # but if you want to make sure, here you can check id exists in database. from sqlalchemy.orm import sessionmaker db_session_maker = sessionmaker(bind=your_db_engine) db_session = db_session_maker() while db_session.query(Table).filter(uuid == rand).limit(1).first() is not None: rand = randint(min_, max_) return rand class Table(Base): uuid = Column(String, default=random_integer, unique=True) </code></pre>
1
2016-08-03T23:26:33Z
[ "python", "random", "sqlalchemy", "unique", "identifier" ]