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 syntax error on mad libs | 38,963,038 | <p>So I'm trying to make a simple Mad Libs program and I'm getting multiple errors and I cannot figure out why. One of them is with the "Noah's First Program" part, and the other is with the printing of the story variable. How do I fix it?</p>
<pre><code>print "Noah's First Program!"
name=raw_input("Enter a name:")
a... | -2 | 2016-08-15T21:04:36Z | 38,963,249 | <p>If you are using Python 2, which <code>raw_input</code> leads me to believe, your code should be as follows:</p>
<pre><code>print "Noah's First Program!"
name=raw_input("Enter a name:")
adjectiveone=raw_input("Enter an Adjective:")
adjectivetwo=raw_input("Enter an Adjective:")
adjectivethree=raw_input("Enter an Ad... | 1 | 2016-08-15T21:20:50Z | [
"python",
"syntax"
] |
What will be faster - grep or pandas TextFileReader for a very large file? | 38,963,102 | <p>I need to search for a particular regex in a very large file I can't load to memory or create dataframe of. Which one, grep or iterating over a TextFileReader will be faster in that case?</p>
<p>Sadly, I don't have time to learn, configure and run a Hadoop.</p>
<p>Cheers </p>
| 1 | 2016-08-15T21:08:45Z | 38,963,174 | <p>Since grep is a compiled C program grep is certainly faster than interpreting bytecode for file scan AND regex processing (although regex lib is native code)</p>
<p>Running with pypy could close the gap, but in the end the compiled code would win.</p>
<p>Of course, on smaller data, if data could be stored in a dic... | 1 | 2016-08-15T21:14:37Z | [
"python",
"pandas",
"grep"
] |
Add quotes around two tuples | 38,963,199 | <p>I have two tuples and I would simply like to add quotes around both of them:</p>
<pre><code>Nord = 52.2
East = 13.3
</code></pre>
<p>What I'd like to print is this statement <code>"52.2, 13.3"</code>.</p>
<p>However if I do print I get <code>'52.2', '13.3'</code>.</p>
<p>How can I get the two values in double qu... | 0 | 2016-08-15T21:16:02Z | 38,963,454 | <p>You may use a simple <code>format()</code>:</p>
<pre><code>Nord = 52.2
East = 13.3
print("\"{0}, {1}\"".format(Nord, East))
# or
print('"{0}, {1}"'.format(Nord, East))
</code></pre>
<p>See the <a href="http://ideone.com/CnCPtg" rel="nofollow">Python demo</a></p>
<p>Note that the <code>'"{0}, {1}"'</code> is prefe... | 2 | 2016-08-15T21:37:08Z | [
"python",
"string",
"tuples",
"parentheses"
] |
Add quotes around two tuples | 38,963,199 | <p>I have two tuples and I would simply like to add quotes around both of them:</p>
<pre><code>Nord = 52.2
East = 13.3
</code></pre>
<p>What I'd like to print is this statement <code>"52.2, 13.3"</code>.</p>
<p>However if I do print I get <code>'52.2', '13.3'</code>.</p>
<p>How can I get the two values in double qu... | 0 | 2016-08-15T21:16:02Z | 38,968,440 | <p>For any tuple <code>tup</code> (with var length) you can do this one:</p>
<pre><code>print('"{}"'.format(', '.join(str(t) for t in tup)))
</code></pre>
| 0 | 2016-08-16T06:59:01Z | [
"python",
"string",
"tuples",
"parentheses"
] |
Python and Mac OS X 10.11 | 38,963,236 | <p>Recently I installed Mac OS X 10.11. I am involved in the development of scientific applications (mainly in Fortran and C++) and I use MacPorts to install different utilities (GCC compiler, MPI libraries, ...). Immediately after the installation of the new OS, I followed the migration instructions for MacPorts (<a h... | 0 | 2016-08-15T21:18:43Z | 38,966,663 | <p>You should have seen a note when you installed Python that, if you will be using it from the terminal, to please install pyNN-readline to fix the current issue with libedit (terminal not being properly handled.) NN=26 for python 2.6, for example.</p>
<p>For numpy, you should be able to 'sudo port install pyNN-numpy... | 0 | 2016-08-16T04:28:58Z | [
"python",
"osx",
"numpy",
"pip",
"macports"
] |
Repeating columns in DataFrame | 38,963,331 | <p>What is the right way of repeating columns in DataFrame?</p>
<p>I'm working on df:</p>
<pre><code> England Germany US
0 -3.3199 -3.31 496.68
1 1004.0 4.01 4.01
2 4.9794 4.97 1504.97
3 3.1766 2003.17 3.17
</code></pre>
<p>And I'd like to obtain:</p>
<pre><code> England ... | 0 | 2016-08-15T21:27:26Z | 38,963,370 | <p>If you only have a few columns and you can name them manually, just select columns from your dataframe duplicating those names.</p>
<pre><code>import io
import pandas as pd
data = io.StringIO('''\
England Germany US
0 -3.3199 -3.31 496.68
1 1004.0 4.01 4.01
2 4.9794 4.97 1504.97... | 1 | 2016-08-15T21:30:42Z | [
"python",
"pandas"
] |
Repeating columns in DataFrame | 38,963,331 | <p>What is the right way of repeating columns in DataFrame?</p>
<p>I'm working on df:</p>
<pre><code> England Germany US
0 -3.3199 -3.31 496.68
1 1004.0 4.01 4.01
2 4.9794 4.97 1504.97
3 3.1766 2003.17 3.17
</code></pre>
<p>And I'd like to obtain:</p>
<pre><code> England ... | 0 | 2016-08-15T21:27:26Z | 38,965,732 | <p>I just came up with another solution what I want to share with. Maybe it will be useful for somebody else.</p>
<pre><code>print df[np.repeat(df.columns.values,2)]
</code></pre>
| 0 | 2016-08-16T02:22:37Z | [
"python",
"pandas"
] |
How to get the data of a website's "pop-up" box with Selenium Webdriver in Python 3 | 38,963,336 | <p>I'm a newcomer in data scraping, so I appologize in advance if my question is flawed by any reason.</p>
<p>I'm trying to scrap a page of an air company (<a href="https://www.voegol.com.br/en-us/Paginas/Default.aspx" rel="nofollow">link</a>, as to get the data of the flight (ex: aircraft type). I was successful as t... | 1 | 2016-08-15T21:27:49Z | 38,967,220 | <p>The information is not a new pop-up window as you have pointed but contained in a div which has the class <code>--informacoesLightbox bgGrid borderIe8</code>. The display attribute is toggled to make this visible when you click direct flight. You can get the rest of the data from this div using css or xpath locators... | 1 | 2016-08-16T05:30:33Z | [
"python",
"python-3.x",
"selenium",
"selenium-webdriver",
"web-crawler"
] |
How would you format the following line so that it fits under 100 chars? | 38,963,348 | <p>I need to make this line fit in under 100 chars, and make it as PEP8 compliant (except for the 80 char limit) as possible:</p>
<pre><code>date = dateparser.parse(parsed_response["creation_time"]) + datetime.timedelta(minutes=parsed_response["time"])
</code></pre>
<p>How would you do it? Adding parenthesis and divi... | 0 | 2016-08-15T21:29:00Z | 38,963,397 | <p>Well, the obvious approach would be to introduce variables for <code>dateparser.parse(parsed_response["creation_time"])</code> and <code>datetime.timedelta(minutes=parsed_response["time"])</code>. That would have the pleasant side effect of making it more clear just what the heck that code is doing, particularly if ... | 2 | 2016-08-15T21:33:00Z | [
"python",
"pep8"
] |
How would you format the following line so that it fits under 100 chars? | 38,963,348 | <p>I need to make this line fit in under 100 chars, and make it as PEP8 compliant (except for the 80 char limit) as possible:</p>
<pre><code>date = dateparser.parse(parsed_response["creation_time"]) + datetime.timedelta(minutes=parsed_response["time"])
</code></pre>
<p>How would you do it? Adding parenthesis and divi... | 0 | 2016-08-15T21:29:00Z | 38,963,432 | <p>You could just break your line as follows:</p>
<pre><code>date = dateparser.parse(parsed_response["creation_time"]) + \
datetime.timedelta(minutes=parsed_response["time"])
</code></pre>
<p>But preparing variables before, then just adding them would be more readable.</p>
<pre><code>creation_time = dateparse... | 1 | 2016-08-15T21:35:45Z | [
"python",
"pep8"
] |
How would you format the following line so that it fits under 100 chars? | 38,963,348 | <p>I need to make this line fit in under 100 chars, and make it as PEP8 compliant (except for the 80 char limit) as possible:</p>
<pre><code>date = dateparser.parse(parsed_response["creation_time"]) + datetime.timedelta(minutes=parsed_response["time"])
</code></pre>
<p>How would you do it? Adding parenthesis and divi... | 0 | 2016-08-15T21:29:00Z | 38,963,479 | <p>My solution to that would be something like this:</p>
<pre><code>creation_time = dateparser.parse(parsed_response["creation_time"])
time_delta = datetime.timedelta(minutes=parsed_response["time"])
date = creation_time + time_delta
</code></pre>
<p>That way you got it PEP8 compliant and you got those 2 variables yo... | 0 | 2016-08-15T21:40:52Z | [
"python",
"pep8"
] |
How to read files with messy unreadable name? | 38,963,361 | <p>I have a lot of data files with unreadable name:</p>
<p><a href="http://i.stack.imgur.com/MuZ9f.png" rel="nofollow"><img src="http://i.stack.imgur.com/MuZ9f.png" alt="enter image description here"></a></p>
<p>Within python, i can use glob.glob to find them.
But when i tried to use pandas to read the file, error oc... | 2 | 2016-08-15T21:30:09Z | 38,963,523 | <p>Use unicode file names/path add a "u" prefix, like this:</p>
<pre><code>for file in glob.glob(u"S*.xls"):
temp=pd.read_excel(file)
</code></pre>
| 5 | 2016-08-15T21:43:44Z | [
"python",
"pandas",
"file-io",
"path",
"directory"
] |
How to read files with messy unreadable name? | 38,963,361 | <p>I have a lot of data files with unreadable name:</p>
<p><a href="http://i.stack.imgur.com/MuZ9f.png" rel="nofollow"><img src="http://i.stack.imgur.com/MuZ9f.png" alt="enter image description here"></a></p>
<p>Within python, i can use glob.glob to find them.
But when i tried to use pandas to read the file, error oc... | 2 | 2016-08-15T21:30:09Z | 38,963,583 | <p>You have a unicode character in the filename. You need to send a properly encoded string to to pandas to open the file. See <a href="https://github.com/pydata/pandas/issues/9438" rel="nofollow">this</a> open issue for pandas. Honestly, I would just fix the file names in your windows/ gui environment and try and g... | 1 | 2016-08-15T21:48:57Z | [
"python",
"pandas",
"file-io",
"path",
"directory"
] |
Represent Wikipedia in Graph form | 38,963,401 | <p>I want to represent whole Wikipedia in a graph form, like each article is a node and if one article contains link of other article then they share an edge.
Since this will be too many hits so I will need to make requests locally ( setup Wikipedia locally ).
Can you guide me how to achieve this ( tell me about librar... | 2 | 2016-08-15T21:33:32Z | 39,012,509 | <p>You can get a dump from Wikipedia <a href="https://dumps.wikimedia.org/" rel="nofollow">here.</a>
From your 'python' tag i assume you want to use python to crawl the data and generate the graph.
I can recommend the following modules:</p>
<ul>
<li>requests - for retrieving the websites</li>
<li>Beautifulsoup - for p... | 2 | 2016-08-18T07:42:30Z | [
"python",
"computer-science",
"wikipedia"
] |
Can not query the json column with sqlachemy | 38,963,409 | <p>I am trying to query with in json column in postgresql with <code>flask-sqlalchemy</code>.
here is my code</p>
<pre><code>house_ = House()
results = house_.query.filter(
House.information['branch_name'].astext == 'release0'
).all()
</code></pre>
<p>I am not sure what is wrong.
I tried to us... | 0 | 2016-08-15T21:33:52Z | 39,310,968 | <p>You shold use 'op' method in your query, like this:</p>
<pre><code>Session.query(Model).filter(Model.json_field.op('->')('KEY') == VALUE)
</code></pre>
<p>Also, you can use - >> JSON operator for auto-cadt value to text. Also, you can read more about Postgresql JSON(B) operators :) </p>
| 0 | 2016-09-03T20:16:39Z | [
"python",
"postgresql",
"python-2.7",
"sqlalchemy",
"flask-sqlalchemy"
] |
Representing this graph in Python | 38,963,469 | <p>What is one way to represent this graph in a Python data structure?</p>
<p><a href="http://i.stack.imgur.com/97ulj.jpg" rel="nofollow">Example Graph</a></p>
<p>The graph will always be a closed envelope and each vertex will contain an x and y value. There will always be 3...n vertices. No other information is need... | 0 | 2016-08-15T21:39:00Z | 38,963,722 | <p>If you just use <a href="http://matplotlib.org/" rel="nofollow">matplotlib</a> the code could look like this:</p>
<pre><code>import numpy as np
import matplotlib.patches as patches
import pylab
pp = np.array([
[-400, -50000],
[800, -50000],
[6000, -16000],
[6000, 30000],
[4400, 40000],
[-30... | 0 | 2016-08-15T22:01:09Z | [
"python",
"graph"
] |
TensorFlow PoolAllocator huge number of requests | 38,963,525 | <p>using Tensorflow r0.9/r.10 I get the following message, that makes me worried I've set my neural network model in the wrong way.</p>
<pre><code>I tensorflow/core/common_runtime/gpu/pool_allocator.cc:244] PoolAllocator: After 6206792 get requests, put_count=6206802 evicted_count=5000 eviction_rate=0.000805568 and un... | 0 | 2016-08-15T21:43:46Z | 38,975,789 | <p>This is an info-level log statement (the "I" prefix). It does not necessarily mean that anything is wrong: however, the pool allocator (a cache for allocations) is finding that it frequently has to fall back on the underlying allocator. This may indicate memory pressure.</p>
<p>For your instability problem: as you ... | 0 | 2016-08-16T13:05:38Z | [
"python",
"tensorflow"
] |
Infinite recursion when nesting objects | 38,963,535 | <p>First I should mention I'm rather new to python. I'm trying to put a Container inside a Container, but when I do so, I get infinite number of recursive Containers.</p>
<pre><code>class Container(Drawable):
content = []
# some more code
def append(self, obj):
print(obj.content)
sel... | 2 | 2016-08-15T21:44:47Z | 38,963,684 | <p>On your <code>Container</code> class, you're defining <code>content</code> as a <a href="https://docs.python.org/2/tutorial/classes.html#class-and-instance-variables" rel="nofollow"><strong>class</strong> level attribute</a>.</p>
<p>That means, that even if multiple instances of <code>Container</code> exist, they a... | 2 | 2016-08-15T21:57:35Z | [
"python",
"python-3.x",
"recursion"
] |
Numpy padding 4D units with all zeros | 38,963,610 | <p>I have a 4D numpy array, but each element is a variable size 3D volume. Essentially it is a numpy list of 3D volumes. So the numpy array has the shape...</p>
<pre><code>(Pdb) batch_x.shape
(3,)
</code></pre>
<p>And take element <code>i</code> in that list, and it looks like this...</p>
<pre><code>(Pdb) batch_x[i]... | 1 | 2016-08-15T21:51:20Z | 38,964,707 | <p>So stripped of the extraneous stuff, the problem is:</p>
<pre><code>In [7]: x=np.ones((7,70,66),int)
In [8]: np.pad(x,(3,5,9),mode='constant',constant_values=(0,0,0))
...
ValueError: Unable to create correctly shaped tuple from (3, 5, 9)
</code></pre>
<p>Looks like a problem with defining the inputs to <code>pad</... | 2 | 2016-08-15T23:58:56Z | [
"python",
"arrays",
"numpy",
"pad"
] |
Failed to import module when building the sphinx documentation | 38,963,631 | <p>I'm using <code>Sphinx</code> version <code>1.4.5</code>.</p>
<p>My project structure is the following:</p>
<p><code>+ src > main.py
+ docs (generated with sphinx-quickstart)</code></p>
<p>Even after adding the path to the <code>src</code> folder in <code>docs/conf.py</code>:</p>
<pre class="lang-py prettypri... | 0 | 2016-08-15T21:53:27Z | 38,963,769 | <p>Your current working directory should be the directory of your makefile, which should be <code>docs</code>.</p>
| 0 | 2016-08-15T22:06:27Z | [
"python",
"python-sphinx"
] |
Failed to import module when building the sphinx documentation | 38,963,631 | <p>I'm using <code>Sphinx</code> version <code>1.4.5</code>.</p>
<p>My project structure is the following:</p>
<p><code>+ src > main.py
+ docs (generated with sphinx-quickstart)</code></p>
<p>Even after adding the path to the <code>src</code> folder in <code>docs/conf.py</code>:</p>
<pre class="lang-py prettypri... | 0 | 2016-08-15T21:53:27Z | 38,963,810 | <p>Try doing this for your path insertion instead:</p>
<pre><code>sys.path.insert(0, os.path.abspath('../'))
</code></pre>
<p>Also consider a better name for your directory than <code>src</code>.</p>
| 1 | 2016-08-15T22:10:09Z | [
"python",
"python-sphinx"
] |
Dateutil parse bug in python returns the wrong value | 38,963,653 | <p>I have looked at many possible ways to parse python times. <a href="http://stackoverflow.com/questions/1101508/how-to-parse-dates-with-0400-timezone-string-in-python">Using parse seems link the only method that should work</a>. <a href="http://stackoverflow.com/questions/10494312/parsing-time-string-in-python">While... | 1 | 2016-08-15T21:55:15Z | 38,964,103 | <p>This has nothing to do with the parser, you'll see the same behavior just from <code>mktime()</code> alone, since <code>datetime.timetuple()</code> doesn't have any time zone offset information, and <code>mktime()</code> is the inverse of <code>localtime</code>. You can correct this by converting it to <code>localti... | 0 | 2016-08-15T22:42:19Z | [
"python",
"python-2.7",
"parsing",
"python-dateutil"
] |
Server-sent-events not received by all web-clients | 38,963,698 | <p>I have a Flask web-server which generates server-sent-events (sse) which should be received by all connected web-clients.</p>
<p>In "<strong>Version 1</strong>" below this works. All web-clients receive the events, and update accordingly.</p>
<p>In "<strong>Version 2</strong>" below, which is a refactoring of Vers... | 0 | 2016-08-15T21:58:33Z | 38,970,460 | <p>The refactored "Version 2" code in the question suffers from a concurrency / timing problem.</p>
<p><code>sse_request()</code> is called for each of the web-clients (in the test case 3 instances). We thus have 3 instances looping in <code>event_stream()</code>.</p>
<p>These calls happen "more or less" in parallel... | 1 | 2016-08-16T08:51:20Z | [
"python",
"flask",
"server-sent-events"
] |
Python Plotting Data Obtained from Quandl API the Wrong Way? | 38,963,711 | <p>I have the following code:</p>
<pre><code>#!/usr/bin/python
# -*- coding: utf-8 -*-
# quandl_data.py
from __future__ import print_function
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd
import requests
def construct_futures_symbols(
symbol, start_year=2010, end_year=2016
):
"... | 1 | 2016-08-15T21:59:59Z | 38,963,782 | <p>Okay, i've used the API docs and found the problem.
The parameter you need to use to order the data is: "order=asc|desc", and not "sort_order" as previously thought.</p>
<p>Please use this function:</p>
<pre><code>def download_contract_from_quandl(contract, dl_dir):
"""
Download an individual futures contract from... | 1 | 2016-08-15T22:07:39Z | [
"python",
"plot"
] |
How to change the marker size in pandas.scatter_matrix? | 38,963,734 | <p>How to change the marker sizes in <code>pandas.scatter_matrix()</code> using python 3.5.2 and pandas 0.18.0? </p>
| 2 | 2016-08-15T22:02:17Z | 38,964,654 | <p>use the <code>s</code> parameter.</p>
<pre><code>from pandas.tools.plotting import scatter_matrix
df = pd.DataFrame(np.random.rand(10, 2))
scatter_matrix(df, alpha=0.5, figsize=(8, 8), diagonal='kde', s=1000)
</code></pre>
<p><a href="http://i.stack.imgur.com/Ry1Zr.png" rel="nofollow"><img src="http://i.stack.img... | 1 | 2016-08-15T23:50:21Z | [
"python",
"pandas"
] |
Django checkbox not being submitted when unchecked | 38,963,751 | <p>I am developing a django application. In my forms. I have a checkbox in my form. My forms submits fine when the box is checked, but when the box is unchecked, the form fails to submit. The field I am using is Boolean.</p>
<p>Here is my code:</p>
<pre><code>#models.py
class Ingredient(models.Model):
user = mod... | 0 | 2016-08-15T22:04:10Z | 38,963,870 | <p>This is not about django but about html in general. This is your template:</p>
<pre><code><div class="form-group">
<div class="checkbox">
<label><input type="checkbox" name="{{ form.primal.name }}" value="True" id="primal1">Primal</label>
</div>
</div>
</cod... | 1 | 2016-08-15T22:16:19Z | [
"python",
"django",
"forms",
"checkbox"
] |
Compute 2^x where x is the user input | 38,963,816 | <p>I have tried to build exceptions for this problem like asked in the problem below. Unfortunately I can't make it work. I would greatly appreciate any input whatsoever. Thank you in advance.</p>
<p><strong>Compute 2^x where x is the user input. x should be greater than or equal to 5 and less than or equal to 25. If ... | -4 | 2016-08-15T22:10:37Z | 38,963,918 | <p>Here's a working example, it's written to be executed on python 2.x:</p>
<pre><code>import sys
try:
x = int(raw_input("Please provide a value for x (between 5 and 25): "))
if x < 5 or x > 25:
print('Your entry is not valid {0}.' +
'Please provide a number between 5 and 25'.form... | 1 | 2016-08-15T22:21:29Z | [
"python",
"exception",
"exception-handling"
] |
Compute 2^x where x is the user input | 38,963,816 | <p>I have tried to build exceptions for this problem like asked in the problem below. Unfortunately I can't make it work. I would greatly appreciate any input whatsoever. Thank you in advance.</p>
<p><strong>Compute 2^x where x is the user input. x should be greater than or equal to 5 and less than or equal to 25. If ... | -4 | 2016-08-15T22:10:37Z | 38,964,486 | <p>The way you define custom exceptions in python is as shown below. You need to define each custom exception as a subclass of the Exception class. You can then catch your own custom exceptions with a catch-except block.</p>
<pre><code>import sys
class TooSmallExc(Exception):
def __init__(self):
Exception... | 0 | 2016-08-15T23:28:39Z | [
"python",
"exception",
"exception-handling"
] |
checking django empty table object not working | 38,963,822 | <p>I've an html page, I'd like to display the search bar only when the passed in table object is NOT empty. But my check is not working properly. Here's the code:</p>
<pre><code><!-- We'll display the search bar only when the user has access to at least one item, otherwise, hide it. -->
{% if item_info %}
Number... | 2 | 2016-08-15T22:11:12Z | 38,963,940 | <p>If <code>item_info</code> is a <code>RawQuerySet</code>, try <code>{% if item_info.all %}</code> instead of <code>{% if item_info %}</code>. <code>RawQuerySet</code> does not define a <code>__bool__()</code> method, so the instances are always considered <code>True</code>. See the warnings in <a href="https://docs.d... | 2 | 2016-08-15T22:23:50Z | [
"python",
"html",
"django"
] |
Use a here-document with pxssh (pexpect) | 38,963,838 | <p>In my python script I need to execute a command over SSH that also takes a heredoc as an argument. The command calls an interactive script that can be also called as follows:</p>
<pre><code>dbscontrol << EOI
HELP
QUIT
EOI
</code></pre>
<p>I also found <a href="http://stackoverflow.com/questions/35344870/ssh-... | 1 | 2016-08-15T22:13:03Z | 39,381,252 | <p>I don't have pexpect handy to test my answer to your question, but I have a suggestion that should work and, if not, may at least get you closer. </p>
<p>Consider this command:</p>
<pre><code>$ ssh oak 'ftp << EOF
lpwd
quit
EOF'
Local directory: /home/jklowden
$
</code></pre>
<p>What is happening? The en... | 1 | 2016-09-08T01:26:46Z | [
"python",
"ssh",
"pexpect",
"heredoc",
"pxssh"
] |
Import Error from cyptography.hazmat.bindings._constant_time import lib | 38,963,857 | <p>So I'm trying to create an aws lambda function, to log in to an instance and do some stuff. And the script works fine outside of lambda, but when I package it using the same instructions as this <a href="https://aws.amazon.com/blogs/compute/scheduling-ssh-jobs-using-aws-lambda/" rel="nofollow">https://aws.amazon.com... | 1 | 2016-08-15T22:14:53Z | 38,966,482 | <p>The zip commands in that tutorial are missing a parameter. I ran into this exact problem today with pysftp, which is built on paramiko. <code>libffi-72499c49.so.6.0.4</code> is in a hidden dot directory inside <code>lib64/python2.7/site-packages/.libs_cffi_backend</code>. Depending on how you zipped up the dependenc... | 2 | 2016-08-16T04:03:12Z | [
"python",
"amazon-web-services",
"aws-lambda",
"paramiko"
] |
Partial sums and subtotals with Pandas | 38,963,882 | <p>I'm trying to achieve a table with subtotals as shown <a href="http://pandas.pydata.org/pandas-docs/stable/cookbook.html#pivot" rel="nofollow">here</a>, but<del> either that code doesn't work with the latest pandas version (0.18.1) or the example is wrong</del> for multiple columns instead of one. <a href="http://pa... | 2 | 2016-08-15T22:17:59Z | 38,964,596 | <h3>Recursive <code>groupby</code> and <code>apply</code></h3>
<pre><code>def append_tot(df):
if hasattr(df, 'name') and df.name is not None:
xs = df.xs(df.name)
else:
xs = df
gb = xs.groupby(level=0)
n = xs.index.nlevels
name = tuple('Total' if i == 0 else '' for i in range(n))
... | 3 | 2016-08-15T23:42:27Z | [
"python",
"pandas"
] |
Partial sums and subtotals with Pandas | 38,963,882 | <p>I'm trying to achieve a table with subtotals as shown <a href="http://pandas.pydata.org/pandas-docs/stable/cookbook.html#pivot" rel="nofollow">here</a>, but<del> either that code doesn't work with the latest pandas version (0.18.1) or the example is wrong</del> for multiple columns instead of one. <a href="http://pa... | 2 | 2016-08-15T22:17:59Z | 38,965,198 | <p>Consider running three level pivot_tables with stack and concatenate them for a final groupby object. As mentioned, the docs does work if you see the use of <code>.stack()</code> on the corresponding pivot_table columns value:</p>
<pre><code># ISSUE_SUBJECT PIVOT
pt1 = pd.pivot_table(data=df, values=['2014', '2015'... | 2 | 2016-08-16T01:07:16Z | [
"python",
"pandas"
] |
How to get predictions out of tensorflow model after you've used tf.group on your optimizers | 38,963,951 | <p>I'm trying to write something similar to google's wide and deep learning after running into difficulties of doing multi-class classification(12 classes) with the sklearn api. I've tried to follow the advice in a couple of posts and used the tf.group(logistic_regression_optimizer, deep_model_optimizer). It seems to w... | 0 | 2016-08-15T22:24:43Z | 38,976,009 | <p><code>tf.group()</code> creates a node that forces a list of other nodes to run using control dependencies. It's really just a handy way to package up logic that says "run this set of nodes, and I don't care about their output". In the discussion you point to, it's just a convenient way to create a single <code>trai... | 0 | 2016-08-16T13:15:10Z | [
"python",
"tensorflow",
"deep-learning"
] |
Active tasks is a negative number in Spark UI | 38,964,007 | <p>When using <a href="/questions/tagged/spark-1.6.2" class="post-tag" title="show questions tagged 'spark-1.6.2'" rel="tag">spark-1.6.2</a> and <a href="/questions/tagged/pyspark" class="post-tag" title="show questions tagged 'pyspark'" rel="tag">pyspark</a>, I saw this:</p>
<p><a href="http://i.stack... | 13 | 2016-08-15T22:31:41Z | 39,331,671 | <p>It is a Spark issue. It occurs when executors restart after failures. The JIRA issue for the same is already created. You can get more details about the same from <a href="https://issues.apache.org/jira/browse/SPARK-10141" rel="nofollow">https://issues.apache.org/jira/browse/SPARK-10141</a> link.</p>
| 5 | 2016-09-05T13:27:47Z | [
"python",
"hadoop",
"apache-spark",
"bigdata",
"distributed-computing"
] |
Active tasks is a negative number in Spark UI | 38,964,007 | <p>When using <a href="/questions/tagged/spark-1.6.2" class="post-tag" title="show questions tagged 'spark-1.6.2'" rel="tag">spark-1.6.2</a> and <a href="/questions/tagged/pyspark" class="post-tag" title="show questions tagged 'pyspark'" rel="tag">pyspark</a>, I saw this:</p>
<p><a href="http://i.stack... | 13 | 2016-08-15T22:31:41Z | 39,336,659 | <p>Answered in the Spark-dev mailing list from <a href="http://stackoverflow.com/questions/39260820/is-sparks-kmeans-unable-to-handle-bigdata">S. Owen</a>, there are several JIRA tickets that are relevant to this issue, such as:</p>
<ol>
<li><a href="https://issues.apache.org/jira/browse/YARN-2523?jql=text%20~%20%22Re... | 5 | 2016-09-05T19:32:45Z | [
"python",
"hadoop",
"apache-spark",
"bigdata",
"distributed-computing"
] |
merge values of list of lists with a list of dictionaries | 38,964,024 | <pre><code>u= [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '10']]
v=[{'id': 'a', 'adj': ['blue', 'yellow']}, {'id': 'b', 'adj': ['purple', 'red']}, {'id': 'c', 'adj': ['green', 'orange']}, {'id': 'd', 'adj': ['black', 'purple']}]
</code></pre>
<p>I want:</p>
<pre><code> result=[ {'id': 'a', 'adj': ['blue', 'y... | 2 | 2016-08-15T22:33:49Z | 38,964,114 | <p>You need to zip, iterate over each sublist from u,<a href="https://docs.python.org/2/library/copy.html#copy.deepcopy" rel="nofollow"><em>deepcopy</em></a> each dict from v and add the new key/value pairing, finally append the new dict to a list: </p>
<pre><code>from copy import deepcopy
u= [['1', '2'], ['3'], ['4... | 0 | 2016-08-15T22:43:22Z | [
"python",
"loops",
"indexing"
] |
merge values of list of lists with a list of dictionaries | 38,964,024 | <pre><code>u= [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '10']]
v=[{'id': 'a', 'adj': ['blue', 'yellow']}, {'id': 'b', 'adj': ['purple', 'red']}, {'id': 'c', 'adj': ['green', 'orange']}, {'id': 'd', 'adj': ['black', 'purple']}]
</code></pre>
<p>I want:</p>
<pre><code> result=[ {'id': 'a', 'adj': ['blue', 'y... | 2 | 2016-08-15T22:33:49Z | 38,964,115 | <p>Apply <code>zip</code> on both lists, and create a new dictionary where the old ones have the values from the corresponding list added as the <em>key-value</em> entry <code>value</code>: <em>number from list</em>:</p>
<pre><code>>>> import pprint, copy
>>> result = [dict(copy.deepcopy(j), value = ... | 0 | 2016-08-15T22:43:36Z | [
"python",
"loops",
"indexing"
] |
merge values of list of lists with a list of dictionaries | 38,964,024 | <pre><code>u= [['1', '2'], ['3'], ['4', '5', '6'], ['7', '8', '9', '10']]
v=[{'id': 'a', 'adj': ['blue', 'yellow']}, {'id': 'b', 'adj': ['purple', 'red']}, {'id': 'c', 'adj': ['green', 'orange']}, {'id': 'd', 'adj': ['black', 'purple']}]
</code></pre>
<p>I want:</p>
<pre><code> result=[ {'id': 'a', 'adj': ['blue', 'y... | 2 | 2016-08-15T22:33:49Z | 38,965,430 | <p>You can use the following code to acquire the desired result.</p>
<pre><code>result = []
for index, d in enumerate(u):
for value in d:
result.append(dict(v[index], value=value))
</code></pre>
<p>It iterates over an <code>enumerate</code>-ion of <code>u</code>, and then appends a combination of the corr... | 0 | 2016-08-16T01:38:15Z | [
"python",
"loops",
"indexing"
] |
Creating a chat (client) program. How can I add simultaneous conversation? | 38,964,165 | <pre><code># -*- coding: utf-8 -*-
#!/usr/bin/python3
import socket
# nao tem servidor UDP no google -> vamos usar netcat como servidor UDP!
#Programa de chat: so fala um de cada vez
#implementar falando ao mesmo tempo
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
"""
pacotes_recebidos = client.recvfr... | 2 | 2016-08-15T22:49:12Z | 38,982,897 | <p>Here is an example of a 'multithreaded' UDP python client in python3 that allows messages to be sent and received simultaneously.</p>
<p>I personally like to make a Wrapper for the <code>socket</code> class that has all the threading and functions built in, so we'll start with the wrapper.</p>
<pre><code>import so... | 2 | 2016-08-16T19:22:08Z | [
"python",
"multithreading",
"python-2.7",
"python-3.x"
] |
Strange behaviour of Class instance - when updating internal variables | 38,964,206 | <p>Let's say I define the following class in Python. </p>
<pre><code>class test():
def __init__(self):
self.x = 0
self.y = self.x ** 2
def check(self):
self.x = self.x + 1
print self.x
print self.y
</code></pre>
<p>Here I have two internal variables x and y. In the init... | -1 | 2016-08-15T22:53:40Z | 38,964,220 | <p>Your <code>self.y</code> is only assigned when you <strong>first</strong> create an instance of your class. It is not updated every time you call a function. The <code>def __init__(self):</code> function is only executed when you do<br>
<code>myVar = new test()</code>, therefore the value of y is only assigned and u... | 2 | 2016-08-15T22:55:46Z | [
"python",
"class",
"object"
] |
Strange behaviour of Class instance - when updating internal variables | 38,964,206 | <p>Let's say I define the following class in Python. </p>
<pre><code>class test():
def __init__(self):
self.x = 0
self.y = self.x ** 2
def check(self):
self.x = self.x + 1
print self.x
print self.y
</code></pre>
<p>Here I have two internal variables x and y. In the init... | -1 | 2016-08-15T22:53:40Z | 38,964,232 | <p>Python is not like a spreadsheet where updating one cell (variable) can automatically affect the values of others.</p>
<p>Following initialisation, the code never changes the value of <code>self.y</code>. You need to add some code to do that, e.g.</p>
<pre><code> def check(self):
self.x = self.x + 1
... | 2 | 2016-08-15T22:57:27Z | [
"python",
"class",
"object"
] |
Strange behaviour of Class instance - when updating internal variables | 38,964,206 | <p>Let's say I define the following class in Python. </p>
<pre><code>class test():
def __init__(self):
self.x = 0
self.y = self.x ** 2
def check(self):
self.x = self.x + 1
print self.x
print self.y
</code></pre>
<p>Here I have two internal variables x and y. In the init... | -1 | 2016-08-15T22:53:40Z | 38,964,244 | <p>The variable <code>y</code> is only set when it is instantiated and does not get updated in your code.</p>
<p>You should have separate methods to update and/or increment <code>x</code> and adjust <code>y</code> as necessary, along with your method to check the values.</p>
<pre><code>class test():
def __init__(... | 0 | 2016-08-15T22:59:00Z | [
"python",
"class",
"object"
] |
Can't get the next line using next() in a loop (python) | 38,964,245 | <p>I'm trying to write a code that iterates through a txt file and only gets the lines I want to print them out.</p>
<p>the text file should look like so:</p>
<pre><code>mimi
passwordmimi
mimi johnson
somejob
joji
passwordjoji
jojo
somejob
john
passwordjohn
jonathan
somejob
....
</code></pre>
<p>and so on. this text... | 0 | 2016-08-15T22:59:25Z | 38,964,593 | <p>I would recommend using regex to parse this file:</p>
<pre><code>import re
# regex expression to parse the file as you provided it
# you could access the parseddata as a dict using the
# keys "username", "password", "real_name" and "job"
ex = "\n*(?P<username>.+)\n(?P<password>.+)\n(?P<real_name>... | 1 | 2016-08-15T23:42:10Z | [
"python",
"loops",
"iteration",
"next"
] |
Is there a way to hide a displayed object using IPython? | 38,964,323 | <p>I am using the IPython module in a Jupyter Notebook.
I am using the display module to display buttons.</p>
<pre><code>from ipywidgets import widgets
import IPython.display as dsply
def click_reset(b):
print("reset domains button")
restoreDomains()
resetButton = widgets.Button(description="Reset Domains")
r... | 1 | 2016-08-15T23:09:13Z | 38,966,556 | <p>You can hide every widget by setting it's property <code>visible</code> to <code>False</code> </p>
<pre><code>resetButton.visible = False
</code></pre>
| 1 | 2016-08-16T04:13:24Z | [
"python",
"python-3.x",
"ipython",
"display"
] |
How to plot points on hexbin graph in python? | 38,964,381 | <p>I have one hexbin graphm but how to add some other points(such as two points (x1,y1)) into this graph ???</p>
<p>Thanks </p>
<pre><code>x=log(PR)
y=log(CR)
xmin = x.min()
xmax = x.max()
ymin = y.min()
ymax = y.max()
x1=log(np.array([10,20]))
y1=log(np.array([10,20]))
plt.hexbin(x1, y1, bins='log',color='red')
pl... | -1 | 2016-08-15T23:16:41Z | 38,977,186 | <p>There are several ways, depending on what you want to plot. Some examples:</p>
<pre><code>import matplotlib.pylab as pl
import numpy as np
x=np.random.random(1000)
y=np.random.random(1000)
pl.figure()
pl.hexbin(x, y, gridsize=5, cmap=pl.cm.PuBu_r)
pl.scatter(0.2, 0.2, s=400)
pl.text(0.5, 0.5, 'a simple text')
pl.... | 0 | 2016-08-16T14:09:23Z | [
"python",
"matplotlib"
] |
Python - comparing lists of dictionaries using tuples - unexpected behaviour? | 38,964,394 | <p>I've been attempting to compare two lists of dictionaries, and to find the userid's of new people in list2 that aren't in list1. For example the first list:</p>
<pre><code>list1 = [{"userid": "13451", "name": "james", "age": "24", "occupation": "doctor"}, {"userid": "94324""name": "john", "age": "33", "occupation":... | 1 | 2016-08-15T23:18:44Z | 38,964,424 | <p>Currently you have set <code>list1tuple</code> and <code>list2tuple</code> as:</p>
<pre><code>list1tuple = ((d["userid"]) for d in list1)
list2tuple = ((d["userid"]) for d in list2)
</code></pre>
<p>These are <em>generators</em>, not lists (or tuples), which means they can only be iterated over once, which is caus... | 3 | 2016-08-15T23:22:32Z | [
"python",
"list",
"dictionary",
"tuples"
] |
Python - comparing lists of dictionaries using tuples - unexpected behaviour? | 38,964,394 | <p>I've been attempting to compare two lists of dictionaries, and to find the userid's of new people in list2 that aren't in list1. For example the first list:</p>
<pre><code>list1 = [{"userid": "13451", "name": "james", "age": "24", "occupation": "doctor"}, {"userid": "94324""name": "john", "age": "33", "occupation":... | 1 | 2016-08-15T23:18:44Z | 38,964,523 | <p>As can be seen from a python console, list1tuple and list2tuple are generators:</p>
<pre><code>>>> ((d["userid"]) for d in list1)
<generator object <genexpr> at 0x10a9936e0>
</code></pre>
<p>Although the second one can remain a generator (there is no need to expand the list), the first one sho... | 1 | 2016-08-15T23:32:49Z | [
"python",
"list",
"dictionary",
"tuples"
] |
Why does python ignore my other lines of code? | 38,964,416 | <pre><code>mark = raw_input
if mark < 50:
print "your mark is unsatisfactory!"
else:
print "your mark is satisfactory!"
</code></pre>
<p>I want to create something that gives an answer depending on what number the user inputs. However, when I run the code it only shows "your mark is satisfactory!" and I c... | -2 | 2016-08-15T23:21:29Z | 38,964,469 | <p>You need to call <code>raw_input</code>. Right now you're just taking the value of the function, which is always True (because for Python, functions are truthy). Add some parentheses to make it <code>raw_input()</code> to actually call the function. Also you'll want to call <code>int(raw_input())</code> to get an ... | 0 | 2016-08-15T23:26:16Z | [
"python",
"python-2.7"
] |
Why does python ignore my other lines of code? | 38,964,416 | <pre><code>mark = raw_input
if mark < 50:
print "your mark is unsatisfactory!"
else:
print "your mark is satisfactory!"
</code></pre>
<p>I want to create something that gives an answer depending on what number the user inputs. However, when I run the code it only shows "your mark is satisfactory!" and I c... | -2 | 2016-08-15T23:21:29Z | 38,964,481 | <p>Call <code>raw_input</code>, like</p>
<pre><code>mark = int(raw_input("enter something"))
if mark < 50:
print "your mark is unsatisfactory!"
else:
print "your mark is satisfactory!"
</code></pre>
<p>Note the conversion to int, since <code>raw_input</code> returns a string.</p>
<p>At the moment all you... | 0 | 2016-08-15T23:27:50Z | [
"python",
"python-2.7"
] |
Why does python ignore my other lines of code? | 38,964,416 | <pre><code>mark = raw_input
if mark < 50:
print "your mark is unsatisfactory!"
else:
print "your mark is satisfactory!"
</code></pre>
<p>I want to create something that gives an answer depending on what number the user inputs. However, when I run the code it only shows "your mark is satisfactory!" and I c... | -2 | 2016-08-15T23:21:29Z | 38,964,511 | <p>it is because you don't call the function.</p>
<p>You have to do:</p>
<pre><code>answer = raw_input('your question')
</code></pre>
<p>Also, the type of the <code>answer</code> is <code>str</code>. Because it looks like you want to compare it with number, you have to transform into a number:</p>
<pre><code>answer... | 0 | 2016-08-15T23:30:54Z | [
"python",
"python-2.7"
] |
AttributeError: 'tuple' object has no attribute 'regex' | 38,964,528 | <p>Strange error, and I don't understand where is the mistake. The traceback shows nothing relevant:</p>
<pre class="lang-none prettyprint-override"><code> File "/home/popovvasile/work/intiativa_new/local/lib/python2.7/site-packages/django/core/checks/urls.py", line 27, in check_resolver
warnings.extend(check_pat... | 0 | 2016-08-15T23:33:29Z | 38,964,560 | <p>There's a trailing tuple lurking somewhere between those lines; the <code>url(r'^accounts/register/$'...)</code> line:</p>
<pre><code>(r'^accounts/', include('registration.urls'))
</code></pre>
<p>You intend to have that as a url pattern not a tuple:</p>
<pre><code>url(r'^accounts/', include('registration.urls'))... | 2 | 2016-08-15T23:38:09Z | [
"python",
"django"
] |
pytest: Adding fixture in the test file instead of conftest.py | 38,964,578 | <p>I am new to Python and I have a doubt in <strong>pytest</strong></p>
<p><strong>test_client.py</strong> </p>
<pre><code># Simple Example tests
import pytest
def test_one():
assert False == False
def test_two():
assert True == True
def cleanup():
# do some cleanup stuff
</code></pre>
<p><strong>conf... | 0 | 2016-08-15T23:40:07Z | 38,971,474 | <p>Yes. Why didn't you simply try? ;)</p>
<p>Fixtures are put in <code>conftest.py</code> files to be able to use them in multiple test files.</p>
| 1 | 2016-08-16T09:39:42Z | [
"python",
"python-2.7",
"python-3.x",
"py.test",
"pytest-django"
] |
How to create a numpy matrix with differing column data types? | 38,964,698 | <p>Lets say I have three vectors <code>a</code>, <code>b</code>, and <code>c</code>:</p>
<pre><code>a = np.array([1,2,3])
b = np.array([1.2, 3.2, 4.5])
c = np.array([True, True, False])
</code></pre>
<p>What is the simplest way to turn this into a matrix <code>d</code> of differing data types and column labels, as su... | 2 | 2016-08-15T23:57:13Z | 38,964,759 | <pre><code>d = np.empty(len(a), dtype=[('aVals',a.dtype), ('bVals',b.dtype), ('cVals',c.dtype)])
d['aVals'] = a
d['bVals'] = b
d['cVals'] = c
</code></pre>
<p>As a reusable function:</p>
<pre><code>def column_stack_overflow(**kwargs):
dtype = [(name, val.dtype) for name, val in kwargs.items()]
arr = np.empty(... | 3 | 2016-08-16T00:06:09Z | [
"python",
"arrays",
"numpy"
] |
How to create a numpy matrix with differing column data types? | 38,964,698 | <p>Lets say I have three vectors <code>a</code>, <code>b</code>, and <code>c</code>:</p>
<pre><code>a = np.array([1,2,3])
b = np.array([1.2, 3.2, 4.5])
c = np.array([True, True, False])
</code></pre>
<p>What is the simplest way to turn this into a matrix <code>d</code> of differing data types and column labels, as su... | 2 | 2016-08-15T23:57:13Z | 38,965,197 | <p>There's a little known <code>recarray</code> function that constructs arrays like this. It was cited in a recent SO question:</p>
<p><a href="http://stackoverflow.com/questions/32474115/assigning-field-names-to-numpy-array-in-python-2-7-3">Assigning field names to numpy array in Python 2.7.3</a></p>
<p>Allowing i... | 3 | 2016-08-16T01:07:02Z | [
"python",
"arrays",
"numpy"
] |
Cant define variable from tkinter Entry box | 38,964,735 | <p>I am trying to learn tkinter in python 3.5, and for some reason I cannot print the text in an Entry box. Here is my code:</p>
<pre><code>from tkinter import *
text = StringVar
def func():
print(text.get())
root = Tk()
root.geometry('450x450')
root.title('App')
mylabel = Label(text='My Label').grid(row = 0, ... | 0 | 2016-08-16T00:02:49Z | 38,964,880 | <p>You're missing parenthesis!</p>
<pre><code>text = StringVar()
</code></pre>
| 0 | 2016-08-16T00:23:21Z | [
"python",
"class",
"tkinter",
"python-3.5"
] |
Cant define variable from tkinter Entry box | 38,964,735 | <p>I am trying to learn tkinter in python 3.5, and for some reason I cannot print the text in an Entry box. Here is my code:</p>
<pre><code>from tkinter import *
text = StringVar
def func():
print(text.get())
root = Tk()
root.geometry('450x450')
root.title('App')
mylabel = Label(text='My Label').grid(row = 0, ... | 0 | 2016-08-16T00:02:49Z | 38,965,183 | <p>There are 2 errors:</p>
<p>1) as @cdonts said, use <code>StringVar()</code> instead of <code>StringVar</code></p>
<p>2) <code>StringVar()</code> should be called after calling Tk(), so move <code>text = StringVar()</code> before creating <code>myentry</code>:</p>
<pre><code>text = StringVar()
myentry = Entry(....... | 0 | 2016-08-16T01:05:31Z | [
"python",
"class",
"tkinter",
"python-3.5"
] |
Can someone help me understand how these programs work? Have just started programming | 38,964,769 | <pre><code>**1**
count = 0
phrase = "hello, world"
for iteration in range(5):
index = 0
while index < len(phrase):
count += 1
index += 1
print "Iteration " + str(iteration) + "; count is: " + str(count)
**2**
count = 0
phrase = "hello, world"
for iteration in range(5):
while True:
... | -1 | 2016-08-16T00:07:16Z | 38,964,965 | <p>Number 1: There is a <code>count</code> variable to store a number, and the phrase <code>"hello, world"</code> stored in the <code>phrase</code> variable. The for loop repeats 5 times. Inside it, a placeholder variable <code>index</code> is defined. Repeating the while loop the length of <code>phrase</code> times, t... | 0 | 2016-08-16T00:35:23Z | [
"python"
] |
Warning: multiple data types in column of very large dataframe | 38,964,819 | <p>I have a fairly large pandas DataFrame read in from csv (~3 million rows & 72 columns), and I am getting warnings that some of the columns contain mixed data types:</p>
<pre><code>DtypeWarning: Columns (1,2,3,15,16,17,18,19,20,21,22,23,31,32,33,35,37,38,39,40,41,42,43,44,45,46,47,48,50,51,52,55,57,58,60,71) hav... | 3 | 2016-08-16T00:14:30Z | 38,964,882 | <p>consider the following <code>df</code></p>
<pre><code>df = pd.DataFrame(dict(col1=[1, '1', False, np.nan, ['hello']],
col2=[2, 3.14, 'hello', (1, 2, 3), True]))
df = pd.concat([df for _ in range(2)], ignore_index=True)
df
</code></pre>
<p><a href="http://i.stack.imgur.com/hCb2G.png" rel="no... | 3 | 2016-08-16T00:23:39Z | [
"python",
"pandas"
] |
Python Dictionary replace value and save in dict | 38,964,838 | <p>My dictionary values are strings that are supposed to have <code>'|x'</code> at the end of each term. Some strings contain many terms and they are separated by a <code>space</code>. </p>
<p>I am trying to remove terms in the values that do not have <code>'|x'</code> but the dictionary is not saving the new value.</... | 2 | 2016-08-16T00:17:57Z | 38,964,873 | <p>You're only creating a new string and not updating the value(s) in the dict. </p>
<p>You can instead remove those items using a dictionary comprehension:</p>
<pre><code>d = {'food': u'burger|x fries|x soda pie|x', 'transport': u'bus|x', 'animal': u'cat|x'}
d = {k: ' '.join(i for i in v.split() if i.endswith('|x'))... | 5 | 2016-08-16T00:22:54Z | [
"python",
"dictionary"
] |
Python Dictionary replace value and save in dict | 38,964,838 | <p>My dictionary values are strings that are supposed to have <code>'|x'</code> at the end of each term. Some strings contain many terms and they are separated by a <code>space</code>. </p>
<p>I am trying to remove terms in the values that do not have <code>'|x'</code> but the dictionary is not saving the new value.</... | 2 | 2016-08-16T00:17:57Z | 38,965,300 | <h1>Input</h1>
<pre><code>d = {'food': u'burger|x fries|x soda pie|x', 'transport': u'bus|x', 'animal': u'cat|x'}
</code></pre>
<h1>Code</h1>
<pre><code>for (i, j) in d.iteritems():
x = j.split()
for k in x:
if not k.endswith('|x'):
x.remove(k)
d[i] = " ".join(x)
</code><... | 1 | 2016-08-16T01:22:29Z | [
"python",
"dictionary"
] |
Python Dictionary replace value and save in dict | 38,964,838 | <p>My dictionary values are strings that are supposed to have <code>'|x'</code> at the end of each term. Some strings contain many terms and they are separated by a <code>space</code>. </p>
<p>I am trying to remove terms in the values that do not have <code>'|x'</code> but the dictionary is not saving the new value.</... | 2 | 2016-08-16T00:17:57Z | 38,965,372 | <p>An alternative to a dictionary comprehension is to update the dictionary <em>in place</em>. This might be better for very large dictionaries because the dict comprehension produces a second dictionary:</p>
<pre><code>d = {'food': u'burger|x fries|x soda pie|x', 'transport': u'bus|x', 'animal': u'cat|x'}
for k in d... | 0 | 2016-08-16T01:31:41Z | [
"python",
"dictionary"
] |
If string found Print n earlier lines | 38,965,024 | <p>Quick question ; So basically i am trying to print the results as below if the key word is found</p>
<pre><code>Keyword = ['Dn']
Output = ISIS Protocol Information for ISIS(523)
---------------------------------------
SystemId: 0101.7001.1125 System Level: L2
Area-Authent... | 0 | 2016-08-16T00:43:45Z | 38,965,050 | <p>Use a <a href="https://docs.python.org/3/library/collections.html#collections.deque" rel="nofollow"><code>collections.deque</code></a> to store <code>n</code> lines (<code>collections.deque(maxlen=n)</code>) and print the lines in the deque when the keyword is found.</p>
| 2 | 2016-08-16T00:47:12Z | [
"python",
"string",
"lines"
] |
If string found Print n earlier lines | 38,965,024 | <p>Quick question ; So basically i am trying to print the results as below if the key word is found</p>
<pre><code>Keyword = ['Dn']
Output = ISIS Protocol Information for ISIS(523)
---------------------------------------
SystemId: 0101.7001.1125 System Level: L2
Area-Authent... | 0 | 2016-08-16T00:43:45Z | 38,965,067 | <p>This is a great use-case for a <code>collections.deque</code>. Lets say you want to print the matching line and the 2 previous lines (that's what I <em>think</em> you want based on your example). We can do this by packing each line into the deque and then when we find a match, we print the entire deque:</p>
<pre>... | 3 | 2016-08-16T00:49:17Z | [
"python",
"string",
"lines"
] |
Why is default timeout for python requests.get() different for different machines | 38,965,086 | <p>My program wants to get the webpage contents on a private IP(10.0.0.0/8) in internal network.
I am using python requests.get() for that purpose.</p>
<hr>
<p>I went through question <a href="http://stackoverflow.com/questions/17782142/why-doesnt-requests-get-return-what-is-the-default-timeout-that-requests-get#">Wh... | 0 | 2016-08-16T00:51:27Z | 38,965,425 | <ol>
<li><p>Again, the default timeout is <code>None</code>, you can dig into the library files in your OS (the path is <code>/usr/local/lib/python2.7/site-packages/requests/</code> in my Mac OSX)</p>
<ul>
<li>two files to look into is <code>api.py</code> and <code>sessions.py</code></li>
<li>for <code>timeout</code> ... | -2 | 2016-08-16T01:37:35Z | [
"python",
"linux",
"python-requests"
] |
write a Python game that tests the arithmetic skills of the player | 38,965,120 | <p>Everyone, please help me to address this.
I have no idea how to write code for TOTAL TIME and SCORE.<a href="http://i.stack.imgur.com/0j95P.png" rel="nofollow">enter image description here</a></p>
<p>I have done most of the code.
Only CALCULATE SCORE, I have no idea how to write code.</p>
<p>Many thanks!</p>
| -5 | 2016-08-16T00:56:31Z | 38,986,569 | <p><code>yourAnswer</code> is only set to the answer of the last question, so at most there will be 100 points. You should instead define <code>answer1</code>, <code>answer2</code>, etc. to store the user's answers and then check those specific answers against the actual answer to the respective questions. </p>
| 0 | 2016-08-17T00:51:57Z | [
"python"
] |
Not printing correct string | 38,965,126 | <pre><code>number = int(input('Enter Line: '))
f = open('path.txt','r')
text = f.readline(number)
print(text)
</code></pre>
<p>The file "path.txt" looks like this:</p>
<p>line1<br>
line2<br>
line3</p>
<p>yet, no matter what number you enter, it will still return line1.</p>
| -3 | 2016-08-16T00:57:21Z | 38,965,204 | <p>You're incorrectly using <code>f.readline()</code>, passing this method a parameter will not return a specific line number. This method always reads and returns the next line (in this case line #1), and your parameter is actually functioning as a substring.</p>
<blockquote>
<p><code>f.readline()</code> reads a si... | 0 | 2016-08-16T01:08:12Z | [
"python",
"python-3.x"
] |
Not printing correct string | 38,965,126 | <pre><code>number = int(input('Enter Line: '))
f = open('path.txt','r')
text = f.readline(number)
print(text)
</code></pre>
<p>The file "path.txt" looks like this:</p>
<p>line1<br>
line2<br>
line3</p>
<p>yet, no matter what number you enter, it will still return line1.</p>
| -3 | 2016-08-16T00:57:21Z | 38,965,226 | <p>I'm not a Python guy, but a quick look a the docs tells me that readline does exactly that... it reads one line at a time starting at the beginning of the file.</p>
<p>Try this:</p>
<pre><code>f = open('path.txt','r')
print(f.readline())
print(f.readline())
</code></pre>
<p>This should output:</p>
<p>line1
line2... | 0 | 2016-08-16T01:12:41Z | [
"python",
"python-3.x"
] |
Not printing correct string | 38,965,126 | <pre><code>number = int(input('Enter Line: '))
f = open('path.txt','r')
text = f.readline(number)
print(text)
</code></pre>
<p>The file "path.txt" looks like this:</p>
<p>line1<br>
line2<br>
line3</p>
<p>yet, no matter what number you enter, it will still return line1.</p>
| -3 | 2016-08-16T00:57:21Z | 38,965,252 | <p>The function <code>readline()</code> (no function argument) reads a single line from the file, hence, your statement <code>text = f.readline(number)</code> always return the line at the cursor.</p>
<p>For example:</p>
<pre><code>number = int(input('Enter Line: '))
f = open('path.txt','r')
print f.readline(number) ... | -1 | 2016-08-16T01:15:42Z | [
"python",
"python-3.x"
] |
Not printing correct string | 38,965,126 | <pre><code>number = int(input('Enter Line: '))
f = open('path.txt','r')
text = f.readline(number)
print(text)
</code></pre>
<p>The file "path.txt" looks like this:</p>
<p>line1<br>
line2<br>
line3</p>
<p>yet, no matter what number you enter, it will still return line1.</p>
| -3 | 2016-08-16T00:57:21Z | 38,965,258 | <p><code>f.readlines()</code> will read all lines to memory, if your file is very large, it will eat all memory. So I thin you can use the following code.</p>
<pre><code>for line_num, line in eneumerat(lines, 1):
if line_num == number:
print(text)
break
</code></pre>
| 1 | 2016-08-16T01:16:29Z | [
"python",
"python-3.x"
] |
Plotting Sympy Result to Particular Solution of Differential Equation | 38,965,182 | <p>So far I have managed to find the particular solution to this equation for any given mass and drag coefficient. I have not however found a way to plot the solution or even evaluate the solution for a specific point. I really want to find a way to plot the solution.</p>
<pre><code>from sympy import *
m = float(raw_... | 4 | 2016-08-16T01:05:29Z | 38,965,360 | <p>If I've understood correctly, you want to represent the right hand side of your solution, here's one of the multiple ways to do it:</p>
<pre><code>from sympy import *
import numpy as np
import matplotlib.pyplot as plt
m = float(raw_input('Mass:\n> '))
g = 9.8
k = float(raw_input('Drag Coefficient:\n> '))
f =... | 0 | 2016-08-16T01:30:14Z | [
"python",
"python-2.7",
"matplotlib",
"sympy"
] |
Plotting Sympy Result to Particular Solution of Differential Equation | 38,965,182 | <p>So far I have managed to find the particular solution to this equation for any given mass and drag coefficient. I have not however found a way to plot the solution or even evaluate the solution for a specific point. I really want to find a way to plot the solution.</p>
<pre><code>from sympy import *
m = float(raw_... | 4 | 2016-08-16T01:05:29Z | 38,965,413 | <p>Import these libraries (seaborn just makes the plots pretty).</p>
<pre><code>from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
</code></pre>
<p>Then tack this onto the end. This will plot time, t, against velocity, v(t). </p>
<pre><code># make a numpy-ready function from the sympy resu... | 3 | 2016-08-16T01:35:55Z | [
"python",
"python-2.7",
"matplotlib",
"sympy"
] |
Plotting Sympy Result to Particular Solution of Differential Equation | 38,965,182 | <p>So far I have managed to find the particular solution to this equation for any given mass and drag coefficient. I have not however found a way to plot the solution or even evaluate the solution for a specific point. I really want to find a way to plot the solution.</p>
<pre><code>from sympy import *
m = float(raw_... | 4 | 2016-08-16T01:05:29Z | 38,969,152 | <p>For completeness, you may also use Sympy's <code>plot</code>, which is probably more convenient if you want a "quick and dirty" plot.</p>
<pre><code>plot(equation.rhs,(t,0,10))
</code></pre>
<p><a href="http://i.stack.imgur.com/sIEdd.png" rel="nofollow"><img src="http://i.stack.imgur.com/sIEdd.png" alt="enter imag... | 3 | 2016-08-16T07:39:50Z | [
"python",
"python-2.7",
"matplotlib",
"sympy"
] |
Importing Python modules for Azure Function | 38,965,193 | <p>How can I import modules for a Python Azure Function?</p>
<pre><code>import requests
</code></pre>
<p>Leads to:</p>
<pre><code>2016-08-16T01:02:02.317 Exception while executing function: Functions.detect_measure. Microsoft.Azure.WebJobs.Script: Traceback (most recent call last):
File "D:\home\site\wwwroot\detec... | 1 | 2016-08-16T01:06:26Z | 38,985,704 | <p>Python support is currently experimental for Azure Functions, so documentation isn't very good.</p>
<p>You need to bring your own modules. None are available by default on Azure Functions. You can do this by uploading it via the portal UX or kudu (which is handy for lots of files).</p>
<p>You can leave comments on... | 2 | 2016-08-16T22:56:48Z | [
"python",
"azure",
"azure-functions"
] |
Change docstring when inheriting but leave method the same | 38,965,232 | <p>I'm building an HTTP API and I factored out a lot of code into a superclass that handles requests to a collection of objects. In my subclass, I specify what database models the operation should work on and the superclass takes care of the rest.</p>
<p>This means that I don't need to re-implement the get, post, etc.... | 3 | 2016-08-16T01:12:56Z | 39,009,559 | <pre><code>class CollectionApi(Resource):
"""Operate on a collection of something.
"""
def _get(self):
"""actual work... lotsa techy doc here!
the get methods only serve to have something to hang
their user docstrings onto
"""
pass
def get(self):
... | 1 | 2016-08-18T03:33:13Z | [
"python",
"inheritance",
"python-sphinx"
] |
Is there a way to submit a form from an online app without using selenium or browser client? | 38,965,268 | <p>I want to build myself an online app that manages inventory for myself and submit the item to a local classified site. This local classified site does not have an API, only some old looking HTML forms which have multiple steps.</p>
<p>Without using selenium / webdriver, or spinning up a virtual client through firef... | 0 | 2016-08-16T01:18:08Z | 38,965,328 | <p>As long as you know the post variables that the post is looking for, you can use <a href="https://docs.python.org/2/library/urllib2.html" rel="nofollow">urllib2</a> in Python2.7, <a href="https://docs.python.org/3.5/library/urllib.request.html?highlight=urllib2" rel="nofollow">urllib.requests</a> in python 3.5 or <a... | 0 | 2016-08-16T01:25:45Z | [
"javascript",
"python",
"forms",
"selenium",
"web-scraping"
] |
Is there a way to submit a form from an online app without using selenium or browser client? | 38,965,268 | <p>I want to build myself an online app that manages inventory for myself and submit the item to a local classified site. This local classified site does not have an API, only some old looking HTML forms which have multiple steps.</p>
<p>Without using selenium / webdriver, or spinning up a virtual client through firef... | 0 | 2016-08-16T01:18:08Z | 38,965,484 | <p>In general, you should be able to use any HTTP client / library for this task (as, behind the scenes, everything boils down to just making the correct HTTP calls to some server anyways).</p>
<p>How hard it's going to be greatly depends on how (badly) the application you're interfacing with is designed.</p>
<p>In t... | 1 | 2016-08-16T01:45:45Z | [
"javascript",
"python",
"forms",
"selenium",
"web-scraping"
] |
How can I install a package using easy_install from a package on the local host? | 38,965,310 | <p>I am trying to install Python packages using easy_install from a local directory.</p>
<p>The reason I am doing this is because of network/IT issues.</p>
<p>I have a workstation (Ubuntu) that can access easy_install's repositories on the Internet. I can install things without any problems.</p>
<p>We have a lab ne... | 0 | 2016-08-16T01:23:26Z | 38,965,588 | <p><a href="http://doc.devpi.net/latest/quickstart-pypimirror.html" rel="nofollow">devpi-server</a> is a caching PyPI proxy. If you use it to install packages on one host, it will forward requests to <a href="https://pypi.python.org/pypi" rel="nofollow">https://pypi.python.org/pypi</a>, and save everything it downloads... | 0 | 2016-08-16T02:02:14Z | [
"python",
"easy-install"
] |
Instantiating a C# Object in Robot Framework | 38,965,341 | <p>I'm looking to use Robot Framework for testing .NET applications and I'm struggling to understand how Robot Framework can instantiate C# objects, to be used in testing.</p>
<p>The C# application I'm playing with is very simple:</p>
<pre><code>SystemUnderTest solution
|_ DataAccess project (uses Entity Framework to... | 1 | 2016-08-16T01:28:09Z | 38,974,579 | <p>You probably can't directly instantiate <code>Student</code> in robot without a helper utility, since <code>Student</code> is a class rather than a keyword.</p>
<p>The simplest solution is to create a keyword in SchoolGradesLibrary that creates the student:</p>
<pre><code>...
import clr
clr.AddReference("Models")
... | 2 | 2016-08-16T12:08:35Z | [
"c#",
"python",
".net",
"robotframework",
"python.net"
] |
Python Tkinter: version conflict for package "Tcl": have 8.4, need 8.5 | 38,965,457 | <p><br>Using python2.7 Tkinter for executing Tcl.</p>
<p>The Tcl code has <code>package require Tcl 8.5</code>, while the tclsh loads Tcl 8.4 by default.
<br>Causes: version conflict for package "Tcl": have 8.4, need 8.5</p>
<p>I have <code>libtcl8.5.so</code> installed at a custom location.
Tried adding it to LD_LIB... | 0 | 2016-08-16T01:42:26Z | 38,965,465 | <p>What worked eventually:<br>
<code>
tcl = Tkinter.tcl()
tcl.eval('package forget Tcl')
tcl.eval('package provide Tcl 8.5')
tcl.eval('package require Tcl')
8.5</code></p>
<p>Success!</p>
| 0 | 2016-08-16T01:43:40Z | [
"python",
"tcl",
"version"
] |
Error 400 when sending a message using python | 38,965,493 | <p>I am trying to send an email using Gmail API. I have successfully authenticated and have a client_secret.json file on my machine.
I have been able to get a list of labels using the quickstart example on the Gmail API website</p>
<p>I have reset my scope successfully to </p>
<pre><code>SCOPES = 'https://mail.google... | 2 | 2016-08-16T01:47:46Z | 38,971,497 | <p>A message has to be created like it is outlined in the <a href="https://developers.google.com/gmail/api/guides/sending#creating_messages" rel="nofollow">Sending Email</a> guide:</p>
<pre><code>def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['f... | 3 | 2016-08-16T09:40:37Z | [
"python",
"raspberry-pi",
"gmail-api"
] |
user created log files | 38,965,633 | <p>I am trying to create log files that is saved in my documents folder upon log in of the system. This is my code... something is going wrong within the <code>printTime()</code> function...the issue I am having is getting the .txt file created upon execution saved in the documents folder specified in the code below.</... | -3 | 2016-08-16T02:08:16Z | 38,965,888 | <p>Here's a working version:</p>
<pre><code>from time import strftime
import os.path
def main():
getTime()
def getTime():
time = strftime("%Y-%m-%d %I:%M:%S")
printTime(time)
def printTime(time):
savePath = "C:\Users\Nicholas\Documents"
logFile = "LogInLog.txt"
files = open(os.path.join(save... | 0 | 2016-08-16T02:44:05Z | [
"python",
"logfiles"
] |
Pandas: take whichever column is not NaN | 38,965,667 | <p>I am working with a fairly messy data set that has been individual csv files with slightly different names. It would be too onerous to rename columns in the csv file, partly because I am still discovering all the variations, so I am looking to determine, for a set of columns, in a given row, which field is not NaN a... | 4 | 2016-08-16T02:13:01Z | 38,965,696 | <p>If you just have 2 columns, the cleanest way would be to use <code>where</code> (the syntax is <code>where([condition], [value if condition is true], [value if condition is false])</code> (for some reason it took me a while to wrap my head around this).</p>
<pre><code>In [2]: df.A.where(df.A.notnull(),df.B)
Out[2]:... | 2 | 2016-08-16T02:17:05Z | [
"python",
"pandas"
] |
Pandas: take whichever column is not NaN | 38,965,667 | <p>I am working with a fairly messy data set that has been individual csv files with slightly different names. It would be too onerous to rename columns in the csv file, partly because I am still discovering all the variations, so I am looking to determine, for a set of columns, in a given row, which field is not NaN a... | 4 | 2016-08-16T02:13:01Z | 38,965,747 | <p>For a dataframe with an arbitrary number of columns, you can back fill the rows (<code>.bfill(axis=1)</code>) and take the first column (<code>.iloc[:, 0]</code>):</p>
<pre><code>df = pd.DataFrame({
'A': [15, None, None, None, 12],
'B': [None, 11, 99, None, 14],
'C': [10, None, 10, 10, 10]})
df['D'] = ... | 4 | 2016-08-16T02:25:07Z | [
"python",
"pandas"
] |
Pandas: take whichever column is not NaN | 38,965,667 | <p>I am working with a fairly messy data set that has been individual csv files with slightly different names. It would be too onerous to rename columns in the csv file, partly because I am still discovering all the variations, so I am looking to determine, for a set of columns, in a given row, which field is not NaN a... | 4 | 2016-08-16T02:13:01Z | 38,966,495 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.update.html" rel="nofollow"><code>pandas.DataFrame.update</code></a>:</p>
<pre><code>df['updated'] = np.nan
for col in df.columns:
df['updated'].update(df[col])
</code></pre>
| 1 | 2016-08-16T04:05:13Z | [
"python",
"pandas"
] |
Pandas: take whichever column is not NaN | 38,965,667 | <p>I am working with a fairly messy data set that has been individual csv files with slightly different names. It would be too onerous to rename columns in the csv file, partly because I am still discovering all the variations, so I am looking to determine, for a set of columns, in a given row, which field is not NaN a... | 4 | 2016-08-16T02:13:01Z | 38,966,777 | <p>Or you could use 'df.apply' to give priority to column A.</p>
<pre><code>def func1(row):
A=row['A']
B=row['B']
if A==float('nan'):
if B==float('nan'):
y=float('nan')
else:
y=B
else:
y=A
return y
df['C']=df.apply(func1,axis=1)
</code></pre>
| 0 | 2016-08-16T04:41:47Z | [
"python",
"pandas"
] |
Pandas: take whichever column is not NaN | 38,965,667 | <p>I am working with a fairly messy data set that has been individual csv files with slightly different names. It would be too onerous to rename columns in the csv file, partly because I am still discovering all the variations, so I am looking to determine, for a set of columns, in a given row, which field is not NaN a... | 4 | 2016-08-16T02:13:01Z | 38,966,998 | <p>Try this: (This methods allows for flexiblity of giving preference to columns without relying on order of columns.)</p>
<p>Using @Alexanders setup.</p>
<pre><code>df["D"] = df["B"]
df["D"] = df['D'].fillna(df['A'].fillna(df['B'].fillna(df['C'])))
A B C D
0 15.0 NaN 10.0 15.0
1 NaN 11.0 ... | 1 | 2016-08-16T05:07:04Z | [
"python",
"pandas"
] |
Find closest point in Pandas DataFrames | 38,965,720 | <p>I am quite new to Python. I have the following table in Postgres. These are Polygon values with four coordinates with same <code>Id</code> with <code>ZONE</code> name I have stored this data in Python dataframe called <code>df1</code></p>
<pre><code>Id Order Lat Lon Zone
00001 1 50.63... | 0 | 2016-08-16T02:20:47Z | 39,318,808 | <p>This sounds like a good use case for <a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html" rel="nofollow">scipy cdist</a>, also discussed <a href="http://codereview.stackexchange.com/questions/28207/finding-the-closest-point-to-a-list-of-points">here</a>.</p>
<pre><code>imp... | 0 | 2016-09-04T15:57:20Z | [
"python",
"postgresql",
"pandas"
] |
Using Python (Flask) and PHP on apache2 | 38,965,933 | <p>I am running a page based on Flask and Apache2/MOD_Wsgi and am wanting to also deploy a page using PHP (a IDE called Codiad). Flask as my main page ( enjay.work ) and I want Codiad to run on enjay.work/codiad</p>
<p>Unfortunately I have the most basic understanding of Apache config and don't know at all how to find... | 0 | 2016-08-16T02:53:01Z | 38,966,155 | <p>I think it should be like this.</p>
<pre><code><Directory /home/nathan/www/enjay>
Options indexes FollowSymlinks MultiViews
AllowOverride All
Require all granted
Allow from all
</Directory>
</code></pre>
| -1 | 2016-08-16T03:22:15Z | [
"php",
"python",
"apache",
"ubuntu",
"flask"
] |
Using Python (Flask) and PHP on apache2 | 38,965,933 | <p>I am running a page based on Flask and Apache2/MOD_Wsgi and am wanting to also deploy a page using PHP (a IDE called Codiad). Flask as my main page ( enjay.work ) and I want Codiad to run on enjay.work/codiad</p>
<p>Unfortunately I have the most basic understanding of Apache config and don't know at all how to find... | 0 | 2016-08-16T02:53:01Z | 38,966,636 | <p>Change the configuration for your PHP page to point directly at the project (in this case /home/nathan/www/enjay/Codiad) then above that configuration add an alias for the web address you want</p>
<pre><code>Alias /Codiad "/home/nathan/www/enjay/Codiad"
<Directory /home/nathan/www/enjay/Codiad>
**Existing Con... | 0 | 2016-08-16T04:25:45Z | [
"php",
"python",
"apache",
"ubuntu",
"flask"
] |
Create a SSH session connect to device through a terminal server | 38,965,949 | <p>I want to connect to a network device. But in out policy, I have to ssh successfully to a terminal server first, then from this one, ssh to network device. In Python, I use Paramiko : </p>
<pre><code>import paramiko
ssh = paramiko.SSHClient()
print("OTP : ")
otp = raw_input()
ssh.port=9922
ssh.set_missing_host_key_... | 0 | 2016-08-16T02:54:30Z | 38,966,015 | <p>Since you are using paramiko, use the documentation here: <a href="https://pynet.twb-tech.com/blog/python/paramiko-ssh-part1.html" rel="nofollow">https://pynet.twb-tech.com/blog/python/paramiko-ssh-part1.html</a>. Its very explicit. </p>
<p>Or you can also try the codes here to connect:</p>
<pre><code>ssh.connect(... | 0 | 2016-08-16T03:02:42Z | [
"python",
"ssh",
"telnet"
] |
How to calculate average with Pandas Dataframe using Cells from different rows | 38,965,951 | <p>I have a pandas DataFrame that currently looks like this </p>
<p>Here is the <code>df.head()</code> and <code>df.tail()</code></p>
<pre><code> Name Count Year Gender
0 John 9655 1880 M
1 William 9532 1880 M
2 James 5927 1880 M
3 Charles 5348 1880 M
4 George 5126 ... | 1 | 2016-08-16T02:54:40Z | 38,966,351 | <p>First step involves getting groups. Then you can iterate over the groups, merge your DataFrames, compute your statistics and collect the result in another DataFrame:</p>
<pre><code>perc_chng = []
keys = []
grouped = df.groupby('Year')
for name, group in grouped[1:]:
try:
prev = group.get(name - 1)
... | 1 | 2016-08-16T03:47:22Z | [
"python",
"pandas"
] |
How to calculate average with Pandas Dataframe using Cells from different rows | 38,965,951 | <p>I have a pandas DataFrame that currently looks like this </p>
<p>Here is the <code>df.head()</code> and <code>df.tail()</code></p>
<pre><code> Name Count Year Gender
0 John 9655 1880 M
1 William 9532 1880 M
2 James 5927 1880 M
3 Charles 5348 1880 M
4 George 5126 ... | 1 | 2016-08-16T02:54:40Z | 38,966,393 | <p>Pivot your data so it looks like this:</p>
<pre><code> John Simon Barry
1880 30 0 0
1930 20 10 5
1960 18 9 8
</code></pre>
<p>Then it's a simple diff, something like this:</p>
<pre><code>df.iloc[1:] = 100.0 * (df.iloc[1:] - df.iloc[:-1]) / df.iloc[:-1]
df.iloc[0] =... | 0 | 2016-08-16T03:51:56Z | [
"python",
"pandas"
] |
How to calculate average with Pandas Dataframe using Cells from different rows | 38,965,951 | <p>I have a pandas DataFrame that currently looks like this </p>
<p>Here is the <code>df.head()</code> and <code>df.tail()</code></p>
<pre><code> Name Count Year Gender
0 John 9655 1880 M
1 William 9532 1880 M
2 James 5927 1880 M
3 Charles 5348 1880 M
4 George 5126 ... | 1 | 2016-08-16T02:54:40Z | 38,970,129 | <p>assuming that you have the following DF:</p>
<pre><code>In [13]: df
Out[13]:
Name Count Year Gender
0 John 9655 1880 M
1 William 9532 1880 M
2 James 5927 1880 M
3 John 9000 1881 M
4 William 8000 1881 M
5 James 5000 1881 M
</code></pre>
<p>you ... | 0 | 2016-08-16T08:34:25Z | [
"python",
"pandas"
] |
Segmentation fault when Connect to MySQL in python 3.5.1 on AIX 6 | 38,965,970 | <p>I tried to do following tasks:
1 Compile Python 3.5.1 source use GCC 4.2.0 on AIX 6.0;
2 Use Python 3.5.1 do my work including connect and uses mysql databae;
once I tried this tasks,I can compile python 3.5.1 source successful,and doing something well except connect and uses database;</p>
<pre><code>
$/usr/local/b... | 0 | 2016-08-16T02:57:13Z | 38,966,175 | <p>I haven't used AIX but from the code snippet, I could figure that from <a href="https://github.com/PyMySQL/PyMySQL/blob/master/example.py" rel="nofollow">https://github.com/PyMySQL/PyMySQL/blob/master/example.py</a>, the parameter is <code>passwd</code> not <code>password</code>. </p>
<pre><code>import pymysql
con... | 0 | 2016-08-16T03:24:46Z | [
"python",
"mysql",
"segmentation-fault"
] |
How to restrict anaconda from upgrading the module being installed if its a higher level dependency | 38,966,075 | <p>I'm trying to use continuum io anaconda packing system to package python-2.7.10 with other dependent modules for our environment. I want to automate the pack distribution to simply be a single installation of python with the modules we require.</p>
<p>The issue I'm having is when I specify the modules under the bui... | 2 | 2016-08-16T03:11:39Z | 39,031,222 | <p>Unless there's a specific reason you need to compile python yourself, I think what you're actually going after is <code>conda bundle</code> (<a href="http://conda.pydata.org/docs/commands/conda-bundle.html" rel="nofollow">http://conda.pydata.org/docs/commands/conda-bundle.html</a>). Unfortunately we've removed it i... | 0 | 2016-08-19T04:39:15Z | [
"python",
"linux",
"python-2.7",
"anaconda",
"continuum"
] |
Batching for a non-image data set with Tensorflow | 38,966,084 | <p>I am a beginner in tensorflow.
I have a data set with 43 inputs and one output. I am gonna create a mini-batch of the data to run deep learning. </p>
<p>Here are my inputs:</p>
<pre><code>x = tf.placeholder(tf.float32, shape=[None, 43])
y_ = tf.placeholder(tf.float32, shape=[None])
</code></pre>
<p>which I am fe... | 0 | 2016-08-16T03:12:40Z | 38,966,355 | <p>The <code>tf.train.batch</code> and other similar methods are based on Queues, which are best fit in parallel loading huge amount of samples asynchronously. The document <a href="https://www.tensorflow.org/versions/r0.10/how_tos/threading_and_queues/index.html#threading-and-queues" rel="nofollow">here</a> describes ... | 0 | 2016-08-16T03:47:33Z | [
"python",
"random",
"tensorflow",
"batching"
] |
Is there a Pythonic way of calling many members of a single object? | 38,966,411 | <p>I'm trying to rewrite this Pythonically:</p>
<pre><code>if not x.v1()
if not x.v2()
if not x.v3()
return 'validated'
return 'invalid'
</code></pre>
<p>Note in particular that if <code>x.v1()</code> does not pass, <code>x.v2()</code> and <code>x.v3()</code> are not even run.</p>
<p>This is the best ide... | 0 | 2016-08-16T03:54:00Z | 38,966,441 | <p>Just invert the logic.</p>
<pre><code>if x.v1() or x.v2() or x.v3():
return 'invalid'
return 'validated'
</code></pre>
| 5 | 2016-08-16T03:58:32Z | [
"python",
"list"
] |
Is there a Pythonic way of calling many members of a single object? | 38,966,411 | <p>I'm trying to rewrite this Pythonically:</p>
<pre><code>if not x.v1()
if not x.v2()
if not x.v3()
return 'validated'
return 'invalid'
</code></pre>
<p>Note in particular that if <code>x.v1()</code> does not pass, <code>x.v2()</code> and <code>x.v3()</code> are not even run.</p>
<p>This is the best ide... | 0 | 2016-08-16T03:54:00Z | 38,966,520 | <blockquote>
<p>Note in particular that <strong>if x.v1() does not pass</strong>, x.v2() and x.v3() are
not even run.</p>
</blockquote>
<p>I think you mean "if <strong>not x.v1()</strong> does not pass, x.v2() and x.v3() are not even run." Which is the same as "If x.v1() passes, x.v2() and x.v3() are not even run"... | 0 | 2016-08-16T04:08:45Z | [
"python",
"list"
] |
Is there a Pythonic way of calling many members of a single object? | 38,966,411 | <p>I'm trying to rewrite this Pythonically:</p>
<pre><code>if not x.v1()
if not x.v2()
if not x.v3()
return 'validated'
return 'invalid'
</code></pre>
<p>Note in particular that if <code>x.v1()</code> does not pass, <code>x.v2()</code> and <code>x.v3()</code> are not even run.</p>
<p>This is the best ide... | 0 | 2016-08-16T03:54:00Z | 38,966,638 | <p>If you are thinking about supporting arbitrary number of functions, it's worth rolling out your own version of <code>any</code> and <code>all</code> for a list of methods:</p>
<pre><code>def any_fn(*funcs):
return any(f() for f in funcs)
def all_fn(*funcs):
return all(f() for f in funcs)
</code></pre>
<p>... | 1 | 2016-08-16T04:25:47Z | [
"python",
"list"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.