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: How to get the closest key from the given key?
37,851,131
<p>Given a dictionary:</p> <pre><code>sample = { '123': 'Foo', '456': 'Bar', '789': 'Hello', '-111': 'World' } </code></pre> <p>What is the most <strong>efficient</strong> way (approach and/or data structure) to get the closest (or less) key from a dictionary? </p> <p>Note:<br> 1. Even if key is ...
3
2016-06-16T06:06:56Z
37,851,350
<pre><code>def get_nearest_less_element(d, k): k = int(k) return d[str(max(key for key in map(int, d.keys()) if key &lt;= k))] </code></pre> <p>Edit to update with @Paul Hankin's code, but using <code>&lt;=</code> I'm not sure it needs a branch at all. Convert all the keys to numbers, find the ones less than o...
5
2016-06-16T06:22:40Z
[ "python", "python-2.7" ]
Python: How to get the closest key from the given key?
37,851,131
<p>Given a dictionary:</p> <pre><code>sample = { '123': 'Foo', '456': 'Bar', '789': 'Hello', '-111': 'World' } </code></pre> <p>What is the most <strong>efficient</strong> way (approach and/or data structure) to get the closest (or less) key from a dictionary? </p> <p>Note:<br> 1. Even if key is ...
3
2016-06-16T06:06:56Z
37,851,454
<p>The below module returns the value if the key is present else it finds the maximum key in a list of keys that are less than the input key.</p> <pre><code>def get_nearest_less_element(sample,key): if key in sample: return sample[key] else: return sample[str(max(x for x in sample.keys() if int(x) &lt; int...
3
2016-06-16T06:29:20Z
[ "python", "python-2.7" ]
Python: How to get the closest key from the given key?
37,851,131
<p>Given a dictionary:</p> <pre><code>sample = { '123': 'Foo', '456': 'Bar', '789': 'Hello', '-111': 'World' } </code></pre> <p>What is the most <strong>efficient</strong> way (approach and/or data structure) to get the closest (or less) key from a dictionary? </p> <p>Note:<br> 1. Even if key is ...
3
2016-06-16T06:06:56Z
37,851,469
<p>Here is a solution. Finds the closest key based on numerical comparison:</p> <pre><code>sample = {'123': 'Foo', '456': 'Bar', '789': 'Hello'} def get_nearest_less_element(inpDict, targetNum): diff = 2**32 - 1 # Very big number. currentKey = None for i in sample.keys(): newDiff = abs(int(i) - ta...
1
2016-06-16T06:30:14Z
[ "python", "python-2.7" ]
Python: How to get the closest key from the given key?
37,851,131
<p>Given a dictionary:</p> <pre><code>sample = { '123': 'Foo', '456': 'Bar', '789': 'Hello', '-111': 'World' } </code></pre> <p>What is the most <strong>efficient</strong> way (approach and/or data structure) to get the closest (or less) key from a dictionary? </p> <p>Note:<br> 1. Even if key is ...
3
2016-06-16T06:06:56Z
37,851,841
<p>I did it this way:</p> <pre><code>def get_nearest_less_element(sample, key): try: if key not in sample: candidates = [] for keys in sample: if int(keys) &lt; int(key): candidates.append(keys) return sample[max(candidates)] r...
1
2016-06-16T06:53:04Z
[ "python", "python-2.7" ]
Python: How to get the closest key from the given key?
37,851,131
<p>Given a dictionary:</p> <pre><code>sample = { '123': 'Foo', '456': 'Bar', '789': 'Hello', '-111': 'World' } </code></pre> <p>What is the most <strong>efficient</strong> way (approach and/or data structure) to get the closest (or less) key from a dictionary? </p> <p>Note:<br> 1. Even if key is ...
3
2016-06-16T06:06:56Z
37,852,176
<p>If you are creating or updating the sample only once or infrequently, but looking up values repeatedly, it would be most efficient to precompute a sorted numeric list in O(n log n) time. Then the entire dictionary doesn't need to be scanned; binary search gives O(log n) access. There is a python library module funct...
2
2016-06-16T07:09:26Z
[ "python", "python-2.7" ]
Python: How to get the closest key from the given key?
37,851,131
<p>Given a dictionary:</p> <pre><code>sample = { '123': 'Foo', '456': 'Bar', '789': 'Hello', '-111': 'World' } </code></pre> <p>What is the most <strong>efficient</strong> way (approach and/or data structure) to get the closest (or less) key from a dictionary? </p> <p>Note:<br> 1. Even if key is ...
3
2016-06-16T06:06:56Z
37,864,813
<p>Given your data set, the most efficient data structure in terms of both set-up and look-up time complexity is a <a href="https://en.wikipedia.org/wiki/Binary_search_tree" rel="nofollow">binary search tree</a>, which gives you O(n log n) set-up and O(log n) look-up time complexity with O(n) space complexity.</p> <p>...
2
2016-06-16T16:35:52Z
[ "python", "python-2.7" ]
Opening a html file from python
37,851,142
<p>In python 3 code example </p> <pre><code>while cond: .... some code... open html page </code></pre> <p>I want to open local html file(pass parameters to the file) within while condition. So as long as the condition is true the file should keep opening.</p> <p>These are the following things ...
0
2016-06-16T06:07:47Z
37,852,069
<p>Using the render_template() function, you pass your parameters as a dictionary file mapping from your python variables to the html variables, something like this:</p> <pre><code>name = 'Tony Stark' workplace = 'Stark Industries' return render_template('file.html', {name:'name', workplace:'workplace'}) </code></pre>...
0
2016-06-16T07:04:32Z
[ "python", "html" ]
Select HTML tags that have one or more specific attributes with bs4
37,851,225
<p>I want to use use <code>soup.find_all</code> to find all HTML tags that have <code>id</code> or <code>name</code> attributes.</p> <p>The following code works for the id attribute:</p> <pre><code>for tag in soup.find_all(attrs={"id": True}): </code></pre> <p>However, the following code with two attributes doesn't:...
0
2016-06-16T06:14:08Z
37,851,646
<pre><code>soup.find_all(lambda element: 'name' in element.attrs or 'id' in element.attrs) </code></pre> <p>We use <code>lambda</code> to access the element inside <code>find_all</code>. And then, we use the <code>in</code> operator to check if <code>element.attrs</code> (it's a dictionary) has key <code>name</code> <...
1
2016-06-16T06:41:48Z
[ "python", "html", "beautifulsoup", "attr" ]
Unexpected input reverse leading to AssertionError #python
37,851,403
<h2>I'm trying to pass a parameter to a function buggy_reverse.</h2> <pre><code>def buggy_reverse(input): m = input m.reverse() return m def test_buggy_reverse(): assert [3,2,1] == buggy_reverse([1,2,3]) assert [] == buggy_reverse([]) input = ["a", "b", "c"] assert ["c", "b", "a"] == bugg...
1
2016-06-16T06:26:13Z
37,851,636
<p>Try this instead (but see below for guessed better and more versatile version):</p> <pre><code>#! /usr/bin/env python def ex_buggy_reverse(in_list): m = in_list[:] m.reverse() return m def test_ex_buggy_reverse(): assert [3, 2, 1] == ex_buggy_reverse([1, 2, 3]) assert [] == ex_buggy_reverse([]...
0
2016-06-16T06:40:49Z
[ "python", "list", "reverse" ]
Using itertools groupby to create a list of lists
37,851,616
<p>I'm getting a list of items in the format <code>parent.id_child.id</code>, like <code>1_2</code>. I tried to group the child's id by parent id, for example: from the input <code>['1_2', '2_2', '1_1', '2_1', '1_3']</code> I need the output <code>[['1','2','3'], ['1','2']]</code>. I have tried this:</p> <pre><code>in...
3
2016-06-16T06:39:47Z
37,851,777
<p>Use a list comprehension, yes; the values themselves are passed into each group iterator unchanged so you need to select again:</p> <pre><code>final = [[g[1] for g in group] for key, group in itertools.groupby(outputlist, lambda x: x[0])] </code></pre> <p>You can do the whole thing in a single expression by nestin...
2
2016-06-16T06:49:36Z
[ "python", "list", "itertools" ]
How to return the value properly in recursion with python?
37,851,743
<p>I wish to implement a function which can recurs the input array <code>a</code> and calculate the value of <code>a_i - a_j</code> where <code>i</code> is in <code>(len(a))</code>, <code>j = i -1</code> and return a list as output finally. So given an array <code>[1, 2, 3, 4, 5, 6]</code>, the result would be <code>[1...
0
2016-06-16T06:46:49Z
37,851,839
<p>add a <code>return</code> to the recursive call to <code>recur_diff</code> in <code>recur_diff(array[:-1], result_array)</code>. Otherwise the results will never be returned back to upper levels </p> <pre><code>if l &gt; 1: # ... return recur_diff(array[:-1], result_array) else: return result_array </co...
1
2016-06-16T06:52:55Z
[ "python", "algorithm" ]
low_memory parameter in read_csv function
37,851,796
<p>What does the <code>low_memory</code> parameter do in the <code>read_csv</code> function from the pandas library?</p>
1
2016-06-16T06:50:41Z
37,851,865
<p>This come from the docs themselves. Have you read them?</p> <blockquote> <p>low_memory : boolean, default True Internally process the file in chunks, resulting in lower memory use while parsing, but possibly mixed type inference. To ensure no mixed types either set False, or specify the type wi...
1
2016-06-16T06:54:05Z
[ "python", "pandas", "ipython", "spyder" ]
python3.5/pandas - rolling mean by week and hour
37,851,798
<p>Trying to figure out how to use the rolling mean that takes into consideration the day and hour before computing the statistic.</p> <p>File looks something like this:</p> <pre><code> date hour price 1/1/2016 1 a 1/1/2016 2 b . . . . . . 1/8/2016 ...
0
2016-06-16T06:50:49Z
37,861,376
<p>It's not 100% clear what you want but here are the assumption I made...</p> <p>You want the mean by hour of all days before a certain date. This code does that...</p> <pre><code>import pandas as pd import numpy as np import datetime # build a sample table np.random.seed(1) values = np.random.choice(range(1, 11), ...
1
2016-06-16T13:57:41Z
[ "python", "pandas" ]
Converting year format in a column and joining 3 other columns to the result in pandas
37,851,818
<p>My data is in the form below however, I managed to put it in a dataframe but now I need to convert the 77 1977 and then create one column with YYYY-MM-DD hh:mm and use it as the index.</p> <p>An example of my data:</p> <p><img src="http://i.stack.imgur.com/Go4k6.png" alt="an example of my data"></p>
1
2016-06-16T06:51:57Z
37,851,978
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> and last if necessary <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.drop.html" rel="nofollow"><code>drop</code></a> these columns:</p> <pr...
0
2016-06-16T06:59:40Z
[ "python", "datetime", "pandas", "dataframe" ]
How to read values from text file and pass it as a URL parameter
37,851,917
<p>I am trying to read values from a text file (stored in a column) and pass them in a URL parameter. The author ID is unique and I want to iterate on the ID values from the text file. </p> <p>The data type for content is a list and looks like this: </p> <pre><code>['7202106849\n', '7201570041\n', ....] </code></pre>...
0
2016-06-16T06:56:27Z
37,852,225
<p>Something like the following should get you going:</p> <pre><code>import requests import json with open('collab_id_2008.txt') as f_input: for id in f_input: url = "https://api.elsevier.com/content/author/author_id/{}?view=metrics".format(id.strip()) resp = requests.get(url, headers={'Accept':'...
2
2016-06-16T07:11:36Z
[ "python", "python-2.7", "url" ]
Transfer file(scp) and run command from jumpserver to finalserver using python script on localhost
37,851,964
<p>A file needs to be uploaded to final-server and a command needs to be run using that file as input. </p> <p>Following will be the steps for whole action to be performed (but I am stuck at step 3):</p> <p>1 - transfer file from localhost to jumpserver (using scp)</p> <p>2 - ssh to jumpserver</p> <p>3 - transfer f...
-1
2016-06-16T06:58:28Z
37,852,082
<p>I suggest to transfer files between server and execute commands with paramiko, just look at example</p> <pre><code>import paramiko local_path = "foo/bar" remote_path = "bar/foo" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect("remote_url", username='username') sftp ...
0
2016-06-16T07:04:56Z
[ "python", "ssh", "scp", "pexpect" ]
Transfer file(scp) and run command from jumpserver to finalserver using python script on localhost
37,851,964
<p>A file needs to be uploaded to final-server and a command needs to be run using that file as input. </p> <p>Following will be the steps for whole action to be performed (but I am stuck at step 3):</p> <p>1 - transfer file from localhost to jumpserver (using scp)</p> <p>2 - ssh to jumpserver</p> <p>3 - transfer f...
-1
2016-06-16T06:58:28Z
37,852,469
<pre><code>&gt; ba_child = pexpect.spawn(ba_cmd) </code></pre> <p>You are spawning a new local child. You should instead be sending the <code>scp</code> command to the <code>ssh_child</code> which is running a shell on the jumpserver.</p> <p>Shaky on the syntax here, but something like</p> <pre><code>ssh_child.s...
1
2016-06-16T07:23:16Z
[ "python", "ssh", "scp", "pexpect" ]
Gathering statistics on how a program is used
37,852,065
<p>I have a few programs that do similar things, but they're written in different languages. I want to somehow monitor the way the programs I write are used - how many times is the code ran? How many times is a particular method/function used? How long did it take to compile? </p> <p>My goal with this is to get a gra...
0
2016-06-16T07:04:24Z
37,852,399
<p>I'll recommend looking at <a href="https://docs.getsentry.com/on-premise/" rel="nofollow">sentry</a>. It's free and has clients for many languages.</p> <p>Basic usage: </p> <pre><code>import time from raven import Client client = Client('https://&lt;key&gt;:&lt;secret&gt;@app.getsentry.com/&lt;project&gt;') sta...
0
2016-06-16T07:19:16Z
[ "python", "usage-statistics" ]
Gathering statistics on how a program is used
37,852,065
<p>I have a few programs that do similar things, but they're written in different languages. I want to somehow monitor the way the programs I write are used - how many times is the code ran? How many times is a particular method/function used? How long did it take to compile? </p> <p>My goal with this is to get a gra...
0
2016-06-16T07:04:24Z
37,852,557
<p>If you'd like to write one thing that will work no matter the language, instead of adding something for each language then option 1, for me, would be to write a wrapper for all of the programs, and replace the originals. You don't mention your operating system, but on Linux I would do the following:</p> <pre><code>...
0
2016-06-16T07:27:06Z
[ "python", "usage-statistics" ]
Want to skip last and first 5 lines while reading file in python
37,852,308
<p>If I want to see only data between line number 5 to what comes before last 5 rows in a file. While I was reading that particular file.</p> <p>Code I have used as of now :</p> <pre><code>f = open("/home/auto/user/ip_file.txt") lines = f.readlines()[5:] # this will start from line 5 but how to set end for line in li...
0
2016-06-16T07:15:24Z
37,852,454
<p>You could use a neat feature of slicing, you can count from the end with negative slice index, (<a href="http://stackoverflow.com/questions/509211/explain-pythons-slice-notation">see also this question</a>):</p> <pre><code>lines = f.readlines()[5:-5] </code></pre> <p>just make sure there are more than 10 lines:</p...
1
2016-06-16T07:22:37Z
[ "python", "file", "file-read" ]
How to add label on top of columns in a python stacked bar?
37,852,316
<p>I have created a stacked bar from pandas dataframe (df):</p> <pre><code>plt.style.use('ggplot') ax= df.plot.bar(stacked=True, title=title,figsize=(11, 7)); ax.set_ylabel("Score") ax.set_xlabel("Item") ax.set_ylim([0,1.4]) ax.set_xticklabels(labels=df.index,rotation=0,minor=False) labels = ["label%d" % i for i in ra...
0
2016-06-16T07:15:43Z
37,855,864
<p>You can use the <code>sum()</code> function to sum values of all columns on a per-x-basis in a pandas dataframe:</p> <pre><code>df = pd.DataFrame({ 'keyword': [.2, .08, .02, 0, .15], 'research': [.2, .12, .09, .17, 0] }) dy = sum(df[c] for c in df.keys()) </code></pre> <p>The resulting values in <code>dy...
0
2016-06-16T09:57:25Z
[ "python", "matplotlib", "label", "stacked-chart" ]
Python dictionary of sets in SQL
37,852,393
<p>I have a dictionary in Python where the keys are integers and the values sets of integers. Considering the potential size (millions of key-value pairs, where a set can contain from 1 to several hundreds of integers), I would like to store it in a SQL (?) database, rather than serialize it with pickle to store it and...
3
2016-06-16T07:18:58Z
37,857,068
<p>You second answer is <em>nearly</em> what I would recommend. What I would do is have three columns:</p> <ul> <li>Set ID</li> <li>Key</li> <li>Value</li> </ul> <p>I would then create a composite primary key on the Set ID and Key which guarantees that the combination is unique:</p> <pre><code>CREATE TABLE something...
1
2016-06-16T10:51:37Z
[ "python", "sql", "database", "dictionary", "sqlite3" ]
Pandas dataframe to dictionary
37,852,436
<p>I have a pandas dataframe like :</p> <pre><code>COL1 VALUE1 VALUE2 A A12 1 B B13 2 A C12 3 B Q12 4 </code></pre> <p>Need a dictionary from the above dataframe where COL1 will be stored as the key and value1 and value2 will be in sub-dict.</p> <p>eg:-</p> <pre><code>di...
2
2016-06-16T07:21:28Z
37,852,585
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.apply.html" rel="nofollow"><code>apply</code></a> converted to <code>dict</...
2
2016-06-16T07:28:44Z
[ "python", "dictionary", "pandas", "group-by" ]
Filled errorbars in matplotlib (rectangles)
37,852,462
<p>Is it possibile to make a plot like this in matplotlib? I care only about the red filled rectangles, the crosses are easily done with <code>errorbar</code>.</p> <p><a href="http://i.stack.imgur.com/wkZq0.png" rel="nofollow"><img src="http://i.stack.imgur.com/wkZq0.png" alt="example"></a></p>
1
2016-06-16T07:23:04Z
37,852,631
<p>Drawing squares is really easy with <code>matplotlib.patches</code>, e.g.:</p> <pre><code>import matplotlib.pyplot as pl import matplotlib.patches pl.figure() ax = pl.gca() ax.add_patch( matplotlib.patches.Rectangle( (1.0, 1.0), # x, y 2.0, # width 2.0, # height color='...
2
2016-06-16T07:31:32Z
[ "python", "matplotlib" ]
Filled errorbars in matplotlib (rectangles)
37,852,462
<p>Is it possibile to make a plot like this in matplotlib? I care only about the red filled rectangles, the crosses are easily done with <code>errorbar</code>.</p> <p><a href="http://i.stack.imgur.com/wkZq0.png" rel="nofollow"><img src="http://i.stack.imgur.com/wkZq0.png" alt="example"></a></p>
1
2016-06-16T07:23:04Z
37,856,171
<p>Unfortunately <code>errorbar</code> can't do this, but you can create a <code>PatchCollection</code> from your error data which can easily be added to the axes. See this quick script for an example of how you could do this.</p> <pre><code>import numpy as np import matplotlib.pyplot as plt from matplotlib.collection...
3
2016-06-16T10:10:57Z
[ "python", "matplotlib" ]
Is __del__ really a destructor?
37,852,560
<p>I do things much in C++, where Dtor is really meant for destruction of an acquired resource, when I start off with python (which is really a fun and fantastic), I came to learn it has GC like java, So there is no heavy emphasize on object ownership(construction and destruction) in python as far as i learned,the <c...
5
2016-06-16T07:27:11Z
37,852,707
<blockquote> <p>Is <strong>del</strong> really a destructor?</p> </blockquote> <p>No, <code>__del__</code> method is not a destructor, is just a normal method you can call whenever you want to perform any operation, but it is always called before the garbage collector destroys the object. Think of it like a clean or...
0
2016-06-16T07:35:36Z
[ "python" ]
Is __del__ really a destructor?
37,852,560
<p>I do things much in C++, where Dtor is really meant for destruction of an acquired resource, when I start off with python (which is really a fun and fantastic), I came to learn it has GC like java, So there is no heavy emphasize on object ownership(construction and destruction) in python as far as i learned,the <c...
5
2016-06-16T07:27:11Z
37,852,762
<p>From the <a href="https://docs.python.org/3/reference/datamodel.html#basic-customization" rel="nofollow">Python 3 docs</a>:</p> <blockquote> <p><code>object.__del__(self)</code></p> <p>Called when the instance is about to be destroyed. This is also called a destructor. If a base class has a <code>__del__()</...
5
2016-06-16T07:38:58Z
[ "python" ]
Is __del__ really a destructor?
37,852,560
<p>I do things much in C++, where Dtor is really meant for destruction of an acquired resource, when I start off with python (which is really a fun and fantastic), I came to learn it has GC like java, So there is no heavy emphasize on object ownership(construction and destruction) in python as far as i learned,the <c...
5
2016-06-16T07:27:11Z
37,854,539
<p>As the other answers have already pointed out, you probably shouldn't implement <code>__del__</code> in Python. If you find yourself in the situation thinking you'd really need a destructor (for example if your class wraps a resource that needs to be explicitly closed) then the Pythonic way to go is using <a href="h...
3
2016-06-16T09:01:53Z
[ "python" ]
Matplotlib remove space of candlestick for missing data
37,852,708
<p>I create a program that generate the candlestick chart and I have a problem with it. my data type is stock so it only have a data in weekdays.</p> <p>So after I plotted it, it has spaces between the candlesticks.</p> <p><a href="http://i.stack.imgur.com/xoXJX.png" rel="nofollow"><img src="http://i.stack.imgur.com/...
2
2016-06-16T07:35:47Z
37,861,564
<p>Check out this link: <a href="http://stackoverflow.com/questions/10529492/how-do-i-plot-only-weekdays-using-pythons-matplotlib-candlestick">How do I plot only weekdays using Python&#39;s matplotlib candlestick?</a></p> <p>This should answer your question. I use it as well in my code.</p>
0
2016-06-16T14:04:58Z
[ "python", "matplotlib", "candlestick-chart" ]
Merging XMLs into parent XML file using Python
37,852,738
<p>I have found a couple of examples of merging XMLs using Python on SO, however I am looking to merge two test case XMLs into a parent XML.</p> <p>Here's my Parent XML (main.xml)</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE propertiesconfiguration_my_campaign&gt; &lt;exconfig&gt; &lt;ma...
2
2016-06-16T07:37:17Z
37,853,734
<pre><code>from xml.etree import ElementTree as et c1, c2 = et.parse("c1.xml"), et.parse("c2.xml") par_xml = et.parse("par.xml") test = par_xml.find(".//testspecif") test.extend([c1.find(".//testcase"), c2.find(".//testcase")]) print(et.tostring(par_xml.getroot())) # par.write("par.xml",encoding="utf-8", xml_decl...
2
2016-06-16T08:24:06Z
[ "python", "xml", "python-3.x" ]
Python: Converting a day number to a day name using calendar
37,852,884
<p>Using the following command I was able to get the numerical day of the week for a given date:</p> <pre><code>from calendar import weekday print(weekday(2015, 5, 8)) </code></pre> <p>This block then produces the number <code>4</code>. How can I convert this into <code>Friday</code>, preferably just using the calen...
0
2016-06-16T07:44:57Z
37,852,956
<p>You can use <a href="https://docs.python.org/2/library/calendar.html#calendar.day_name"><code>calendar.day_name</code></a> which is a list of week days in current locale:</p> <pre><code>&gt;&gt;&gt; import calendar &gt;&gt;&gt; calendar.day_name[4] 'Friday' </code></pre>
6
2016-06-16T07:48:40Z
[ "python", "date", "calendar" ]
Python: Converting a day number to a day name using calendar
37,852,884
<p>Using the following command I was able to get the numerical day of the week for a given date:</p> <pre><code>from calendar import weekday print(weekday(2015, 5, 8)) </code></pre> <p>This block then produces the number <code>4</code>. How can I convert this into <code>Friday</code>, preferably just using the calen...
0
2016-06-16T07:44:57Z
37,853,016
<p>Never mind, I've found an answer but I'll leave the question up if anyone else is curious. The calendar library has an array called <code>day_name</code> with the days of the week in it:</p> <blockquote> <p><code>An array that represents the days of the week in the current locale.</code></p> </blockquote> <p>I w...
1
2016-06-16T07:51:11Z
[ "python", "date", "calendar" ]
Compute a “mirror”, where the first half of the image is copied, flipped (l-r) and then copied into the second half using tensorflow
37,852,994
<p>I want to solve this problem using tensorflow but I searched the web and found git issue#206 states that indexing and slicing is still not supported on a tensor variable initialized from a numpy array.</p> <p>Otherwise I would have done...</p> <pre><code>image = mpimg.imread(filename) height, width, depth = image....
0
2016-06-16T07:50:30Z
37,853,713
<p>You have to use <code>tf.slice</code> and <code>tf.reverse</code>, and then concatenate the results.</p> <pre class="lang-py prettyprint-override"><code>image = tf.placeholder(tf.float32, [height, width, depth]) half_left = tf.slice(image, [0, 0, 0], [height, width/2, depth]) half_right = tf.reverse(half_left, [Fa...
0
2016-06-16T08:23:06Z
[ "python", "numpy", "indexing", "tensorflow" ]
In python multiprocessing,queue.put will block subprocess
37,853,005
<p>If put in q only 10 data, output looks below.</p> <pre><code>if cnt&gt;10: # kk's size is about 2000. Begin CountChangePercentMT1 at 2016-06-16 15:19:30.706000: end-in 0 2016-06-16 15:19:33.291000 end-in 1 2016-06-16 15:19:34.990000 end-in 2 2016-06-16 15:19:36.921000 end 0 end 1 end 2 end-in 3 2016-06-16 15:19...
0
2016-06-16T07:50:49Z
37,853,169
<pre><code>def do_somthing(q_out,q,i,trueStartDate,trueEndDate,preStartDate,allExistTables,stock_gainian): #Init conn conn = MySQLdb.connect(host='localhost',db='tushare',user='root',passwd='',port=3306,charset='UTF8') #Init df_Cc df_Cc = pd.DataFrame() df_Cc['ticker'] = pd.Series(dtype=numpy.int64,index=df_Cc.index) d...
0
2016-06-16T07:57:41Z
[ "python" ]
python unittest fails running all testMethods, while each testMethod runs well
37,853,023
<p>I'm using PYCharm and unittest in python to test my Classes. </p> <p>Running each testMethod one by one and all tests are passing well.<br> Running all tests together it fails with assertionErrors. The setup and teardown methods are set.</p> <p>Here is the code of my testClass:</p> <pre><code># -*- coding: utf-8...
0
2016-06-16T07:51:31Z
37,854,718
<p>You are using <code>setUpClass()</code> and <code>tearDownClass()</code>, which are called just once for the entire class. This is causing your different test methods to interfere with each other by changing the <code>_interpolation</code> attribute.</p> <p>You could use <code>setUp()</code> and <code>tearDown()</c...
0
2016-06-16T09:09:47Z
[ "python", "unit-testing" ]
global name 'localset' is not defined
37,853,361
<p>I get this error. </p> <blockquote> <p>global name 'localset' is not defined</p> </blockquote> <p>Following is my code.</p> <pre><code>from django.shortcuts import render, render_to_response, RequestContext from forms import SignUpForm # Create your views here. def home(request): form= SignUpForm(request...
0
2016-06-16T08:07:25Z
37,853,881
<p>In the last line of code:</p> <pre><code>return render_to_response("signup.html", localset, context_instance= RequestContext(request)) </code></pre> <p>The variable <strong>localset</strong> is not defined.</p>
0
2016-06-16T08:31:23Z
[ "python", "django-models", "django-forms", "django-views" ]
global name 'localset' is not defined
37,853,361
<p>I get this error. </p> <blockquote> <p>global name 'localset' is not defined</p> </blockquote> <p>Following is my code.</p> <pre><code>from django.shortcuts import render, render_to_response, RequestContext from forms import SignUpForm # Create your views here. def home(request): form= SignUpForm(request...
0
2016-06-16T08:07:25Z
37,861,081
<p>@Amin A answer is correct for your original question. You do have a variable set within the <code>render_to_response</code> function which is not defined within your view function.</p> <p>You should change the <code>render_to_response</code> line to look like this:</p> <pre><code>return render_to_response( 'si...
0
2016-06-16T13:43:27Z
[ "python", "django-models", "django-forms", "django-views" ]
global name 'localset' is not defined
37,853,361
<p>I get this error. </p> <blockquote> <p>global name 'localset' is not defined</p> </blockquote> <p>Following is my code.</p> <pre><code>from django.shortcuts import render, render_to_response, RequestContext from forms import SignUpForm # Create your views here. def home(request): form= SignUpForm(request...
0
2016-06-16T08:07:25Z
37,874,011
<p>from django.shortcuts import render, render_to_response, RequestContext from forms import SignUpForm</p> <h1>Create your views here.</h1> <p>def home(request): form= SignUpForm(request.POST or None) if form.is_valid(): save_it=form.save(commit=False)</p> <pre><code> save_it.save() return render...
0
2016-06-17T05:47:55Z
[ "python", "django-models", "django-forms", "django-views" ]
Error while running collect() action in PySpark
37,853,521
<p>While practising Apache Spark using Python, I am getting error while running collect() command. I am trying the below code in Jupyter notebook.</p> <pre><code>vehicledata = sc.textFile("/home/newuser/Desktop/vehicle_data.csv") vehicledata.collect() [u'suzuki,gas,std,two,hatchback,fwd,four,69,4900,31,36,5118', u'v...
-1
2016-06-16T08:14:59Z
37,855,110
<p>This issue isn't specific to Spark at all.</p> <p>First look at the Specific error message thrown: list Index out of range. Now look at the last line of your data -- its empty. Which means splitting it by ',' will give you empty result.</p>
3
2016-06-16T09:27:29Z
[ "python", "apache-spark", "pyspark" ]
Faster Scraping of JSON from API: Asynchronous or?
37,853,548
<p>I need to scrape roughly 30GB of JSON data from a website API as quickly as possible. I don't need to parse it -- I just need to save everything that shows up on each API URL.</p> <ul> <li>I can request quite a bit of data at a time -- say 1MB or even 50MB 'chunks' (API parameters are encoded in the URL and allow m...
0
2016-06-16T08:16:03Z
37,854,042
<p>You are parsing the content and then serializing it again. You can just write the content directly to a file.</p> <pre><code>curr_url_request = requests.get(encoded_URL_i, timeout=timeout_secs) if curr_url_request.ok: with open('json_output.txt', 'w') as outfile: outfile.write(curr_url_request.content) ...
2
2016-06-16T08:39:08Z
[ "python", "asynchronous", "web-scraping", "python-requests" ]
Faster Scraping of JSON from API: Asynchronous or?
37,853,548
<p>I need to scrape roughly 30GB of JSON data from a website API as quickly as possible. I don't need to parse it -- I just need to save everything that shows up on each API URL.</p> <ul> <li>I can request quite a bit of data at a time -- say 1MB or even 50MB 'chunks' (API parameters are encoded in the URL and allow m...
0
2016-06-16T08:16:03Z
37,871,151
<p><code>tornado</code> has a very powerful asynchronous client. Here's a basic code that may do the trick:</p> <pre><code>from tornado.httpclient import AsyncHTTPClient import tornado URLS = [] http_client = AsyncHTTPClient() loop = tornado.ioloop.IOLoop.current() def handle_request(response): if response.code...
0
2016-06-16T23:56:38Z
[ "python", "asynchronous", "web-scraping", "python-requests" ]
Numpy slice 2D array with every two alternating elements
37,853,559
<p>Is there an elegant way to slice a <code>numpy</code> array such that every second element (alternating by the row) is extracted? (assume the width and height are multiples of 2)</p> <p>example extraction pattern:</p> <pre><code>[[ X, - , X , -], [ -, X , - , X], [ X, - , X , -], [ -, X , - , X], ...]] </code>...
1
2016-06-16T08:16:30Z
37,853,745
<p>There is no way to do that with strides, as there is no way you can address those elements with a simple function. </p> <p>Fancy indexing using e.g. a mask would be the way to go. This seems fairly elegant:</p> <pre><code>&gt;&gt;&gt; arr = np.random.random_integers(0,9, (4,4)) &gt;&gt;&gt; mask = np.fromfunction(...
1
2016-06-16T08:24:59Z
[ "python", "numpy" ]
Numpy slice 2D array with every two alternating elements
37,853,559
<p>Is there an elegant way to slice a <code>numpy</code> array such that every second element (alternating by the row) is extracted? (assume the width and height are multiples of 2)</p> <p>example extraction pattern:</p> <pre><code>[[ X, - , X , -], [ -, X , - , X], [ X, - , X , -], [ -, X , - , X], ...]] </code>...
1
2016-06-16T08:16:30Z
37,853,919
<p>After trying for a while I also found an answer which will halve the width of the original array</p> <pre><code>x = np.random.random((6,4)) res = np.vstack(zip(x[0::2, 0::2], x[1::2, 1::2])).reshape((x.shape[0], x.shape[1]//2)) </code></pre>
0
2016-06-16T08:33:08Z
[ "python", "numpy" ]
How to integrate existing gstreamer video stream with python
37,853,616
<p>Hi i'm using gstreamer for multimedia streaming from raspberry pi to remote PC. Im using these piplelines in my raspberry pi</p> <pre><code>raspivid -t 0 -h 720 -w 1080 -fps 25 -hf -b 2000000 -o - | gst-launch- 1.0 -v fdsrc ! h264parse ! rtph264pay config-interval=1 pt=96 ! gdppay ! tcpserversink host=YOUR_R...
1
2016-06-16T08:18:53Z
38,186,764
<p>For python3/Gst1.*/Gtk3 pygst is basically deprecated. You should move to the <a href="https://lazka.github.io/pgi-docs/" rel="nofollow">GObject introspection API</a>. You can find <a href="https://www.google.it/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8#q=python%20gstreamer%20gobject" rel="nofo...
0
2016-07-04T14:11:03Z
[ "python", "raspberry-pi", "gstreamer", "pygst" ]
How to efficiently resample a DatetimeIndex
37,853,623
<p>Pandas has a <code>resample</code> method on a series/dataframe but there seems no way to resample a <code>DatetimeIndex</code> on its own?</p> <p>Concretely, I have a daily <code>Datetimeindex</code> with possibly missing dates and I want to resample it at an hourly freq but only including days which are in the or...
3
2016-06-16T08:18:59Z
37,855,496
<p>Another option would be to generate the hourly index directly, and remove non-business days afterwards:</p> <pre><code>hourly_index = pd.date_range('01-Jan-2017', '31-Jan-2017', freq='H') hourly_index = hourly_index[hourly_index.dayofweek &lt; 5] </code></pre> <hr> <p>Performance comparison:</p> <ul> <li>OP's so...
2
2016-06-16T09:42:07Z
[ "python", "pandas" ]
How to efficiently resample a DatetimeIndex
37,853,623
<p>Pandas has a <code>resample</code> method on a series/dataframe but there seems no way to resample a <code>DatetimeIndex</code> on its own?</p> <p>Concretely, I have a daily <code>Datetimeindex</code> with possibly missing dates and I want to resample it at an hourly freq but only including days which are in the or...
3
2016-06-16T08:18:59Z
37,855,921
<pre> | Method | Time | Relative | |---------------------------------|---------|----------| | OP's updated approach | 1.31 ms | 17.6 % | | Generate daterange, np.in1d | 1.75 ms | 23.5 % | | Generate daterange, Series.isin | 1.90 ms | 25.5 % | | Resample with dummy Series ...
3
2016-06-16T10:00:08Z
[ "python", "pandas" ]
Segmentation fault (core dumped) in python
37,853,765
<p>I have python 2.7 and i have installed Tensorflow 0.8.0. It was working fine formonths. I installed sklearn today and after that when i call Tensorflow python closes with this error:</p> <pre><code>Segmentation fault (core dumped) </code></pre> <p>How to proceed?</p>
-1
2016-06-16T08:26:01Z
37,862,209
<p>currently Tensorflow 0.8.0 has an issue . You have to import numpy first then Tensorflow then the problem is resolved. Although in starting I was able to call Tensorflow alone but now I have to call numpy to resolve the problem.</p>
1
2016-06-16T14:32:19Z
[ "python", "scikit-learn", "tensorflow" ]
Best way to make df.apply a function of index and column
37,853,820
<p>I would like to have a single function be applied element-wise to a DataFrame. I would also like this function to take as arguments the current column and index. </p> <p>For example:</p> <pre><code>In [1]: import numpy as np In [2]: import pandas as pd In [3]: df = pd.DataFrame(np.arange(4).reshape(2, 2), index=...
2
2016-06-16T08:28:23Z
37,854,738
<p>One idea is to use <code>at</code> method of the dataframe. <code>loc</code> would work too but a bit slower.</p> <pre><code>foo = dict(a=1, b=2) bar = dict(c=3, d=4) for i in df.index: for j in df.columns: df.at[i, j] += foo[i] + bar[j] </code></pre>
1
2016-06-16T09:10:46Z
[ "python", "pandas" ]
How to save all files, not replacing the file?
37,853,832
<p>I have 100 text files and I want to save it into 100 text files too. Right now, my coding can read all the files but it save only one file, which is the latest result. Here I attached the code.</p> <pre><code>def nama(): path = "C:/Amar/code/" infilename = os.listdir(path) print len(infilename) for filename in infi...
0
2016-06-16T08:28:56Z
37,853,949
<p>Append a string that will act as a unique identifier for each output file. You can use the input filename for this:</p> <pre><code>outfilename = path + filename + "_result.txt" # e.g reports_result.txt </code></pre>
1
2016-06-16T08:34:21Z
[ "python" ]
Function to validate pin code, why doesn't this code work?
37,853,850
<p>So I have been trying to teach myself how to do this stuff and have had marginal success so far, I'm working on an exercise I found on codewars.com and I'm kind of stuck. The goal is to make a function that verifies the inputted pin meets the requirements, those requirements being: PIN must be either 4 or 6 digits l...
2
2016-06-16T08:29:52Z
37,854,134
<p>If you are allowed to use regex as I see from your code, why doesn't you use this regex <code>^(\d{4}|\d{6})$</code>. </p> <pre><code>import re p = re.compile(ur'^(\d{4}|\d{6})$') return re.match(p, pin) </code></pre>
2
2016-06-16T08:43:16Z
[ "python" ]
Function to validate pin code, why doesn't this code work?
37,853,850
<p>So I have been trying to teach myself how to do this stuff and have had marginal success so far, I'm working on an exercise I found on codewars.com and I'm kind of stuck. The goal is to make a function that verifies the inputted pin meets the requirements, those requirements being: PIN must be either 4 or 6 digits l...
2
2016-06-16T08:29:52Z
37,854,186
<p>There is a simpler way to validate it using regex. The reason why you're getting False returned on <code>"1234"</code> is because of that regex match. A point (<code>.</code>) matches ALL characters except for newline, so that match will almost always succeed. That's not what you want.</p> <p>Here is a simpler solu...
1
2016-06-16T08:46:04Z
[ "python" ]
Function to validate pin code, why doesn't this code work?
37,853,850
<p>So I have been trying to teach myself how to do this stuff and have had marginal success so far, I'm working on an exercise I found on codewars.com and I'm kind of stuck. The goal is to make a function that verifies the inputted pin meets the requirements, those requirements being: PIN must be either 4 or 6 digits l...
2
2016-06-16T08:29:52Z
37,854,331
<p>Since your </p> <blockquote> <p>PIN must be strictly numerical</p> </blockquote> <p>This should not constitute something that will need a regex:</p> <pre><code>def validate_pin(pin): return len(pin) in (4, 6) and all(p in '0123456789' for p in pin) </code></pre>
2
2016-06-16T08:53:12Z
[ "python" ]
AWS boto3 source code
37,853,897
<p>How can we get a look at the AWS boto library code. Not all the code is present in the python package.</p> <p>For example if I wanted to understand how the <strong>wait_until_running()</strong> method of Waiter class is implemented i.e. if it is implemented serialized fashion and other features of the code. Althoug...
0
2016-06-16T08:32:23Z
37,882,369
<p>boto3 uses botocore as a dependency for the core functionality. The sourcecode can be found for both on github.com:</p> <ul> <li><a href="https://github.com/boto/boto3/" rel="nofollow">https://github.com/boto/boto3/</a></li> <li><a href="https://github.com/boto/botocore/" rel="nofollow">https://github.com/boto/boto...
1
2016-06-17T13:06:57Z
[ "python", "amazon-web-services", "amazon-ec2", "boto", "boto3" ]
Python - Autocomplete extension for numbers and suggestion using random queries
37,853,984
<p>I have a very minimalistic code that performs autocompletion for input queries set by the user by storing a historical data of names(close to 1000) in a list. Right now, it gives suggestion in lexicographical smallest order.</p> <p>The names stored in a list are (fictitious):</p> <pre><code>names = ["show me 7 won...
0
2016-06-16T08:36:08Z
37,854,581
<p>It's O(n) but it works. Your function is checking if it starts with a prefix, but the behavior you describe you want is checking if the string contains the query</p> <pre><code>def __init__(self, words): self.index = sorted(words, key=str.lower, reverse=True) def by_prefix(self, prefix): for item in self.i...
0
2016-06-16T09:03:28Z
[ "python", "algorithm", "autocomplete" ]
Python - Autocomplete extension for numbers and suggestion using random queries
37,853,984
<p>I have a very minimalistic code that performs autocompletion for input queries set by the user by storing a historical data of names(close to 1000) in a list. Right now, it gives suggestion in lexicographical smallest order.</p> <p>The names stored in a list are (fictitious):</p> <pre><code>names = ["show me 7 won...
0
2016-06-16T08:36:08Z
37,854,627
<p>If you are not concerned by performance, you can use <code>if prefix in item:</code> for every <code>item</code> in your list <code>names</code>. This statement matches if prefix is part of the string item, e.g.:</p> <pre><code>prefix item match 'foo' 'foobar' True 'bar' 'foobar' True 'ob' 'fo...
0
2016-06-16T09:05:16Z
[ "python", "algorithm", "autocomplete" ]
Python - Autocomplete extension for numbers and suggestion using random queries
37,853,984
<p>I have a very minimalistic code that performs autocompletion for input queries set by the user by storing a historical data of names(close to 1000) in a list. Right now, it gives suggestion in lexicographical smallest order.</p> <p>The names stored in a list are (fictitious):</p> <pre><code>names = ["show me 7 won...
0
2016-06-16T08:36:08Z
37,855,096
<p>Another option is to add more entries to your index, e.g. for the item <code>"most beautiful places"</code>:</p> <pre><code>"most beautiful places" "beautiful places" "places" </code></pre> <p>If you do this, you also get matches if you start typing a word that's not the first word in the sentence. You can modify ...
0
2016-06-16T09:26:43Z
[ "python", "algorithm", "autocomplete" ]
Detect mishapen blobs in python using OpenCV
37,853,987
<p>I would like to detect two blobs in the following image:</p> <p>Original:</p> <p><a href="http://i.stack.imgur.com/2L6hP.png" rel="nofollow"><img src="http://i.stack.imgur.com/2L6hP.png" alt="enter image description here"></a></p> <p>I want to have the inside detected like this:</p> <p><a href="http://i.stack.im...
1
2016-06-16T08:36:17Z
37,863,914
<p>For detecting the inner blob, you can also try clustering and <a href="https://en.wikipedia.org/wiki/Maximally_stable_extremal_regions" rel="nofollow">MSER</a>s, because the region looks flat. I downsampled a cropped version of your image and applied these techniques.</p> <p>Downsampled image</p> <p><a href="http:...
1
2016-06-16T15:51:52Z
[ "python", "opencv", "matplotlib", "computer-vision", "edge-detection" ]
Fetch webpage including jQuery post in Crontab
37,854,247
<p>I want to make a cronjob that simply "visits" a webpage as a normal browser. On this webpage I have a script:</p> <pre><code>&lt;script&gt; var x = 0; while(x&lt;10) { setTimeout( function() { if ($(".instashow-gallery-media-image img")[0]){ // If image exists var html = $('#instaWrapp...
0
2016-06-16T08:48:50Z
37,854,440
<p>You can use CURL in PHP like so:</p> <pre><code>&lt;?php $ch = curl_init('http://www.google.com/'); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_NOBODY, 0); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_USERAGENT, 'Enter your browser agent string here'); curl_setopt($ch, CURLOPT_RE...
0
2016-06-16T08:57:53Z
[ "php", "jquery", "python", "linux", "curl" ]
how to read date and time on ecmwf file
37,854,256
<p>I have global datasets in netcdf file. Time information on data file is: </p> <pre><code>&lt;type 'netCDF4._netCDF4.Variable'&gt; int32 time(time) units: hours since 1900-01-01 00:00:0.0 long_name: time calendar: gregorian unlimited dimensions: time current shape = (5875,) filling off </code></pre> <p>...
3
2016-06-16T08:49:21Z
37,860,449
<p>You could: </p> <pre><code>from datetime import date, timedelta hours = [ 876600, 876624, 876648, 1017528, 1017552, 1017576] base = date(1900, 1, 1) for hour in hours: base + timedelta(hours=hour) 2000-01-02 2000-01-03 2000-01-04 2016-01-30 2016-01-31 2016-02-01 </code></pre> <p>Use <code>datetime</code...
1
2016-06-16T13:17:22Z
[ "python", "datetime", "pandas", "time-series", "data-analysis" ]
how to read date and time on ecmwf file
37,854,256
<p>I have global datasets in netcdf file. Time information on data file is: </p> <pre><code>&lt;type 'netCDF4._netCDF4.Variable'&gt; int32 time(time) units: hours since 1900-01-01 00:00:0.0 long_name: time calendar: gregorian unlimited dimensions: time current shape = (5875,) filling off </code></pre> <p>...
3
2016-06-16T08:49:21Z
37,862,251
<p>The soln using <code>.apply</code> is horribly inefficient, not to mention non-idiomatic and ugly. pandas already has built-in vectorized methods of doing timedelta conversions.</p> <pre><code>In [17]: hours = [ 876600, 876624, 876648, 1017528, 1017552, 1017576]*10000 In [18]: df = pd.DataFrame(hours, columns=['...
1
2016-06-16T14:34:32Z
[ "python", "datetime", "pandas", "time-series", "data-analysis" ]
how to read date and time on ecmwf file
37,854,256
<p>I have global datasets in netcdf file. Time information on data file is: </p> <pre><code>&lt;type 'netCDF4._netCDF4.Variable'&gt; int32 time(time) units: hours since 1900-01-01 00:00:0.0 long_name: time calendar: gregorian unlimited dimensions: time current shape = (5875,) filling off </code></pre> <p>...
3
2016-06-16T08:49:21Z
37,863,693
<p>The ideal way to do this is using <a href="http://unidata.github.io/netcdf4-python/#netCDF4.num2date" rel="nofollow">netCDF4 num2date</a></p> <pre><code>import netCDF4 ncfile = netCDF4.Dataset('./foo.nc', 'r') time = ncfile.variables['time'] dates = netCDF4.num2date(time[:], time.units, time.calendar) </code></pre...
1
2016-06-16T15:40:07Z
[ "python", "datetime", "pandas", "time-series", "data-analysis" ]
Selenium inside scrapy does not work
37,854,278
<p>I have a scrapy Crawlspider that parses links and returns html content just fine. For javascript pages however I enlisted Selenium to access the 'hidden' content. The problem is that while Selenium works outside the scrapy parsing, it does not work inside the parse_items function</p> <pre><code>from scrapy.spiders ...
0
2016-06-16T08:50:23Z
37,854,778
<p>You have some variable issues. In init method you are assigning browser instance to self.selenium and then in method <em>parse_item</em> you are using self.driver as browser instance. I have updated your script. Try now.</p> <pre><code>from scrapy.spiders import CrawlSpider, Rule, Spider from scrapy.selector impor...
0
2016-06-16T09:12:17Z
[ "python", "python-2.7", "selenium", "selenium-webdriver", "scrapy" ]
Selenium inside scrapy does not work
37,854,278
<p>I have a scrapy Crawlspider that parses links and returns html content just fine. For javascript pages however I enlisted Selenium to access the 'hidden' content. The problem is that while Selenium works outside the scrapy parsing, it does not work inside the parse_items function</p> <pre><code>from scrapy.spiders ...
0
2016-06-16T08:50:23Z
37,872,029
<p>Great! a combination of Hassan answer and better knowledge of the urls I was scraping lead to the answer (turns out the website had planted 'fake' urls that never loaded)</p>
0
2016-06-17T02:07:13Z
[ "python", "python-2.7", "selenium", "selenium-webdriver", "scrapy" ]
How to generate documentation from Django models?
37,854,379
<p>At the moment we use <a href="http://www.sphinx-doc.org/en/stable/" rel="nofollow">Sphinx</a> for project documentation and Django models field description. </p> <p>The main problem is that: after changing models, we manually updated Sphinx docs and sometimes forget/miss some fields in docs.</p> <p>Is there some t...
1
2016-06-16T08:55:13Z
37,854,660
<p>The <a href="https://docs.djangoproject.com/en/1.9/internals/contributing/writing-documentation/#getting-started-with-sphinx" rel="nofollow">documentation</a> says:</p> <blockquote> <p>Django’s documentation uses the Sphinx documentation system, which in turn is based on docutils. The basic idea is that light...
2
2016-06-16T09:07:03Z
[ "python", "django" ]
How to generate documentation from Django models?
37,854,379
<p>At the moment we use <a href="http://www.sphinx-doc.org/en/stable/" rel="nofollow">Sphinx</a> for project documentation and Django models field description. </p> <p>The main problem is that: after changing models, we manually updated Sphinx docs and sometimes forget/miss some fields in docs.</p> <p>Is there some t...
1
2016-06-16T08:55:13Z
37,962,110
<p>The best way to generate docs for Django - use <strong>admindocs</strong> <a href="https://docs.djangoproject.com/ja/1.9/ref/contrib/admin/admindocs/" rel="nofollow">app</a>.</p>
0
2016-06-22T08:06:34Z
[ "python", "django" ]
Scraping using Inspect element
37,854,569
<p>I am trying to get some information from Instagram by scraping it. I have tried this code on twitter and it was working fine but it shows no result on Instagram both of the code are available here.</p> <hr> <p>Twitter code:</p> <pre><code>from bs4 import BeautifulSoup from urllib2 import urlopen theurl = "https:/...
3
2016-06-16T09:03:08Z
37,857,535
<p>First of all there seems to be a typo in the address on line 3.</p> <pre><code>from bs4 import BeautifulSoup from urllib2 import urlopen theurl = "https://www.instagram.com/barackobama/" thepage = urlopen(theurl) soup = BeautifulSoup(thepage,"html.parser") print(soup.find('div',{"class":"_bugdy"})) </code></pre> <...
0
2016-06-16T11:14:43Z
[ "python", "twitter", "beautifulsoup", "instagram", "screen-scraping" ]
Scraping using Inspect element
37,854,569
<p>I am trying to get some information from Instagram by scraping it. I have tried this code on twitter and it was working fine but it shows no result on Instagram both of the code are available here.</p> <hr> <p>Twitter code:</p> <pre><code>from bs4 import BeautifulSoup from urllib2 import urlopen theurl = "https:/...
3
2016-06-16T09:03:08Z
37,857,607
<p>If you look at the source, you will see the content is dynamically loaded so there is no <code>div._bugdy</code> in what is returned by your request, depending on what it is you want you may be able to pull it from the script json:</p> <pre><code>import requests import re import json r = requests.get("https://www....
0
2016-06-16T11:17:58Z
[ "python", "twitter", "beautifulsoup", "instagram", "screen-scraping" ]
Extract cpu info from text with regex
37,854,605
<p>I have a text file like below:</p> <pre><code>cpu:5120*2 cpu:5140*2 cpu:5335*2 cpu:5506*2 cpu:5520*2 cpu:5560*2 cpu:5606*2 cpu:5620*2 cpu:5640*2 cpu:E-5620*2 cpu:E-5700*2 cpu:E2430*2 cpu:E5 2603*2 cpu:E5-2407*2 cpu:E5-2407*2 cpu:E5-2420*2 cpu:E5-2420 v2*2 cpu:E5-2609 v2*2 cpu:E5-2618Lv3*2 cpu:E5-2620*2 cpu:E5-2620 ...
0
2016-06-16T09:04:29Z
37,854,919
<pre><code>lines = tuple(open('filename.txt', 'r')) for line in lines : print line.replace('cpu:','').replace('*',' ').replace('V2','').replace('V3','') </code></pre> <p>In this case, how about this :</p> <pre><code>import re data=open('filename.txt', 'r').read() out = re.sub("cpu:", '', data) out = re.sub("V2", ...
0
2016-06-16T09:18:38Z
[ "python", "regex" ]
Extract cpu info from text with regex
37,854,605
<p>I have a text file like below:</p> <pre><code>cpu:5120*2 cpu:5140*2 cpu:5335*2 cpu:5506*2 cpu:5520*2 cpu:5560*2 cpu:5606*2 cpu:5620*2 cpu:5640*2 cpu:E-5620*2 cpu:E-5700*2 cpu:E2430*2 cpu:E5 2603*2 cpu:E5-2407*2 cpu:E5-2407*2 cpu:E5-2420*2 cpu:E5-2420 v2*2 cpu:E5-2609 v2*2 cpu:E5-2618Lv3*2 cpu:E5-2620*2 cpu:E5-2620 ...
0
2016-06-16T09:04:29Z
37,855,563
<p>KHELILI's decision is wonderful, but since you're asking about a regex, here's a script using a regex that, I think, fits the situation:</p> <pre><code>import re while input('Continue? [y/n] ') == 'y': check = input('The string: ') res = (re.match('^cpu:([A-Za-z\s]*\s)?([A-Za-z]*\d{0,1}[-\s]{0,1}\d{3,4})([...
0
2016-06-16T09:44:48Z
[ "python", "regex" ]
Odoo PoS get orderline product
37,854,789
<p>I'm updating the <strong>update_payment_summary</strong> function in the Point_Of_Sale, this function is part of the <strong>PaymentScreenWidget</strong>. Now I'd like to retrieve the products from the orderlines.</p> <p>I tried with </p> <pre><code>var order = this.pos.get('selectedOrder'); var orderlines = orde...
2
2016-06-16T09:12:34Z
37,857,283
<p>use the <code>get_orderlines()</code> function to get OrderLines from particular Order.</p> <pre><code>var order = this.pos.get_order(); var products = _.map(order.get_orderlines(), function (line) {return line.product; }); console.log(products); </code></pre> <p>here i user Underscore.js for create a list of prod...
1
2016-06-16T11:01:50Z
[ "javascript", "python", "openerp", "product", "point-of-sale" ]
Odoo PoS get orderline product
37,854,789
<p>I'm updating the <strong>update_payment_summary</strong> function in the Point_Of_Sale, this function is part of the <strong>PaymentScreenWidget</strong>. Now I'd like to retrieve the products from the orderlines.</p> <p>I tried with </p> <pre><code>var order = this.pos.get('selectedOrder'); var orderlines = orde...
2
2016-06-16T09:12:34Z
37,857,743
<p>Yes there is a reason why it shows object.</p> <p>OrderlineCollection definition.</p> <pre><code>module.OrderlineCollection = Backbone.Collection.extend({ model: module.Orderline, }); </code></pre> <p>Orderline definition in Order Model.</p> <pre><code>orderLines: new module.OrderlineCollection() </c...
1
2016-06-16T11:23:16Z
[ "javascript", "python", "openerp", "product", "point-of-sale" ]
Retrieving the resolution of .dpx files in Python
37,854,873
<p>I'm currently writing a program that searches through an inputted folder and flags errors such as missing or empty files. One of the errors I need to check is if all of the .dpx images have the same resolution. However, I can't seem to find a way to check this. PIL can't open the file and I can't find a way to check...
1
2016-06-16T09:16:22Z
37,857,677
<p>Unfortunately Pillow/PIL doesn't understand the SMPTE Digital Picture Exchange Format yet.</p> <p>However, <a href="http://www.imagemagick.org/script/motion-picture.php" rel="nofollow">ImageMagick supports</a> it and ImageMagick can be <a href="http://stackoverflow.com/questions/7895278/can-i-access-imagemagick-api...
0
2016-06-16T11:20:47Z
[ "python", "image", "python-imaging-library" ]
x-www-form-urlencoded parse by Django
37,854,916
<p>I create android API using django framework.I send post request to server in x-www-form-urlencoded form but i dont know how to parse by django framework.so how to parse it.</p> <p>i am using postman to test api and using <code>**post method =&gt; body =&gt; x-www-form-urlencoded**</code> and send data is </p> <pre...
0
2016-06-16T09:18:24Z
37,855,163
<p><code>Django</code> is already parsing the <code>POST</code> data as a <code>dict-like</code> object in <code>request.POST</code>. </p> <p>For example you can get the <code>name</code> using: <code>request.POST.get('name')</code>. You can read more about <code>Django's</code> <code>request</code> object and the so-...
3
2016-06-16T09:29:46Z
[ "android", "python", "json", "django" ]
Pika: Consume the next message even the last message was not acknowledged
37,854,973
<p>For server automation, we're trying to develop a tool, which can handle and execute a lot of tasks on different servers. We send the task and the server hostname into a queue. The queue is then consumed from a requester, which give the information to the ansible api. To achieve that we can execute more then one task...
2
2016-06-16T09:21:17Z
37,856,008
<p>Disable auto-acknowledge and set the prefetch count to something bigger then 1, depending on how many messages would you like your consumer to take.</p> <p>Here is how to set prefetch <code>channel.basic_qos(prefetch_count=1)</code>, found <a href="https://www.rabbitmq.com/tutorials/tutorial-two-python.html" rel="n...
1
2016-06-16T10:04:15Z
[ "python", "multithreading", "rabbitmq", "pika" ]
How to iterate over a dictionary using for loops?
37,855,048
<p>I want to decompress a dictionary and a list into a sentence. For example:</p> <pre><code>newlist = [1, 2, 3, 4, 5, 6] new_dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1} </code></pre> <p>The original sentence is <code>'My code is broken please help'</code>. The list shows the posit...
0
2016-06-16T09:24:28Z
37,855,181
<p>Invert the dictionary and proceed. Try the following code. </p> <pre><code>&gt;&gt;&gt; d = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1} &gt;&gt;&gt; numbers = [1, 2, 3, 4, 5, 6] &gt;&gt;&gt; d_inv = {v:k for k,v in d.items()} &gt;&gt;&gt; ' '.join([d_inv[i] for i in numbers]) 'my code is bro...
4
2016-06-16T09:30:36Z
[ "python", "list", "dictionary" ]
How to iterate over a dictionary using for loops?
37,855,048
<p>I want to decompress a dictionary and a list into a sentence. For example:</p> <pre><code>newlist = [1, 2, 3, 4, 5, 6] new_dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1} </code></pre> <p>The original sentence is <code>'My code is broken please help'</code>. The list shows the posit...
0
2016-06-16T09:24:28Z
37,855,270
<p>I assume you don't want to invert the dictionary, so you can try something like this:</p> <pre><code>dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1} numbers = [1, 2, 3, 4, 5, 6] sentence = [] for number in numbers: for key in dictionary.keys(): if dictionary[key] == numb...
2
2016-06-16T09:34:00Z
[ "python", "list", "dictionary" ]
How to iterate over a dictionary using for loops?
37,855,048
<p>I want to decompress a dictionary and a list into a sentence. For example:</p> <pre><code>newlist = [1, 2, 3, 4, 5, 6] new_dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1} </code></pre> <p>The original sentence is <code>'My code is broken please help'</code>. The list shows the posit...
0
2016-06-16T09:24:28Z
37,855,291
<p>Sorted the dict with using the values. </p> <pre><code>import operator new_dictionary = {'code': 2, 'help': 6, 'broken': 4, 'is': 3, 'please': 5, 'my': 1} sorted_x = sorted(new_dictionary.items(), key=operator.itemgetter(1)) print ' '.join(i[0] for i in sorted_x) </code></pre> <p><strong>result</strong></p> <pre...
1
2016-06-16T09:34:50Z
[ "python", "list", "dictionary" ]
Why does accumulate work for numpy.maximum but not numpy.argmax
37,855,059
<p>These two look like they should be very much equivalent and therefore what works for one should work for the other? So why does accumulate only work for maximum but not argmax?</p> <p>EDIT: A natural follow-up question is then how does one go about creating an efficient argmax accumulate in the most pythonic/numpy-...
1
2016-06-16T09:24:58Z
37,855,371
<p>Because <code>max</code> is associative, but <code>argmax</code> is not:</p> <ul> <li><code>max(a, max(b, c)) == max(max(a, b), c)</code></li> <li><code>argmax(a, argmax(b, c)) != argmax(argmax(a, b), c)</code></li> </ul>
1
2016-06-16T09:37:49Z
[ "python", "numpy", "numpy-ufunc" ]
Why does accumulate work for numpy.maximum but not numpy.argmax
37,855,059
<p>These two look like they should be very much equivalent and therefore what works for one should work for the other? So why does accumulate only work for maximum but not argmax?</p> <p>EDIT: A natural follow-up question is then how does one go about creating an efficient argmax accumulate in the most pythonic/numpy-...
1
2016-06-16T09:24:58Z
37,864,628
<p>Is this the kind of <code>argmax</code> accumulate you want?</p> <p>sample array:</p> <pre><code>In [135]: a Out[135]: array([4, 6, 5, 1, 4, 4, 2, 0, 8, 4]) </code></pre> <p>the maximum that you already got:</p> <pre><code>In [136]: am=np.maximum.accumulate(a) In [137]: am Out[137]: array([4, 6, 6, 6, 6, 6, ...
1
2016-06-16T16:25:40Z
[ "python", "numpy", "numpy-ufunc" ]
Rudimentary caching not working in a Google App Engine application
37,855,252
<p>I'm making a blog using Google App Engine, which for now just allows me to post entries and see them listed out. I was following the Web Development course by Steve Huffman on Udacity where he showed a simple caching technique to decrease the database queries. Here's my code (which he instructed):</p> <pre><code>CA...
0
2016-06-16T09:33:16Z
37,856,011
<p>You are caching at instance level and you can have number of instances or an instance can be recycled (<em>shut down</em>) and a new one instantiated on a request.</p> <p>Try to use Memcache if you want to share cache between instances: <a href="https://cloud.google.com/appengine/docs/python/memcache/" rel="nofollo...
3
2016-06-16T10:04:31Z
[ "python", "python-2.7", "google-app-engine", "caching", "google-cloud-datastore" ]
Common IDs across all categories in a column of Dataframe- Python
37,855,286
<p>I have a dataframe with three columns as ID, Name and Social-Site, How can I find common IDs/ or the data associated for all Social- Sites/ or any of them. Data is following </p> <pre><code>ID Name Social_Site 1 Jon Facebook 1 Jon Twitter 2 Bob Twitter 2 Bob Linkedin 3 Tony Facebook 3 Tony Linkedin...
1
2016-06-16T09:34:45Z
37,855,497
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.pivot.html" rel="nofollow"><code>pivot</code></a>:</p> <pre><code>print (df.pivot(index='ID', columns='Social_Site', values='Name')) Social_Site Facebook Linkedin Twitter ID 1 ...
3
2016-06-16T09:42:10Z
[ "python", "numpy", "pandas", "dataframe" ]
Reading .grd file in Python
37,855,316
<p>Some files in <code>ESRI grid format</code>(suffixed in <strong>.grd</strong>) is a geospatial dataset with left low X corner, left low Y corner and value. </p> <p>The file look like this(using vim to read it): </p> <pre><code> 1 ncols 2880 2 nrows 1440 3 xllcorner -180.0 4 yllcorner -90.0 5 ...
0
2016-06-16T09:35:45Z
37,855,780
<p>You can write a function for it. Here's a sample (assuming that your line numbers are from vim, not actually present in the file):</p> <pre><code>import numpy as np def read_grd(filename): with open(filename) as infile: ncols = int(infile.readline().split()[1]) nrows = int(infile.readline().spl...
2
2016-06-16T09:54:13Z
[ "python", "numpy", "pandas", "gis", "raster" ]
How to find out the starting point of code execution in any Python project?
37,855,381
<p>I have been looking at various open source GitHub Python projects like, <a href="https://github.com/eliangcs/http-prompt" rel="nofollow"><code>http-prompt</code></a> and <a href="https://github.com/Theano/Theano" rel="nofollow">Theano</a></p> <p>What I am not able to figure out is where their starting points are, ...
0
2016-06-16T09:38:18Z
37,855,651
<p>There are two ways a Python script can be loaded:</p> <ul> <li>By import : <code>import mymodule</code></li> <li>By commandline : <code>$ python mymodule.py</code></li> </ul> <p>In both cases all code inside the script is executed</p> <p>Usually <code>if __name__ == '__main__':</code> defines the entry point : ...
3
2016-06-16T09:48:32Z
[ "python", "debugging" ]
How to find out the starting point of code execution in any Python project?
37,855,381
<p>I have been looking at various open source GitHub Python projects like, <a href="https://github.com/eliangcs/http-prompt" rel="nofollow"><code>http-prompt</code></a> and <a href="https://github.com/Theano/Theano" rel="nofollow">Theano</a></p> <p>What I am not able to figure out is where their starting points are, ...
0
2016-06-16T09:38:18Z
37,859,995
<p>The Python equivalent of a manifest file is generally <code>setup.py</code>, so this is a good place to start looking. A package can:</p> <ul> <li>define scripts that should be installed, using <a href="http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html#the-scripts-keyword-argument" rel="nof...
1
2016-06-16T12:58:59Z
[ "python", "debugging" ]
Merge Pandas DataFrames in Python
37,855,450
<p>I have two pandas dataframes. The first one contains 3401 row 1 column, the second one is 4 row with 3 column. </p> <p>But what I got is (exemple output of my script): </p> <pre><code> DataFrame1 | DataFrame2 </code></pre> <hr> <pre><code> - email1 | -Id1 -Project1 -Descr1 - email2 ...
1
2016-06-16T09:40:46Z
37,858,773
<p>To make one row from a DateFrame use <code>stack</code>. Then iterate over it creating new column in first DateFrame.</p> <pre><code>&gt;&gt;&gt; df1 0 0 email1 1 email2 2 email3 3 email4 4 email5 5 email6 &gt;&gt;&gt; df2 0 1 2 0 Id1 Project1 Descr1 1 Id2 Project2 Descr2 2 I...
1
2016-06-16T12:08:03Z
[ "python", "pandas", "dataframe", "merge", "append" ]
adding new key inside a new key and assigning value in python dictionary
37,855,490
<p>I have a dictionary:</p> <p><code>dic = {'Test': {'cities':5}}</code></p> <p>it is easy to add a key-value pair inside </p> <p><code>dic['test']</code></p> <p>by simply writing</p> <p><code>dic['Test']['random'] = 1</code> </p> <p>which gives output like this. </p> <p><code>{'Test' : {'cities':5, 'random':1}}...
4
2016-06-16T09:41:57Z
37,855,552
<p>...</p> <pre><code>dic['Test']['class'] = {'section': 5} </code></pre>
6
2016-06-16T09:44:29Z
[ "python", "python-2.7", "dictionary" ]
adding new key inside a new key and assigning value in python dictionary
37,855,490
<p>I have a dictionary:</p> <p><code>dic = {'Test': {'cities':5}}</code></p> <p>it is easy to add a key-value pair inside </p> <p><code>dic['test']</code></p> <p>by simply writing</p> <p><code>dic['Test']['random'] = 1</code> </p> <p>which gives output like this. </p> <p><code>{'Test' : {'cities':5, 'random':1}}...
4
2016-06-16T09:41:57Z
37,855,614
<p>Two options, in one line:</p> <pre><code>dic['Test']['class'] = {'section': 5} </code></pre> <p>in two lines:</p> <pre><code>dic['Test']['class'] = {} dic['Test']['class']['section'] = 5 </code></pre>
3
2016-06-16T09:46:57Z
[ "python", "python-2.7", "dictionary" ]
adding new key inside a new key and assigning value in python dictionary
37,855,490
<p>I have a dictionary:</p> <p><code>dic = {'Test': {'cities':5}}</code></p> <p>it is easy to add a key-value pair inside </p> <p><code>dic['test']</code></p> <p>by simply writing</p> <p><code>dic['Test']['random'] = 1</code> </p> <p>which gives output like this. </p> <p><code>{'Test' : {'cities':5, 'random':1}}...
4
2016-06-16T09:41:57Z
37,855,625
<p>You can use <code>update</code> also.</p> <pre><code>dic['Test'].update({'class':{'section': 5}}) </code></pre>
1
2016-06-16T09:47:16Z
[ "python", "python-2.7", "dictionary" ]
adding new key inside a new key and assigning value in python dictionary
37,855,490
<p>I have a dictionary:</p> <p><code>dic = {'Test': {'cities':5}}</code></p> <p>it is easy to add a key-value pair inside </p> <p><code>dic['test']</code></p> <p>by simply writing</p> <p><code>dic['Test']['random'] = 1</code> </p> <p>which gives output like this. </p> <p><code>{'Test' : {'cities':5, 'random':1}}...
4
2016-06-16T09:41:57Z
37,855,671
<pre><code>&gt;&gt;&gt; dic {'Test': {'cities': 5}} &gt;&gt;&gt; dic['Test'] {'cities': 5} &gt;&gt;&gt; dic['Test']['random'] = 1 &gt;&gt;&gt; dic {'Test': {'random': 1, 'cities': 5}} &gt;&gt;&gt; dic['Test']['class'] = {'section':5} &gt;&gt;&gt; dic {'Test': {'random': 1, 'cities': 5, 'class': {'section': 5}}} &gt;&gt...
0
2016-06-16T09:49:34Z
[ "python", "python-2.7", "dictionary" ]
Python Igraph community cluster colors
37,855,553
<p>I want to have clusters in different colours after community infomap, but problem is when I deleted single nodes it makes a mess an each node is different color or everything is red. How to do that in python?</p> <p>Code:</p> <pre><code>E = ig.Graph(edges) E.vs\['label'\] = labels degree = 0 community = E.communit...
1
2016-06-16T09:44:30Z
37,857,477
<p>I found solution. First delete single nodes than convert to igraph and do community.</p>
0
2016-06-16T11:10:59Z
[ "python", "plot", "igraph" ]
Two Pandas Series replacement values using intermediate one
37,855,604
<p>I'am new to Pandas, trying to use three Series like this ...</p> <p>First one X :</p> <pre><code>DATE 2015-10-10 00:00:00 0.0 2015-10-10 01:00:00 290.0 2015-10-10 02:00:00 225.0 2015-10-10 03:00:00 4.0 2015-10-10 04:00:00 2.0 Name: X, dtype: bool </code></pre> <p>Second one S :</p> <pre><cod...
2
2016-06-16T09:46:40Z
37,855,833
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.where.html" rel="nofollow"><code>where</code></a> passing in the <code>Series</code> to test against:</p> <pre><code>In [231]: Average.where(S==True, X) Out[231]: DATE 2015-10-10 00:00:00 0.00 2015-10-10 01:00:00 290.0...
2
2016-06-16T09:56:15Z
[ "python", "pandas", "time-series", "series" ]
Python telnet connection successful
37,855,617
<p>I'm wondering if it is possible to know if my telnet connection is successful?</p> <p>So, if I'm connected to my switch and if I could write commands</p> <pre><code>telnet = telnetlib.Telnet(IP) telnet.read_until(b"User Name:") telnet.write(b"LOGIN\n") telnet.read_until(b"Password:") telnet.write(b"PASSWORD\n") # ...
1
2016-06-16T09:47:06Z
37,856,198
<p>You could go this way:</p> <pre><code>def is_connected(telnet_obj ): answer = telnet_obj.read_all() if "connected" in answer: #this test condition is not real is an example return True else: return False </code></pre> <p>If you observe what yout router/switch returns you can...
1
2016-06-16T10:11:59Z
[ "python", "telnet", "telnetlib" ]
Python telnet connection successful
37,855,617
<p>I'm wondering if it is possible to know if my telnet connection is successful?</p> <p>So, if I'm connected to my switch and if I could write commands</p> <pre><code>telnet = telnetlib.Telnet(IP) telnet.read_until(b"User Name:") telnet.write(b"LOGIN\n") telnet.read_until(b"Password:") telnet.write(b"PASSWORD\n") # ...
1
2016-06-16T09:47:06Z
37,856,656
<p>Don't use <code>read_all</code> if you plan on writing something after authentication. It blocks the connection until <code>EOF</code> is reached / connection is closed. </p> <p>First check the output telnet server is giving when an authentication is successful using putty or something else. <code>read_untill</code...
0
2016-06-16T10:32:51Z
[ "python", "telnet", "telnetlib" ]
Numpy: get the index of the top value sorted that are superior to 0
37,855,796
<p>I have a numpy array and I wan to have the index of the top value sorted that are superior to 0 for instance:</p> <pre><code>[-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7] </code></pre> <p>And I want to have:</p> <pre><code>[6, 1, 4, 5] </code></pre> <p>I can do it using a function I implemented but I guess for this kind of t...
2
2016-06-16T09:54:38Z
37,855,942
<p>You can implement with <code>np.where</code></p> <pre><code>a = np.array([-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7]) np.where(a &gt; 0)[0].tolist() </code></pre> <p><strong>Result</strong></p> <pre><code>[1, 4, 5, 6] </code></pre> <p>The result of <code>np.where(a &gt; 0)</code> is in the form of tuple of numpy array. So ...
2
2016-06-16T10:01:01Z
[ "python", "arrays", "numpy" ]
Numpy: get the index of the top value sorted that are superior to 0
37,855,796
<p>I have a numpy array and I wan to have the index of the top value sorted that are superior to 0 for instance:</p> <pre><code>[-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7] </code></pre> <p>And I want to have:</p> <pre><code>[6, 1, 4, 5] </code></pre> <p>I can do it using a function I implemented but I guess for this kind of t...
2
2016-06-16T09:54:38Z
37,855,970
<p>Use <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.where.html" rel="nofollow"><code>np.where()</code></a>. </p> <p><code>d &gt; 0.0</code> generates a boolean mask and <code>where</code> fetches all the values where the mask is true.</p> <pre><code>&gt;&gt;&gt; d=np.array([-0.4, 0.6, 0,...
1
2016-06-16T10:02:25Z
[ "python", "arrays", "numpy" ]
Numpy: get the index of the top value sorted that are superior to 0
37,855,796
<p>I have a numpy array and I wan to have the index of the top value sorted that are superior to 0 for instance:</p> <pre><code>[-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7] </code></pre> <p>And I want to have:</p> <pre><code>[6, 1, 4, 5] </code></pre> <p>I can do it using a function I implemented but I guess for this kind of t...
2
2016-06-16T09:54:38Z
37,856,047
<p>You can also do:</p> <pre><code>L = [-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7] [L.index(i) for i in sorted(filter(lambda x: x&gt;0, L), reverse=True)] Out[72]: [6, 1, 4, 5] </code></pre>
3
2016-06-16T10:05:57Z
[ "python", "arrays", "numpy" ]
Numpy: get the index of the top value sorted that are superior to 0
37,855,796
<p>I have a numpy array and I wan to have the index of the top value sorted that are superior to 0 for instance:</p> <pre><code>[-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7] </code></pre> <p>And I want to have:</p> <pre><code>[6, 1, 4, 5] </code></pre> <p>I can do it using a function I implemented but I guess for this kind of t...
2
2016-06-16T09:54:38Z
37,856,196
<p>Here's a vectorized approach -</p> <pre><code>idx = np.where(A&gt;0)[0] out = idx[A[idx].argsort()[::-1]] </code></pre> <p>Sample run -</p> <pre><code>In [37]: A = np.array([-0.4, 0.6, 0, 0, 0.4, 0.2, 0.7]) In [38]: idx = np.where(A&gt;0)[0] In [39]: idx[A[idx].argsort()[::-1]] Out[39]: array([6, 1, 4, 5]) </co...
2
2016-06-16T10:11:52Z
[ "python", "arrays", "numpy" ]
Appium : Getting exception while running tests
37,855,829
<pre><code>Appium 1.5.0 Xcode 7.3 IOS 10.11.4 OSX EI Capitan Using on:Simulator iOS 8.1 </code></pre> <p>Exception:</p> <pre><code>[Appium] Had trouble ending session 93536764-0715-4f18-a8b0-4a06335e2d94: Instruments did not terminate after 5 seconds! [Appium] Removing session 93536764-0715-4f18-a8b0-4a06335e2d94 f...
1
2016-06-16T09:55:58Z
38,335,795
<p>Ru using debug build of the app ?? iOS requires debug app Have u enabled ui automation in developer options of iOS device ??</p> <p>Looks like an problem from appium - <a href="http://github.com/appium/appium/issues/6238" rel="nofollow">Appium Bug</a></p>
1
2016-07-12T17:48:51Z
[ "python", "ios-simulator", "appium", "appium-ios", "python-appium" ]
Plot a non-square matrix according to the value at that point
37,856,126
<p>I have an 2 dimensional array generated randomly as:-</p> <pre><code>In [159]: arr arr Out[159]: array([[ 0.22415888, 0.75510844, 0.30900038, 0.88540865], [ 0.57742895, 0.17051546, 0.5770795 , 0.92893646], [ 0.39222077, 0.84292636, 0.92571946, 0.3890262 ], [ 0.83965826, 0.30913694, ...
2
2016-06-16T10:08:52Z
37,856,271
<p>is that what you want?</p> <pre><code>sns.heatmap(a, annot=True) </code></pre> <p><a href="http://i.stack.imgur.com/7GHgD.png" rel="nofollow"><img src="http://i.stack.imgur.com/7GHgD.png" alt="enter image description here"></a></p> <p>Full code:</p> <pre><code>import matplotlib.pyplot as plt import seaborn as sn...
3
2016-06-16T10:14:47Z
[ "python", "numpy", "pandas", "matplotlib", "seaborn" ]
Inserting tag within a tag using BeautifulSoup
37,856,154
<p>I have the following HTML structure: </p> <pre class="lang-html prettyprint-override"><code>&lt;BODY&gt;&lt;tag1&gt;&lt;/tag1&gt;&lt;tag2&gt;&lt;/tag2&gt;&lt;/BODY&gt; </code></pre> <p> I need to insert a table just prior to <code>&lt;/BODY&gt;</code> using BeautifulSoup. </p> <p>What I have till now is: </p> <p...
1
2016-06-16T10:10:21Z
37,866,856
<p>You don't need a regex, you can just <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#append" rel="nofollow">append</a> the table to the body:</p> <pre><code>In [45]: soup = BeautifulSoup("&lt;BODY&gt;&lt;tag1&gt;&lt;/tag1&gt;&lt;tag2&gt;&lt;/tag2&gt;&lt;/BODY&gt;", "html.parser") In [46]: soup.body...
1
2016-06-16T18:31:59Z
[ "python", "html", "insert", "tags", "beautifulsoup" ]