title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Python - Speech Recognition time offsets
38,642,310
<p>I am trying to do speech recognition using python. In addition to this, I need to get the times of beginning and end of each word.</p> <p>I would rather use a free library that can deal with this. I've heard that Sphinx is able to do this but I couldn't find any examples (for python anyway).</p> <p>I would appreci...
2
2016-07-28T16:47:00Z
38,647,498
<p>Something like this:</p> <pre><code>from os import environ, path from pocketsphinx.pocketsphinx import * from sphinxbase.sphinxbase import * MODELDIR = "../../../model" DATADIR = "../../../test/data" config = Decoder.default_config() config.set_string('-hmm', path.join(MODELDIR, 'en-us/en-us')) config.set_string...
0
2016-07-28T22:04:38Z
[ "python", "speech-recognition", "cmusphinx" ]
Python 3 int() function is not converting input string to integer
38,642,339
<p>I am working on a small program that reads data from a CSV file. As part of the program, user input is used to only select data that >= but I get <strong>TypeError: unorderable types: str() >= int()</strong> when I run the code. Looks like the sting is not converting to integer.</p> <pre><code>def get_csv_data(data...
0
2016-07-28T16:48:19Z
38,642,406
<p><code>int</code> does not <em>cast</em> its parameters to integer in-place. In fact those parameters are immutable.</p> <p><code>int(sessions)</code> does not <em>exactly</em> do what you think it does. <code>session</code> is not modified, but the return value of that call is an <code>int</code>.</p> <p>You shoul...
3
2016-07-28T16:52:04Z
[ "python", "int" ]
Using +level-colors from ImageMagick in Python with Wand
38,642,347
<p>I'm going to use Wand to cut out some parts of an image. The image has a transparent background. But before I cut out the parts, I first want to make some adjustments to the source image (without actually altering the source file).</p> <p>The adjustments I want to make are:</p> <ol> <li>Change the black point to g...
0
2016-07-28T16:48:36Z
38,677,963
<p>Since your output image is grey anyway, you don't really need <code>+level-colors</code>, you can do the same thing like this:</p> <pre><code>convert movies.png -channel RGB -colorspace gray +level 50,100% -background black -alpha remove output.png </code></pre> <p>Another option may be to use the <code>-fx</code>...
1
2016-07-30T19:58:13Z
[ "python", "imagemagick", "wand" ]
Using +level-colors from ImageMagick in Python with Wand
38,642,347
<p>I'm going to use Wand to cut out some parts of an image. The image has a transparent background. But before I cut out the parts, I first want to make some adjustments to the source image (without actually altering the source file).</p> <p>The adjustments I want to make are:</p> <ol> <li>Change the black point to g...
0
2016-07-28T16:48:36Z
38,690,063
<p>The <code>-level-colors</code> behavior can be applied by <code>wand.image.Image.level</code> method, but will need to be executed for each color channel. The two colors provided are used as reference black/white points.</p> <p>For example...</p> <pre class="lang-py prettyprint-override"><code>from wand.image impo...
1
2016-08-01T02:04:33Z
[ "python", "imagemagick", "wand" ]
How to run a command within a subprocess in Python script?
38,642,382
<p>I'm trying to run a script that runs putty and within the putty terminal that gets created, run a command. I've been able to start putty from my script using Python's subprocess module with check_call or Popen. However, I'm confused as to how I can run a command within the subprocess Putty terminal from my script. I...
2
2016-07-28T16:50:50Z
38,642,471
<p>You need to set the <code>stdin</code> argument to <code>PIPE</code> and use the <code>communicate</code> function of <code>Popen</code> to send data to stdin.</p> <pre><code>from subprocess import Popen, PIPE p = Popen('/the/command', stdin=PIPE, stdout=PIPE, stderr=PIPE) std_out, std_err = p.communicate('command...
0
2016-07-28T16:55:39Z
[ "python", "subprocess", "putty" ]
Matrix multiplication speeds in R as fast as in Python?
38,642,521
<p>I am experiencing substantially slower matrix multiplication in R as compared to python. This is for large matrices. For example (in python):</p> <pre><code>import numpy as np A = np.random.rand(4112, 23050).astype('float32') B = np.random.rand(23050, 2500).astype('float32') %timeit np.dot(A, B) 1 loops, best of...
1
2016-07-28T16:58:09Z
38,643,751
<p>I use <code>MRO</code> and <code>python</code> with <code>anaconda</code> and the <code>MKL</code> BLAS. Here are my results for the same data generating process, i.e. <code>np.random.rand</code> (<code>'float64'</code>) or <code>rnorm</code> and identical dimensions (<em>average and standard deviation over 10 repli...
2
2016-07-28T18:06:46Z
[ "python", "numpy", "rcpp", "matrix-multiplication" ]
Matrix multiplication speeds in R as fast as in Python?
38,642,521
<p>I am experiencing substantially slower matrix multiplication in R as compared to python. This is for large matrices. For example (in python):</p> <pre><code>import numpy as np A = np.random.rand(4112, 23050).astype('float32') B = np.random.rand(23050, 2500).astype('float32') %timeit np.dot(A, B) 1 loops, best of...
1
2016-07-28T16:58:09Z
38,645,650
<p>Slightly tangential, but too long for a comment I think. To check whether the relevant compiler flags (e.g. <code>-fopenmp</code>) are set, use <code>sourceCpp("testeigen.cpp",verbose=TRUE)</code>.</p> <p>On my system, this showed that the OpenMP flags are <em>not</em> defined by default.</p> <p>I did this to ena...
1
2016-07-28T19:58:09Z
[ "python", "numpy", "rcpp", "matrix-multiplication" ]
Query records through urlsafe key from ndb python
38,642,556
<p>Hi i inserted a record in ndb. I successfully got its url safe key. Now on the basis of this key i want to query the ndb to fetch the records. How can i do this. Please help.</p> <p>Code to get URL safe Key.</p> <pre><code> user = Users() user.name = name user.email =...
0
2016-07-28T16:59:40Z
38,642,626
<p>You can reconstruct the key based on it's <a href="https://cloud.google.com/appengine/docs/python/ndb/keyclass#Constructors" rel="nofollow">urlsafe</a> constructor parameter and then call <code>Key.get</code> to fetch the entity:</p> <pre><code>from google.appengine.ext import ndb key = ndb.Key(urlsafe=chk) # chk...
1
2016-07-28T17:03:43Z
[ "python", "app-engine-ndb" ]
how to load jinja template directly from filesystem
38,642,557
<p>I'm relatively inexperienced at python, so I went astray when I read the <a href="http://jinja.pocoo.org/docs/dev/api/#" rel="nofollow">jinja API document at pocoo.org</a>. It reads:</p> <blockquote>The simplest way to configure Jinja2 to load templates for your application looks roughly like this:</blockquote> <...
0
2016-07-28T16:59:42Z
38,642,558
<p><strong>Here's how</strong>: use a <code>FileSystemLoader</code> instead of a <code>PackageLoader</code>. I found examples on the web <a href="http://matthiaseisen.com/pp/patterns/p0198/" rel="nofollow">here</a> and <a href="http://kagerato.net/articles/software/libraries/jinja-quickstart.html" rel="nofollow">here<...
0
2016-07-28T16:59:42Z
[ "python", "templates", "jinja2" ]
How to test file locking in Python
38,642,623
<p>So I want to write some files that might be locked/blocked for write/delete by other processes and like to test that upfront.</p> <p>As I understand: <code>os.access(path, os.W_OK)</code> only looks for the permissions and will return true although a file cannot currently be written. So I have this little function:...
0
2016-07-28T17:03:27Z
38,643,576
<p>You are trying to implement the file locking problem using just the system call <strong>open()</strong>. The Unix-like systems uses by default <a href="http://www.thegeekstuff.com/2012/04/linux-file-locking-types/" rel="nofollow">advisory file locking</a>. This means that cooperating processes may use locks to coord...
1
2016-07-28T17:57:04Z
[ "python", "windows", "file", "locking" ]
How to test file locking in Python
38,642,623
<p>So I want to write some files that might be locked/blocked for write/delete by other processes and like to test that upfront.</p> <p>As I understand: <code>os.access(path, os.W_OK)</code> only looks for the permissions and will return true although a file cannot currently be written. So I have this little function:...
0
2016-07-28T17:03:27Z
38,645,902
<p>Alright! Thanks to those guys I actually have something now! So this is my function:</p> <pre><code>def lock_test(path): """ Checks if a file can, aside from it's permissions, be changed right now (True) or is already locked by another process (False). :param str path: file to be checked :rtype...
0
2016-07-28T20:12:55Z
[ "python", "windows", "file", "locking" ]
Python: Set PYTHONPATH according to requirements.txt at runtime
38,642,658
<p>I have a Python application that comes with a command line script. I expose the script via <code>setuptools</code> "entry point" feature. Whenever a user runs the script, I would like the environment to be consistent with the package's <code>requirements.txt</code>. This means that the environment must contain versi...
2
2016-07-28T17:05:13Z
38,642,807
<p>I don't see why it wouldn't be possible for a Python program to install its own dependencies before importing them, but it is unheard of in the Python community.</p> <p>I'd rather look at options to make your application a standalone executable, as explained <a href="https://stackoverflow.com/questions/112698/py2ex...
1
2016-07-28T17:14:32Z
[ "python" ]
Python: Set PYTHONPATH according to requirements.txt at runtime
38,642,658
<p>I have a Python application that comes with a command line script. I expose the script via <code>setuptools</code> "entry point" feature. Whenever a user runs the script, I would like the environment to be consistent with the package's <code>requirements.txt</code>. This means that the environment must contain versi...
2
2016-07-28T17:05:13Z
38,648,250
<blockquote> <p>Does Python have an equivalent? That is, a way to set the environment at runtime according to requirements.txt without imposing additional complexity on the user?</p> </blockquote> <p>Yes, more than one.</p> <p>One is <a href="https://pex.readthedocs.io/en/stable/" rel="nofollow">pex</a></p> <block...
1
2016-07-28T23:21:08Z
[ "python" ]
Use translate to replace punctuation, what's the difference between these 3 ways?
38,642,689
<p>I'm trying to replace punctuation to space in a string. I searched the answer and tried them in my python 2.7, they show different results. </p> <pre><code>s1=" merry's home, see a sign 'the-shop $on sale$ **go go!'" #sample string print s1.translate(string.maketrans("",""), string.punctuation) #way1 print s1.t...
2
2016-07-28T17:06:47Z
38,642,747
<p>There isn't really a functional difference in the first two ... You're either passing an empty translation table (<code>string.maketrans("","")</code>) or you're telling python to skip the translation step (<code>None</code>). After the translation, you're removing all punctuation since you pass <code>string.puncti...
1
2016-07-28T17:11:09Z
[ "python", "string", "python-2.x", "punctuation" ]
Use translate to replace punctuation, what's the difference between these 3 ways?
38,642,689
<p>I'm trying to replace punctuation to space in a string. I searched the answer and tried them in my python 2.7, they show different results. </p> <pre><code>s1=" merry's home, see a sign 'the-shop $on sale$ **go go!'" #sample string print s1.translate(string.maketrans("",""), string.punctuation) #way1 print s1.t...
2
2016-07-28T17:06:47Z
38,642,812
<p>The documentation for <code>translate</code> specifies <a href="https://docs.python.org/2/library/stdtypes.html#str.translate" rel="nofollow"><code>str.translate(table[, deletechars])</code></a></p> <blockquote> <p>Return a copy of the string where all characters occurring in the optional argument deletechars are...
1
2016-07-28T17:14:56Z
[ "python", "string", "python-2.x", "punctuation" ]
Assertions vs exceptions for library API type checking
38,642,720
<p>Python encourages duck typing over explicit type checking. However, sometimes it is useful to explicitly check types.</p> <p>When a Python library need to do type checking, should it use assertions or exceptions?</p> <pre><code>def foo(bar): assert isinstance(bar, str) def foo(bar): if not isinstance(bar...
0
2016-07-28T17:09:08Z
38,642,849
<p>Assertion evaluation can be deactivated by running python with the <code>-O</code> command line option which can be good if you want to check things more extensively than you would in production.</p> <p>Have a look at <a href="https://wiki.python.org/moin/UsingAssertionsEffectively" rel="nofollow">https://wiki.pyth...
-1
2016-07-28T17:17:14Z
[ "python" ]
matplotlib: how to make sizes of the subfigures without colorbars consistent with those with colorbars?
38,642,839
<p>Here is my figure composed of two subfigures below, one with colorbar and the other without colorbar. Currently they are not of the same size due to the presence of the colorbar, I am wondering if there is a way to fix this?</p> <p><a href="http://i.stack.imgur.com/hoEFX.png" rel="nofollow"><img src="http://i.stac...
2
2016-07-28T17:16:22Z
38,646,984
<p>Add colorbar manually:</p> <pre><code>import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import numpy as np fig, (ax1, ax2) = plt.subplots(1, 2) x = np.random.random(50) y = np.random.random(50) c = np.random.random(50) s = 500 * np.random.random(50) im1 = ax1.scatter(x, ...
0
2016-07-28T21:22:48Z
[ "python", "matplotlib" ]
Pandas, conditional column assignment based on column values
38,643,012
<p>How can I have conditional assignment in pandas by based on the values of two columns? Conceptually something like the following:</p> <pre><code>Column_D = Column_B / (Column_B + Column_C) if Column_C is not null else Column_C </code></pre> <p>Concrete example:</p> <pre><code>import pandas as pd import numpy as n...
4
2016-07-28T17:27:11Z
38,643,133
<p>try this (if you want to have your desired result set - checking <code>b</code> column):</p> <pre><code>In [30]: df['d'] = np.where(df.b.notnull(), df.b/(df.b+df.c), df.c) In [31]: df Out[31]: b c d 0 2.0 NaN NaN 1 NaN 1.0 1.000000 2 4.0 2.0 0.666667 3 2.0 NaN NaN 4 NaN NaN ...
5
2016-07-28T17:33:28Z
[ "python", "pandas", "numpy", "dataframe" ]
bitcoinrpc calls return nothing
38,643,016
<p>I am using bitcoind in my project and when I deploy it on my server bitcoind works strange. I use this lib to work with rpc <a href="https://github.com/jgarzik/python-bitcoinrpc" rel="nofollow">https://github.com/jgarzik/python-bitcoinrpc</a>. On local dev server everything is fine but when I deploy it to vps it sto...
1
2016-07-28T17:27:12Z
38,644,632
<p>Omg that was bug in the repo, and I fixed it locally several month ago and forgot about that! If you have the same problem you can mannually edit <code>lib/python2.7/site-packages/bitcoinrpc/authproxy.py</code> delete <code>else:</code> on 146 line and move out <code>return response['result']</code> from <code>elif<...
0
2016-07-28T18:56:58Z
[ "python", "django", "json-rpc", "bitcoind" ]
Trouble updating json files
38,643,145
<p>I have two <code>json</code> files. One of them is a dictionary which is a subset of the other. </p> <p><code>json_file_1.json</code> contains <code>{'foo': 1, 'bar': 2, 'baz': 3}</code></p> <p><code>json_file_2.json</code> contains <code>{'foo': 100, 'bar': 200}</code>. </p> <p>I want to create a final <code>jso...
0
2016-07-28T17:34:16Z
38,643,256
<p><a href="https://docs.python.org/3/library/stdtypes.html?highlight=update#dict.update" rel="nofollow"><code>dict.update</code></a> updates a dictionary in-place and returns <code>None</code>. </p> <p>You need to dump <code>original_info</code></p> <p>For reference, </p> <pre><code>In [11]: d1 = {'foo': 1, 'bar': ...
2
2016-07-28T17:39:32Z
[ "python", "json" ]
Importing structured data into python
38,643,151
<p>I have a text file with a set of arrays in it that looks like this:</p> <pre><code>[(0,1,3),(0,4,5),...(1,9,0)] [(9,8,7),(0,4,5),...(1,9,0)] </code></pre> <p>where the rows are not the same length. </p> <p>This is essentially a list of paths, where each set of points is a path, ie:</p> <pre><code>(0,1,3),(0,4,5...
0
2016-07-28T17:34:36Z
38,644,104
<p>The following code reads the data in (assuming one path per line, and no extra whitespace) into a list of numpy arrays, then demonstrates how to compute the distance between two points.</p> <pre><code>import numpy as np import numpy.linalg as la #replace with your datafile datafile = "../data/point_path.txt" paths...
0
2016-07-28T18:26:06Z
[ "python", "arrays", "numpy", "import" ]
How to define models/serializers correctly for Django REST Framework?
38,643,178
<p>We are creating a mobile web application with this stack:</p> <p>Python Django, SQLite DB Django REST Ionic Cordova Angular JS</p> <p>This is a quiz application, in which you answer questions from 4 multiple choices. Questions and answers are stored in the database. With the help of REST framework an endpoint has ...
3
2016-07-28T17:35:56Z
38,643,485
<p>The urls come because you inherit <code>HyperlinkedModelSerializer</code>.</p> <pre><code>class QuestionSerializer(serializers.HyperlinkedModelSerializer): ... </code></pre> <p>If you don't want them, use a different base class - perhaps just a <a href="http://www.django-rest-framework.org/api-guide/serializer...
2
2016-07-28T17:52:17Z
[ "python", "json", "django", "django-rest-framework" ]
How to define models/serializers correctly for Django REST Framework?
38,643,178
<p>We are creating a mobile web application with this stack:</p> <p>Python Django, SQLite DB Django REST Ionic Cordova Angular JS</p> <p>This is a quiz application, in which you answer questions from 4 multiple choices. Questions and answers are stored in the database. With the help of REST framework an endpoint has ...
3
2016-07-28T17:35:56Z
38,643,551
<p>I believe this will work.</p> <pre><code>class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('answerid', 'text') class QuestionSerializer(serializers.ModelSerializer): answer = AnswerSerializer(source="answers) class Meta: model = Question fields ...
2
2016-07-28T17:55:51Z
[ "python", "json", "django", "django-rest-framework" ]
python parse string to get contents between text
38,643,235
<p>How can i collect the text (data) between a set of strings? For example I have this code snippet below, which is a modified version of json, which I don't have the ability to change. </p> <p>However I want to collect the data between <code>presets = {...}</code></p> <pre><code>{ data = { friends = { ...
1
2016-07-28T17:38:26Z
38,643,580
<p>You can use <code>re</code> here.</p> <pre><code>import re filepath = r"C:/Users/jmartini/Projects/rogue_presetsManager/assets/tool_leveleditormodule_source.cfg" f=open(filepath, "r") data = f.read() print re.findall(r"presets\s*=\s*\{\s*([^}]*?)\s*}", data) </code></pre>
1
2016-07-28T17:57:21Z
[ "python", "parsing" ]
python parse string to get contents between text
38,643,235
<p>How can i collect the text (data) between a set of strings? For example I have this code snippet below, which is a modified version of json, which I don't have the ability to change. </p> <p>However I want to collect the data between <code>presets = {...}</code></p> <pre><code>{ data = { friends = { ...
1
2016-07-28T17:38:26Z
38,643,748
<p>Use <a href="http://pyyaml.org/wiki/PyYAML" rel="nofollow">PyYaml</a> to get the required data</p> <blockquote> <p>pip install PyYaml</p> </blockquote> <pre><code>import yaml def testjson(): with open('data.json') as datafile: data = datafile.read().replace("\n", "").replace("=", ":") ...
2
2016-07-28T18:06:25Z
[ "python", "parsing" ]
Python post data to url
38,643,278
<p>I'm using App Engine and I'm trying to post data to a URL similar to this : </p> <pre><code>https://push.geckoboard.com/v1/send/&lt;widget-id&gt; </code></pre> <p>I've tried the following code:</p> <pre><code>data = { "api_key" : api_key, "data" : { "item" : [ ...
1
2016-07-28T17:40:51Z
38,643,872
<p>The error 400 was caused because the data was url encoded which it shouldn't be. By changing </p> <pre><code>conn.request("POST", "", encoded_args) </code></pre> <p>to </p> <pre><code>conn.request("POST", "", json.dumps(data)) </code></pre> <p>the problem was solved.</p> <p>Thanks for the help!</p>
0
2016-07-28T18:12:40Z
[ "python", "http", "google-app-engine", "http-post" ]
Parsing whole terms in Python/json profanity filter
38,643,309
<p>I have a json file containing terms to check against for a profanity filter.</p> <pre><code>["bad", "word", "plug"] </code></pre> <p>And I am using this (found from another article) to parse the json and search any data object for set words. </p> <pre><code>def word_filter(self, *field_names): import json ...
0
2016-07-28T17:42:43Z
38,643,579
<p>You can use string.split() as a way to isolate whole words of the field_name. When you split, it returns a list of each part of the string split up by the specified delimiter. Using that, you can check if the profane term is in the split list:</p> <pre><code>import json with open('terms.json') as data_file: ...
0
2016-07-28T17:57:14Z
[ "python", "sqlalchemy", "flask-restless" ]
Select and order records in one to many relationship
38,643,315
<p>Consider the following tables:</p> <pre><code>Student ------- id name </code></pre> <p>and</p> <pre><code>Assignment ---------- id name </code></pre> <p>and</p> <pre><code>Grade ----- id student_id assignment_id grade </code></pre> <p>A student can have multiple grades, corresponding to different assignments.<...
1
2016-07-28T17:43:01Z
38,644,355
<p>In Oracle you may consider something like this</p> <pre><code>with tab as( select s.name as student, a.name as assignment, g.v as grade from grade g inner join student s on g.s_n = s.n inner join assignment a on g.a_n = a.n ) select * from tab pivot (min(grade) for assignmen...
0
2016-07-28T18:40:59Z
[ "python", "sql", "sqlalchemy", "order" ]
Select and order records in one to many relationship
38,643,315
<p>Consider the following tables:</p> <pre><code>Student ------- id name </code></pre> <p>and</p> <pre><code>Assignment ---------- id name </code></pre> <p>and</p> <pre><code>Grade ----- id student_id assignment_id grade </code></pre> <p>A student can have multiple grades, corresponding to different assignments.<...
1
2016-07-28T17:43:01Z
38,644,748
<p>If you are using SQLite, you have to use the lowest common denominator of SQL, meaning a join for every single assignment you want to consider:</p> <pre><code>SELECT name, Grade1.grade AS assignment1, Grade2.grade AS assignment2, Grade3.grade AS assignment3 FROM Student LEFT JOIN Grade AS Grade1 ON (Stu...
2
2016-07-28T19:03:37Z
[ "python", "sql", "sqlalchemy", "order" ]
Quickest Algorithmn for Normalization of Region Proposals
38,643,385
<p>In order to normalize the region proposal algorithm (that is, applying regression to every X-by-Y area of an image), I need to create a region proposal normalization when summing the activation of each proposal. Currently, for a 128x128 patch of an image, in Python I'm running this bit of code</p> <pre><code>region...
2
2016-07-28T17:46:58Z
38,644,827
<p><strong>Reverse engineer it!</strong></p> <p>Well, let's take a look at the output for a small image and smaller <code>N</code> case, as we will try to reverse engineer this loopy code. So, with <code>N = 4</code> (where <code>N</code> was <code>128</code> in the original case) and image.shape = <code>(10,10)</co...
3
2016-07-28T19:08:01Z
[ "python", "performance", "numpy", "vectorization", "normalization" ]
Quickest Algorithmn for Normalization of Region Proposals
38,643,385
<p>In order to normalize the region proposal algorithm (that is, applying regression to every X-by-Y area of an image), I need to create a region proposal normalization when summing the activation of each proposal. Currently, for a 128x128 patch of an image, in Python I'm running this bit of code</p> <pre><code>region...
2
2016-07-28T17:46:58Z
38,645,331
<p>The value of any given point i,j in your renormalization is equal to the number of 128x128 windows that contain it. Note that this is the product of the degrees of freedom on the x axis and on the y axis. So all we have to do is figure out the degrees of freedom for each possible x and y, value, then use broadcastin...
1
2016-07-28T19:38:23Z
[ "python", "performance", "numpy", "vectorization", "normalization" ]
How to separate yaml.dump key:value pair by a new line?
38,643,420
<p>I am trying to make yaml dump each key:value pair on a separate line. Is there a native option to do that? I have tried line_break but couldn't get it to work.</p> <p>Here is a code example:</p> <pre><code>import yaml def test_yaml_dump(): obj = {'key0': 1, 'key1': 2} with open('test.yaml', 'w') as tmpf...
1
2016-07-28T17:48:23Z
38,643,516
<p>If you add the argument <code>default_flow_style=False</code> to dump then the output will be:</p> <pre><code>key1: 2 key0: 1 </code></pre> <p>(the so called block style). That is the much more readable way of dumping Python dicts to YAML mappings. In <code>ruamel.yaml</code> this is the default when using <code>r...
1
2016-07-28T17:54:07Z
[ "python", "yaml" ]
Python: Can an exception class identify the object that raised it?
38,643,450
<p>When a Python program raises an exception, is there a way the exception handler can identify the object in which the exception was raised?</p> <p>If not, I believe I can find out by defining the exception class like this...</p> <pre><code>class FoobarException(Exception) : def __init__(self,message,context) : ...
0
2016-07-28T17:50:10Z
38,643,844
<p>It quickly gets messy if you want the exception itself to figure out where in the stack it is. You can do something like this:</p> <pre><code>import inspect frameinfo = inspect.getframeinfo(inspect.stack()[1][0]) caller_name = frameinfo[2] file_name = frameinfo[0] </code></pre> <p>This, however, will only really w...
0
2016-07-28T18:11:23Z
[ "python", "class", "exception-handling" ]
Weird TypeError when using the Datetime/Time module?
38,643,554
<p>So I'm new to programming and I had coded this tiny script to turn my internet on from two a.m. to eight a.m. (long story);</p> <pre><code>import os import datetime as dt from time import sleep def connect(): print("Connecting...") os.system("netsh wlan connect Sushi") def disconnect(): print("Disco...
0
2016-07-28T17:56:13Z
38,643,726
<p>Lines 46 and 54 (<code>x = tdelta(nowto8)</code>) are calling <code>tdelta</code> with an integer argument, not a string. Change lines 46-47 from</p> <pre><code>x = tdelta(nowto8) sleep(x) </code></pre> <p>to</p> <pre><code>sleep(nowto8) </code></pre> <p>and lines 54-55 from</p> <pre><code>x = tdelta(nowto8) sl...
0
2016-07-28T18:05:30Z
[ "python", "python-3.x", "debugging" ]
JSON TypeError: expected string or buffer
38,643,555
<p>I'm trying to store an exception error to json. Even though I'm pretty sure I'm storing a string, it's still giving me a typeerror. </p> <p>Relevant section of code: </p> <pre><code>except ConnectionError as e: s = str(e) print type(s) data = json.loads({'error message': s}) print "...
0
2016-07-28T17:56:17Z
38,644,429
<p>You are looking for <code>json.dumps()</code>, not <code>json.loads()</code>. Try this:</p> <pre><code> data = json.dumps({'error message': s}) </code></pre> <p><a href="https://docs.python.org/3/library/json.html#json.dumps" rel="nofollow"><code>json.dumps(obj)</code></a>: Serialize <code>obj</code> to a JSON ...
0
2016-07-28T18:45:34Z
[ "python", "json", "python-2.7" ]
Calling a private property of a Python instance using a string
38,643,693
<p>I'm somewhat new to OOP in Python (and Python in general), and I'm running into an issue when I try to access an instances private property from within one of the methods, and using a string as the property name.</p> <p>The goal here is to basically have a list of properties that will be displayed (in a <em>key - v...
1
2016-07-28T18:03:31Z
38,643,786
<p>double underscores invoke python <a href="https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references" rel="nofollow">name-mangling</a>:</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... def __init__(self): ... self.__private = 1 ... &gt;&gt;&gt; f = Foo() &gt;&gt;&gt; vars(...
1
2016-07-28T18:08:17Z
[ "python", "python-2.7", "oop", "getter", "getter-setter" ]
Calling a private property of a Python instance using a string
38,643,693
<p>I'm somewhat new to OOP in Python (and Python in general), and I'm running into an issue when I try to access an instances private property from within one of the methods, and using a string as the property name.</p> <p>The goal here is to basically have a list of properties that will be displayed (in a <em>key - v...
1
2016-07-28T18:03:31Z
38,643,804
<p>Attributes with a double underscore (e.g. <code>__foo</code>) are <a href="https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references" rel="nofollow">mangled</a> to make it harder to access them. The rules are as follows:</p> <blockquote> <p>Since there is a valid use-case for cl...
2
2016-07-28T18:09:03Z
[ "python", "python-2.7", "oop", "getter", "getter-setter" ]
How can I randomly populate a list of lists in Python?
38,643,703
<p>I have been trying to produce an exploration game, so naturally I started with a world generator. I am stuck, however, on populating my list of biomes. The "biome_map" list is essentially an array that is equal in width and height to whatever size the user requested. Here is the code I have written:</p> <pre><code>...
0
2016-07-28T18:04:16Z
38,643,897
<p>You are using a reference to the same list <code>EWbiome_map</code> when creating <code>biome_map</code>. Instead do something like:</p> <pre><code>biome_map = [['empty']*E_W_Size]*N_S_Size </code></pre> <p>Your entire code could however be pretty much shortened to:</p> <pre><code>biome_map = [[random.choice(biom...
1
2016-07-28T18:14:17Z
[ "python", "python-3.x" ]
How can I randomly populate a list of lists in Python?
38,643,703
<p>I have been trying to produce an exploration game, so naturally I started with a world generator. I am stuck, however, on populating my list of biomes. The "biome_map" list is essentially an array that is equal in width and height to whatever size the user requested. Here is the code I have written:</p> <pre><code>...
0
2016-07-28T18:04:16Z
38,643,931
<p>Your problem is the line</p> <pre><code>biome_map = biome_map + [EWbiome_map] </code></pre> <p>You are making <code>biome_map</code> to be a list where each element is the list <code>EWbiome_map</code>. Note that each element is not a <em>copy</em> of the list, it is the list itself. To correct this you want a <em...
0
2016-07-28T18:16:17Z
[ "python", "python-3.x" ]
How can I randomly populate a list of lists in Python?
38,643,703
<p>I have been trying to produce an exploration game, so naturally I started with a world generator. I am stuck, however, on populating my list of biomes. The "biome_map" list is essentially an array that is equal in width and height to whatever size the user requested. Here is the code I have written:</p> <pre><code>...
0
2016-07-28T18:04:16Z
38,644,308
<p>As other answers have mentioned, you are referencing the same EWbiome_map each time, which causes you to alter it in all rows of biome_map.</p> <p>However, your code also does a lot of unnecessary things, like initializing an empty map and iterating with 'chunk3' and 'element' instead of just using x and y directly...
0
2016-07-28T18:38:02Z
[ "python", "python-3.x" ]
How to get results from python unit tests in Django using custom settings
38,643,736
<p>I am trying to generate a report from the unit tests in Django. For running the tests and retrieving the results I am using a custom TestResult class, which works fine:</p> <pre><code>results = TestResult() loader = unittest.TestLoader() suites = loader.discover('test_folder') for suite in suites: suite(results...
0
2016-07-28T18:05:51Z
38,643,865
<p>Well, if you are using command <code>./manage.py test</code>, then you could just parse the commandline argument and see if it's a <code>test</code>, then have an <code>if</code> statement in your <code>settings.py</code>:</p> <pre><code>if 'test' in sys.argv: DATABASES = { 'default': { 'ENG...
0
2016-07-28T18:12:25Z
[ "python", "django", "unit-testing", "python-unittest" ]
Reading two files, a csv and xls, and bring columns from csv to xls based on subnet(csv)/ip(xls) match
38,643,756
<p>I am trying to make a program that reads two files, a csv and xls, and use some python logic that parses and transfers certain columns from the csv to xls, based on a ip/subnet match.</p> <p>The csv has subnet, mask, and cidr, in columns B,C, and D. (csv has about 10k rows, not all will be used.)</p> <p>The xls ha...
0
2016-07-28T18:06:59Z
38,644,396
<p>To begin with you could try this script </p> <pre><code>import openpyxl from xlrd import open_workbook import csv #To read XLX book = open_workbook('IPADR.xlsx') sheet = book.sheet_by_index(0) keys = [sheet.cell(row_index, 0).value for row_index in xrange(sheet.nrows)] print keys # To read Csv exampleFile = op...
0
2016-07-28T18:43:17Z
[ "python", "excel", "python-3.x", "csv", "subnet" ]
How to scrape GIS coordinates from a map (e.g. Pokevision) using python and selenium?
38,643,991
<p>I'd like to scrape PokemonVision so that I can get all the longitude and latitude coordinates of the Pokemon being displayed. </p> <p>The URL of the webpage contains the longitude and latitude of the flag marker . For example the following url contains 39.95142302373031,-75.17986178398132: <a href="https://pokevisi...
1
2016-07-28T18:20:37Z
38,650,073
<p>If you click the map the URL updates with the coordinates at that point. You can find all visible pokemon on the map, click them, then parse the coordinates from the updated URL. Example code:</p> <pre><code>from pprint import pprint as pp from selenium import webdriver from selenium.common.exceptions import WebDr...
2
2016-07-29T03:28:56Z
[ "python", "html", "selenium", "gis", "pokemon-go" ]
wxPython - how to stop a wx.Control from losing focus on arrow key press?
38,644,013
<pre><code>import wx class Control(wx.Control): def __init__(self, parent): wx.Control.__init__(self, parent) self.Bind(wx.EVT_CHAR, self.OnKey) self.Bind(wx.EVT_KEY_DOWN, self.OnKey) self.Bind(wx.EVT_KEY_DOWN, self.OnKey) self.Bind(wx.EVT_LEFT_DOWN, self.OnMouseClick) ...
0
2016-07-28T18:21:38Z
38,644,119
<p>Both of you event handlers are missing the call to:</p> <pre><code>event.Skip() </code></pre> <p>Those events are non-wxCommandEvents and in order for them to work properly, OS has to perform whatever needs to be performed. That's what Skip() is for. Otherwise the event will be eaten by the control.</p> <p>Please...
0
2016-07-28T18:27:15Z
[ "python", "wxpython", "wxwidgets", "wx" ]
Sort list of dictionaries based on keys
38,644,055
<p>I want to sort a list of dictionaries based on the presence of keys. Let's say I have a list of keys [key2,key3,key1], I need to order the list in such a way the dictionary with key2 should come first, key3 should come second and with key1 last.</p> <p>I saw this answer (<a href="http://stackoverflow.com/questions/...
0
2016-07-28T18:23:20Z
38,644,377
<p>How about something like this</p> <pre><code>def sort_key(dict_item, sort_list): key_idx = [sort_list.index(key) for key in dict_item.iterkeys() if key in sort_list] if not key_idx: return len(sort_list) return min(key_idx) dict_list.sort(key=lambda x: sort_key(x, sort_list)) </code></pre> <p>...
0
2016-07-28T18:41:58Z
[ "python", "dictionary" ]
Sort list of dictionaries based on keys
38,644,055
<p>I want to sort a list of dictionaries based on the presence of keys. Let's say I have a list of keys [key2,key3,key1], I need to order the list in such a way the dictionary with key2 should come first, key3 should come second and with key1 last.</p> <p>I saw this answer (<a href="http://stackoverflow.com/questions/...
0
2016-07-28T18:23:20Z
38,644,495
<p>I'd do this with:</p> <pre><code>sorted_list = sorted(dict_list, key = lambda d: next((i for (i, k) in enumerate(key_list) if k in d), len(key_list) + 1)) </code></pre> <p>That uses a generator expression to find the index in the key list of the first key that's in each dictionary, then use that value as the sort ...
0
2016-07-28T18:49:13Z
[ "python", "dictionary" ]
Sort list of dictionaries based on keys
38,644,055
<p>I want to sort a list of dictionaries based on the presence of keys. Let's say I have a list of keys [key2,key3,key1], I need to order the list in such a way the dictionary with key2 should come first, key3 should come second and with key1 last.</p> <p>I saw this answer (<a href="http://stackoverflow.com/questions/...
0
2016-07-28T18:23:20Z
38,644,522
<p>Just use <code>sorted</code> using a list like <code>[key1 in dict, key2 in dict, ...]</code> as the key to sort by. Remember to reverse the result, since <code>True</code> (i.e. key is in dict) is sorted after <code>False</code>.</p> <pre><code>&gt;&gt;&gt; dicts = [{1:2, 3:4}, {3:4}, {5:6, 7:8}] &gt;&gt;&gt; keys...
1
2016-07-28T18:50:59Z
[ "python", "dictionary" ]
How to subset a dataframe and resolve the SettingWithCopy warning in Python?
38,644,073
<p>I've read an Excel sheet of survey responses into a dataframe in a Python 3 Jupyter notebook, and want to remove rows where the individuals are in one particular program. So I've subset from dataframe 'df' to a new dataframe 'dfgeneral' using .loc .</p> <pre><code>notnurse = df['Program Code'] != 'NSG' dfgeneral =...
0
2016-07-28T18:24:26Z
38,644,252
<pre><code>dfgeneral = df.loc[notnurse,:] </code></pre> <p>This line (second line) takes a slice of the DataFrame and assigns it to a variable. When you want to manipulate that variable, you see the warning (A value is trying to be set on a copy of a slice from a DataFrame). </p> <p>Change that line to:</p> <pre><co...
2
2016-07-28T18:35:00Z
[ "python", "pandas", "dataframe", "subset" ]
Create a bar graph using datetimes
38,644,150
<p>I am using matplotlib and pyplot to create some graphs from a CSV file. I can create line graphs no problem, but I am having a lot of trouble creating a bar graph.</p> <p>I referred to this post <a href="http://stackoverflow.com/questions/5902371/matplotlib-bar-chart-with-dates">matplotlib bar chart with dates</a> ...
3
2016-07-28T18:28:55Z
38,647,731
<p>I could not fully reproduce your problem with your data and code. I get </p> <pre><code>&gt; UZTWC = np.genfromtxt(data_file, delimiter=';', names=columns, &gt; usecols=("UZTWC")) File &gt; "C:\Python34-64bit\lib\site-packages\numpy\lib\npyio.py", line 1870, &gt; in genfromtxt &gt; output = np.array(data, dty...
0
2016-07-28T22:25:14Z
[ "python", "numpy", "matplotlib" ]
merge python dictionaries when a key has a certain value
38,644,179
<p>I have a list of python dictionaries, looking like this:</p> <pre><code>[{key1: value1, key2: array1}, {key1: value2, key2: array2}, {key1: value3, key3: array3},...] </code></pre> <p>In my case, some of these dictionaries have the same value for key1, for example, value1 = value3. How can I end up getting an arra...
-1
2016-07-28T18:30:44Z
38,644,562
<p>The best way to do what you want is to re-structure your data, at least temporarily. If you were to use a dictionary that mapped from <code>value</code> to <code>array</code> (without the fixed keys), you could put all the data into a single place and efficiently detect when duplicate values occur so that you can me...
0
2016-07-28T18:53:18Z
[ "python", "dictionary" ]
merge python dictionaries when a key has a certain value
38,644,179
<p>I have a list of python dictionaries, looking like this:</p> <pre><code>[{key1: value1, key2: array1}, {key1: value2, key2: array2}, {key1: value3, key3: array3},...] </code></pre> <p>In my case, some of these dictionaries have the same value for key1, for example, value1 = value3. How can I end up getting an arra...
-1
2016-07-28T18:30:44Z
38,644,853
<p>Since you want to group by <code>key1</code>, you can use <code>itertools.groupby()</code>.</p> <pre><code>from operator import itemgetter from itertools import groupby list_of_dicts = [{'key1': 1, 'key2': [1, 2]}, {'key1': 2, 'key2': [3, 4]}, {'key1': 1, 'key2': [5, 6]}] grouped...
0
2016-07-28T19:09:43Z
[ "python", "dictionary" ]
Insert table data from website into table on my own website using Python and Beautiful Soup
38,644,251
<p>I wrote some code that grabs the numbers I need from <a href="http://abri.une.edu.au/online/cgi-bin/i4.dll?1=2021292A&amp;2=2420&amp;3=56&amp;5=2B3C2B3C3A&amp;6=59585A242621582623&amp;9=5251595A" rel="nofollow">this website</a>, but I don't know what to do next. </p> <p>It grabs the numbers from the table at the bo...
0
2016-07-28T18:34:55Z
38,674,424
<p>It sounds like you would want to use something like <a href="https://www.djangoproject.com" rel="nofollow">Django</a>. Although the learning curve is a bit steep, it is worth it <em>and</em> it (of course) supports python.</p>
0
2016-07-30T13:23:53Z
[ "python", "html", "web-scraping", "beautifulsoup", "html-parsing" ]
Python Multiprocessing apply_async Only Using One Process
38,644,254
<p>This is my code: </p> <pre><code>import multiprocessing import time import os def worker(): print str(os.getpid()) + " is going to sleep..." time.sleep(1) print str(os.getpid()) + " woke up!" return if __name__ == "__main__": pool = multiprocessing.Pool(processes = 8) for _ in range(5): ...
0
2016-07-28T18:35:18Z
38,644,894
<p>You are <strong>calling</strong> the <code>worker</code> function, so <em>the current process</em> executes that code and <em>then</em> the result of <code>worker</code> (i.e. <code>None</code>) is passed to <code>apply_asynch</code> which does nothing.</p> <p>Change it to <a href="https://docs.python.org/3.5/libra...
1
2016-07-28T19:12:00Z
[ "python", "multiprocessing" ]
how to increment a whole word match in python using a variable in the regex
38,644,263
<p>I am trying to show how many words match in a txt file using python and regex but instead of using the term 'like' I would like to use the variable 'words'</p> <pre><code>text = 'I like and love green grass' positive_words = positive_words=open("positive.txt").read() words = text.split(' ') if re.search(r'\blike\...
3
2016-07-28T18:35:45Z
38,644,352
<p>From the regex point of view, this should work:</p> <pre><code>re.search(r'\b(I|like|and|love|green|grass)\b', positive_words) </code></pre> <p>To build the re from your text variable (note, I'm coding this from memory, you may need to tweak it somewhat):</p> <pre><code>regex = r'\b(%s)\b' % "|".join(words) re.se...
1
2016-07-28T18:40:40Z
[ "python", "regex", "variables", "increment" ]
how to increment a whole word match in python using a variable in the regex
38,644,263
<p>I am trying to show how many words match in a txt file using python and regex but instead of using the term 'like' I would like to use the variable 'words'</p> <pre><code>text = 'I like and love green grass' positive_words = positive_words=open("positive.txt").read() words = text.split(' ') if re.search(r'\blike\...
3
2016-07-28T18:35:45Z
38,644,391
<pre><code>text = 'I like and love green grass' positive_words = positive_words=open("positive.txt").read() words = text.split(' ') for word in words: if re.search(r'\b' + word + r'\b',positive_words): positive_counter=positive_counter+1 print positive_counter </code></pre> <p>Just looping all of the wor...
3
2016-07-28T18:42:59Z
[ "python", "regex", "variables", "increment" ]
using a ModelForm to sanitize post data in Django
38,644,280
<p>I've come across <a href="http://stackoverflow.com/questions/30699794/how-to-create-object-from-querydict-in-django">How to create object from QueryDict in django?</a> , which answers what I want to do. However I want to sanitize the data. What does the Brandon mean by "using a ModelForm" to sanitize posted data?</...
0
2016-07-28T18:36:50Z
38,644,380
<p>What he mean is that with <code>ModelForm</code> you can not only create model instance from <code>QueryDict</code>, but also do a bunch of validation on data types and it's requirements as for example if value's length correct, if it's required etc. Also you will pass only needed data from <code>QueryDict</code> to...
1
2016-07-28T18:42:06Z
[ "python", "django" ]
using a ModelForm to sanitize post data in Django
38,644,280
<p>I've come across <a href="http://stackoverflow.com/questions/30699794/how-to-create-object-from-querydict-in-django">How to create object from QueryDict in django?</a> , which answers what I want to do. However I want to sanitize the data. What does the Brandon mean by "using a ModelForm" to sanitize posted data?</...
0
2016-07-28T18:36:50Z
38,644,708
<p><code>ModelForm</code> are very helpful when you want to create just model instances. If you create a form that closely looks like a model then you should go for a model form instead. Here is an example. Going by the example provided in the Django <a href="https://docs.djangoproject.com/en/dev/topics/forms/modelform...
4
2016-07-28T19:01:44Z
[ "python", "django" ]
Chunking for Tamil language
38,644,313
<p>I want to use the NLTK chunker for Tamil language (which is an Indic language). <a href="http://www.nltk.org/_modules/nltk/chunk.html" rel="nofollow">However, it says that it doesn't support Unicode because it uses the 'pre' module for regular expressions.</a></p> <blockquote> <h2>Unresolved Issues</h2> <p>I...
1
2016-07-28T18:38:16Z
38,644,769
<p>You can use <a href="http://ltrc.iiit.ac.in/" rel="nofollow">LTRC</a>'s <a href="http://ltrc.iiit.ac.in/showfile.php?filename=downloads/shallow_parser.php" rel="nofollow">Shallow Parser</a> for Tamil Language.</p> <p>You can check online demo, <a href="http://ltrc.iiit.ac.in/analyzer/tamil/" rel="nofollow">here</a>...
0
2016-07-28T19:04:30Z
[ "python", "unicode", "nltk", "chunking", "indic" ]
Chunking for Tamil language
38,644,313
<p>I want to use the NLTK chunker for Tamil language (which is an Indic language). <a href="http://www.nltk.org/_modules/nltk/chunk.html" rel="nofollow">However, it says that it doesn't support Unicode because it uses the 'pre' module for regular expressions.</a></p> <blockquote> <h2>Unresolved Issues</h2> <p>I...
1
2016-07-28T18:38:16Z
38,685,330
<p>Chunkers are language-specific, so you need to train one for Tamil anyway. Of course if you are happy with available off-the-shelf solutions (I've got no idea if there are any, e.g. if the link in the now-deleted answer is any good), you can stop reading here. If not, you can train your own but you'll need a corpus ...
2
2016-07-31T15:08:30Z
[ "python", "unicode", "nltk", "chunking", "indic" ]
How do I increase the width between xaxis ticks in a seaborn facetgrid plot?
38,644,375
<p>I have a seaborn Facetgrid, stripplot</p> <pre><code>m=sns.FacetGrid(group, col='myGroupCol' , size=15, aspect=0.9, sharex=False, sharey=True) m.map(sns.stripplot,'myX','myY',hue='myColorBy',data=pandas.groupby(), order=order_list, jitter=0.4, hue_order=\ ['T','C','TT','TC','CT','CC'],palette="Set1", split=True, s...
0
2016-07-28T18:41:48Z
38,644,498
<p>Well just adjusted the aspect ratio and jitter appropriately and got the desired plot.</p>
1
2016-07-28T18:49:28Z
[ "python", "matplotlib", "seaborn" ]
Dataframe with column of ranges. Given number, select row where number occurs
38,644,388
<p>I have a dataframe with a column of a range of numbers, and then more columns of data</p> <pre><code>[1, 2, 3, ..., 10] | a | b [11, 12, 13, 14, ...] | c | d </code></pre> <p>Given a number like 10, 14, etc. how do I select the row where that number is in the range, i.e for 10 I want <code>[1, 2, 3, ..., 10]...
0
2016-07-28T18:42:46Z
38,644,492
<p>Use <code>apply</code> to loop through column <code>B</code> and check each element individually which returns a logical index for subsetting:</p> <pre><code>df = pd.DataFrame({"B": [list(range(1,11)), list(range(11,21))], "col1":["a", "b"], "col2":["c", "d"]}) df[df["B"].apply(lambda x: 10 in x)] # ...
1
2016-07-28T18:48:57Z
[ "python", "pandas" ]
Dataframe with column of ranges. Given number, select row where number occurs
38,644,388
<p>I have a dataframe with a column of a range of numbers, and then more columns of data</p> <pre><code>[1, 2, 3, ..., 10] | a | b [11, 12, 13, 14, ...] | c | d </code></pre> <p>Given a number like 10, 14, etc. how do I select the row where that number is in the range, i.e for 10 I want <code>[1, 2, 3, ..., 10]...
0
2016-07-28T18:42:46Z
38,644,500
<pre><code>df = pd.DataFrame({'ranges':[range(11), range(11,20)], 'dat1':['a','c'], 'dat2':['b','d']}) mask = df.ranges.apply(lambda x: 10 in x) df.ix[mask] </code></pre>
1
2016-07-28T18:49:34Z
[ "python", "pandas" ]
PyMySQL Error inserting values into table. - Python
38,644,397
<p>I am trying to make a login system with python and mysql. I connected to the database, but when I try to insert values into a table, it fails. I'm not sure what's wrong. I am using python 3.5 and the PyMySQL module. </p> <pre><code> #!python3 import pymysql, sys, time try: print('Connecting.....'...
0
2016-07-28T18:43:18Z
38,646,773
<p>I think it may have to do with the order of the statements in the connection. According to the PyMySQL github (found <a href="https://github.com/PyMySQL/PyMySQL/blob/master/example.py" rel="nofollow">here</a>) the correct order is host, port, user, passwd, db.</p>
0
2016-07-28T21:07:57Z
[ "python", "mysql", "python-3.x", "pymysql" ]
Error running executable compiled with py2exe
38,644,417
<p>I'm trying use py2exe to compile an eye tracking experiment written in Python 2.7 (32-bit). The experiment uses the psychopy library. I wrote the experiment using the PyCharm IDE, and the experiment runs when I run it through the PyCharm IDE, using an interpreter in a virtual environment located at <code>C:\Users\...
0
2016-07-28T18:44:59Z
38,666,497
<p>This is probably a missing config/prefs file. PsychoPy uses the configobj library to read and validate preferences but my guess is that py2exe is only automatically packaging py/pyc files and needs to include the .spec files in the psychopy/preferences folder.</p>
0
2016-07-29T19:50:08Z
[ "python", "windows", "compiler-errors", "py2exe", "psychopy" ]
Splitting line and adding numbers to a numpy array
38,644,441
<p>I have several text files in a folder, all with data in the form of numbers, each separated by 3 spaces. There are no line breaks. I want to take the numbers, put them in order in a numpy array, and then reshape it to be a 240 by 240 array. (I have the correct number of data points in each file to do so.) Afterwards...
0
2016-07-28T18:46:08Z
38,645,414
<p>It sounds like a number with reading one of the files. I'd suggest first doing a </p> <pre><code> lines = file.readlines() </code></pre> <p>and making sure that the lines look right. You may also want to add a <code>strip</code></p> <pre><code>In [244]: [int(x) for x in '121 342 123\n'.strip().split(' ')] Ou...
2
2016-07-28T19:44:26Z
[ "python", "arrays", "python-3.x", "numpy" ]
Batch renaming in python
38,644,477
<p>I want to rename image files in bulk, and give them names like 1.jpg, 2.jpg and so on. It works fine if I do it the first time. But as soon as I copy a new file with a different name like abc.jpg, the program behaves weirdly, sometimes just leaving the file abc.jpg as it is, while other times renaming it as I want, ...
-1
2016-07-28T18:48:22Z
38,645,503
<p>try this, it worked for me. You can add an if statement to check if the folder exists if u want. - </p> <pre><code> import os sourcepath = 'D:\Pictures' path = os.listdir(sourcepath) i = 1 for files in path: if not os.path.isfile(os.path.join(sourcepath, files)): continue ...
0
2016-07-28T19:49:42Z
[ "python", "python-2.7", "batch-rename" ]
Reading JSON file with Python 3
38,644,480
<p>I'm using Python 3.5.2 on Windows 10 x64. The <code>JSON</code> file I'm reading is <a href="http://pastebin.com/Yjs6FAfm" rel="nofollow" title="this">this</a> which is a <code>JSON</code> array containing 2 more arrays.</p> <p>I'm trying to parse this <code>JSON</code> file using the <code>json</code> module. As d...
0
2016-07-28T18:48:25Z
38,644,565
<p>Try this</p> <pre><code>import json with open('filename.txt', 'r') as f: array = json.load(f) print (array) </code></pre>
1
2016-07-28T18:53:24Z
[ "python", "json", "parsing" ]
Reading JSON file with Python 3
38,644,480
<p>I'm using Python 3.5.2 on Windows 10 x64. The <code>JSON</code> file I'm reading is <a href="http://pastebin.com/Yjs6FAfm" rel="nofollow" title="this">this</a> which is a <code>JSON</code> array containing 2 more arrays.</p> <p>I'm trying to parse this <code>JSON</code> file using the <code>json</code> module. As d...
0
2016-07-28T18:48:25Z
38,644,625
<p>Based on reading over the <a href="https://docs.python.org/3/library/json.html#json.load" rel="nofollow">documentation</a> again, it appears you need to either change the third line to </p> <pre><code>json_data = json.loads(text) </code></pre> <p>or remove the line</p> <pre><code>text = json_file.read() </code></...
1
2016-07-28T18:56:23Z
[ "python", "json", "parsing" ]
How to use a dictionary in recursion
38,644,493
<p>I have a recursive function that is similar to DFS on a graph G=(V,E) that finds all simple paths. The recursion is in a for loop so that when the function returns it may recurse again before returning itself. </p> <p>Just to set the picture:</p> <pre><code>def algo(M,v): for u in v.neighbors: # do stu...
-1
2016-07-28T18:49:06Z
38,651,681
<p>Do you simply want to insert an item into a dictionary, recur, and then remove the item:</p> <pre><code>def algo(M, v): for u in v.neighbors: # do stuff M[u.name] = u # temporarily extend dictionary result = algo(M, u) del M[u.name] # clean up # check result </code></pr...
1
2016-07-29T06:13:05Z
[ "python", "dictionary", "recursion", "copy" ]
Nearest value iteration
38,644,511
<pre><code>s1 = pd.Series({11:100, 13:102, 17:99}) s2 = pd.Series({10:1, 14:2, 18:3}) </code></pre> <p>Having these series, individually I can find s2's value by the nearest index of s2, using s1's index. Example:</p> <p><code>s2.values[np.abs(s2.index - s1.index[0]).argmin()]</code> </p> <p>Returns 1 because 11, s1...
1
2016-07-28T18:50:17Z
38,644,762
<p>If I understand correctly, I think you want to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.reindex.html" rel="nofollow"><code>reindex</code></a> on <code>s2</code> with <code>method='nearest'</code>:</p> <pre><code>s2 = s2.reindex(s1.index, method='nearest') df = pd.DataFrame({'...
2
2016-07-28T19:04:15Z
[ "python", "pandas" ]
Pandas query causing RuntimeWarning: divide by zero encountered in log10
38,644,532
<p>I saw a similar post (<a href="http://stackoverflow.com/questions/32659279/runtimewarning-divide-by-zero-encountered-in-log10-in-pandas-align-py-prob-fro">RuntimeWarning: divide by zero encountered in log10 in pandas align.py, prob from `query`-- cause/solution?</a>), but there was no sample code, followup or answer...
2
2016-07-28T18:51:36Z
38,644,712
<p>There is a <a href="https://github.com/pydata/pandas/issues/13135" rel="nofollow">bug</a> and it's still open.</p> <p>It's working properly for me:</p> <pre><code>In [2]: df Out[2]: C A B 1 14 0.159137 2 15 2.275652 3 16 0.798102 4 17 0.774097 5 18 2.361938 In [3]: df.query('15 &lt;= B &lt;= 17'...
0
2016-07-28T19:01:55Z
[ "python", "python-3.x", "pandas", "dataframe" ]
How to pass the value of a variable into a mongo query?
38,644,539
<p>The following mongo query works correctly: <code>db.data.find({"data.id": "5" })</code></p> <p>I want to pass the value of a variable for an argument list to the query in a python program:</p> <pre><code>import pymongo from pymongo import MongoClient client=MongoClient() db=client.dhlab data=db.data for data in d...
0
2016-07-28T18:52:04Z
38,644,654
<p>First, could you share you existing document schema? for refferences. </p> <pre><code>db.data.findOne() </code></pre> <p>Did you explicitly use have field <code>id</code> on the document?</p> <p>MongoDB store document using <code>_id</code>, maybe you got it wrong.</p>
0
2016-07-28T18:58:15Z
[ "python", "mongodb" ]
Import error on 'from six import raise_from'
38,644,575
<p>I'm trying to use the gmusicapi(<a href="https://github.com/simon-weber/gmusicapi" rel="nofollow">https://github.com/simon-weber/gmusicapi</a>). However when I try the following line:</p> <pre><code>from gmusicapi import Webclient </code></pre> <p>I get the following error message:</p> <pre><code>Traceback (most ...
0
2016-07-28T18:54:03Z
38,644,781
<p>It works fine for me. And I have python 2.7.5.</p> <p>Try this <code>pip install --upgrade six</code></p>
0
2016-07-28T19:05:24Z
[ "python", "six" ]
Python: How to delete rows ending in certain characters?
38,644,696
<p>I have a large data file and I need to delete rows that end in certain letters.</p> <p>Here is an example of the file I'm using:</p> <pre><code>User Name DN MB212DA CN=MB212DA,CN=Users,DC=prod,DC=trovp,DC=net MB423DA CN=MB423DA,OU=Generic Mailbox,DC=prod,DC=trovp,DC=net MB424PL CN=MB424PL,CN=...
9
2016-07-28T19:01:08Z
38,644,778
<p>Instead of <code>regular expressions</code>, you can use the <a href="https://docs.python.org/3/library/stdtypes.html#str.endswith" rel="nofollow"><code>endswith()</code></a> method to check if a string ends with a specific pattern.</p> <p>I.e.:</p> <pre><code>for row in rows: if row.endswith('DA') or row.ends...
0
2016-07-28T19:05:17Z
[ "python", "python-3.x", "pandas" ]
Python: How to delete rows ending in certain characters?
38,644,696
<p>I have a large data file and I need to delete rows that end in certain letters.</p> <p>Here is an example of the file I'm using:</p> <pre><code>User Name DN MB212DA CN=MB212DA,CN=Users,DC=prod,DC=trovp,DC=net MB423DA CN=MB423DA,OU=Generic Mailbox,DC=prod,DC=trovp,DC=net MB424PL CN=MB424PL,CN=...
9
2016-07-28T19:01:08Z
38,644,843
<p>You can use a boolean mask whereby you check if the last two characters of <code>User_Name</code> are in not (<code>~</code>) in a set of two character endings:</p> <pre><code>&gt;&gt;&gt; df[~df.User_Name.str[-2:].isin(['DA', 'PA'])] User_Name DN 2 MB424PL CN=...
2
2016-07-28T19:09:09Z
[ "python", "python-3.x", "pandas" ]
Python: How to delete rows ending in certain characters?
38,644,696
<p>I have a large data file and I need to delete rows that end in certain letters.</p> <p>Here is an example of the file I'm using:</p> <pre><code>User Name DN MB212DA CN=MB212DA,CN=Users,DC=prod,DC=trovp,DC=net MB423DA CN=MB423DA,OU=Generic Mailbox,DC=prod,DC=trovp,DC=net MB424PL CN=MB424PL,CN=...
9
2016-07-28T19:01:08Z
38,644,862
<p>You could use this expression</p> <pre><code>df = df[~df['User Name'].str.contains('(?:DA|PL)$')] </code></pre> <p>It will return all rows that don't end in either DA or PL. </p> <p>The <code>?:</code> is so that the brackets would not capture anything. Otherwise, you'd see pandas returning the following (harmles...
7
2016-07-28T19:10:13Z
[ "python", "python-3.x", "pandas" ]
In scipy classification models (such as the svm.svc), how can one get a list of the names for all classes?
38,644,787
<p>In scipy classification models (such as the svm.svc), how can one get a list of the names for all classes the model may classify points into?</p>
0
2016-07-28T19:05:36Z
38,688,820
<p>For <a href="http://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html" rel="nofollow">svm.SVC</a> (and many other models, like LogisticRegression etc.) there is an attribute <code>classes_</code> thus on trained model <code>clf</code> you can do</p> <pre><code>print clf.classes_ </code></pre>
1
2016-07-31T22:14:52Z
[ "python", "machine-learning", "scikit-learn", "classification", "svm" ]
pandas.DataFrame.replace, and for the first column
38,644,794
<p>How to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>pandas.DataFrame.replace</code></a> to replace all occurrences of a string in a pandas dataframe? </p> <p>This seems to be rather dumb question, but please <a href="https://gist.github.com/s...
1
2016-07-28T19:06:05Z
38,645,236
<p>The issue with your other two uses of replace is that replace only works on the values in the columns, not in the index, and in <code>p</code> and <code>r</code> 'fo' is only found in the index! So, one approach that would work is:</p> <pre><code>p.index = p.index.to_series().replace('fo','fu', regex=True) r.index ...
0
2016-07-28T19:32:23Z
[ "python", "python-3.x", "replace", "dataframe" ]
pandas.DataFrame.replace, and for the first column
38,644,794
<p>How to use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.replace.html" rel="nofollow"><code>pandas.DataFrame.replace</code></a> to replace all occurrences of a string in a pandas dataframe? </p> <p>This seems to be rather dumb question, but please <a href="https://gist.github.com/s...
1
2016-07-28T19:06:05Z
38,645,342
<h3>Making replacements in just one column</h3> <p>Get that column as a Series and use the <code>Series.replace</code> method:</p> <pre><code>df['A'] = df['A'].replace("fo", "fu", regex=True) </code></pre> <p>or</p> <pre><code>df['A'].replace("fo", "fu", regex=True, inplace=True) </code></pre> <h3>Making replaceme...
1
2016-07-28T19:39:32Z
[ "python", "python-3.x", "replace", "dataframe" ]
PyCurl Timing Out With Working Network Connection on Windows 10
38,644,845
<p>When using GrabLib, which uses PyCurl/LibCurl to make requests, I keep getting a timeout error when sending a request. When using the requests module, however, the requests.get method connects to the third-party website with no issues. </p> <p>Here is my sample code which uses requests and pycurl:</p> <pre><code>i...
0
2016-07-28T19:09:12Z
38,708,479
<p>After translating some Russian Google Group comments I've determined that downgrading from "PycURL / 7.43. 0 libcurl / 7.47. 0 OpenSSL / 1.0 2e zlib / 1.2 8 c -.. Ares / 1.10 0 libssh2 / 1.6 0" to "PycURL/7.19.5.3 libcurl/7.45.0 WinSSL zlib/1.2.8" (printed with "print (pycurl.version)") fixes whatever issue I was ha...
0
2016-08-01T21:33:18Z
[ "python", "networking", "windows-10", "libcurl", "pycurl" ]
How can i tell if this repository is using python3 or 2?
38,644,870
<p><a href="https://github.com/tekno45/dndchar" rel="nofollow">https://github.com/tekno45/dndchar</a></p> <p>I forked this repository and i'd like to work on it at work. Is there a way to tell if it's written in 3 or 2?</p>
-2
2016-07-28T19:10:29Z
38,644,887
<p>It's written in Python 2.</p> <p>The biggest hint is that <code>print</code> is a statement there, not a function.</p>
4
2016-07-28T19:11:38Z
[ "python", "python-2.7", "python-3.x", "github" ]
Cython - Exposing C++ (vector and non-vector) objects returned by C++ function to Python
38,644,895
<p>I am working on a project where I have a large C++ code base available which I want to wrap with cython and made available in python.</p> <p>In doing so, I am facing a situation where some of my C++ functions returns Vector object or simple object (with multiple attributes). I want to return this object to Python s...
0
2016-07-28T19:12:02Z
38,647,224
<p>If C++ methods return pointers to objects (or if the ownership of the data can be transferred), and the underlying data can be accessed, memory views should be usable.</p> <p>The following example is for a <code>vector</code> of integers (<code>int</code>). Class <code>test_view</code> has a reference to the object...
0
2016-07-28T21:43:11Z
[ "python", "c++", "object", "cython" ]
Cython - Exposing C++ (vector and non-vector) objects returned by C++ function to Python
38,644,895
<p>I am working on a project where I have a large C++ code base available which I want to wrap with cython and made available in python.</p> <p>In doing so, I am facing a situation where some of my C++ functions returns Vector object or simple object (with multiple attributes). I want to return this object to Python s...
0
2016-07-28T19:12:02Z
38,674,182
<p>A very simple example that duplicates your issue (when compiled incorrectly) and demonstrates how to fix it by changing the compile options.</p> <pre><code>cdef extern from "&lt;utility&gt;" namespace "std": int&amp;&amp; move(int&amp;&amp;) cdef class someclass: cdef int i cdef move_from(self, int&am...
0
2016-07-30T12:53:14Z
[ "python", "c++", "object", "cython" ]
Telegram.org API: calling method invokeWithLayer in Python
38,644,901
<p>In reference to <a href="http://stackoverflow.com/questions/30661644/how-to-implement-authorization-using-a-telegram-api/34929980#_=_">How to implement authorization using a Telegram API?</a> This is the best telegram documentation I have yet to find! Thanks for that.</p> <p>I am attempting to create a Python libra...
1
2016-07-28T19:12:24Z
38,660,855
<p>1) I get the latest telegram schema from here: <a href="https://raw.githubusercontent.com/telegramdesktop/tdesktop/master/Telegram/SourceFiles/mtproto/scheme.tl" rel="nofollow">https://raw.githubusercontent.com/telegramdesktop/tdesktop/master/Telegram/SourceFiles/mtproto/scheme.tl</a></p> <p>You can build your own ...
0
2016-07-29T14:04:52Z
[ "python", "api", "telegram" ]
SciPy Parabolic Cylinder D and Complex Arguments
38,644,932
<p>I'm trying to use the Parabolic Cylinder D function from SciPy and am having trouble with complex arguments. Sample code to produce the error is:</p> <pre><code>#!/usr/bin/env python import numpy import scipy.special as special # test real numbers test = 0.735759 A = test - special.pbdv(1,2)[0] print A # test com...
1
2016-07-28T19:14:28Z
38,646,012
<p>I still don't understand why the scipy implementation of the function doesn't accept complex arguments, all the functions under the hood accept complex arguments.</p> <p>I managed to get the function defined in <a href="https://en.wikipedia.org/wiki/Parabolic_cylinder_function" rel="nofollow">Abramowitz and Stegun<...
1
2016-07-28T20:19:37Z
[ "python", "numpy", "math", "scipy" ]
How to use AnyObject method in zeep library for Python?
38,644,935
<p>I read in the documentation that it is done like this.</p> <p><a href="http://i.stack.imgur.com/7jxIS.png" rel="nofollow"><img src="http://i.stack.imgur.com/7jxIS.png" alt="enter image description here"></a></p> <p>I did a simple code to try this out and I have the following. (ucmdb is the client)</p> <pre><code>...
0
2016-07-28T19:14:35Z
38,660,236
<p>You might want to try it with latest version. Otherwise submit an issue in github.com/mvantellingen/python-zeep</p>
0
2016-07-29T13:33:00Z
[ "python", "xsd", "python-3.5", "webservice-client" ]
Tornado multiple IOLoop in multithreads
38,644,963
<p>I am trying to run multiple IOLoop in multiple threads and I am wondering how the IOLoop actually works. </p> <pre><code>class WebThread(threading.Thread): def __init__(self): threading.Thread.__init__(self, name='WebThread') def run(self): curdir = os.path.dirname(os.path.realpath(__file__...
0
2016-07-28T19:16:13Z
38,648,368
<blockquote> <p>In general you should use IOLoop.current as the default when constructing an asynchronous object, and use IOLoop.instance when you mean to communicate to the main thread from a different one.</p> </blockquote> <p><a href="http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.current" ...
1
2016-07-28T23:36:54Z
[ "python", "multithreading", "tornado" ]
What is the equivalent of Serial.available() in pyserial?
38,645,060
<p>When I am trying to read multiple lines of serial data on an Arduino, I use the following idiom:</p> <pre><code>String message = ""; while (Serial.available()){ message = message + serial.read() } </code></pre> <p>In Arduino C, <code>Serial.available()</code> returns the number of bytes available to be read fr...
0
2016-07-28T19:22:19Z
38,646,191
<p>The property <a href="https://pythonhosted.org/pyserial/pyserial_api.html#serial.Serial.in_waiting" rel="nofollow"><code>Serial.in_waiting</code></a> returns the "the number of bytes in the receive buffer". </p> <p>This seems to be the equivalent of <a href="https://www.arduino.cc/en/Serial/Available" rel="nofollow...
1
2016-07-28T20:31:59Z
[ "python", "serial-port" ]
What is the equivalent of Serial.available() in pyserial?
38,645,060
<p>When I am trying to read multiple lines of serial data on an Arduino, I use the following idiom:</p> <pre><code>String message = ""; while (Serial.available()){ message = message + serial.read() } </code></pre> <p>In Arduino C, <code>Serial.available()</code> returns the number of bytes available to be read fr...
0
2016-07-28T19:22:19Z
38,651,454
<p>I have written my code as below. Hope you can use it modify your code</p> <pre><code>import serial import csv import os import time import sys import string from threading import Timer def main(): pass if __name__ == '__main__': main() COUNT=0 f=open("test.csv","w+"); result = csv.writer(f,de...
-1
2016-07-29T05:56:01Z
[ "python", "serial-port" ]
Assigning headers in text files and building arrays
38,645,078
<p>I am writing a program that reads a text file and parses the information inside it. An example of the text file is as follows:</p> <pre><code>-&gt;DQB1*02:02:01:01 GAACTTTGCTCTTTTCACCAAAACTTAAGGCTCCTCAGGGTGTGTCTAAGACAACAGCAGTAAAAATGTCTATGACAGCAATTTTCTCTCCCCTGAAATATGATCCCCACTTAATTTGCCCTATTGAAAGAATCCCAAGTATAAGAACAACT...
0
2016-07-28T19:23:23Z
38,645,929
<p>Your example is broken. All lines start with <code>-&gt;</code></p> <p>So I assume that you want to split them at the first space character.</p> <pre><code>#! /usr/bin/env python # read the file and split into lines y = open("testAllele1.txt", "r").read() z = y.splitlines() # initialize header = [] sequence = []...
1
2016-07-28T20:14:18Z
[ "python", "arrays", "python-2.7", "header" ]
How to delete a line break character in list item python
38,645,099
<p>I have a small question regarding python lists. See this code:</p> <pre><code>passwords = [] fob = open("/path/to/file", "r") for add_items in fob : passwords.append(add_items) print passwords fob.close() </code></pre> <p>The code result:</p> <pre><code>['Monster1\n', 'Monster2\n', 'Monster3'] </code></pr...
2
2016-07-28T19:24:17Z
38,645,115
<p>Use <code>rstrip('\n')</code> or just <code>rstrip()</code>:</p> <pre><code>passwords.append(add_items.rstrip('\n')) </code></pre>
3
2016-07-28T19:25:17Z
[ "python", "list" ]
How to delete a line break character in list item python
38,645,099
<p>I have a small question regarding python lists. See this code:</p> <pre><code>passwords = [] fob = open("/path/to/file", "r") for add_items in fob : passwords.append(add_items) print passwords fob.close() </code></pre> <p>The code result:</p> <pre><code>['Monster1\n', 'Monster2\n', 'Monster3'] </code></pr...
2
2016-07-28T19:24:17Z
38,645,154
<p>Above answer would work. So would this, without directly stripping each line or using list comprehension:</p> <pre><code>with open("C:\Users\Bucky\Desktop\pass.txt", "r") as fob: passwords = fob.read().splitlines() </code></pre>
0
2016-07-28T19:27:26Z
[ "python", "list" ]
How to delete a line break character in list item python
38,645,099
<p>I have a small question regarding python lists. See this code:</p> <pre><code>passwords = [] fob = open("/path/to/file", "r") for add_items in fob : passwords.append(add_items) print passwords fob.close() </code></pre> <p>The code result:</p> <pre><code>['Monster1\n', 'Monster2\n', 'Monster3'] </code></pr...
2
2016-07-28T19:24:17Z
38,645,160
<p>You could clean it up a bit better and remove all surrounding white space by using <code>strip</code>. Also, you could simplify things by using a comprehension and a context manager: </p> <pre><code>with open("C:\Users\Bucky\Desktop\pass.txt") as f: passwords = [data.strip() for data in f] </code></pre> <p>In ...
2
2016-07-28T19:27:39Z
[ "python", "list" ]
How to delete a line break character in list item python
38,645,099
<p>I have a small question regarding python lists. See this code:</p> <pre><code>passwords = [] fob = open("/path/to/file", "r") for add_items in fob : passwords.append(add_items) print passwords fob.close() </code></pre> <p>The code result:</p> <pre><code>['Monster1\n', 'Monster2\n', 'Monster3'] </code></pr...
2
2016-07-28T19:24:17Z
38,645,211
<p>You can use a list comprehension towether with <code>replace</code> to clean all instances of <code>\n</code> within the string (assuming the password should not contain a carriage return):</p> <pre><code>&gt;&gt;&gt; [pw.replace('\n', '') for pw in passwords] ['Monster1', 'Monster2', 'Monster3'] </code></pre>
1
2016-07-28T19:30:57Z
[ "python", "list" ]
How can I do multidimensional matrix multiplication in numpy, scipy
38,645,111
<p>I have a scipy sparse matrix with shape (8,9) and another array with shape (9, 12 , 17). I want to multiply these such that I get a matrix/array of size (8,12,17) where the (8,9) matrix has effectively multiplied the first dimension only. Do I have to use Kronecker products to do this or is there a simple way in num...
0
2016-07-28T19:25:03Z
38,646,244
<p>Here are a couple of ways I can get it to work. The second seems to be better and is about 12 times faster when I tested. </p> <pre><code>def multiply_3D_dim_zero_slow(matrix, array): shape = array.shape final_shape = (matrix.shape[0], array.shape[1], array.shape[2]) result = np.zeros(final_shape) for i in xrange(s...
0
2016-07-28T20:34:36Z
[ "python", "numpy", "matrix", "scipy" ]
How can I do multidimensional matrix multiplication in numpy, scipy
38,645,111
<p>I have a scipy sparse matrix with shape (8,9) and another array with shape (9, 12 , 17). I want to multiply these such that I get a matrix/array of size (8,12,17) where the (8,9) matrix has effectively multiplied the first dimension only. Do I have to use Kronecker products to do this or is there a simple way in num...
0
2016-07-28T19:25:03Z
38,646,481
<p>As hpaulj suggests in the comments, the easiest way to do this is <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html" rel="nofollow"><code>np.einsum</code></a> with a dense matrix:</p> <pre><code>&gt;&gt;&gt; a = np.random.randn(8, 9) &gt;&gt;&gt; b = np.random.randn(9, 12, 17) &gt;&gt;&...
1
2016-07-28T20:50:01Z
[ "python", "numpy", "matrix", "scipy" ]
How can I do multidimensional matrix multiplication in numpy, scipy
38,645,111
<p>I have a scipy sparse matrix with shape (8,9) and another array with shape (9, 12 , 17). I want to multiply these such that I get a matrix/array of size (8,12,17) where the (8,9) matrix has effectively multiplied the first dimension only. Do I have to use Kronecker products to do this or is there a simple way in num...
0
2016-07-28T19:25:03Z
38,646,519
<p>If <code>m1</code> is the 2d sparse matrix, <code>m1.A</code> is its dense array form. The dinmensions practically write the <code>einsum</code> expression.</p> <pre><code>np.einsum('ij,jkl-&gt;ikl', m1.A, m2) </code></pre> <p>for example:</p> <pre><code>In [506]: M = sparse.random(8, 9, 0.1) In [507]: A = np.on...
2
2016-07-28T20:52:03Z
[ "python", "numpy", "matrix", "scipy" ]
How can I do multidimensional matrix multiplication in numpy, scipy
38,645,111
<p>I have a scipy sparse matrix with shape (8,9) and another array with shape (9, 12 , 17). I want to multiply these such that I get a matrix/array of size (8,12,17) where the (8,9) matrix has effectively multiplied the first dimension only. Do I have to use Kronecker products to do this or is there a simple way in num...
0
2016-07-28T19:25:03Z
38,647,553
<p>@Divakar recommended <code>np.tensordot</code>, and @hpaulj and @Praveen suggested <code>np.einsum</code>. Yet another way is transposing axes:</p> <pre><code>(a @ b.transpose((2, 0, 1))).transpose((1, 2, 0)) </code></pre> <p>For the small dimensions that you quote, <code>np.einsum</code> and transposition seem to...
1
2016-07-28T22:09:29Z
[ "python", "numpy", "matrix", "scipy" ]
Regex replacing pairs of dollar signs
38,645,212
<p>I have a string like: <code>The old man $went$ to the $barn$.</code> How would I convert this to <code>The old man ~!went! to the ~!barn!.</code></p> <p>If I didn't need to add the <code>~</code> in front of the first occurrence, I could simply do <code>text.replace('$', '!')</code> in Python.</p>
1
2016-07-28T19:30:58Z
38,645,273
<p>Use a capture group so that your replacement string can put the text between the <code>$</code> back in place.</p> <p>So the regex would be:</p> <pre><code>\$([^$]*)\$ </code></pre> <p>And then the replacement string would be:</p> <pre><code>~!\1! </code></pre> <p><a href="https://regex101.com/r/xT8yR1/2" rel="...
1
2016-07-28T19:34:48Z
[ "python", "regex" ]
Regex replacing pairs of dollar signs
38,645,212
<p>I have a string like: <code>The old man $went$ to the $barn$.</code> How would I convert this to <code>The old man ~!went! to the ~!barn!.</code></p> <p>If I didn't need to add the <code>~</code> in front of the first occurrence, I could simply do <code>text.replace('$', '!')</code> in Python.</p>
1
2016-07-28T19:30:58Z
38,645,277
<p>Yes, regex this. Capture groups will help.</p> <pre><code>result = re.sub(r'\$(.*?)\$', r'~!\1!', my_str) </code></pre>
1
2016-07-28T19:34:59Z
[ "python", "regex" ]