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
How can I scrape data from a <span> locked tag?
38,153,046
<p>I'm using <code>bs4</code> and <code>urllib2</code> to fetch some info from a website.</p> <p>Here's the <a href="http://www.ribeiraosaude.com.br/detalhe/937" rel="nofollow">webpage</a>.</p> <p>I must fetch the rest of the telephone <code>3610...</code>... but first I must press this button to show the rest of the...
3
2016-07-01T19:52:37Z
38,153,230
<p>How you approach this depends on what happens when the button is clicked. </p> <p>If the button triggers JavaScript that displays the number you can scrape the JavaScript called by the button. </p> <p>Eg. <code>function displayNumber(){ document.body.yourSpan.innerHTML = 'NUMBER'</code></p> <p>However, if the but...
3
2016-07-01T20:07:39Z
[ "python", "html", "web-scraping", "beautifulsoup" ]
logging.debug error during string formatting
38,153,133
<p>I am trying to print a variable using <code>logging.debug</code> and running into below error,how to fix it?</p> <pre><code>logging.debug('ATTEMPTS:{0}',attempts) </code></pre> <p>Error:-</p> <pre><code>Traceback (most recent call last): File "C:\Python27\lib\logging\__init__.py", line 846, in emit msg = se...
0
2016-07-01T19:59:57Z
38,153,153
<p>You're <a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">formatting the string</a> incorrectly, try:</p> <p><code>logging.debug('ATTEMPTS:{0}'.format(attempts))</code></p>
0
2016-07-01T20:01:34Z
[ "python" ]
logging.debug error during string formatting
38,153,133
<p>I am trying to print a variable using <code>logging.debug</code> and running into below error,how to fix it?</p> <pre><code>logging.debug('ATTEMPTS:{0}',attempts) </code></pre> <p>Error:-</p> <pre><code>Traceback (most recent call last): File "C:\Python27\lib\logging\__init__.py", line 846, in emit msg = se...
0
2016-07-01T19:59:57Z
38,153,167
<p>you should try as</p> <pre><code>logging.debug('ATTEMPTS:{0}'.format(attempts)) </code></pre>
-1
2016-07-01T20:02:55Z
[ "python" ]
logging.debug error during string formatting
38,153,133
<p>I am trying to print a variable using <code>logging.debug</code> and running into below error,how to fix it?</p> <pre><code>logging.debug('ATTEMPTS:{0}',attempts) </code></pre> <p>Error:-</p> <pre><code>Traceback (most recent call last): File "C:\Python27\lib\logging\__init__.py", line 846, in emit msg = se...
0
2016-07-01T19:59:57Z
38,153,450
<p>You could either use</p> <pre><code>logging.debug('ATTEMPTS:%s', attempts) </code></pre> <p>or</p> <pre><code>logging.debug('ATTEMPTS:{0}'.format(attempts)) </code></pre> <p>The first method passes two parameters into the logging.debug function which will automatically format the log. The second method passes in...
0
2016-07-01T20:27:10Z
[ "python" ]
Finding length of max discountinuity
38,153,136
<p>I'm migrating some code from python list primitive to a pandas implementation. For some time series, I want to find all the discontinuous segments with their durations. Is there a clean way of doing this in pandas?</p> <p>My dataframe looks like this:</p> <pre><code>In [23]: df Out[23]: 2016-07-01 05:35:00 60.4...
3
2016-07-01T20:00:02Z
38,153,282
<p>This should work as long as you have a series or a single-column dataframe.</p> <pre><code>&gt;&gt;&gt;pd.Series(df.isnull().index).diff() </code></pre> <p>Which can be improved to get a useful output with:</p> <pre><code>MIN_GAP_TIMEDELTA = Timedelta(minutes=30) discontinuities = pd.Series(df.isnull().index).dif...
6
2016-07-01T20:12:17Z
[ "python", "numpy", "pandas", "time-series" ]
Finding length of max discountinuity
38,153,136
<p>I'm migrating some code from python list primitive to a pandas implementation. For some time series, I want to find all the discontinuous segments with their durations. Is there a clean way of doing this in pandas?</p> <p>My dataframe looks like this:</p> <pre><code>In [23]: df Out[23]: 2016-07-01 05:35:00 60.4...
3
2016-07-01T20:00:02Z
38,154,347
<p>Not as elegant or short as pandas based solution(s), but with performance in mind, one can look to use NumPy arrays and functions. So, to solve such a case and assuming the date-times have a regular frequency, here's a NumPy based approach to get discontinuity lengths, max-lengths and thresholded counts -</p> <pre>...
2
2016-07-01T21:56:20Z
[ "python", "numpy", "pandas", "time-series" ]
Can someone give a python requests example of uploading a release asset in github?
38,153,418
<pre><code>url = 'https://github.abc.defcom/api/v3/repos/abc/def/releases/401/assets?name=foo.sh' r = requests.post(url, headers={'Content-Type':'application/binary'}, data=open('sometext.txt','r'), auth=('user','password')) </code></pre> <p>This is giving me </p> <pre><code>&gt;&gt;&gt; r.text u'{"message":"Not Foun...
0
2016-07-01T20:24:49Z
38,164,576
<p>So I'll preface this with the advice that if you use a library it's as easy as:</p> <pre><code>from github3 import GitHubEnterprise gh = GitHubEnterprise(token=my_token) repository = gh.repository('abc', 'def') release = repository.release(id=401) asset = release.upload_asset(content_type='application/binary', nam...
1
2016-07-02T21:20:18Z
[ "python", "github", "github-api" ]
twisted client call from a library function
38,153,442
<p>I'm trying to implement a function that will act as a Twisted client. It's called from code I don't have control over. I tried something like (this taken from the pbsimpleclient.py example code):</p> <pre><code># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb f...
0
2016-07-01T20:26:30Z
38,157,481
<p>Remove <code>reactor.run()</code> from the <code>remcall</code> function and append it at the end. Also remove <code>d.addCallback(lambda _: reactor.stop())</code></p> <pre><code>def remcall(**kw): factory = pb.PBClientFactory() reactor.connectTCP("localhost", 8789, factory) d = factory.getRootObject()...
1
2016-07-02T07:04:18Z
[ "python", "twisted", "twisted.client" ]
twisted client call from a library function
38,153,442
<p>I'm trying to implement a function that will act as a Twisted client. It's called from code I don't have control over. I tried something like (this taken from the pbsimpleclient.py example code):</p> <pre><code># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. from twisted.spread import pb f...
0
2016-07-01T20:26:30Z
38,184,598
<p>The answer is to use crochet.</p> <pre><code># Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. ## Add these two lines from crochet import setup, wait_for setup() from twisted.spread import pb from twisted.internet import reactor from twisted.python import util ## Add a wait_for decorator @w...
0
2016-07-04T12:17:57Z
[ "python", "twisted", "twisted.client" ]
compare list of datetime to dict of datetime
38,153,456
<p>I have a task to create sets of dates based on specific condition, for example "greater than 2" will be passed and I need to create a set of all dates in this month that have a day > 2. also Ill be getting a start time and a stop time for e.g. 10am-6pm in this case I will create a set of all the dates > 2 and in eve...
14
2016-07-01T20:27:41Z
38,154,658
<p>Frankly speaking I am not sure if I understand what is your problem, I tried something like this: </p> <pre><code>for date in dateList: for everyrange in dateRange: find=False for i in dateRange[everyrange]: #print('date={date} ,key={everyrange},i={i}'.format(date=date, everyrange=ev...
1
2016-07-01T22:36:36Z
[ "python", "datetime", "dictionary" ]
compare list of datetime to dict of datetime
38,153,456
<p>I have a task to create sets of dates based on specific condition, for example "greater than 2" will be passed and I need to create a set of all dates in this month that have a day > 2. also Ill be getting a start time and a stop time for e.g. 10am-6pm in this case I will create a set of all the dates > 2 and in eve...
14
2016-07-01T20:27:41Z
38,154,823
<p>I am not sure I fully understood your question, but I am assuming you want to find the dates from the 'dateList' list that fall between a specific range in the 'dateRange' dic.</p> <p>I tried to structure my code based on your logic. This should work:</p> <pre><code>for date in dateList: for key,value in date...
1
2016-07-01T22:58:35Z
[ "python", "datetime", "dictionary" ]
compare list of datetime to dict of datetime
38,153,456
<p>I have a task to create sets of dates based on specific condition, for example "greater than 2" will be passed and I need to create a set of all dates in this month that have a day > 2. also Ill be getting a start time and a stop time for e.g. 10am-6pm in this case I will create a set of all the dates > 2 and in eve...
14
2016-07-01T20:27:41Z
38,276,279
<p>I tried this example, based on your demand and worked well =). The algorithm is very similar to the one you've posted, the only diference is in the end of the algorithm. I choose to create a new list, to be returned in the function you are building.</p> <p>Here's the code:</p> <pre><code>list_1 = ['a 1', 'a 2', 'a...
1
2016-07-08T22:33:48Z
[ "python", "datetime", "dictionary" ]
compare list of datetime to dict of datetime
38,153,456
<p>I have a task to create sets of dates based on specific condition, for example "greater than 2" will be passed and I need to create a set of all dates in this month that have a day > 2. also Ill be getting a start time and a stop time for e.g. 10am-6pm in this case I will create a set of all the dates > 2 and in eve...
14
2016-07-01T20:27:41Z
38,286,851
<p>It sounds like you're trying to optimize your algorithm. To be honest, with data this size, it's probably not necessary. However, if you are interested, the general rule of thumb is that <a href="http://stackoverflow.com/questions/2831212/python-sets-vs-lists">sets are faster than lists</a> in Python when checking...
5
2016-07-09T22:23:20Z
[ "python", "datetime", "dictionary" ]
compare list of datetime to dict of datetime
38,153,456
<p>I have a task to create sets of dates based on specific condition, for example "greater than 2" will be passed and I need to create a set of all dates in this month that have a day > 2. also Ill be getting a start time and a stop time for e.g. 10am-6pm in this case I will create a set of all the dates > 2 and in eve...
14
2016-07-01T20:27:41Z
38,353,155
<p>I'm still not absolutely certain what you're trying to achieve but please have a look at this code and tell me if this is what you want.</p> <p>There is an option to input month as well.</p> <p>The list named list1 is equivalent to your dictionary dictD.</p> <p>The list named list2 is equivalent to your list list...
1
2016-07-13T13:28:40Z
[ "python", "datetime", "dictionary" ]
Fastest way to read file searching for pattern matches
38,153,471
<p>I made a python script to analyze logs. I have one observation to share, and two questions to ask. </p> <p>When I use gzip.open to open each file and go through every line, it takes around 200 seconds just to going through all the lines and files.</p> <pre><code>with gzip.open(file) as fp: for line in fp: ...
-2
2016-07-01T20:29:00Z
38,228,780
<p>'grep' contains decade's worth of optimizations, and re-implementing it in any programming language, not just Python, will be slower. *1</p> <p>Therefore, if speed is important to you, your technique of calling 'grep' directly is probably the way to go. To do this using 'subprocess', without having to write any tem...
1
2016-07-06T16:15:10Z
[ "python", "grep" ]
How can I transfer a CSV file from the output of python script into SQL?
38,153,573
<p>I have a python script that takes data from my ARCGIS Online account and brings down into a CSV into a specified file. The script can be found at the bottom. I then want to take the CSV file and put it into SQL. I want the process to be automated. I run the script in the command prompt (example in the image). Can i ...
-3
2016-07-01T20:38:36Z
38,153,781
<p>Python comes with an sqlite library: <a href="https://docs.python.org/2/library/sqlite3.html" rel="nofollow">https://docs.python.org/2/library/sqlite3.html</a> Read carefully.</p>
0
2016-07-01T20:58:29Z
[ "python", "sql", "database", "command-prompt", "arcgis" ]
Python subprocess Popen.terminate() still stuck on wait()
38,153,635
<p>I am trying to implement a radio player using RPi. The goal is to setup a playlist and start playing once playlist is populated. The player and radio processes are expected to exit once stop code is executed.</p> <p>The radio process terminates nicely but the player process still remains on wait even after calling ...
4
2016-07-01T20:43:32Z
38,213,110
<p>As @J.F.Sebastian mentioned, using <code>player.stdout.close()</code> works. The entire code base is published here <a href="https://github.com/hex007/pifm_server" rel="nofollow">https://github.com/hex007/pifm_server</a></p> <p>So the final code looks something like this </p> <pre><code>while playlist: player ...
2
2016-07-05T21:31:37Z
[ "python", "raspberry-pi", "subprocess", "python-multithreading" ]
Join the same argument mulitple times from list
38,153,761
<p>I'm dynamically generating a list of check boxes using values from a list as follows:</p> <pre><code>return flask.jsonify(result='\n'.join('&lt;input type="checkbox" class="av-sources"&gt;%s&lt;br&gt;'% src for src in my_list)) </code></pre> <p>The problem I am facing is, when trying to include a list item multipl...
0
2016-07-01T20:56:48Z
38,153,913
<p>Looks like you just have a bracket in the wrong place.</p> <p>Change...</p> <pre><code>'\n'.join('&lt;input type="checkbox" class="av-sources" value="{0}"&gt;{0}&lt;br&gt;'.format(src for src in sources)) </code></pre> <p>...to...</p> <pre><code>'\n'.join('&lt;input type="checkbox" class="av-sources" value="{0}"...
3
2016-07-01T21:10:58Z
[ "python", "python-2.7", "flask" ]
django Get foreign-key model in view and show in html
38,153,772
<p>So I have two models:</p> <pre><code>class UserMeasurements(models.Model): user = models.CharField(max_length=20) time = models.DateTimeField(blank=True, null=True) set = models.ForeignKey(PhotoSets, models.DO_NOTHING) class Meta: managed = False db_table = 'user_measurements' clas...
0
2016-07-01T20:57:46Z
38,153,826
<p>I don't know what you're trying to do with that <code>a</code> variable, but you don't need to do any of this. You should just follow the foreign key when you output each measurement, eg in your template:</p> <pre><code>{% for measurement in measurement_list %} User: {{ measurement.user }} Time: {{ measurement....
1
2016-07-01T21:02:38Z
[ "python", "django", "foreign-keys" ]
django Get foreign-key model in view and show in html
38,153,772
<p>So I have two models:</p> <pre><code>class UserMeasurements(models.Model): user = models.CharField(max_length=20) time = models.DateTimeField(blank=True, null=True) set = models.ForeignKey(PhotoSets, models.DO_NOTHING) class Meta: managed = False db_table = 'user_measurements' clas...
0
2016-07-01T20:57:46Z
38,153,828
<p>Would you give it a try in your main.html</p> <pre><code>{% for item in measurement_list %} {{ item.image_dir }} {% endfor %} </code></pre>
1
2016-07-01T21:02:45Z
[ "python", "django", "foreign-keys" ]
Cannot read property error using d3.js
38,153,814
<p>I've been trying to visualize a Parse Tree generated by a Python Script via HTML and d3.js. The Python Script generates an HMTL document that look like this:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;meta charset="utf-8"&gt; &lt;head&gt;&lt;title&gt; Tree Visualization &lt;/title&gt;&lt;/head&gt; &lt;script src="ht...
1
2016-07-01T21:01:50Z
38,154,261
<p>It may be the version of d3 you are using, I see you are loading:</p> <pre><code>&lt;script src="https://d3js.org/d3.v4.min.js"&gt;&lt;/script&gt; </code></pre> <p>It may be the case that in v4 there is no <code>d3.layout.tree()</code> object. Try switching to different version, may be this one:</p> <pre><code>&l...
0
2016-07-01T21:47:51Z
[ "javascript", "python", "html", "d3.js" ]
Cannot read property error using d3.js
38,153,814
<p>I've been trying to visualize a Parse Tree generated by a Python Script via HTML and d3.js. The Python Script generates an HMTL document that look like this:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;meta charset="utf-8"&gt; &lt;head&gt;&lt;title&gt; Tree Visualization &lt;/title&gt;&lt;/head&gt; &lt;script src="ht...
1
2016-07-01T21:01:50Z
38,479,454
<p>d3js v4 doesn't use <code>d3.layout.tree</code> any more. Instead use like following</p> <pre><code>var tree = d3.layout.tree(); //v3 var tree = d3.tree(); //v4 </code></pre> <p>Check the <a href="https://github.com/d3/d3/blob/master/CHANGES.md#hierarchies-d3-hierarchy" rel="nofollow">changelog</a> for the diff...
3
2016-07-20T11:01:48Z
[ "javascript", "python", "html", "d3.js" ]
Custom cluster colors of SciPy dendrogram in Python (link_color_func?)
38,153,829
<p>I want to color my clusters with a color map that I made in the form of a dictionary (i.e. <code>{leaf: color}</code>). </p> <p>I've tried following <a href="https://joernhees.de/blog/2015/08/26/scipy-hierarchical-clustering-and-dendrogram-tutorial/" rel="nofollow">https://joernhees.de/blog/2015/08/26/scipy-hierar...
11
2016-07-01T21:02:57Z
38,206,728
<p>I found a hackish solution, and does require to use the color threshold (but I need to use it in order to obtain the same original coloring, otherwise the colors are not the same as presented in the OP), but could lead you to a solution. However, you may not have enough information to know how to set the color palet...
-1
2016-07-05T14:59:48Z
[ "python", "machine-learning", "scipy", "hierarchical-clustering", "dendrogram" ]
Custom cluster colors of SciPy dendrogram in Python (link_color_func?)
38,153,829
<p>I want to color my clusters with a color map that I made in the form of a dictionary (i.e. <code>{leaf: color}</code>). </p> <p>I've tried following <a href="https://joernhees.de/blog/2015/08/26/scipy-hierarchical-clustering-and-dendrogram-tutorial/" rel="nofollow">https://joernhees.de/blog/2015/08/26/scipy-hierar...
11
2016-07-01T21:02:57Z
38,208,611
<p>Here a solution that uses the return matrix <code>Z</code> of <code>linkage()</code> (described early but a little hidden in the <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.hierarchy.linkage.html" rel="nofollow">docs</a>) and <code>link_color_func</code>:</p> <pre><code># see question...
3
2016-07-05T16:43:58Z
[ "python", "machine-learning", "scipy", "hierarchical-clustering", "dendrogram" ]
Python Multi-threading with PySerial object
38,153,897
<p>I am new to Python and programming in general. I am trying to write a device driver using pyserial. I opened a thread that would read data from the device and send it to std out. On my main loop I used a function that would read instructions from std in as strings and write them to the device using a dictionary. </p...
3
2016-07-01T21:09:44Z
38,154,084
<p>You can do it like this:</p> <pre><code>import serial from threading import Thread from functools import wraps # decorate the function - start another thread def run_async(func): @wraps(func) def async_func(*args, **kwargs): func_hl = Thread(target = func, args = args, kwargs = kw...
1
2016-07-01T21:28:08Z
[ "python", "multithreading", "pyserial" ]
np.load to a paths file
38,154,010
<p>I have a file with all of my pathnames for each .npy file. I have about 5 million files so I would like to avoid unnecessary fors.</p> <p>What I need to do is to load them all into my data variable like this:</p> <p>data = np.load( input_file_w_pathnames )</p> <p>I know this will not work but I was wondering if s...
1
2016-07-01T21:20:41Z
38,154,695
<p><code>np.load</code> takes a filename or a file object (a file that you opened). It uses standard Python file reading tools. It does not take multiple names or files.</p> <pre><code>np.stack([np.load(f) for f in ['x.npy','x.npy','x.npy']]) </code></pre> <p>can join the arrays in each file into a larger array, it...
1
2016-07-01T22:41:05Z
[ "python", "numpy", "path", "load" ]
Save Dataframe to csv directly to s3 Python
38,154,040
<p>I have a pandas DataFrame that I want to upload to a new CVS file. The problem is that I don't want to save the file locally before transferring it to s3. Is there a method like to_csv for writing the dataframe to s3 directly? I am using boto3.<br> Here is what I have so far:</p> <pre><code>import boto3 s3 = boto3....
3
2016-07-01T21:23:50Z
38,154,116
<p>If you pass <code>None</code> as the first argument to <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html" rel="nofollow"><code>to_csv()</code></a> the data will be returned as a string. From there it's an easy step to upload that to S3 in one go.</p> <p>It should also be po...
2
2016-07-01T21:31:45Z
[ "python", "csv", "amazon-s3", "dataframe", "boto3" ]
How to create a django model field mixin
38,154,107
<p>I am trying to make a generic mixin for model fields (as opposed to form fields), the init for the mixin takes named arguments. I am running into trouble instantiating the mixin with another class.</p> <p>Here is the code</p> <pre><code>class MyMixin(object): def __init__(self, new_arg=None, *args, **kwargs): ...
6
2016-07-01T21:30:14Z
38,162,312
<p>So I figured it out after lots of tinkering and re-reading the <a href="https://docs.djangoproject.com/en/1.9/howto/custom-model-fields/" rel="nofollow">django docs on custom model fields</a> You need a deconstructor along with your init. Django fields need a <code>deconstruct</code> method to serialize.</p> <p>The...
1
2016-07-02T16:38:22Z
[ "python", "django" ]
How to create a django model field mixin
38,154,107
<p>I am trying to make a generic mixin for model fields (as opposed to form fields), the init for the mixin takes named arguments. I am running into trouble instantiating the mixin with another class.</p> <p>Here is the code</p> <pre><code>class MyMixin(object): def __init__(self, new_arg=None, *args, **kwargs): ...
6
2016-07-01T21:30:14Z
38,162,421
<blockquote> <p>First, why is init running 3 times?</p> </blockquote> <p>Although the <code>models.py</code> is only imported once, the <code>Field</code> objects created therein, such as...</p> <pre><code>myfield = MyMixinCharField(max_length=512, new_arg="myarg") </code></pre> <p>...are cloned several times, whi...
1
2016-07-02T16:50:49Z
[ "python", "django" ]
How can I call box.commit from python client
38,154,128
<p>I want to execute some code in single transaction. I use tarantool 1.6 with python client (0.5.4) My code looks like this (it does'not work):</p> <pre><code>import tarantool tnt = tarantool.Connection(**params) tnt.call('box.begin') tnt.update(space1, 1, [('=', 2, 100)]) tnt.update(space2, 1, [('+', 1, 200)]) tnt....
0
2016-07-01T21:33:37Z
38,154,163
<p>Sorry, I make small mistaske in code, this variant works fine:</p> <pre><code>import tarantool tnt = tarantool.Connection(**params) tnt.call('box.begin') tnt.update(space1, 1, [('=', 2, 100)]) tnt.update(space2, 1, [('+', 1, 200)]) tnt.call('box.commit') </code></pre>
0
2016-07-01T21:37:00Z
[ "python", "transactions", "tarantool" ]
Custom Matplotlib View Window
38,154,179
<p>I've got a graph plotted using the <code>matplotlib</code> library, and would like to know if there is a way to view from a custom range. I have several vertical lines, starting 0. The beginning of the plot also starts at zero and makes seeing that first line difficult. Is there a way that I can have a view window s...
0
2016-07-01T21:39:47Z
38,154,281
<p>Use <code>plt.xlim</code> (or <code>plt.ylim</code>)</p> <p>import matplotlib.pyplot as plt import numpy as np import numpy.random as rnd</p> <pre><code>def f(t): s1 = np.sin(2 * np.pi * t) e1 = np.exp(-t) return np.absolute((s1 * e1)) + .05 t = np.arange(0.0, 5.0, 0.1) s = f(t) nse = rnd.normal(0.0, ...
1
2016-07-01T21:49:37Z
[ "python", "matplotlib" ]
New to Python 3.4+ Scripting and Manipulating JSON
38,154,196
<p>I'm currently trying to manipulate JSON with a script that I've wrote. And it is doing what I want it to do, but there's something needed to be adjust, and that is to change the Class? of the JSON? not sure if that's what is called in JSON.</p> <pre><code>"rooms": { "1": { "tiles": { "-3,1"...
-1
2016-07-01T21:41:13Z
38,154,423
<p>Convert your JSON string into a python object using <a href="https://docs.python.org/2/library/json.html" rel="nofollow"><code>json.loads</code></a>, then you can update the inner dict at key <code>tiles</code> like so:</p> <pre><code>d = {"rooms": { "1": { "tiles": { "-3,1": {...
1
2016-07-01T22:06:35Z
[ "python", "json" ]
Scrapy Login Authentication Isn't Working
38,154,213
<p>Hi I'm working with scrapy to log into some random website. I followed the tutorials on scrapy and it doesn't seem to be working. When i try it, i notice that the "isAuthenticated": False. And the html body i return doesn't contain everything that the actual website does. I'm not sure what the issue is. I thought it...
1
2016-07-01T21:43:06Z
38,156,632
<p>To login to website, you will need to use <strong>FormRequest</strong> but for some website, i.e. <strong><em>bitbucket</em></strong> in your example, </p> <p>they use predefined form attributes like CSRFtoken, session info and other tokens which can only be used from the previous page user have visited</p> <p>In ...
0
2016-07-02T04:57:29Z
[ "python", "python-2.7", "scrapy", "scrapy-spider" ]
Slow Python socket transfers
38,154,227
<p>I have a question about some Python socket programming. I'm pretty new to sockets and probably just have a poor understanding of how they work. I need to transfer a binary file between two machines while running a python application and figured doing some socket programming would be better/faster than doing a system...
0
2016-07-01T21:44:34Z
38,195,391
<p>I would suggest increasing the size of the buffer from 4096 to a larger size. This would reduce the number of times items would reduce the number of times of going through stack operations and interpretations of Python, which may increase the speed at which the data is transferred.</p> <p>Currently, at 4096 (4K) b...
0
2016-07-05T04:52:45Z
[ "python", "python-2.7", "sockets" ]
Efficiency of checking for string in querystring parameters in python
38,154,247
<p>I am running a query that needs to exclude all previously seen items and return a certain number of items (10 in this case). The list of items is sent in a querystring parameter and are uuid4 strings separated by '&amp;'. </p> <p>With a possible very large database, I don't think it makes sense to add the exclude s...
0
2016-07-01T21:46:42Z
38,154,327
<p>Whatever you are doing will be much faster if you use Python's built in <code>set</code> data structure. Checking for inclusion then is very fast, if you have some memory available, but 1k items is nothing. see <a href="https://docs.python.org/2/library/stdtypes.html#set" rel="nofollow">https://docs.python.org/2/l...
1
2016-07-01T21:53:40Z
[ "python", "string", "list" ]
Python GTK3: how to use gtk_*_new_*() functions
38,154,458
<p>In GTK3, how can I use <code>gtk_*_new_*()</code> constructors?</p> <p>For instance, consider:</p> <pre><code>GtkWidget * gtk_recent_chooser_menu_new_for_manager () </code></pre> <p>How can I use it?</p> <p>I am trying to port a PyGTK2 program, and I can workaround things like <code>gtk_text_view_new_with_buffer...
1
2016-07-01T22:11:39Z
38,154,643
<p>I figure it out.</p> <p>Apparently you can just use things like:</p> <pre><code>view = Gtk.TextView.new_with_buffer(buffer) </code></pre> <p>Interestingly, <code>Gtk.TextView.new() == Gtk.TextView()</code></p>
1
2016-07-01T22:34:43Z
[ "python", "gtk3" ]
Python GTK3: how to use gtk_*_new_*() functions
38,154,458
<p>In GTK3, how can I use <code>gtk_*_new_*()</code> constructors?</p> <p>For instance, consider:</p> <pre><code>GtkWidget * gtk_recent_chooser_menu_new_for_manager () </code></pre> <p>How can I use it?</p> <p>I am trying to port a PyGTK2 program, and I can workaround things like <code>gtk_text_view_new_with_buffer...
1
2016-07-01T22:11:39Z
38,169,479
<p><strong>tl;dr</strong>: Use the Python constructor normal form to set construction properties instead of the convenience C API.</p> <p>The various <code>_new</code> constructors in the C API, including the basic <code>_new()</code> one, are just wrappers around <code>g_object_new()</code>. Constructors like <code>t...
1
2016-07-03T11:26:56Z
[ "python", "gtk3" ]
Using Selenium WebDriver in Python to Open Link in New Tab/Window
38,154,483
<p>I'm having an issue in <em>Selenium</em> where I want to open a link in a new tab. It doesn't have an href either, so obtaining the url as a string doesn't seem possible.</p> <p>I have tried to use <code>ActionChains</code> from <em>Selenium</em>, but I can't get it to work.</p> <pre><code>actions = ActionChains(s...
-1
2016-07-01T22:14:51Z
38,160,880
<p>if webdriver click is not working, you could use javascript to click on an element which opens a new tab/window. </p> <pre><code>def click_using_javascript(): browser.execute_script('arguments[0].click();', element) </code></pre>
0
2016-07-02T13:47:46Z
[ "python", "selenium-webdriver" ]
Force pandas xaxis datetime index using a specific format
38,154,489
<p>my pandas dataframe looks like this:</p> <pre><code> data1 data2 data3 DateTime .... 2016-04-18 16:16:53 -66 1 94.8654 2016-04-18 16:17:03 -67 1 94.8601 2016-04-18 16:17:13 -68 1 94.8410 2016-04-18 ...
1
2016-07-01T22:15:38Z
38,156,663
<p>You have to use functions from matplotlib.dates module:</p> <pre><code>import pandas as pd from datetime import datetime import numpy as np import matplotlib.pylab as plt import matplotlib.dates as mdates timeInd = pd.date_range(start = datetime(2016,4,17,23,0,0), end = datetime(2016,4,20,1,0,0), freq = 'H') d =...
1
2016-07-02T05:04:21Z
[ "python", "pandas", "matplotlib" ]
Python string match (without string manipulation functions)
38,154,518
<p>The other day I got this problem and I think I came out with a very complicated solution. How would you solve it?</p> <p>Write a function to determine whether an input string x is a substring of another input string y. For example, "bat" is a substring of "abate", but not of "beat". Basically implement something si...
0
2016-07-01T22:19:38Z
38,154,622
<p>Python makes this very easy, with your example both print statements below will execute:</p> <pre><code>st = "abate" if "bat" in st: print("Yes, this is a substring of st") # do something else if "xyz" not in st: print("No, this isn't a substring of st.") # do something else </code></pre>
0
2016-07-01T22:32:24Z
[ "python", "string" ]
Microbit python Invalid syntax
38,154,623
<p>I'm trying out the BBC microbit educational computer for my kids. I thought I'd do something simple, like traverse an array, using buttons A &amp; B to increment left and right (looping at the ends). I can't work out what's wrong with my code (reports syntax error on line 3)? Also is my presumption about 'input â†...
0
2016-07-01T22:32:41Z
38,154,956
<p>That is not valid Python code. Python functions usually start with <code>def main():</code></p> <p>The first two lines with</p> <pre><code># Add your Python code here. E.g. from microbit import *` </code></pre> <p>are valid python though.</p> <p>The code following that is intended for the 'TouchDevelop' environm...
0
2016-07-01T23:21:56Z
[ "python", "bbc-microbit" ]
Microbit python Invalid syntax
38,154,623
<p>I'm trying out the BBC microbit educational computer for my kids. I thought I'd do something simple, like traverse an array, using buttons A &amp; B to increment left and right (looping at the ends). I can't work out what's wrong with my code (reports syntax error on line 3)? Also is my presumption about 'input â†...
0
2016-07-01T22:32:41Z
38,155,157
<p>After Dennis pointed out that I wasn't using Python, I took another go. This time it worked. :)</p> <pre><code> from microbit import * alphabetIndex = 0 alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" while True: if button_a.is_pressed(): if (alphabetIndex == 0): alphab...
0
2016-07-01T23:54:14Z
[ "python", "bbc-microbit" ]
Python Regular Expression: Matching Car Speeds without Highway Names
38,154,673
<p>I'm trying to match speed descriptions of highway tickets, for example,text lines:</p> <p>"L A 16-25MPH" should return 2 groups: 16, 25 <br /> "LMT ACC 6-10" should return 2 groups: 6, 10 <br /> "6 OVER" should return 1 group: 6<br /><br /> I'm OK with all of the above situations, but I run into issues for strin...
4
2016-07-01T22:38:33Z
38,154,758
<p><em>Negative lookbehinds</em> must be of fixed length (see the <a href="https://docs.python.org/2/library/re.html" rel="nofollow">Python doc</a> for more detail), so things like <code>\d+</code> would not be allowed.</p> <p>You could use a lookbehind to check for certain fixed-width indicators of highways, though, ...
3
2016-07-01T22:48:46Z
[ "python", "regex", "python-2.7" ]
Python Regular Expression: Matching Car Speeds without Highway Names
38,154,673
<p>I'm trying to match speed descriptions of highway tickets, for example,text lines:</p> <p>"L A 16-25MPH" should return 2 groups: 16, 25 <br /> "LMT ACC 6-10" should return 2 groups: 6, 10 <br /> "6 OVER" should return 1 group: 6<br /><br /> I'm OK with all of the above situations, but I run into issues for strin...
4
2016-07-01T22:38:33Z
38,155,961
<h1>Description</h1> <pre class="lang-regex prettyprint-override"><code>([0-9]+)(?:-([0-9]+)|\s*over) </code></pre> <p><img src="https://www.debuggex.com/i/GEmbvcQ7TsQJfvkP.png" alt="Regular expression visualization"></p> <p><sub>** To see the image better, simply right click the image and select view in new window<...
2
2016-07-02T02:33:42Z
[ "python", "regex", "python-2.7" ]
Numpy csv file groupby
38,154,677
<p>I'm reading a CSV file with 2 columns, the second column describes a label, I want to see how many of each labels exists in my CSV file, I came up with a simple loop and a dictionary object. Wondering if there is a numpy function like groupby which gives me same functionality.</p> <pre><code>dataset = np.genfromtxt...
1
2016-07-01T22:38:59Z
38,154,959
<p>You could use numpy's fancy indexing by turning your dataset into a structured array:</p> <pre><code>dataset = np.genfromtxt(input_file, invalid_raise=False, missing_values='N/A', delimiter=",", dtype=[('data', 'S50'), ('label', 'S50')], skip_header=1) </code></pre> <p>and then you get the ...
1
2016-07-01T23:22:22Z
[ "python", "csv", "numpy" ]
Parallelizing loop for downloading data
38,154,699
<p>I'm new to Python. I want to run a simple script in Google App Engine that retrieves many files into an object as quickly as possible. Would parallelization be a smart option and how would I go about doing it? Thanks in advance for the brainstorming</p> <pre><code>import requests ... theData=[] for q in range(0, l...
2
2016-07-01T22:41:21Z
38,154,741
<p>You should make your code more Pythonic by using list comprehensions:</p> <pre><code># A list of tuples theData = [(q,requests.get(theURLs[q]).text) for q in range(0, len(theURLs))] # ... or ... # A list of lists theData = [[q,requests.get(theURLs[q]).text] for q in range(0, len(theURLs))] </code></pre> <p>If yo...
3
2016-07-01T22:47:17Z
[ "python" ]
Parallelizing loop for downloading data
38,154,699
<p>I'm new to Python. I want to run a simple script in Google App Engine that retrieves many files into an object as quickly as possible. Would parallelization be a smart option and how would I go about doing it? Thanks in advance for the brainstorming</p> <pre><code>import requests ... theData=[] for q in range(0, l...
2
2016-07-01T22:41:21Z
38,154,777
<p>I seriously doubt it. Parallelization can really only speed up calculations, while the bottleneck here is data transfer.</p>
-1
2016-07-01T22:51:25Z
[ "python" ]
Parallelizing loop for downloading data
38,154,699
<p>I'm new to Python. I want to run a simple script in Google App Engine that retrieves many files into an object as quickly as possible. Would parallelization be a smart option and how would I go about doing it? Thanks in advance for the brainstorming</p> <pre><code>import requests ... theData=[] for q in range(0, l...
2
2016-07-01T22:41:21Z
38,155,681
<p>In "regular" Python this is pretty simple.</p> <pre><code>from multiprocessing.pool import ThreadPool import requests responses = ThreadPool(10).map(requests.get, urls) </code></pre> <p>Replace 10 with # of threads that produces best results for you.</p> <p>However you specified GAE which has restrictions on spaw...
3
2016-07-02T01:34:44Z
[ "python" ]
How do I convert a string to a string literal in python?
38,154,736
<p>I'm writing some code that uses an Onclick event to get some file paths. I need to make sure these file paths are literals to make sure they're correct so the rest of my code can run. Right now I think I'm getting the file paths as unicode. Essentially I need this:</p> <pre><code>u"File\location\extra\slash" </code...
0
2016-07-01T22:46:27Z
38,154,846
<p>You can use eval.</p> <pre><code>MacBookPro:~ DavidLai$ python Python 2.7.11 (default, Jan 22 2016, 08:29:18) [GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; x = u"File\location\extra\slash" &gt;&gt;&gt; y = eval(...
-1
2016-07-01T23:02:49Z
[ "python", "string", "arcgis" ]
How do I convert a string to a string literal in python?
38,154,736
<p>I'm writing some code that uses an Onclick event to get some file paths. I need to make sure these file paths are literals to make sure they're correct so the rest of my code can run. Right now I think I'm getting the file paths as unicode. Essentially I need this:</p> <pre><code>u"File\location\extra\slash" </code...
0
2016-07-01T22:46:27Z
38,234,809
<p>From your comments, you have <code>a = u'File\\location\\extra\\slash'</code>, and you want to extract <code>e = 'slash'</code>, <code>f = 'extra'</code>, and <code>g = 'File\location'</code>. Nothing here requires converting strings to string literals; you've just gotten really confused by various levels of string ...
1
2016-07-06T22:26:47Z
[ "python", "string", "arcgis" ]
Pyside + Qt Designer Better Coding
38,154,753
<p>I want to improve my code but currently have not much idea how. So I used <strong>Qt Designer</strong> and created a main window plus 3 dialogs which can be opened from main window. Converted .ui files to .py files and created the MainWindow class which manages all. Everything works fine, but for me this looks wrong...
0
2016-07-01T22:48:08Z
38,167,235
<p>I think you should never use the <code>sender</code> method of Qt because it makes calling the method from another function impossible, you can then only use it via the signal/slot mechanism. It therefore says in <a href="http://doc.qt.io/qt-5/qobject.html#sender" rel="nofollow">the documentation</a> that: <em>"This...
1
2016-07-03T06:12:18Z
[ "python", "pycharm", "pyside", "qt-designer" ]
Periodic high response time in Tornado web server
38,154,783
<p>I've implemented a Tornado webserver to handle requests from another PHP webserver. The php requests will cause there to be some simple and consistent data processing before responding. However, when I view the logs I'm periodically seeing spikes in the response time. For example:</p> <pre><code>INFO:tornado.acce...
0
2016-07-01T22:52:26Z
38,168,900
<p><a href="http://www.tornadoweb.org/en/stable/ioloop.html#tornado.ioloop.IOLoop.set_blocking_log_threshold" rel="nofollow"><code>IOLoop.set_blocking_log_threshold</code></a> is one tool for debugging these kinds of issues. Call <code>IOLoop.current().set_blocking_log_threshold(0.010)</code> and it will log a stack tr...
0
2016-07-03T10:14:40Z
[ "php", "python", "tornado" ]
Proving a function has no proper input validation
38,154,832
<p><strong>The Problem:</strong></p> <p>I have this artificial example function:</p> <pre><code>def test_function(target, words): pattern = re.compile(r"|".join(words)) return bool(pattern.search(target)) </code></pre> <p>which takes a list of words and dynamically constructs a regular expression pattern <e...
2
2016-07-01T23:01:17Z
38,154,883
<p>There are plenty of ways you could do this. For example, a word that isn't a valid regex:</p> <pre><code>&gt;&gt;&gt; test_function('a', ['*']) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;string&gt;", line 2, in test_function File "/usr/lib64/python2.6/re.py", ...
2
2016-07-01T23:08:22Z
[ "python", "regex", "input-sanitization" ]
Python Newbie: using eval() to assign a value to a self.variable
38,154,901
<p>I am a newbie at Python and i have a class with a lot of variables, like this:</p> <pre><code>class trash: def __init__(self): self.var1=1 self.var2=1 self.var3=1 ... def replaceByTwo(self, var_name) self.eval(var_name) = 2 </code></pre> <p>but when i call replaceB...
2
2016-07-01T23:12:16Z
38,154,915
<p>the error you are getting is because you are trying to call <code>self.eval()</code>, but eval is a global function and not a member of your instance.</p> <p>and anyway for what you want to do, eg set member / attribute by name, you should use <code>setattr()</code>.</p>
4
2016-07-01T23:14:03Z
[ "python", "class", "eval" ]
Python Newbie: using eval() to assign a value to a self.variable
38,154,901
<p>I am a newbie at Python and i have a class with a lot of variables, like this:</p> <pre><code>class trash: def __init__(self): self.var1=1 self.var2=1 self.var3=1 ... def replaceByTwo(self, var_name) self.eval(var_name) = 2 </code></pre> <p>but when i call replaceB...
2
2016-07-01T23:12:16Z
38,154,916
<p><code>eval</code> is a builtin not a default method for Python classes. But what you seek is <code>setattr</code>:</p> <pre><code>def replaceByTwo(self, var_name): setattr(self, var_name, 2) </code></pre> <p>Trial:</p> <pre><code>&gt;&gt;&gt; t = trash() &gt;&gt;&gt; print(t.var2) 1 &gt;&gt;&gt; t.replaceByT...
3
2016-07-01T23:14:24Z
[ "python", "class", "eval" ]
numpy - incrementally rebuild an ndarray by filtering unneded members
38,154,903
<p>Consider that I have an ndarray:</p> <pre><code>all_data.shape (220000, 28, 28) type(all_data) numpy.ndarray </code></pre> <p>I want to go over each member of this array and filter out those which I don't want. As result I want to get new ndarray of exactly same shape.</p> <p>Something like:</p> <pre><code>#sav...
1
2016-07-01T23:12:25Z
38,159,402
<p>Copied from comments:</p> <p>It is better to accumulate component arrays in a list, and apply <code>concatenate</code> once to the whole list. Also get in the habit checking dimensions as you go along.</p> <p>@hpaulj last suggestion worked, thanks!</p>
1
2016-07-02T11:01:34Z
[ "python", "arrays", "numpy" ]
SQL insert into.. where (python)
38,154,982
<p>I have the following code:</p> <pre><code>def create_table(): c.execute('CREATE TABLE IF NOT EXISTS TEST(SITE TEXT, SPORT TEXT, TOURNAMENT TEXT, TEAM_1 TEXT, TEAM_2 TEXT, DOUBLE_CHANCE_1X TEXT, DOUBLE_CHANCE_X2 TEXT, DOUBLE_CHANCE_12 TEXT, DRAW_1 TEXT, DRAW_2 TEXT DATE_ODDS TEXT, TIME_ODDS TEXT)') create_t...
0
2016-07-01T23:26:02Z
38,156,024
<p>Use the UPDATE statement to update columns in an existing row.</p> <pre><code>UPDATE TEST SET DRAW_1=value1,DRAW_2=value2 WHERE column3=value3; </code></pre> <p>If data_entry(1) is always called first, then change the statement in data_entry_2() to UPDATE. If not you will need to check if the row exists in both ca...
0
2016-07-02T02:45:53Z
[ "python", "mysql", "sql", "database" ]
Setting values on Pandas DataFrame subset (copy) is slow
38,154,997
<pre><code>import timeit import pandas as pd import numpy as np df = pd.DataFrame(np.random.rand(10, 10)) dft = df[[True, False] * 5] # df = dft dft2 = dft.copy() new_data = np.random.rand(5, 10) print(timeit.timeit('dft.loc[:, :] = new_data', setup='from __main__ import dft, new_data', number=100)) print(timeit.ti...
11
2016-07-01T23:29:02Z
38,355,664
<p>This is not exactly a new question on SO. <a href="http://stackoverflow.com/questions/22532302/pandas-peculiar-performance-drop-for-inplace-rename-after-dropna">This</a>, and <a href="http://stackoverflow.com/questions/17960511/pandas-subindexing-dataframes-copies-vs-views">this</a> are related posts. <a href="http:...
3
2016-07-13T15:16:18Z
[ "python", "performance", "pandas", "dataframe" ]
Interactive Python Mac OS X help()
38,155,033
<p>When I run Python interactively in Terminal and call </p> <pre><code>help(print) </code></pre> <p>I get the help information, but then Python seems to get stuck. At the end of the help information is the following, which is greyed out:</p> <p><code>(END)</code></p> <p>At this point, I have to exit the interacti...
2
2016-07-01T23:34:34Z
38,155,074
<p><code>help()</code> prints its output using a pager, so that if the output is longer than a screenful it will pause at each screen end and let you tell it to continue. And at the end it prints <code>(END)</code>, and it's waiting for you to tell it what to do. Type <kbd>q</kbd> to exit from the pager. And type <kbd>...
4
2016-07-01T23:39:17Z
[ "python", "osx", "terminal" ]
What is the difference between native int type and the numpy.int types?
38,155,039
<p>Can you please help understand what are the main differences (if any) between the native int type and the numpy.int32 or numpy.int64 types?</p>
2
2016-07-01T23:34:58Z
38,155,060
<p>Not a complete answer but this should get you started <a href="http://docs.scipy.org/doc/numpy-1.10.1/user/basics.types.html" rel="nofollow">http://docs.scipy.org/doc/numpy-1.10.1/user/basics.types.html</a></p> <blockquote> <p>There are 5 basic numerical types representing booleans (bool), integers (int), unsigne...
-2
2016-07-01T23:37:43Z
[ "python", "numpy" ]
What is the difference between native int type and the numpy.int types?
38,155,039
<p>Can you please help understand what are the main differences (if any) between the native int type and the numpy.int32 or numpy.int64 types?</p>
2
2016-07-01T23:34:58Z
38,155,077
<p>I think that the biggest difference is that the numpy types are compatible with their C counterparts. For one thing, this means that numpy ints can overflow...</p> <pre><code>&gt;&gt;&gt; np.int32(2**32) 0 </code></pre> <p>This is why you can create an array of integers and specify the datatype as <code>np.int32<...
0
2016-07-01T23:40:13Z
[ "python", "numpy" ]
What is the difference between native int type and the numpy.int types?
38,155,039
<p>Can you please help understand what are the main differences (if any) between the native int type and the numpy.int32 or numpy.int64 types?</p>
2
2016-07-01T23:34:58Z
38,156,630
<p>There are several major differences. The first is that python integers are flexible-sized (at least in python 3.x). This means they can grow to accommodate any number of any size (within memory constraints, of course). The numpy integers, on the other hand, are fixed-sized. This means there is a maximum value the...
2
2016-07-02T04:57:20Z
[ "python", "numpy" ]
What is the difference between native int type and the numpy.int types?
38,155,039
<p>Can you please help understand what are the main differences (if any) between the native int type and the numpy.int32 or numpy.int64 types?</p>
2
2016-07-01T23:34:58Z
38,156,888
<p>Another way to look at the differences is to ask what methods do the 2 kinds of objects have.</p> <p>In Ipython I can use tab complete to look at methods:</p> <pre><code>In [1277]: x=123; y=np.int32(123) </code></pre> <p><code>int</code> methods and attributes:</p> <pre><code>In [1278]: x.&lt;tab&gt; x.bit_lengt...
2
2016-07-02T05:38:56Z
[ "python", "numpy" ]
Why does subprocess.call(["module","list"]) fail?
38,155,084
<p>I'm finding the subprocess module wherein you load a list instead of a string (shell=True) to really frustrating. Intuitively, subprocess.call(["module","list"]) should work, but it doesn't and yields this:</p> <pre><code> File "test.py", line 45, in main subprocess.call(["module","list"]) File "/tools/gene...
0
2016-07-01T23:41:05Z
38,155,347
<p>This is simply the format of the command. When parsing without going through a shell, it goes through each command and argument individually. But when the interpreter is told to just use the gnome-shell (which is much better at parsing whole command-strings AND is nitpicky about spacing) the format of the command wi...
-1
2016-07-02T00:27:04Z
[ "python", "subprocess" ]
looping over multiple aws profiles with boto3
38,155,103
<p>I cant seem to find a really good way to initiate multiple sessions with boto3. If I have 10 accounts and want to lets say, make a new IAM user, I cant seem to change the boto3.session.Session with new calls. </p> <p>So example code:</p> <pre><code> for user in usernames: for acct in accounts: ...
0
2016-07-01T23:44:33Z
38,200,592
<p>You are not using the session your boto3.session() returns. Instead you are using the same default session. You can develop from the following code snippet:</p> <pre><code> for acct in accounts: session = boto3.Session(profile_name=acct) iam = session.client('iam') for user in usernames: ...
1
2016-07-05T10:04:50Z
[ "python", "amazon-web-services", "boto", "amazon-iam", "boto3" ]
How do I get pytest to run all functions as test
38,155,169
<p>I have looked around and I can't find a pytest.ini flag to pass in that says the equivalent of </p> <pre><code>def test_one(): # you run this by default def two(): # despite not having test in the name you should also run this </code></pre> <p>reason: test function name lengths are getting to long when I'm ...
0
2016-07-01T23:56:22Z
39,035,985
<p>From <a href="http://doc.pytest.org/en/latest/example/pythoncollection.html" rel="nofollow">documentation</a></p> <pre><code># content of setup.cfg # can also be defined in in tox.ini or pytest.ini file [pytest] python_files=check_*.py python_classes=Check python_functions=*_check </code></pre> <p>Replace <code>*_...
1
2016-08-19T09:50:27Z
[ "python", "unit-testing", "py.test" ]
How do I get pytest to run all functions as test
38,155,169
<p>I have looked around and I can't find a pytest.ini flag to pass in that says the equivalent of </p> <pre><code>def test_one(): # you run this by default def two(): # despite not having test in the name you should also run this </code></pre> <p>reason: test function name lengths are getting to long when I'm ...
0
2016-07-01T23:56:22Z
39,579,821
<p>Try this as shown below, it will ask py.test collection tests from all python files.</p> <pre><code># content of pytest.ini [pytest] python_files = *.py </code></pre> <p>you can check this part of document, </p> <p><a href="http://doc.pytest.org/en/latest/example/pythoncollection.html#customizing-test-collection-...
0
2016-09-19T18:29:12Z
[ "python", "unit-testing", "py.test" ]
Digit separators in Python code
38,155,177
<p>Is there any way to group digits in a Python code to increase code legibility? I've tried <code>'</code> and <code>_</code> which are <a href="https://en.wikipedia.org/wiki/Integer_literal#Digit_separators"><em>digit separators</em></a> of some other languages, but no avail.</p> <p>A weird operator which concatenat...
12
2016-07-01T23:58:08Z
38,155,210
<p>This is not implemented in python at the present time. You can look at the lexical analysis for strict definitions <a href="https://docs.python.org/2/reference/lexical_analysis.html#numeric-literals">python2.7</a>, <a href="https://docs.python.org/3.5/reference/lexical_analysis.html#numeric-literals">python3.5</a> ...
10
2016-07-02T00:03:10Z
[ "python", "literals" ]
Digit separators in Python code
38,155,177
<p>Is there any way to group digits in a Python code to increase code legibility? I've tried <code>'</code> and <code>_</code> which are <a href="https://en.wikipedia.org/wiki/Integer_literal#Digit_separators"><em>digit separators</em></a> of some other languages, but no avail.</p> <p>A weird operator which concatenat...
12
2016-07-01T23:58:08Z
38,155,213
<p>There is no such function in Python but it was proposed to integrate it in the future.</p> <p>You can see the proposal in the <a href="https://www.python.org/dev/peps/pep-0515/" rel="nofollow">PEP515</a>.</p>
2
2016-07-02T00:03:27Z
[ "python", "literals" ]
Digit separators in Python code
38,155,177
<p>Is there any way to group digits in a Python code to increase code legibility? I've tried <code>'</code> and <code>_</code> which are <a href="https://en.wikipedia.org/wiki/Integer_literal#Digit_separators"><em>digit separators</em></a> of some other languages, but no avail.</p> <p>A weird operator which concatenat...
12
2016-07-01T23:58:08Z
38,155,236
<p>The closest thing I've seen in python is <code>12 * 1000 * 1000</code>, which is not ideal, but can be useful if <code>12000000</code> is needed. Be advised though, while in C, those are equivalent, because at compile time it converts both to the same thing, python may not share this optimization.</p>
1
2016-07-02T00:06:40Z
[ "python", "literals" ]
Digit separators in Python code
38,155,177
<p>Is there any way to group digits in a Python code to increase code legibility? I've tried <code>'</code> and <code>_</code> which are <a href="https://en.wikipedia.org/wiki/Integer_literal#Digit_separators"><em>digit separators</em></a> of some other languages, but no avail.</p> <p>A weird operator which concatenat...
12
2016-07-01T23:58:08Z
38,155,280
<p>Currently there is no thousands separator in Python, but you can use <code>locale</code> module to convert string with such separators to an int:</p> <pre><code>import locale locale.setlocale(locale.LC_ALL, '') locale.atoi("1,000,000") </code></pre>
3
2016-07-02T00:15:17Z
[ "python", "literals" ]
Get text from span tags issue
38,155,201
<p>In <a href="http://www.notebookcheck.net/Overwatch-Notebook-and-Desktop-Benchmarks.166833.0.html" rel="nofollow">this</a> link, I want to get text from span tags in <code>r_compare_bars_value</code> class. If you search for that class, you'll see the text as <code>104 (min: 88) fps</code>, I wanted to take only <cod...
1
2016-07-02T00:01:25Z
38,162,649
<p>There is no way to do it without manipulating the text returned by splitting, stripping etc.. <em>r_compare_bars_value</em> is actually also inside a span not a div so <code>soup.select("span.r_compare_bars_value")</code> is the correct selector.</p> <p>This is actually a good use case for a regex:</p> <pre><code>...
0
2016-07-02T17:15:27Z
[ "python", "html", "web-scraping", "beautifulsoup", "python-3.4" ]
Scrape a table class in Python
38,155,206
<p>I am trying to scrape <a href="http://emojipedia.org/emoji/" rel="nofollow">http://emojipedia.org/emoji/</a> , but I am not sure what is the most efficient way to do so. What I would like to scrape is found inside the table class ="emoji_list". I would like to save the stuff inside each "td" in separate columns. The...
2
2016-07-02T00:02:19Z
38,155,286
<p><code>soup.findAll('tr', limit=2)</code> won't do much considering that just gets the first two trs on the page. You need to first find all the rows of the <em>table</em> then extract what you want which is inside the two <em>tds</em> in each <em>tr</em>:</p> <pre><code>import requests from bs4 import BeautifulSoup...
2
2016-07-02T00:16:29Z
[ "python", "web-scraping", "beautifulsoup", "python-requests" ]
Condition check worksheet range python
38,155,246
<p>I have a program that parses data from multiple workbook with multiple worksheets.</p> <p>sheets 2 to 9 are days of the week(Sun-Sat). However some sheets have a different sheet range. </p> <p>Some sheets have 2 to 5(Mon-Fri). Everything else is the same only some workbook have a total of 10 sheets while other hav...
0
2016-07-02T00:08:23Z
38,155,404
<p>You can actually iterate through the worksheets as follows:</p> <pre><code>for sheet in wb: if sheet.title=='Title': #Skip the title page with continue or do something to it here continue else: #for all pages other than the title page for i in range(2, 57): From ...
0
2016-07-02T00:37:11Z
[ "python", "excel", "openpyxl" ]
.mat to python data transfer
38,155,254
<p>I am somewhat new to the python environment and I am transferring an existing MATLAB program into Python. I have imported a .mat file containing four fields in which I am interested in one with 14 subfields of 11340x1, 11340x7, and 11340x8 arrays as well as a handful of strings of meteorological data. I have success...
0
2016-07-02T00:10:49Z
38,155,329
<p>Notice that <code>datagroup['T']</code> (and <code>datagroup['P']</code>) is a list of a list of a <code>numpy</code> array. Therefore, if you want to extract the <code>numpy</code> array, you need to do:</p> <pre><code>T = datagroup['T'][0][0] P = datagroup['P'][0][0] </code></pre>
0
2016-07-02T00:23:26Z
[ "python", "matlab", "scipy" ]
.mat to python data transfer
38,155,254
<p>I am somewhat new to the python environment and I am transferring an existing MATLAB program into Python. I have imported a .mat file containing four fields in which I am interested in one with 14 subfields of 11340x1, 11340x7, and 11340x8 arrays as well as a handful of strings of meteorological data. I have success...
0
2016-07-02T00:10:49Z
38,155,354
<p>I have a slightly different and sometimes more stable solution.</p> <p>I have found that the best solution when moving data between Matlab/Python is to use a JSON export library in matlab (e.g. <a href="https://www.mathworks.com/matlabcentral/fileexchange/33381-jsonlab--a-toolbox-to-encode-decode-json-files" rel="n...
0
2016-07-02T00:28:23Z
[ "python", "matlab", "scipy" ]
.mat to python data transfer
38,155,254
<p>I am somewhat new to the python environment and I am transferring an existing MATLAB program into Python. I have imported a .mat file containing four fields in which I am interested in one with 14 subfields of 11340x1, 11340x7, and 11340x8 arrays as well as a handful of strings of meteorological data. I have success...
0
2016-07-02T00:10:49Z
38,157,015
<p>I can make an array that prints like your example with:</p> <pre><code>In [1355]: A=np.array([[None]]) In [1356]: A[0,0]=np.array([[-5,-4,-3]]) In [1357]: A Out[1357]: array([[array([[-5, -4, -3]])]], dtype=object) In [1359]: print(A) [[array([[-5, -4, -3]])]] </code></pre> <p>It's a single element, 2d object...
0
2016-07-02T05:58:30Z
[ "python", "matlab", "scipy" ]
Missing code when I decode bytes (HTML) in Python (requests, BeautifulSoup, urllib)
38,155,285
<p>I'm very newbish with Python, and I'm trying to get the source code of web pages to work with their HTML elements.</p> <p>But, when I convert bytes to <code>utf-8</code>, some of the HTML code just disappears. Here is my code:</p> <pre><code>import urllib.request req = urllib.request.Request('http://avast.softoni...
1
2016-07-02T00:16:26Z
38,155,692
<p>There are a some carriage returns i.e <code>\r</code> embedded in the html:</p> <pre><code>\r&lt;br /&gt;&lt;!--[/lead]--&gt;&lt;/p&gt;\r &gt;\r&lt;p&gt;A big plus point for Avast Free Antivirus 2016 </code></pre> <p>and many more.</p> <p>Once you remove that everything will work fine in your IDE and you can see ...
1
2016-07-02T01:37:07Z
[ "python", "beautifulsoup", "python-requests", "decode", "urllib" ]
itsdangerous.BadSignature error in token integration using TimedJSONWebSerializer - App Backend Server?
38,155,288
<p>I am authenticating the user by a <code>secret_key</code> known only to the backend and the client side and passed through the headers in Postman. My code so far is as follows:</p> <pre><code>from itsdangerous import TimedJSONWebSignatureSerializer from constants import SECRET_KEY @app.route('/authUser', methods=[...
0
2016-07-02T00:16:47Z
38,713,193
<p>Can you first make sure you set the secret key, like</p> <pre><code>app.secret_key = 'whatever the secret is' </code></pre> <p>This will initialize the secret.</p>
1
2016-08-02T06:29:19Z
[ "python", "api", "flask", "token", "restful-authentication" ]
bash cannot find .profile when run bash command from directories other than the $home directory
38,155,318
<p>In my /home/user directory, clearly there is a .profile file. Within this directory, I can run bash command, e.g. <code>$bash run.sh</code>. But in any other directories, when input <code>$bash</code>, it always complains </p> <pre><code>bash: .profile: No such file or directory </code></pre> <p>PS.: I need to run...
0
2016-07-02T00:21:42Z
38,155,373
<p>Please try this solution and let me know if it works--as I do not have access to your script and/or file structure, and this issue is the only one I can see in the available information, I will present this as a possible answer:</p> <p>This may result from splitting your input when using the <code>shell=True</code>...
1
2016-07-02T00:32:12Z
[ "python", "bash", "shell" ]
Firebase get request: TypeError: __init__() got an unexpected keyword argument 'strict'
38,155,320
<p>Trying to get Firebase set up and this code produces the error. I've also tried making the restful call simply using <code>requests</code> and I'm getting the exact same error. I'm using python 3.4. What's going on here?</p> <pre><code>from firebase import firebase firebase = firebase.FirebaseApplication('https://t...
0
2016-07-02T00:21:54Z
38,155,428
<p>My requests module was not up to date. </p> <pre><code>sudo pip install requests --upgrade </code></pre>
1
2016-07-02T00:41:23Z
[ "python", "firebase", "python-requests" ]
integer comparision failure
38,155,321
<p>Can anyone help to understand why the following integer comparison fails</p> <pre><code>import subprocess cmd = "adb -s serialid shell getprop sys.boot" proc = subprocess.Popen(cmd.split(' '), stdout=subprocess.PIPE, stderr=subprocess.PIPE) outs, errs = proc.communicate() print outs if outs ==1: print "Conditio...
0
2016-07-02T00:22:00Z
38,155,337
<p><code>outs</code> is the stuff that the process prints to standard output. As such, it will be a string, not an int. Since they are different types, the comparison will always fail.</p> <p>Perhaps your condition should be something like:</p> <pre><code>if outs.strip() == '1': ... </code></pre>
2
2016-07-02T00:24:36Z
[ "android", "python" ]
How to prevent auto field to update when Sql Server raise error?
38,155,352
<p>I have this primary key : transaction_number</p> <p>It auto increment when I insert a model with a valid token.</p> <p>Whenever I try to insert two models with the same token, I use the exception <code>IntegrityError</code> to ignore.</p> <p>The problem is, if the current index from transaction_number is 5 and I ...
0
2016-07-02T00:27:53Z
38,155,377
<p>Instead of testing if the tokens are the same when you insert them, query the database to see if anything has the same token. If nothing is returned add it:</p> <pre><code>if not Transaction.objects.get(token=new_token): # do whatever </code></pre>
1
2016-07-02T00:32:56Z
[ "python", "django", "sql-server-2008", "django-models" ]
How to use a backslash in quotes (Python)
38,155,384
<p>I'm trying to use <code>head, sep, tail = email.partition('\')</code> but having trouble escaping the backslash properly. What is the proper way to get a partition at the <code>\</code> using this line of code?</p>
0
2016-07-02T00:33:57Z
38,155,388
<p>By escaping the backslash.</p> <pre><code>'\\' </code></pre>
2
2016-07-02T00:34:23Z
[ "python" ]
How to compress hdf5 file when resizing?
38,155,420
<p>Here is my code:</p> <pre><code>n = 100000 #This is what makes it tricky - lots of files going into this hdf5 file with h5py.File('image1.h5','w') as f: dset_X = f.create_dataset('X',(1,960,224,224),maxshape=(None,960,224,224),chunks=True,compression='gzip') dset_y = f.create_dataset('y',(1,112,224*2...
6
2016-07-02T00:39:09Z
38,383,549
<p>I ended up doing this successfully using pytables.</p> <pre><code>def get_arrays(each_file): lab = color.rgb2lab(io.imread(each_file)) X = lab[:,:,:1] y = lab[:,:,1:] X_rows,X_columns,X_channels=X.shape y_rows,y_columns,y_channels=y.shape X_channels_first = np.transpose(X,(2,0,1)) X_samp...
0
2016-07-14T20:18:28Z
[ "python", "hdf5", "h5py" ]
Is there a better (i.e. more Pythonic) way to deal with packing/unpacking function arguments?
38,155,425
<p>I'm writing a method to "adds ticks" to an object. (What "adding ticks" means doesn't matter for my question. You can also ignore the 'batch' variable in my code samples.) All the ticks will have the same width and length, but are at different tick positions, and there can be a variable number of ticks with each cal...
2
2016-07-02T00:40:56Z
38,155,478
<p>I would go with option (3) and just store the ticks in a list from the start. In my opinion, the extra <code>[]</code> you would need to type is not a big problem and having a list would have some advantages from the point of view off the <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow">Zen of Pyth...
2
2016-07-02T00:51:45Z
[ "python", "python-2.7", "argument-unpacking" ]
How do I maintain the same length of a string?
38,155,447
<p>I have a text file where each line represents a record and fields separated with commas</p> <p>Bank_Account_Id, bank_description, Account_id, Account_description\n</p> <p>I tried it with:</p> <pre><code>def create_record(bank_account_id, bank_descr, account_id, account_descr): return "{0:4},{1:30},{2:4},{3:30...
1
2016-07-02T00:43:50Z
38,155,458
<p>Specifying a precision in string conversion will force a maximum length regardless of the length of the format target.</p> <pre><code>&gt;&gt;&gt; '{0:4.4}'.format('foobar') 'foob' </code></pre>
2
2016-07-02T00:46:30Z
[ "python", "string" ]
isn't this suppose to run for single time range(3,3,2) python
38,155,487
<p>I am trying to write a prime number program in python. But when user inputs 3. My program is not working. Further checking with print statements i found its not going in for loop.</p>
-2
2016-07-02T00:53:00Z
38,155,511
<p>I'm going to assume in your program you have <code>range(3,i,2)</code>, where <code>i</code> is the input. When your user inputs 3, there will be no range since you're going from 3 to 3. </p> <p>A good way to fix this is at the beginning of the function. Before you get your range, return <code>[2,3]</code> if the i...
0
2016-07-02T00:58:21Z
[ "python", "python-3.x" ]
Python crontab try except ValueError
38,155,532
<p>I've got this script than when I run from command line it works fine...</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import time from time import sleep import os import logging import glob import sys import subprocess import pymssql import shutil import StringIO from StringIO import StringIO #Check sh...
0
2016-07-02T01:03:36Z
38,156,431
<p>Your issue is that you are unpacking an Exception. Exceptions should not be assumed to be iterables, nor should you assume they contain arguments.</p> <pre><code>In [2]: try: ...: assert False ...: except Exception as e: ...: c, m = e ...: ---------------------------------------------------...
0
2016-07-02T04:18:19Z
[ "python", "linux", "try-catch", "pymssql" ]
Python crontab try except ValueError
38,155,532
<p>I've got this script than when I run from command line it works fine...</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import time from time import sleep import os import logging import glob import sys import subprocess import pymssql import shutil import StringIO from StringIO import StringIO #Check sh...
0
2016-07-02T01:03:36Z
38,165,358
<p>Updated and working code:</p> <pre><code>#!/usr/bin/python # -*- coding: utf-8 -*- import time from time import sleep import os import logging import glob import sys import subprocess import pymssql import shutil import StringIO from StringIO import StringIO import mechanize from BeautifulSoup import BeautifulSoup...
0
2016-07-02T23:33:49Z
[ "python", "linux", "try-catch", "pymssql" ]
First of two blocks of code of reading from a file not executing in python
38,155,790
<p>As part of an assignment I'm writing an assembler in python that takes simplified assembly language and outputs binary machine language. Part of my code is below, where I'm reading from the assembly code in two passes. The first pass (the first line of with open(filename, "r") as asm_file) in the first block of read...
0
2016-07-02T01:55:39Z
38,155,853
<p>In the first <code>with</code>, starting with</p> <pre><code>#search for beginning of pseudocommand </code></pre> <p>are you quite sure you don't want that and the following lines dedented a level?</p> <p>As is, the only way to get to your <code>print</code> is if a line satisfies both</p> <pre><code>if '//' in ...
0
2016-07-02T02:08:31Z
[ "python", "file", "assembly", "io" ]
First of two blocks of code of reading from a file not executing in python
38,155,790
<p>As part of an assignment I'm writing an assembler in python that takes simplified assembly language and outputs binary machine language. Part of my code is below, where I'm reading from the assembly code in two passes. The first pass (the first line of with open(filename, "r") as asm_file) in the first block of read...
0
2016-07-02T01:55:39Z
38,155,858
<p>Your problem seems to be that your code checks if a line starts with a <code>(</code>, but in the assembly it has a tab before an instruction so that it doesn't work. You should probably do a <code>line.strip()</code> after your first if statement like so</p> <pre><code>with open(filename, "r") as asm_file: num...
1
2016-07-02T02:09:58Z
[ "python", "file", "assembly", "io" ]
Building Python C extension
38,155,988
<p>I need to create a new python module as a c extension for both performance and CUDA utilization. I have tried a couple of tutorials for this and was unsuccessful. Here are my files:</p> <p><strong>hellomodule.c</strong></p> <pre><code>#include &lt;Python.h&gt; static PyObject* say_hello(PyObject* self, PyObject* ...
1
2016-07-02T02:39:04Z
38,163,356
<p>The problem with your approach is that you relied on tutorials/guides for Python 2.7.x (maybe <a href="https://docs.python.org/2.7/extending/extending.html" rel="nofollow">this</a>?) while you are using a Python 3.5.x interpreter.</p> <p>The way to construct a C extension has <a href="https://docs.python.org/3.5/ex...
1
2016-07-02T18:38:50Z
[ "python", "c", "windows", "build", "compiler-errors" ]
Properly shifting irregular time series in Pandas
38,156,023
<p>What's the proper way to shift this time series, and re-align the data to the same index? E.g. How would I generate the data frame with the same index values as "data," but where the value at each point was the last value seen as of 0.4 seconds after the index timestamp?</p> <p>I'd expect this to be a rather common...
1
2016-07-02T02:45:18Z
38,160,821
<p>Just like on <a href="http://stackoverflow.com/q/38131287/478288">this question</a>, you are asking for an asof-join. Fortunately, the next release of pandas (soon-ish) will have it! Until then, you can use a pandas Series to determine the value you want.</p> <p>Original DataFrame:</p> <pre><code>In [44]: data Out...
1
2016-07-02T13:41:27Z
[ "python", "pandas" ]
Properly shifting irregular time series in Pandas
38,156,023
<p>What's the proper way to shift this time series, and re-align the data to the same index? E.g. How would I generate the data frame with the same index values as "data," but where the value at each point was the last value seen as of 0.4 seconds after the index timestamp?</p> <p>I'd expect this to be a rather common...
1
2016-07-02T02:45:18Z
38,161,056
<p>Using chrisaycock answer.. Your data is below <code>0.4s</code> intervals. So, your results are correct. <code>1s</code> shows it works. </p> <pre><code>pd.Series(x, data.index).asof(data.index + pd.Timedelta('1s')) # 2016-07-02 01:10:52.418745856 0 # 2016-07-02 01:10:53.687532544 2 # 2016-07-02 ...
0
2016-07-02T14:09:01Z
[ "python", "pandas" ]
url() got an unexpected keyword argument 'namespace'
38,156,069
<p>New to Django here, so pardon the rookie question...</p> <p>I'm getting the <code>url() got an unexpected keyword argument 'namespace'</code> error when I try to call on the <code>reverse</code> function. Tried a few different ways to fix it but nothing seems to be working. Any advice would be greatly appreciated. ...
0
2016-07-02T02:57:21Z
38,156,125
<p><code>include()</code> expects the keyword argument <code>namespace</code> not <code>url()</code> so your last line in <code>mysite/urls.py</code> should be</p> <pre><code>url(r'^comments/', include('comments.urls', namespace='comments')), </code></pre>
1
2016-07-02T03:09:02Z
[ "python", "django" ]
url() got an unexpected keyword argument 'namespace'
38,156,069
<p>New to Django here, so pardon the rookie question...</p> <p>I'm getting the <code>url() got an unexpected keyword argument 'namespace'</code> error when I try to call on the <code>reverse</code> function. Tried a few different ways to fix it but nothing seems to be working. Any advice would be greatly appreciated. ...
0
2016-07-02T02:57:21Z
38,156,175
<p>You can refer the syntax and options for the url <code>include()</code> method in official django documentation <a href="https://docs.djangoproject.com/en/1.9/ref/urls/#include" rel="nofollow">here</a>. You need to use the namespace inside the <code>include()</code> method and not in the outside <code>url()</code> m...
1
2016-07-02T03:21:58Z
[ "python", "django" ]
How do I get Pycharm to find a file that I want to use in my code?
38,156,102
<p>How do I get Pycharm to find the .txt file that I want to open? </p> <p>I'm trying to open a file with a simple piece of code </p> <pre><code>file_name = "coding_dna.txt" my_file = open(file_name) my_file_contents = my_file.read() </code></pre> <p>print(my_file_contents)</p> <p>But I keep getting the error below...
0
2016-07-02T03:03:41Z
38,156,138
<p>By importing the <code>os</code> module, we can find where any file is located as long as we have the correct path. </p> <p><strong>Try this code below.</strong></p> <pre><code>import os path = "C:/Users/NicolasSaenz/(The directory where "coding_dna.txt" is in)" file_name = os.path.join(path, "coding_dna.txt") m...
0
2016-07-02T03:11:20Z
[ "python", "osx", "ide", "pycharm" ]
How do I get Pycharm to find a file that I want to use in my code?
38,156,102
<p>How do I get Pycharm to find the .txt file that I want to open? </p> <p>I'm trying to open a file with a simple piece of code </p> <pre><code>file_name = "coding_dna.txt" my_file = open(file_name) my_file_contents = my_file.read() </code></pre> <p>print(my_file_contents)</p> <p>But I keep getting the error below...
0
2016-07-02T03:03:41Z
38,171,540
<p>It's possible to set working directory for your program in run configuration. </p> <p>Just go to <code>Run - Edit Configurations - Your script configuration</code> and update 'Working directory' field. See screenshot below.</p> <p><a href="http://i.stack.imgur.com/qUTzG.png" rel="nofollow"><img src="http://i.stack...
0
2016-07-03T15:38:14Z
[ "python", "osx", "ide", "pycharm" ]
Mix three vectors in a numpy array, then sort it
38,156,241
<p>I have 3 numpy.ndarray vectors, X, Y and intensity. I would like to mix it in an numpy array, then sort by the third column (or the first one). I tried the following code:</p> <pre><code>m=np.column_stack((X,Y)) m=np.column_stack((m,intensity)) m=np.sort(m,axis=2) </code></pre> <p>Then I got the error: ValueError:...
0
2016-07-02T03:37:58Z
38,156,488
<p><code>Axis=2</code> does not refer to the column index but rather, to the dimension of the array. It means numpy will try to look for a third dimension in the data and sorts it from smallest to largest in the third dimension. Sorting from smallest to largest in the first dimension (<code>axis = 0</code>) would be ha...
0
2016-07-02T04:28:16Z
[ "python", "sorting", "numpy" ]