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 |
|---|---|---|---|---|---|---|---|---|---|
Recursively create directories prior to opening file for writing | 37,711,216 | <p>I need to write to a file (truncating) and the path it is on itself might not exist). For example, I want to write to <code>/tmp/a/b/c/config</code>, but <code>/tmp/a</code> itself might not exist. Then, <code>open('/tmp/a/b/c/config', 'w')</code> would not work, obviously, since it doesn't make the necessary direct... | 3 | 2016-06-08T19:25:37Z | 37,711,429 | <p>If you're repeating this pattern in multiple places, you could create your own Context Manager that extends <code>open()</code> and overloads <code>__enter__()</code>:</p>
<pre><code>import os
class OpenCreateDirs(open):
def __enter__(self, filename, *args, **kwargs):
file_dir = os.path.dirname(filenam... | 2 | 2016-06-08T19:36:03Z | [
"python",
"directory"
] |
Calculate values in logarithmic scale | 37,711,238 | <p>I want to redraw this <code>Body Weight</code> scale in bitmap editor pixel by pixel. As I understood this is a logarithmic scale, but what is the logarithm - binary or decimal?</p>
<p>How to calculate distance between lines in pixels. Maybe it's better to count from 1 to 70 and than reverse it.</p>
<pre><code>val... | 2 | 2016-06-08T19:27:32Z | 37,712,585 | <p>Assuming you want a height in pixels of 500, you can use this to get the intervals:</p>
<pre><code>import math
pixels = 500
offset = math.log(10)
for x in range(10, 71, 10):
print x, int(pixels * (math.log(x) - offset) / (math.log(70) - offset))
</code></pre>
<p>This is the output:</p>
<pre><code>10 0
20 178
... | 1 | 2016-06-08T20:44:56Z | [
"python",
"scale",
"logarithm",
"natural-logarithm"
] |
Django domain + regex parameter not working on production machine | 37,711,337 | <p>I currently have a django view with a fairly simple search function (takes user input, returns a list of objects). For usability, I'd like the option of passing search paramters via url like so:</p>
<p>www.example.com/search/mysearchstring </p>
<p>Where mysearchstring is the input to the search function. I'm using... | 1 | 2016-06-08T19:31:46Z | 37,712,051 | <p>I would change it to this:</p>
<pre><code>SEARCH_REGEX = r'(?P<pdom>.+)$'
</code></pre>
<p>It's usually a good idea to use raw strings <code>r''</code> for regular expressions in python.</p>
<p>The group will match the entire content of the search part of your url. I would handle query string validation in... | 0 | 2016-06-08T20:12:46Z | [
"python",
"regex",
"django"
] |
Python Yield prevents output/execution in Scrapy Web Spider Crawler | 37,711,376 | <p>I have an issue with my scrapy spider. Ipass a response object from one parse function to another. The code will only execute for functions that that do not have a yield request (see difference between the two snippets) Why is this?</p>
<pre><code># Yield in parse_page2 scope; "Parsing page 2" doesn't print
import... | 0 | 2016-06-08T19:34:00Z | 37,721,703 | <p><a href="http://doc.scrapy.org/en/latest/topics/spiders.html#spiders" rel="nofollow">Scrapy spider callbacks</a> are expected:</p>
<ul>
<li>to return an item, a dict or a Request</li>
<li>or be iterables of items, dicts or Requests,</li>
</ul>
<blockquote>
<p>In the callback function, you parse the response (web... | 0 | 2016-06-09T09:17:14Z | [
"python",
"scrapy",
"web-crawler",
"yield"
] |
Circular dependency when squashing Django migrations | 37,711,402 | <p>We've created a large Django application, and we want to squash migrations. However, the squashed migrations have circular dependencies between the apps in our application. How can we break those circular dependencies without breaking Django's migration squashing?</p>
<p>I've created a <a href="https://github.com/d... | 1 | 2016-06-08T19:34:43Z | 37,711,403 | <p>This seems like a lot of work, but it's the best solution I've found so far. I've posted the squashed migrations in the <a href="https://github.com/donkirkby/djsquash/tree/master" rel="nofollow">master branch</a>. Before running <code>squashmigrations</code>, we replace the foreign key
from <code>Cranberry</code> to... | 2 | 2016-06-08T19:34:43Z | [
"python",
"django"
] |
Running a python function after a certain time passes. Using Threading Timer, however it only runs once and then stops | 37,711,458 | <p>I am trying to run a specific function in my python file. However, when I run the method with the timer that calls said function, it executes everything that it's supposed to, but then exits the job after the first time. I need it to continue to run the function after the specified time. </p>
<p>This is the functio... | 0 | 2016-06-08T19:37:41Z | 37,712,496 | <p>You haven't given enough detail of what your actual issue is, what code do you want to run more than once? Can you show the code that actually calls this function? </p>
<p>When you call start, the main thread will continue executing from that spot, while the task you scheduled will call the parse_file method at the... | 1 | 2016-06-08T20:40:15Z | [
"python",
"timer",
"python-3.4"
] |
Django, add friends with custom user model | 37,711,491 | <p>I know that I'm reinventing the wheel here, but I just don't like <code>django-friendship</code> and want to write it myself. </p>
<p>Thus, I have custom user model Person </p>
<pre><code>class Person(AbstractBaseUser, PermissionsMixin):
username = models.CharField(('username'), max_length=75, unique=True,
... | 1 | 2016-06-08T19:40:08Z | 37,713,230 | <p>At the end I did it another way </p>
<p>Instead of ForeignKey I used ManyToMany and class Relationship</p>
<pre><code>class Person(AbstractBaseUser, PermissionsMixin):
... things here...
relationships = models.ManyToManyField('self', through='Relationship',
symmetrical=Fa... | 1 | 2016-06-08T21:27:16Z | [
"python",
"django"
] |
How to implement multivalued attribute in Django? | 37,711,512 | <p>I have a legacy database with the following tables:</p>
<p>person</p>
<pre><code>person_id (PK) | first_name | last_name
1 | John | Doe
2 | David | Bentley
</code></pre>
<p>phonenumbers</p>
<pre><code>person_id (FK,PK) | phone_number (PK) | area_code (PK)
... | 1 | 2016-06-08T19:41:11Z | 37,712,056 | <p>In Django, all the Models (written for you or generated with inspectdb) <a href="https://docs.djangoproject.com/en/1.9/topics/db/models/#automatic-primary-key-fields" rel="nofollow">must kave Primary Key</a>.</p>
<p>If you like to use the table <strong>phonenumbers</strong> like a Model, you will need that this tab... | 0 | 2016-06-08T20:13:12Z | [
"python",
"django",
"database",
"legacy-database"
] |
How to implement multivalued attribute in Django? | 37,711,512 | <p>I have a legacy database with the following tables:</p>
<p>person</p>
<pre><code>person_id (PK) | first_name | last_name
1 | John | Doe
2 | David | Bentley
</code></pre>
<p>phonenumbers</p>
<pre><code>person_id (FK,PK) | phone_number (PK) | area_code (PK)
... | 1 | 2016-06-08T19:41:11Z | 37,716,599 | <p>Django does not support composite primary keys and your PhoneNumbers table has a primary key that spans three columns. This <a href="https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys" rel="nofollow">ticket</a> has been open for years. There is a <a href="https://github.com/simone/django-compositekey" rel... | 0 | 2016-06-09T04:04:43Z | [
"python",
"django",
"database",
"legacy-database"
] |
matplotlib 3d axes ticks, labels, and LaTeX | 37,711,538 | <p>I am running <a href="http://matplotlib.org/examples/mplot3d/lines3d_demo.html" rel="nofollow">this</a> sample script, with the following modifications:</p>
<pre><code>import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
mpl.rcParams['legend.fontsize']... | 2 | 2016-06-08T19:43:17Z | 37,713,788 | <blockquote>
<p>How do I adjust the axis ticks to that of my choosing? I.e., how would
I get the z-axis to only label 2, 0, and -2, and in the font size that
I want? I know how to do this in 2D but not 3D.</p>
</blockquote>
<p>You have to change properties of <code>zticks</code>.</p>
<blockquote>
<p>Why is th... | 1 | 2016-06-08T22:09:08Z | [
"python",
"matplotlib",
"plot",
"3d",
"latex"
] |
Django 1.9: render cannot pass context to my template | 37,711,627 | <p>I'm trying to use render(request,'sell.thml',context) in django 1.9, I use mysql to be my database. but nothing show up in my template. I don't know why I cannot use render to pass my context variable to template. Anyone can help me about it?</p>
<p>In my view.py:</p>
<pre><code>def sellmainpage(request):
prod... | 0 | 2016-06-08T19:48:12Z | 37,712,036 | <p>Show us your setting, you should have a folder "template", and inside the html</p>
<p>Example settings.py</p>
<pre><code>BASE_DIR = os.path.dirname(os.path.realpath(__file__))
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'template'... | 1 | 2016-06-08T20:11:41Z | [
"python",
"django"
] |
Django 1.9: render cannot pass context to my template | 37,711,627 | <p>I'm trying to use render(request,'sell.thml',context) in django 1.9, I use mysql to be my database. but nothing show up in my template. I don't know why I cannot use render to pass my context variable to template. Anyone can help me about it?</p>
<p>In my view.py:</p>
<pre><code>def sellmainpage(request):
prod... | 0 | 2016-06-08T19:48:12Z | 39,776,855 | <p>instead of </p>
<pre><code>return render(request, "sell.html", context)
</code></pre>
<p>try</p>
<pre><code>loader.get_template('sell.html')
return HttpResponse(template.render(context,request))
</code></pre>
<p>don't forget to import needed things.</p>
<pre><code>from django.template import loader
from django.... | 0 | 2016-09-29T17:47:35Z | [
"python",
"django"
] |
plot pandas period_range with matplotlib - set freq of axis | 37,711,642 | <p>I got a pandas DataFrame with values for time spans with variable lenths. I want to plot a horizontal line for the value of each timespan with the length of the timespan. Therfore, I converted the timespan to an PeriodIndex by</p>
<pre><code>ax0=fig.add_axes([.16,.2,0.8,.7])
ax0.plot_date(data['periodIndex'], data[... | 0 | 2016-06-08T19:49:16Z | 37,712,201 | <p>I constructed data to demonstrate what I believe was your question.</p>
<p>If you fill in a dataframe with data for only a specific range of the index and then plot it, it will only generate a line for when that data was not null.</p>
<pre><code>import pandas as pd
import numpy as np
ts = pd.date_range(end='2016-... | 0 | 2016-06-08T20:23:01Z | [
"python",
"pandas",
"matplotlib"
] |
I want to install pyOpt for python, but pyopt is already installed and pip is case insensitive | 37,711,671 | <p>I'm new to this forum and relatively new to python. The problem I'm having is a follows: I'm trying to install the module pyOpt(the optimization package) but when I use my ide's command line and pip install it says that the package is already installed. However, the package that is currently installed is pyopt. I've... | 0 | 2016-06-08T19:50:48Z | 39,076,209 | <p><a href="https://pypi.python.org/pypi/pyopt/0.84" rel="nofollow">pyopt</a> is not <a href="http://www.pyopt.org/" rel="nofollow">pyOpt</a>. In fact, pyOpt is not on pypi, so you have to download it separately and install e.g. with setup.py. Depending on your system it might be available through the package managemen... | 0 | 2016-08-22T09:44:05Z | [
"python",
"module",
"pip"
] |
How to refresh the window with Tkinter | 37,711,674 | <p>I am trying to create a window filled with random integers between 0 and 9. After a certain amount of time, the window should refresh and display new randomly selected integers. My code does the first step just fine but fails at the second part. I have looked up functions like after() but it still doesn't work. The ... | 0 | 2016-06-08T19:50:58Z | 37,711,697 | <pre><code>root.after(5000,ch())
</code></pre>
<p>This calls <code>ch</code> immediately and registers whatever the return value is to execute five seconds later. Instead, try:</p>
<pre><code>root.after(5000,ch)
</code></pre>
<hr>
<p>Edit: another problem you have is that <code>ch</code> adds new labels to the wind... | 1 | 2016-06-08T19:52:22Z | [
"python",
"tkinter"
] |
How to refresh the window with Tkinter | 37,711,674 | <p>I am trying to create a window filled with random integers between 0 and 9. After a certain amount of time, the window should refresh and display new randomly selected integers. My code does the first step just fine but fails at the second part. I have looked up functions like after() but it still doesn't work. The ... | 0 | 2016-06-08T19:50:58Z | 37,732,334 | <p>Btw, this is the final working form: </p>
<pre><code>from tkinter import *
from random import *
root=Tk()
col=200
row=57
num=[randint(0,9) for i in range(col*row)]
st=""
for k in range(0,col*row,col):
st=st + (' '.join(str(e) for e in num[k:k+col])) + '\n'
theLabel= Label(root,text=st)
theLabel.pack()
def ... | 0 | 2016-06-09T17:13:40Z | [
"python",
"tkinter"
] |
pip failing with attribute error: no attribute _handerList | 37,711,730 | <p>I just installed "logging" from pip and now pip is broken. I've tried <code>sudo rm /usr/local/bin/pip*; sudo easy_install pip</code> and it didn't resolve the issue. The full result from attempting to install a package: </p>
<pre><code> Traceback (most recent call last):
File "/usr/local/bin/pip", line 9, in ... | 0 | 2016-06-08T19:54:02Z | 37,712,320 | <p>You could attempt to properly reinstall <code>pip</code> either via Python itself or using <code>easy_install</code> with upgrade enforced.</p>
<p><strong>Python</strong></p>
<p><code>python -m pip install --upgrade --force pip</code></p>
<p><strong>easy_install</strong></p>
<p><code>sudo easy_install --upgrade ... | 1 | 2016-06-08T20:29:46Z | [
"python",
"pip"
] |
Running python demo script with dll/pyd dependencies | 37,711,813 | <p>I'm writing some python code that depends on a c++ library (I'm using Boost.Python). I use cmake to build and put the library dll and pyd files into bin. My folder structure looks a bit like this:</p>
<pre><code>Project
|-- bin: folder where test executables, dll, and pyd files get put after build
|-- cpp: all cpp/... | 0 | 2016-06-08T19:59:03Z | 37,735,177 | <p>In the end, I'm settling for adding the bin folder to the python path programmatically with </p>
<pre><code>import os, sys
moduleDir = os.path.dirname(os.getcwd()) + os.sep + "bin"
sys.path.insert(0, moduleDir)
</code></pre>
<p>It solves my issue in the short term although it doesn't look nice. </p>
| 0 | 2016-06-09T20:02:58Z | [
"python",
"c++",
"dll"
] |
Generate all possible outcomes of k balls in n bins (sum of multinomial / categorical outcomes) | 37,711,817 | <p>Suppose we have <code>n</code> bins in which we are throwing <code>k</code> balls. What is a <strong>fast</strong> (i.e. using numpy/scipy instead of python code) way to generate all possible outcomes as a matrix?</p>
<p>For example, if <code>n = 4</code> and <code>k = 3</code>, we'd want the following <code>numpy.... | 8 | 2016-06-08T19:59:35Z | 37,712,597 | <p>Here's a generator solution using <code>itertools.combinations_with_replacement</code>, don't know if it will be suitable for your needs.</p>
<pre><code>def partitions(n, b):
masks = numpy.identity(b, dtype=int)
for c in itertools.combinations_with_replacement(masks, n):
yield sum(c)
output = nump... | 1 | 2016-06-08T20:45:58Z | [
"python",
"numpy",
"scipy",
"permutation",
"combinatorics"
] |
Generate all possible outcomes of k balls in n bins (sum of multinomial / categorical outcomes) | 37,711,817 | <p>Suppose we have <code>n</code> bins in which we are throwing <code>k</code> balls. What is a <strong>fast</strong> (i.e. using numpy/scipy instead of python code) way to generate all possible outcomes as a matrix?</p>
<p>For example, if <code>n = 4</code> and <code>k = 3</code>, we'd want the following <code>numpy.... | 8 | 2016-06-08T19:59:35Z | 37,713,063 | <p>here is a naive implementation with list comprehensions, not sure about performance compared to numpy</p>
<pre><code>def gen(n,k):
if(k==1):
return [[n]]
if(n==0):
return [[0]*k]
return [ g2 for x in range(n+1) for g2 in [ u+[n-x] for u in gen(x,k-1) ] ]
> gen(3,4)
[[0, 0, 0, 3],
[0... | 0 | 2016-06-08T21:15:53Z | [
"python",
"numpy",
"scipy",
"permutation",
"combinatorics"
] |
Generate all possible outcomes of k balls in n bins (sum of multinomial / categorical outcomes) | 37,711,817 | <p>Suppose we have <code>n</code> bins in which we are throwing <code>k</code> balls. What is a <strong>fast</strong> (i.e. using numpy/scipy instead of python code) way to generate all possible outcomes as a matrix?</p>
<p>For example, if <code>n = 4</code> and <code>k = 3</code>, we'd want the following <code>numpy.... | 8 | 2016-06-08T19:59:35Z | 37,821,406 | <p>For reference purposes, the following code uses <a href="https://en.wikipedia.org/wiki/Loopless_algorithm" rel="nofollow">Ehrlich's algorithm</a> to iterate through all possible combinations of a multiset in C++, Javascript, and Python:</p>
<blockquote>
<p><a href="https://github.com/ekg/multichoose" rel="nofollo... | 0 | 2016-06-14T20:21:20Z | [
"python",
"numpy",
"scipy",
"permutation",
"combinatorics"
] |
Generate all possible outcomes of k balls in n bins (sum of multinomial / categorical outcomes) | 37,711,817 | <p>Suppose we have <code>n</code> bins in which we are throwing <code>k</code> balls. What is a <strong>fast</strong> (i.e. using numpy/scipy instead of python code) way to generate all possible outcomes as a matrix?</p>
<p>For example, if <code>n = 4</code> and <code>k = 3</code>, we'd want the following <code>numpy.... | 8 | 2016-06-08T19:59:35Z | 38,691,110 | <p>Here's the solution I came up with for this.</p>
<pre><code>import numpy, itertools
def multinomial_combinations(n, k, max_power=None):
"""returns a list (2d numpy array) of all length k sequences of
non-negative integers n1, ..., nk such that n1 + ... + nk = n."""
bar_placements = itertools.combinatio... | 0 | 2016-08-01T04:36:42Z | [
"python",
"numpy",
"scipy",
"permutation",
"combinatorics"
] |
How can I connect points on a 3D scatter plot? | 37,711,843 | <p>So currently, I have all these coordinates and so it's quite easy to create a 3D scatter plot of all the combination of coordinates.</p>
<pre><code>fig = plt.figure(figsize=(20,10))
ax = plt.axes(projection='3d')
z = numpy.transpose(z_coords_row)[0:100]
x = numpy.transpose(x_coords_row)[0:100]
y = numpy.transpose(... | 1 | 2016-06-08T20:01:02Z | 37,712,075 | <p>If you have enough points using only your coordinates I think what you are looking for is <a href="http://matplotlib.org/mpl_toolkits/mplot3d/api.html#mpl_toolkits.mplot3d.axes3d.Axes3D.plot3D" rel="nofollow"><code>plot3D</code></a>. If you need it more smooth line it might be worth looking into <a href="http://docs... | 1 | 2016-06-08T20:14:31Z | [
"python",
"matplotlib",
"3d"
] |
Django object in view? | 37,711,850 | <p>I'm using Django templates with HTML/JS to show the results of simulations in python/Anaconda. The simulation depends on the setting of different parameters. After the initial data is loaded (from files) and visualized by the first call of the page, the parameters can be chosen in textfields/dropdowns in the templat... | 0 | 2016-06-08T20:01:20Z | 37,712,058 | <p>Unless you set up some kind of socket (for instance using Django Channels) you'll have to resend the entire request data on each request. This doesn't seem to be much of a problem for your use case, though.</p>
| 0 | 2016-06-08T20:13:25Z | [
"python",
"ajax",
"django"
] |
Python regex not matching but works on regex tester | 37,711,913 | <pre><code>import re as regex
pattern = regex.compile(r'\w[\w\/\\-]*(\s*[\w\/\\-])*')
print pattern.findall("HELLO-WORLD")
</code></pre>
<p>This just prints out <code>['']</code></p>
<p>The regex works correctly on an online regex tester. Why is it not matching?</p>
| 1 | 2016-06-08T20:05:35Z | 37,712,067 | <p>You can use a <em>non-capturing</em> group (i.e. <code>(?:\s*[\w/\\-])</code>, the <code>(?:...)</code> does not form a capturing group and <code>re.findall</code> returns the whole match, not the captured group value(s)):</p>
<pre><code>import re
pattern = re.compile(r'\w[\w/\\-]*(?:\s*[\w/\\-])*')
print(pattern.... | 1 | 2016-06-08T20:14:10Z | [
"python",
"regex",
"python-2.7"
] |
Parallel processing in Python when clearing all variables | 37,711,931 | <p>I'm trying to run parallel process using python. I managed to do that using the multiprocessing module.</p>
<p>The problem is that when I add a "Clear all variables" at the beginning of the code, the algorithm gives me this error:</p>
<blockquote>
<p>Traceback (most recent call last):</p>
<p>File "", line 1... | 0 | 2016-06-08T20:06:08Z | 37,734,134 | <p>It probably has to do with the restrictions of using <a href="https://docs.python.org/2/library/multiprocessing.html#windows" rel="nofollow">multiprocessing on Windows</a>.</p>
<blockquote>
<p>Since Windows lacks <code>os.fork()</code> it has a few extra restrictions.</p>
</blockquote>
<p>It may be that some glo... | 1 | 2016-06-09T18:59:05Z | [
"python",
"parallel-processing",
"multiprocessing"
] |
Arrows on Scatter | 37,711,936 | <p>Having had no luck myself I'm looking for a bit of assistance with this problem I have run into.</p>
<p>I have CSV data in this format.</p>
<pre><code>Flow Amount,X_Start,Y_Start,X_End,Y_End
4,36.20740741,31.97407407,48.103125,9.4125
4,50.71851852,48.46666667,65.65714286,73.81785714
3,50.71851852,48.46666667,48.10... | 0 | 2016-06-08T20:06:22Z | 37,715,460 | <p>You can use 'arrow' to plot arrow, like here:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
data = np.genfromtxt('file1.dat', delimiter=',', skip_header=1, names=['MAG', 'X0', 'Y0','X1','Y1'])
plt.scatter(data['X0'], data['Y0'], color='r', zorder=10)
plt.scatter(data['X1'], data['Y1'], col... | 0 | 2016-06-09T01:22:16Z | [
"python",
"python-2.7",
"csv",
"matplotlib"
] |
bug while trying to create a function from other functions in python | 37,712,040 | <p>I have been trying to create a calculator and i had for practical reasons i tried to import functions from a separate python file. It works at some extent but it breaks when it tries to do the calculations. The bug is is that the add is not defined but i did defined it while importing the function. Here is the code:... | 0 | 2016-06-08T20:12:08Z | 37,712,189 | <p>In the <code>if</code> statements, like this:</p>
<pre><code>if xn == "a":
addition = add.addition
x = self.addition()
self.x = x
return x
</code></pre>
<p><code>addition</code> is created as a variable local to the function <code>choice</code>, but you're then setting <code>x</code> to be <code>se... | 0 | 2016-06-08T20:21:48Z | [
"python",
"function",
"import",
"calculator"
] |
error in "if" loop (Sage) | 37,712,178 | <p>I'm using "Sage," but I do not think that it is relevant for this question.</p>
<p>I have made the following definitions, and attempted to implement an if loop:</p>
<pre><code>Q = DiagonalQuadraticForm(ZZ,[1,1,1,1])
L = Q.representation_number_list(10)
for i in range(len(L)):
if L[i] == 0 % 2:
... | -1 | 2016-06-08T20:21:23Z | 37,712,369 | <p>You intend to print even numbers? This should work:</p>
<pre><code>Q = DiagonalQuadraticForm(ZZ,[1,1,1,1])
L = Q.representation_number_list(10)
for i, v in enumerate(L):
if v % 2 == 0:
print i
</code></pre>
<p><code>enumerate(...)</code> can replace <code>range(len(...))</code></p>
| 0 | 2016-06-08T20:32:37Z | [
"python",
"if-statement",
"sage"
] |
error in "if" loop (Sage) | 37,712,178 | <p>I'm using "Sage," but I do not think that it is relevant for this question.</p>
<p>I have made the following definitions, and attempted to implement an if loop:</p>
<pre><code>Q = DiagonalQuadraticForm(ZZ,[1,1,1,1])
L = Q.representation_number_list(10)
for i in range(len(L)):
if L[i] == 0 % 2:
... | -1 | 2016-06-08T20:21:23Z | 37,712,842 | <p>Modulus syntax in Python (and most other programming languages) is not the same as mathematical notation. In math, you write</p>
<pre><code>a â¡ b (mod n)
</code></pre>
<p>to indicate that <code>a</code> and <code>b</code> are congruent modulo <code>n</code>. In programming languages, <code>modulus</code> is trea... | 1 | 2016-06-08T21:00:45Z | [
"python",
"if-statement",
"sage"
] |
Possible to keep same lines in same color in different plots in matplotlib? | 37,712,243 | <p>Say I have a figure A consists of 10 lines : 1 to 10, colored by default settings of matplotlib.</p>
<p>Now I want to plot lines 1-5 in figure B and lines 6-10 in figure C, but keep the colors of the lines consistent. I mean in figure B, colors of line 1-5 are the same with line 1-5 in figure A; and in figure C, co... | 2 | 2016-06-08T20:25:34Z | 37,713,375 | <p>For the lines 6-10 just plot 5 blank lines before plotting the actual lines that you want to. 1-5 will already have the default colors that match the 1-10 scheme. </p>
<pre><code>import matplotlib.pyplot as plt
plt.plot([0]) # line 1
plt.plot([0]) # line 2
plt.plot([0]) # line 3
plt.plot([0]) # line 4
plt.plot([0])... | 0 | 2016-06-08T21:38:14Z | [
"python",
"matplotlib"
] |
Possible to keep same lines in same color in different plots in matplotlib? | 37,712,243 | <p>Say I have a figure A consists of 10 lines : 1 to 10, colored by default settings of matplotlib.</p>
<p>Now I want to plot lines 1-5 in figure B and lines 6-10 in figure C, but keep the colors of the lines consistent. I mean in figure B, colors of line 1-5 are the same with line 1-5 in figure A; and in figure C, co... | 2 | 2016-06-08T20:25:34Z | 39,164,870 | <p>If you link your plots by assigning a label (useful if you have a legend anyway) then you can lookup the previous colour.</p>
<p>Original problem:</p>
<pre><code>import matplotlib.pyplot as plt
plt.style.use('ggplot')
import numpy as np
f, axs = plt.subplots(3)
lines = [np.random.rand(10,1) for a in range(10)]
... | 0 | 2016-08-26T11:07:43Z | [
"python",
"matplotlib"
] |
Python multiprocessing and save data in order | 37,712,249 | <p>I'm analyzing a cvs file data line by line. For each line, I will generate a string storing the analyzed results.</p>
<p>Since the file is huge, I must do multiprocessing. But because I have to access the results by their index,I have to store them in order (to a local file). </p>
<p>One way I tried and worked is ... | 0 | 2016-06-08T20:25:50Z | 37,712,975 | <p><a href="https://docs.python.org/3/library/concurrent.futures.html#threadpoolexecutor-example" rel="nofollow">ThreadPoolExecuter</a> is great for running the same method in parallel with different sets of data, and for re-assembling the results from each thread.</p>
<p>As the results come back from each thread put ... | 0 | 2016-06-08T21:08:42Z | [
"python",
"performance",
"python-multiprocessing"
] |
Python multiprocessing and save data in order | 37,712,249 | <p>I'm analyzing a cvs file data line by line. For each line, I will generate a string storing the analyzed results.</p>
<p>Since the file is huge, I must do multiprocessing. But because I have to access the results by their index,I have to store them in order (to a local file). </p>
<p>One way I tried and worked is ... | 0 | 2016-06-08T20:25:50Z | 37,713,052 | <p>I'd suggest using a <code>multiprocessing.Pool</code> and using its <code>imap</code> method to do the work. Have the workers <code>return</code> values instead of writing them directly, with the main process performing all the I/O. <code>imap</code> guarantees you get the results in the order the tasks were dispatc... | 2 | 2016-06-08T21:15:20Z | [
"python",
"performance",
"python-multiprocessing"
] |
How can I use regular expression/Python to find all integers after a known string, an unknown string, and another known string? | 37,712,252 | <p>I'm new to regular expression/Python, but I'm trying to extract a revision number from an HTML page. I used a proxy and urllib to store the read page into a string. I have some text that looks like:</p>
<pre><code><p>Proxy 3.2.1 r72440<br>
SlotBios 11.00</p>
<p><strong><span style="... | 2 | 2016-06-08T20:25:54Z | 37,712,381 | <p>If you know you're only looking for lines that contain the pattern <code>color: rgb(255, 0, 0)</code>, then add that pattern to your regexp:</p>
<pre><code>paragraphs = re.findall(r'color: rgb\(255, 0, 0\).*r(\d*)<br>',str(html))
</code></pre>
| 0 | 2016-06-08T20:33:12Z | [
"python",
"html",
"regex",
"string"
] |
How can I use regular expression/Python to find all integers after a known string, an unknown string, and another known string? | 37,712,252 | <p>I'm new to regular expression/Python, but I'm trying to extract a revision number from an HTML page. I used a proxy and urllib to store the read page into a string. I have some text that looks like:</p>
<pre><code><p>Proxy 3.2.1 r72440<br>
SlotBios 11.00</p>
<p><strong><span style="... | 2 | 2016-06-08T20:25:54Z | 37,712,533 | <p>You need to use a HTML parser to help you filter out the tags that have the red color applied, then use your regular expression on the tag's contents:</p>
<pre><code>>>> from bs4 import BeautifulSoup
>>> html = ''' (your html here) '''
>>> parser = BeautifulSoup(html, 'html.parser')
>&... | 1 | 2016-06-08T20:42:17Z | [
"python",
"html",
"regex",
"string"
] |
Python: How do you keep all of your data when using .Value_counts()? | 37,712,274 | <p>.Value_counts() gets rid of the rest of my data. Analyze my data without loosing the rest of the information? Or is there another word counter code I can use that doesn't remove the rest of my columns of data?</p>
<p>Here's my code:</p>
<pre><code>from pandas import DataFrame, read_csv
import pandas as pd
f1 = p... | 0 | 2016-06-08T20:26:56Z | 37,713,013 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.duplicated.html" rel="nofollow"><code>DataFrame.duplicated</code></a> to determine which rows are duplicates, and then filter using <code>loc</code>:</p>
<pre><code>f = f.loc[~f.duplicated(subset=['User Name'], keep=False), ... | 1 | 2016-06-08T21:12:38Z | [
"python",
"python-3.x",
"pandas"
] |
pyAudio and PJSIP in a Virtual Machine | 37,712,275 | <p>I am writing a SIP client in python. I am able to make my script run on my computer just fine. It plays a wav file, grabs the audio and then sends the audio out using a sip session. I am having a very hard time getting this to run in the AWS ec2 VM. The VM is running SUSE 12. </p>
<p>There seems to be a lot of ques... | 1 | 2016-06-08T20:26:57Z | 37,734,848 | <p>Alright, this isn't the most reliable solution but it does seem to work. </p>
<p>To start with you must verify you have pulseaudio installed and working</p>
<p>Use what ever package installer you need:</p>
<p>apt-get/yum/zypper pulseaudio pulseaudio-devel alsa-lib alsa-devel alsa-plugins-pulseaudio</p>
<p>pulsea... | 0 | 2016-06-09T19:42:05Z | [
"python",
"audio",
"amazon-ec2",
"pjsip",
"pyaudio"
] |
BadValueError when storing repeated KeyProperty with custom validator | 37,712,279 | <p>I'm trying to simplify the JSON serialization and de-serialization of ndb KeyProperties by utilizing a custom validator that converts a string to a <code>Key</code> of the respective kind.</p>
<p>The idea is to have a property like this: </p>
<pre><code>def key_validator(kind):
def validator(prop, value):
if... | 2 | 2016-06-08T20:27:09Z | 37,714,989 | <p>Ok, found it. <code>KeyProperty</code> has this really weird constructor "signature magic" (<a href="https://github.com/GoogleCloudPlatform/datastore-ndb-python/blob/8f777e76818c7ae130a8abf5efea79575e1f4be8/ndb/model.py#L1963" rel="nofollow">model.py, line 1963</a>).</p>
<p>The point is that if the first parameter ... | 0 | 2016-06-09T00:17:22Z | [
"python",
"google-app-engine",
"app-engine-ndb"
] |
Python fill a list with the same string | 37,712,284 | <p>I have a pandas DataFrame and I would like to make a new column with the same string in each row. </p>
<p>Currently I'm doing this. </p>
<pre><code>tag=[]
for x in xrange(len(preds)): #preds is a np.array, same length of df
tag.append('MY STRING')
df['TAG']=tag
</code></pre>
<p>I know there must be a smarter... | 1 | 2016-06-08T20:27:27Z | 37,712,673 | <p><code>df['TAG'] = ['MY STRING'] * len(preds)</code></p>
| 2 | 2016-06-08T20:50:55Z | [
"python",
"pandas"
] |
Testing consistency with Selenium scraping | 37,712,286 | <p>This script scrapes data from a website with upcoming sports games into a dictionary (<a href="http://www.oddsportal.com" rel="nofollow">www.oddsportal.com</a>). Takes under 2.5 mins.</p>
<pre><code>from selenium.common.exceptions import TimeoutException
from selenium import webdriver
from selenium.webdriver.common... | 1 | 2016-06-08T20:27:31Z | 37,714,829 | <p>I noticed that the website creates a cookie for the user timezone, you can exploit that by adding it yourself</p>
<pre><code>driver.add_cookie({'name': 'op_user_time_zone', 'value': '-4'})
</code></pre>
<p>That should do the trick</p>
<p>In case it doesn't work edit the current code to what you tried, also check ... | 1 | 2016-06-08T23:58:01Z | [
"python",
"datetime",
"selenium",
"selenium-webdriver"
] |
How to round float down to a given precision? | 37,712,306 | <p>I need a way to round a float to a given number of decimal places, but I want to always round down.</p>
<p>For example, instead of</p>
<pre><code>>>> round(2.667, 2)
2.67
</code></pre>
<p>I would rather have</p>
<pre><code>>>> round_down(2.667, 2)
2.66
</code></pre>
| 3 | 2016-06-08T20:28:54Z | 37,712,374 | <p>You can use <code>math.floor</code> to "round down" to the nearest whole number. So to round to the 3rd decimal place, you can try <code>math.floor(1000*number) / 1000</code>.</p>
<p>In general, to "round down" a number <code>num</code> to precision <code>n</code>, you can try:</p>
<pre><code>from math import floo... | 1 | 2016-06-08T20:32:48Z | [
"python",
"rounding"
] |
How to round float down to a given precision? | 37,712,306 | <p>I need a way to round a float to a given number of decimal places, but I want to always round down.</p>
<p>For example, instead of</p>
<pre><code>>>> round(2.667, 2)
2.67
</code></pre>
<p>I would rather have</p>
<pre><code>>>> round_down(2.667, 2)
2.66
</code></pre>
| 3 | 2016-06-08T20:28:54Z | 37,712,389 | <p>Something like this should work for whatever number of digits you want to do:</p>
<pre><code>>>> import math
>>> def round_down(num,digits):
factor = 10.0 ** digits
return math.floor(num * factor) / factor
>>> round_down(2.667,2)
2.66
</code></pre>
| 2 | 2016-06-08T20:33:45Z | [
"python",
"rounding"
] |
How to round float down to a given precision? | 37,712,306 | <p>I need a way to round a float to a given number of decimal places, but I want to always round down.</p>
<p>For example, instead of</p>
<pre><code>>>> round(2.667, 2)
2.67
</code></pre>
<p>I would rather have</p>
<pre><code>>>> round_down(2.667, 2)
2.66
</code></pre>
| 3 | 2016-06-08T20:28:54Z | 37,712,409 | <p>You've got a friend in <a href="https://docs.python.org/3/library/decimal.html#decimal.Decimal.quantize" rel="nofollow"><code>quantize</code></a> and <a href="https://docs.python.org/3/library/decimal.html#decimal.ROUND_FLOOR" rel="nofollow"><code>ROUND_FLOOR</code></a> </p>
<pre><code>>>> from decimal imp... | 4 | 2016-06-08T20:35:00Z | [
"python",
"rounding"
] |
How to round float down to a given precision? | 37,712,306 | <p>I need a way to round a float to a given number of decimal places, but I want to always round down.</p>
<p>For example, instead of</p>
<pre><code>>>> round(2.667, 2)
2.67
</code></pre>
<p>I would rather have</p>
<pre><code>>>> round_down(2.667, 2)
2.66
</code></pre>
| 3 | 2016-06-08T20:28:54Z | 37,712,554 | <p>You can also play around this using strings</p>
<pre><code>def round_down(num, prec):
if isinstance(num, float):
s = str(num)
return float(s[:s.find('.') + prec + 1])
else:
raise ValueError
round_down(2.6667, 2)
# 2.66
</code></pre>
<p>Patch the code with more checks like precision... | 0 | 2016-06-08T20:43:27Z | [
"python",
"rounding"
] |
pyodbc - read primary keys from MS Access (MDB) database | 37,712,307 | <p>When I try to use <code>cursor.primaryKeys("tablename")</code> then exception occurs:</p>
<p><code>Error: ('IM001', '[IM001] [Microsoft][ODBC Driver Manager] Driver does not support this function (0) (SQLPrimaryKeys)')</code></p>
<p><code>list(cursor.columns(table='tablename'))</code> does not reveal primary keys ... | 2 | 2016-06-08T20:28:55Z | 37,712,996 | <p>Here is solution using pythonnet and Oledb Jet driver. Note that this does not preserve the order of primary keys as columns:</p>
<pre><code>import clr
import System
import System.Data.OleDb
from System.Data.OleDb import OleDbSchemaGuid
def getKeyNames(tableName, mdbname):
conn = System.Data.OleDb.OleDbConnect... | 1 | 2016-06-08T21:11:07Z | [
"python",
"sql",
"database",
"ms-access",
"pyodbc"
] |
pyodbc - read primary keys from MS Access (MDB) database | 37,712,307 | <p>When I try to use <code>cursor.primaryKeys("tablename")</code> then exception occurs:</p>
<p><code>Error: ('IM001', '[IM001] [Microsoft][ODBC Driver Manager] Driver does not support this function (0) (SQLPrimaryKeys)')</code></p>
<p><code>list(cursor.columns(table='tablename'))</code> does not reveal primary keys ... | 2 | 2016-06-08T20:28:55Z | 37,713,906 | <p>For Access ODBC we can get the Primary Key columns via the <code>.statistics</code> method of the pyodbc <code>cursor</code> object:</p>
<pre class="lang-python prettyprint-override"><code>crsr = conn.cursor()
table_name = 'MyTable'
# dict comprehension: {ordinal_position: col_name}
pk_cols = {row[7]: row[8] for ro... | 3 | 2016-06-08T22:20:11Z | [
"python",
"sql",
"database",
"ms-access",
"pyodbc"
] |
django - FormSet: ingore forms contaning only initial values | 37,712,328 | <p>I have a FormSet and each form contains one filed with initial value:</p>
<pre><code>class IssueForm(forms.Form):
date_of_issue = forms.DateField(
initial=date.today().strftime("%d.%m.%Y"),
widget=forms.TextInput(attrs={
'placeholder': date.today().strftime("%d.%m.%Y"),
... | 1 | 2016-06-08T20:30:07Z | 37,760,454 | <p>Thx @håken-lid for pushing me into the code. I should have done it in the first place.</p>
<p>At the end I don't know what did the trick. I've overwritten most of the clean functions and check the errors at the levels of validation (read the <a href="https://docs.djangoproject.com/en/dev/ref/forms/validation/" rel... | 0 | 2016-06-11T05:54:10Z | [
"python",
"django",
"django-forms",
"formset"
] |
Adding Python 2 kernel to Ipython | 37,712,353 | <p>I have Jupyter Notebook installed on Ubuntu. Python 2 and 3 run OK on the terminal but only Python 3 shows up on IPython. I am trying to get both kernels (2 and 3) up on IPython.</p>
<p>I've tried to manually install ipykernel from <a href="https://github.com/ipython/ipykernel" rel="nofollow">https://github.com/ipy... | 2 | 2016-06-08T20:31:36Z | 38,780,202 | <p>I experienced the same issue and found that a <code>backports</code> package was installed in both the Python 2.7 system site directory <em>and</em> the user site directory. Furthermore, the <code>backports.shutil_get_terminal_size</code> package was only in the system site directory:</p>
<pre><code>$ ls -l $(find... | 0 | 2016-08-05T02:30:29Z | [
"python",
"linux",
"ipython"
] |
what is the meaning of the return values of the scipy.cluster.hierarchy.linkage? | 37,712,465 | <p>Let assume that we have X matrix as follows:</p>
<pre><code>[[9 0]
[1 4]
[2 3]
[8 5]]
</code></pre>
<p>Then,</p>
<pre><code>from scipy.cluster.hierarchy import linkage
Z = linkage(X, method="ward")
print(Z)
</code></pre>
<p>The returning matrix is follows:</p>
<pre><code>[[ 1. 2. 1.41421356... | 1 | 2016-06-08T20:38:33Z | 37,712,929 | <p>Although this has <a href="http://stackoverflow.com/questions/9838861/scipy-linkage-format">been answered before</a>, it was a "read the docs" answer. I think it is useful to explain the docs a bit.</p>
<p>From the docs, we read that:</p>
<blockquote>
<p>An (nâ1) by 4 matrix Z is returned. At the i-th iteratio... | 1 | 2016-06-08T21:06:02Z | [
"python",
"scipy",
"hierarchical-clustering"
] |
find elements in html DOM | 37,712,501 | <p>I want to get Name/logo/Description/type from this HTML DOM
I use python Beautiful Soup and got Description and Type
using </p>
<pre><code>soup = BeautifulSoup(html_data)
for h in soup.findAll("span", { "class" : "description" }):
print h.text
</code></pre>
<p>But Unable to get the Name and logo in a Json fi... | 0 | 2016-06-08T20:40:29Z | 37,712,638 | <p>I would get both name and logo using the class attributes:</p>
<pre><code>logo = soup.find("div", class_="logo").img["src"]
name = soup.find("div", class_="identity").find("div", class_="name").get_text()
print(logo, name)
</code></pre>
<p>Or, via <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#cs... | 2 | 2016-06-08T20:48:21Z | [
"python",
"html",
"beautifulsoup"
] |
Differences between Cython, extending C/C++ with Python.h, etc | 37,712,561 | <p>Right now I have an image processing algorithm that is roughly 100 lines or so in Python. It takes about 500ms using <code>numpy</code>, <code>PIL</code> and <code>scipy</code>. I am looking to get it faster, and as the actual algorithm seems pretty optimized thus far, I'm wondering if using a different approach suc... | 1 | 2016-06-08T20:43:38Z | 37,712,741 | <p>It helps to know what you need to do here.</p>
<p>If you're not using <code>ctypes</code> for function calls, it's unlikely that it will save you anything to just have <code>ctypes</code> types involved. If you already have some DLL lying around with a "solve it for me" function, then sure, <code>ctypes</code> it i... | 1 | 2016-06-08T20:54:57Z | [
"python",
"cython",
"ctypes",
"python-extensions"
] |
django - mezzanine - staticfiles - frustrating error | 37,712,665 | <p>I'm new to Django. I have some difficulties, my static files are not loaded properly.</p>
<p>My project directory looks like this:</p>
<ul>
<li>myNewWebSite
<ul>
<li>myNewWebSite</li>
<li>home</li>
<li>static
<ul>
<li>css
<ul>
<li>home.css </li>
</ul></li>
</ul></li>
<li>templates
<ul>
<li>home
<ul>
<li>index... | 0 | 2016-06-08T20:50:19Z | 37,714,398 | <p>Django does not serve static files if DEBUG=False. The <code>--insecure</code> option seems to be a workaround or more precisely, the dev server runs automatically insecure if in debug mode.</p>
<p>The proper way is in a production environment would be to run <code>python manage.py collectstatic</code> and point th... | 1 | 2016-06-08T23:08:37Z | [
"python",
"css",
"django",
"django-staticfiles",
"mezzanine"
] |
Configure WSGI with Django on OpenShift | 37,712,689 | <p>I tried to configure WSGI with <strong>wsgi.py</strong> in my project folder</p>
<pre><code>import os
import sys
sys.path.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR']))
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
virtenv = os.environ['OPENSHIFT_HOMEDIR'] + 'python/virtenv/'
os.environ['PYTH... | 0 | 2016-06-08T20:51:44Z | 37,735,184 | <p>I had on the top of <strong>wsgi.py</strong></p>
<pre><code>os.path.join(os.environ['OPENSHIFT_HOMEDIR'], 'app-root/repo')
</code></pre>
<p>and I didn't have this error !
And I also put all my code under folder which have the name of my project in order to match</p>
<pre><code>os.environ['DJANGO_SETTINGS_MODULE']... | 0 | 2016-06-09T20:03:33Z | [
"python",
"django",
"openshift",
"wsgi",
"django-1.8"
] |
Python Linear Programming | 37,712,721 | <p>I am trying to solve the following equation:</p>
<p><code>maximize x^{T}Ax</code> where <code>x</code> is a <code>3 X 1</code> vector of the variables to be maximized and <code>A</code> is a <code>3 X 3</code> matrix of values.</p>
<p>So basically <code>x^{T} = [a,b,c]</code> which are the unknowns to be maximiz... | 0 | 2016-06-08T20:53:49Z | 37,713,770 | <p>I don't believe PuLP supports quadratic programming (QP). Your model is quadratic and PuLP is only for linear programming models (LPs and MIPs). There are quite a few options to express QPs in Python. High performance commercial solvers often provide Python bindings, and otherwise you can look at for example <a href... | 0 | 2016-06-08T22:07:27Z | [
"python",
"optimization",
"linear-programming",
"pulp"
] |
TensorFlowDNNClassifier class is deprecated but replacement does not seem to work? | 37,712,723 | <p>Using the following with TF .9.0rc0 on 60,000 (train) and 26,000 (test) on or so records with 145 coded columns (1,0) trying to predict 1 or 0 for class identification..</p>
<pre><code>classifier_TensorFlow = learn.TensorFlowDNNClassifier(hidden_units=[10, 20, 10],n_classes=2, steps=100)
classifier_TensorFlow.fit(... | 2 | 2016-06-08T20:54:07Z | 37,793,193 | <p>I don't think it is a bug, from the source code of DNNClassifier, I can tell that its usage differs from TensorFlowDNNClassifier. The constructor of DNNClassifier doesn't have the steps param: </p>
<pre><code>def __init__(self,
hidden_units,
feature_columns=None,
model_dir=None,
... | 3 | 2016-06-13T15:05:52Z | [
"python",
"tensorflow",
"skflow"
] |
'SSHClient' object has no attribute 'known_hosts' on ssh.connect() | 37,712,921 | <p>I am trying to connect ssh server using code below</p>
<pre><code>ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))
ssh.connect("10.1.3.2", username = "root")
</code></pre>
... | 0 | 2016-06-08T21:05:25Z | 37,712,982 | <p>This is a <a href="https://github.com/paramiko/paramiko/pull/176" rel="nofollow">known bug</a> and the fix was released to version 1.12.1; you seem to be using 1.12.0. Try upgrading to the latest release:</p>
<pre><code>pip install --upgrade paramiko
</code></pre>
| 1 | 2016-06-08T21:09:27Z | [
"python",
"ssh",
"paramiko"
] |
'SSHClient' object has no attribute 'known_hosts' on ssh.connect() | 37,712,921 | <p>I am trying to connect ssh server using code below</p>
<pre><code>ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))
ssh.connect("10.1.3.2", username = "root")
</code></pre>
... | 0 | 2016-06-08T21:05:25Z | 37,713,041 | <p>A quick fix:</p>
<pre><code>ssh = paramiko.SSHClient()
ssh.known_hosts = None
...
...
</code></pre>
<p>The <code>bug</code> was fixed <a href="https://github.com/paramiko/paramiko/pull/176/commits/026739aef57143fb606bec32dcff49c632cfe738" rel="nofollow">here</a>.</p>
| 1 | 2016-06-08T21:14:41Z | [
"python",
"ssh",
"paramiko"
] |
Struggling to add numbers in a list together (unsupported operand type) | 37,713,012 | <p>Trying to get this program to work for a school project, but in line 26 of the code I get an unsupported operand type error for 'int' and 'str'. Any help would be appreciated. Here is the code:</p>
<pre><code>final = False
while final == False:
while True:
try:
eventName = str(input... | 0 | 2016-06-08T21:12:37Z | 37,713,064 | <p>Instead of:</p>
<pre><code>judgeScoreList = judgeScores.split()
</code></pre>
<p>You want:</p>
<pre><code>judgeScoreList = [int(X) for X in judgeScores.split()]
</code></pre>
<p>I'd also recommend getting rid of all these little single-purpose functions.</p>
| 3 | 2016-06-08T21:15:53Z | [
"python",
"list"
] |
how to change XLOC ID to Ensembl ID from Cuffdiff | 37,713,122 | <p>I did RNA-Seq analysis, the GTF file I used was from Ensembl. The output of cuffdiff replaced the Ensembl IDs with XLOC's although it also output gene names (e.g. MX2). Ensembl IDs were no longer there. </p>
<p>I saw a post that showed to modify the merged.gtf using this python script</p>
<p><a href="http://seqans... | 0 | 2016-06-08T21:20:56Z | 37,952,601 | <p>As @ppperry commented, indentation matters in Python:</p>
<pre><code>#!/usr/bin/python
gtf_handle = "/PATH/TO/merged.gtf"
fh = open(gtf_handle, "r")
import re
trans_ids = {}
with open('merged2.gtf', 'w') as f:
for line in fh:
line = line.strip('\n') ##strip the line to remove white spaces
##prin... | 0 | 2016-06-21T19:03:32Z | [
"python"
] |
Do Python lists not have a len attribute? | 37,713,144 | <p>The output of the following script:</p>
<pre><code>a = ['abc', 'def', 'ghi', 'jkl']
print len(a)
print hasattr(a,"len")
</code></pre>
<p>is</p>
<pre><code>4
False
</code></pre>
<p>I was expecting the <code>False</code> to be <code>True</code>, especially since <code>len()</code> works on <code>a</code>. Am I m... | -1 | 2016-06-08T21:22:32Z | 37,713,187 | <p>Yes, you're missing something. <a href="https://docs.python.org/3/library/functions.html#len" rel="nofollow"><code>len(x)</code></a> returns <a href="https://docs.python.org/3/reference/datamodel.html#object.__len__" rel="nofollow"><code>x.__len__()</code></a>, not <code>x.len</code>.</p>
<p>Try running <a href="ht... | 5 | 2016-06-08T21:24:48Z | [
"python"
] |
filter multi lines separated by a date time field | 37,713,149 | <p>I have a logfile that are multi-lines separated by a date-time field like this:</p>
<pre><code>2016-06-06 07:26:46,038: sometext...
sometext...
sometext...
sometext...
2016-06-06 08:21:46,591:sometext1234...This is what I want...
sometext...abcd1234
2016-06-06 09:06:47,003: sometext...
2016-06-06 09:16:46,957: so... | 0 | 2016-06-08T21:22:46Z | 37,868,678 | <p>PowerShell <a href="https://technet.microsoft.com/en-us/library/dn807178.aspx" rel="nofollow"><code>ConvertFrom-String</code></a> can take a template and convert data to structure output. <strong>You may have to adjust the template for your actual data.</strong></p>
<h1>Example</h1>
<pre><code>$log = @"
2016-06-0... | 0 | 2016-06-16T20:20:26Z | [
"python",
"powershell"
] |
filter multi lines separated by a date time field | 37,713,149 | <p>I have a logfile that are multi-lines separated by a date-time field like this:</p>
<pre><code>2016-06-06 07:26:46,038: sometext...
sometext...
sometext...
sometext...
2016-06-06 08:21:46,591:sometext1234...This is what I want...
sometext...abcd1234
2016-06-06 09:06:47,003: sometext...
2016-06-06 09:16:46,957: so... | 0 | 2016-06-08T21:22:46Z | 38,235,521 | <p>Sorry, it took me a while, but I finally figured it out. And many thanks for everyone, who gave me ideas to test. Even though, @TravisEz13's convertfrom-string was almost what I want, and I did use it in other applications, very useful, but I didn't use it for this case. I ended up reading the file with get-conten... | 0 | 2016-07-06T23:40:26Z | [
"python",
"powershell"
] |
Python Element Tree Writing to New File | 37,713,184 | <p>Hi so I've been struggling with this and can't quite figure out why I'm getting errors. Trying to export just some basic XML into a new file, keeps giving me a TypeError. Below is a small sample of the code</p>
<pre><code>from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
from x... | -1 | 2016-06-08T21:24:41Z | 37,713,268 | <p>The <a href="https://docs.python.org/3/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write" rel="nofollow"><code>ElementTree.write</code></a> method defaults to us-ascii encoding and as such expects a file opened for writing binary:</p>
<blockquote>
<p>The output is either a string (str) or... | 0 | 2016-06-08T21:30:06Z | [
"python",
"xml",
"tree",
"element",
"writing"
] |
How do you ask a user to input a matrix on Python? | 37,713,276 | <p>I'm pretty new to Python, and I'm trying to translate a Matlab code. I'm trying to write a program that begins with a user uploading or entering their data from an IR training spectrum, and then the program appending it into an array or a matrix. But I'm not certain that I'm doing this right (especially because I ... | 0 | 2016-06-08T21:30:40Z | 37,713,603 | <p>Your code is ok so far but <code>btrain = [input("Input btrain as a list of values separated by commas.")]</code> will end up being a list of a single string or a list of a tuple of your values if you're on python 2.7. The correct way to do it would be </p>
<pre><code>btrain = input("Input btrain as a list of value... | 1 | 2016-06-08T21:53:50Z | [
"python",
"arrays",
"matlab",
"matrix"
] |
How to build a JSON file with nested records from a flat data table? | 37,713,329 | <p>I'm looking for a Python technique to build a nested JSON file from a flat table in a pandas data frame. For example how could a pandas data frame table such as:</p>
<pre><code>teamname member firstname lastname orgname phone mobile
0 1 0 John Doe Anon 916-555-1234 ... | 7 | 2016-06-08T21:34:48Z | 37,822,561 | <p>With some input from @root I used a different tack and came up with the following code, which seems to get most of the way there:</p>
<pre><code>import pandas
import json
from collections import defaultdict
inputExcel = 'E:\\teamsMM.xlsx'
exportJson = 'E:\\teamsMM.json'
data = pandas.read_excel(inputExcel, sheetn... | 0 | 2016-06-14T21:38:26Z | [
"python",
"json",
"table",
"pandas",
"nested"
] |
How to build a JSON file with nested records from a flat data table? | 37,713,329 | <p>I'm looking for a Python technique to build a nested JSON file from a flat table in a pandas data frame. For example how could a pandas data frame table such as:</p>
<pre><code>teamname member firstname lastname orgname phone mobile
0 1 0 John Doe Anon 916-555-1234 ... | 7 | 2016-06-08T21:34:48Z | 37,927,283 | <p>This is the a solution that works and creates the desired JSON format. First, I grouped my dataframe by the appropriate columns, then instead of creating a dictionary (and losing data order) for each column heading/record pair, I created them as lists of tuples, then transformed the list into an Ordered Dict. Anot... | 1 | 2016-06-20T16:17:24Z | [
"python",
"json",
"table",
"pandas",
"nested"
] |
Write object array to .txt file | 37,713,484 | <p>When I do</p>
<pre><code>k=12
rsf = np.zeros((int(k), 9), dtype='object')
for i in range(0, int(k)):
rsf[i, 0] = "FREQ"
for j in range(1, 9):
rsf[i, j] = sampled[8*i+j-1, 0]
</code></pre>
<p>and then try to write it by</p>
<pre><code>np.savetxt('test.txt', rsf, delimiter=',')
</code></pre>
<p>I... | 0 | 2016-06-08T21:45:26Z | 37,713,961 | <p>More of the error message:</p>
<pre><code>-> 1162 % (str(X.dtype), format))
1163 if len(footer) > 0:
1164 footer = footer.replace('\n', '\n' + comments)
TypeError: Mismatch between array dtype ('object') and format specifier ('%.18e,%.18e,%.18e,%.... | 1 | 2016-06-08T22:25:30Z | [
"python",
"numpy"
] |
What's going on with closed file descriptors? | 37,713,514 | <p>In the example code below we open a file descriptor to sandbox.log, provide it as stdout to a subprocess, and then close the file descriptor, yet the subprocess can still write to the file. Is subprocess.Popen duping the file descriptor internally? Is it safe to close a file descriptor after passing it to a subpro... | 2 | 2016-06-08T21:47:02Z | 37,713,654 | <p>Each process has its own set of file descriptors. Closing an fd in one program will not affect another program. This is why every program can use the same fd numbers for stdin (0), stdout (1), and stderr (2), and why shell scripts can usually just open fd 3 without having to check if it's available.</p>
<p>File des... | 4 | 2016-06-08T21:56:58Z | [
"python",
"unix",
"file-descriptor",
"python-os"
] |
Check if my module was imported | 37,713,581 | <p>I'm wanting to trigger a function inside the module for when the module <strong>itself</strong> is imported;</p>
<p>From what I've tested it seems that I can just check if <code>__name__</code> isn't <code>__main__</code> and use that as a solution; but I was wondering if there was a better way with some sort of im... | 1 | 2016-06-08T21:51:43Z | 37,713,787 | <p>Python run's top level logic once on import. Examples can be found in the stdlib hashlib implementation here (github is down at moment). <a href="https://fossies.org/dox/Python-3.5.1/hashlib_8py_source.html#name=l00131" rel="nofollow">https://fossies.org/dox/Python-3.5.1/hashlib_8py_source.html#name=l00131</a></p>... | 1 | 2016-06-08T22:09:03Z | [
"python"
] |
I have trouble installing mtTkinter? | 37,713,588 | <p>This window shows up when I attempt to install mtTkinter with "python mtTkinter.py install" through command prompt:</p>
<p><a href="http://i.stack.imgur.com/6hogO.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/6hogO.jpg" alt="enter image description here"></a></p>
<p>This is the command prompt log from the... | 1 | 2016-06-08T21:52:32Z | 37,715,116 | <p>Most tutorials that indicate to run:</p>
<pre><code>python setup.py install
</code></pre>
<p>Will use the specific filename <code>setup.py</code>, usually if there is no <code>setup.py</code> the file is usable as it is or needs to be installed manually, in this case the <code>mtTkinter.py</code> file has no need ... | 0 | 2016-06-09T00:34:17Z | [
"python",
"python-2.7",
"tkinter"
] |
Nuitka error Cannot find ' ' in package ' ' as absolute import | 37,713,589 | <p>I'm trying to use the nuitka tool to turn my python program into executable on ubuntu. It works fine if the program doesn't have any import statements but breaks when I use it on a program that imports something e.g. </p>
<p>test.py</p>
<pre><code>import numpy
print "hello, world."
</code></pre>
<p>type this on... | 5 | 2016-06-08T21:52:32Z | 38,305,187 | <p>I don't know about your particular use case but I also faced similar Cannot find '' in Package errors when using nuitka.</p>
<p>I was using sqlalchemy and had a similar issue with <code>configparser</code>.<br>
After about a day of debugging I found out that Nuitka trips up with SWIG (Dynamically Loaded shared obje... | 2 | 2016-07-11T10:57:48Z | [
"python",
"nuitka"
] |
Nuitka error Cannot find ' ' in package ' ' as absolute import | 37,713,589 | <p>I'm trying to use the nuitka tool to turn my python program into executable on ubuntu. It works fine if the program doesn't have any import statements but breaks when I use it on a program that imports something e.g. </p>
<p>test.py</p>
<pre><code>import numpy
print "hello, world."
</code></pre>
<p>type this on... | 5 | 2016-06-08T21:52:32Z | 38,823,170 | <p><a href="http://nuitka.net/posts/nuitka-release-0520.html" rel="nofollow">Official answer from Nuitaka.</a></p>
<p>What problem you facing same like another problem one user facing <code>package 'matplotlib' as absolute import.</code> this problem, then there nuitaka given comments below check if it useful for belo... | 1 | 2016-08-08T07:09:24Z | [
"python",
"nuitka"
] |
Python/Tkinter Combobox - return index position | 37,713,616 | <p>In a combobox in Python/Tkinter, I want to return not the contents of list item selected, but the index # of the line.</p>
<p>I tried <code>boxname.getvalue()</code> but I am getting a message that it has no such attribute.</p>
<p>NOTE: I ran it with just <code>get()</code> and it returns the proper text from the... | 1 | 2016-06-08T21:54:24Z | 37,715,100 | <p>I'm not sure if I understood correctly, but if I did, I think you should use the <a href="http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Combobox.html" rel="nofollow"><code>current</code></a> method.</p>
<pre><code>import tkinter as tk
from tkinter import ttk
r = tk.Tk()
c = ttk.Combobox(r)
c["values"] = ... | 1 | 2016-06-09T00:31:48Z | [
"python",
"combobox",
"tkinter"
] |
Reading a JSON in python and converting it to dataframe | 37,713,642 | <p>Suppose I have a JSON file as follows,</p>
<pre><code>{u'level': u'INFO',
u'message': {"method":"someMethod","params":{"frameId":"9.6","loaderId":"3.2","requestId":"4.6"}}
u'timestamp': 654789L}
</code></pre>
<p>For parsing this into dataframe, for the first level, I am able to do <code>data[1]['level']</code>, <... | -1 | 2016-06-08T21:56:09Z | 37,724,241 | <p>You can use <code>pandas.read_json</code> this will automatically read the file into a DataFrame. </p>
<pre><code>import pandas as pd
data = pd.read_json('test.json')
</code></pre>
<p>but the data you show in the question is not in valid JSON format. For the correct format please see this <a href="http://www.w3sc... | 0 | 2016-06-09T11:07:15Z | [
"python",
"json",
"pandas"
] |
Python - Fitting exponential decay curve from recorded values | 37,713,691 | <p>I'm aware that there are threads pertaining to this, but i'm confused to where I want to I fit my data to the fit.</p>
<p>My data is imported and plotted as such.</p>
<pre><code>import matplotlib.pyplot as plt
%matplotlib inline
import pylab as plb
import numpy as np
import scipy as sp
import csv
FreqTime1 = []
D... | 1 | 2016-06-08T21:59:21Z | 37,714,159 | <p>You have to use <code>curve_fit</code> from scipy.optimize: <a href="http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.optimize.curve_fit.html" rel="nofollow">http://docs.scipy.org/doc/scipy-0.16.1/reference/generated/scipy.optimize.curve_fit.html</a></p>
<pre><code>from scipy.optimize import curve_f... | 3 | 2016-06-08T22:46:11Z | [
"python",
"matplotlib",
"scipy",
"curve-fitting"
] |
Python - Fitting exponential decay curve from recorded values | 37,713,691 | <p>I'm aware that there are threads pertaining to this, but i'm confused to where I want to I fit my data to the fit.</p>
<p>My data is imported and plotted as such.</p>
<pre><code>import matplotlib.pyplot as plt
%matplotlib inline
import pylab as plb
import numpy as np
import scipy as sp
import csv
FreqTime1 = []
D... | 1 | 2016-06-08T21:59:21Z | 37,726,500 | <p><em>"I'm returned with this error message</em></p>
<pre><code>TypeError: ufunc 'multiply' did not contain a loop with signature matching types dtype('S32') dtype('S32') dtype('S32')
</code></pre>
<p><em>Any idea on how to resolve this?"</em></p>
<p>Your code that reads the CSV file to create <code>FreqTime1</code... | 1 | 2016-06-09T12:49:53Z | [
"python",
"matplotlib",
"scipy",
"curve-fitting"
] |
Python pandas dataframe "Date" Index different format in xlsx and csv | 37,713,729 | <p>I have an xlsx file with multiple tabs, each tab has a <code>Date</code> column in the format of <code>MM/DD/YYYY</code></p>
<p>Read each tab into a pandas dataframe, applied some operations on each tab, and then write the dataframe back into two formats: xlsx and csv</p>
<p>In the xlsx file, the <code>Date</code>... | 2 | 2016-06-08T22:03:24Z | 37,717,624 | <p>You can convert the date to a string. If the date is in the index, you could do:</p>
<pre><code>df.set_index(df.index.map(lambda x: x.strftime('%m/%d/%Y'))).to_excel()
</code></pre>
| 0 | 2016-06-09T05:36:11Z | [
"python",
"excel",
"datetime",
"pandas",
"dataframe"
] |
Python pandas dataframe "Date" Index different format in xlsx and csv | 37,713,729 | <p>I have an xlsx file with multiple tabs, each tab has a <code>Date</code> column in the format of <code>MM/DD/YYYY</code></p>
<p>Read each tab into a pandas dataframe, applied some operations on each tab, and then write the dataframe back into two formats: xlsx and csv</p>
<p>In the xlsx file, the <code>Date</code>... | 2 | 2016-06-08T22:03:24Z | 37,736,228 | <p>You are seeing the datetime in the default pandas Excel datetime format. However, you can easily set it to whatever you want:</p>
<pre><code># Set the default datetime and/or date formats.
writer = pd.ExcelWriter("pandas_datetime.xlsx",
engine='xlsxwriter',
date_forma... | 0 | 2016-06-09T21:09:48Z | [
"python",
"excel",
"datetime",
"pandas",
"dataframe"
] |
App Engine instance memory constantly increasing | 37,713,846 | <p>I'd expect the memory usage of my app engine instances (Python) to be relatively flat after an initial startup period. Each request to my app is short lived, and it seems all memory usage of single request should be released shortly afterwards.</p>
<p>This is not the case in practice however. Below is a snapshot ... | 1 | 2016-06-08T22:14:16Z | 38,038,411 | <p>I found <a href="http://stackoverflow.com/questions/33036334/memory-leak-in-google-ndb-library">another answer</a> that explains part of what is going on here. I'll give a summary based on that answer:</p>
<ol>
<li><p>When using NDB, entities are stored in a context cache, and the context cache is part of your mem... | 1 | 2016-06-26T12:13:12Z | [
"python",
"google-app-engine",
"memory",
"memory-management",
"app-engine-ndb"
] |
pyspark: TypeError: 'Row' object does not support item assignment | 37,713,847 | <p>I used the following code to replace the <code>None</code> value in a DataFrame row to an empty string:</p>
<pre><code>def replaceNone(row):
row_len = len(row)
for i in range(0, row_len):
if row[i] is None:
row[i] = ""
return row
</code></pre>
<p>in my pyspark code:</p>
<pre><code>data_out = d... | 0 | 2016-06-08T22:14:16Z | 37,724,912 | <p><code>Row</code> is a subclass of <code>tuple</code> and <code>tuples</code> in Python are immutable hence don't support item assignment. If you want to replace an item stored in a tuple you have rebuild it from scratch:</p>
<pre class="lang-py prettyprint-override"><code>## replace "" with placeholder of your choi... | 1 | 2016-06-09T11:38:05Z | [
"python",
"pyspark",
"spark-dataframe"
] |
(Django) By updating the UserProfile, the image is not saving correctly | 37,713,864 | <p>I made a view, to update a userprofile. When uploading an image the image is saved correctly, but when updating the profile again, the image is not saved anymore, how can I solve that problem? I am glad for any help!</p>
<p>my class UserProfile looks like this:</p>
<pre><code>class UserProfile(models.Model):
u... | 1 | 2016-06-08T22:16:46Z | 37,716,385 | <p>Since you are using a ModelForm subclass instead of a Form subclass you should make use of it's functionality, particularly the <a href="https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#the-save-method" rel="nofollow">save method.</a></p>
<blockquote>
<p>Every ModelForm also has a save() method. Thi... | 1 | 2016-06-09T03:43:36Z | [
"python",
"django",
"django-models",
"django-views",
"django-uploads"
] |
Understanding Basic Python Google API Sample | 37,713,882 | <p>I mentioned trying to get google java sample code working in one of my previous questions on StackOverflow, but abandoned trying to do that after realizing how deprecated the samples were. Since I dabbled in python a bit about 4 years ago, I decided that I would take a look at the Google Blogger API for Python.</p>
... | 1 | 2016-06-08T22:18:22Z | 37,714,318 | <p>The sample code is self explanatory:</p>
<pre><code>#libraries used to connect with googles api
from oauth2client import client
from googleapiclient import sample_tools
def main(argv):
# Authenticate and construct service.
service, flags = sample_tools.init(
argv, 'blogger', 'v3', __doc__, __file__,
... | 0 | 2016-06-08T23:01:28Z | [
"python",
"google-api",
"blogger"
] |
How to replace a specific index inside of an array with a new string, and then revert it back to its original value? | 37,713,900 | <pre><code>gameMap = [['.'] * 5 for _ in xrange(5)] # '.' represents grass.
</code></pre>
<p>This should print something along the lines of: </p>
<pre><code>[['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.']]
</code></pre>
<p>I... | 0 | 2016-06-08T22:19:45Z | 37,713,959 | <p>Just save the old value in a variable, e.g. <code>player_room_char</code>:</p>
<pre><code>player_room_char = gameMap[i][j]
gameMap[i][j] = 'P'
...
gameMap[i][j] = player_room_char
</code></pre>
<p>Presumably there is only one player, so you should only need a single variable.</p>
| 3 | 2016-06-08T22:25:21Z | [
"python"
] |
What kind of scores are returned by cross_validation.cross_val_score? | 37,713,953 | <p>I can't find this information in sci-kit learn documentation. But based on the numbers I got, it doesn't look like scores are mean squared error. </p>
| 2 | 2016-06-08T22:24:56Z | 37,723,226 | <p><code>cross_val_score</code> calls the <code>.score()</code> method of the estimator you pass in and what that returns varies depending on the estimator. You have to look into the documentation for each estimator to find out what the corresponding <code>.score()</code> method returns. You can override this default b... | 1 | 2016-06-09T10:20:58Z | [
"python",
"scikit-learn"
] |
Python - Sudoku Solver stuck in infinite loop given certain values | 37,713,979 | <p>here is the code for my sudoku solver. At the end, I put certain values in certain squares. The solver works when I include all values except the last one. When I include the last (commented out) value, the solver enters an infinite loop. Is anyone able to see why this is?</p>
<pre><code>class Cell:
def __init_... | -1 | 2016-06-08T22:26:58Z | 37,714,263 | <p>I think the last continue need to be indented more inside</p>
| 0 | 2016-06-08T22:56:30Z | [
"python",
"loops",
"infinite",
"sudoku"
] |
Softlayer Object Storage Python API Time To Live | 37,714,040 | <p>How do I set time to live for a file on object storage?</p>
<p>Looking at the code in <a href="https://github.com/softlayer/softlayer-object-storage-python/blob/master/object_storage/storage_object.py" rel="nofollow">https://github.com/softlayer/softlayer-object-storage-python/blob/master/object_storage/storage_obj... | 0 | 2016-06-08T22:33:31Z | 37,730,431 | <p>You need to make sure that the "ttl" is available in the headers, The "TTL" header is available when your container has enabled CDN.</p>
<p>so to verify that the ttl header exist you can use this code line:</p>
<pre><code>sl_storage['myContainserName']['MyFileName'].headers
</code></pre>
<p>then you can update th... | 0 | 2016-06-09T15:36:46Z | [
"python",
"softlayer"
] |
Softlayer Object Storage Python API Time To Live | 37,714,040 | <p>How do I set time to live for a file on object storage?</p>
<p>Looking at the code in <a href="https://github.com/softlayer/softlayer-object-storage-python/blob/master/object_storage/storage_object.py" rel="nofollow">https://github.com/softlayer/softlayer-object-storage-python/blob/master/object_storage/storage_obj... | 0 | 2016-06-08T22:33:31Z | 38,439,525 | <p>You need to set up the header "X-Delete-At: 1417341600" where 1417341600 is a Unix timestamp see more information here <a href="http://docs.openstack.org/developer/swift/overview_expiring_objects.html" rel="nofollow">http://docs.openstack.org/developer/swift/overview_expiring_objects.html</a></p>
<p>using the Pytho... | 0 | 2016-07-18T14:38:17Z | [
"python",
"softlayer"
] |
Extract Columns from html using Python (Beautifulsoup) | 37,714,116 | <p>I need to extract the info from this page -<a href="http://www.investing.com/currencies/usd-brl-historical-data" rel="nofollow">http://www.investing.com/currencies/usd-brl-historical-data</a>. I need Date, Price, Open, High, Low,Change %.
I`m new to Python so I got stuck at this step:</p>
<pre><code>import requests... | 1 | 2016-06-08T22:41:42Z | 37,714,463 | <p>Here's a way to convert the html table into a nested list</p>
<p>The solution is to find the specific table, then loop through each tr in the table, creating a sublist of the text of all the items inside that tr. The code to do this is a nested list comprehension.</p>
<pre><code>import requests
from bs4 import Bea... | 1 | 2016-06-08T23:15:52Z | [
"python",
"html",
"web-scraping"
] |
Extract Columns from html using Python (Beautifulsoup) | 37,714,116 | <p>I need to extract the info from this page -<a href="http://www.investing.com/currencies/usd-brl-historical-data" rel="nofollow">http://www.investing.com/currencies/usd-brl-historical-data</a>. I need Date, Price, Open, High, Low,Change %.
I`m new to Python so I got stuck at this step:</p>
<pre><code>import requests... | 1 | 2016-06-08T22:41:42Z | 37,714,661 | <p>How to parse the table from that site I have already answered <a href="http://stackoverflow.com/a/37668294/2141635">here</a> but since you want a <em>DataFrame</em>, just use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_html.html" rel="nofollow">pandas.read_html</a></p>
<pre><code>url ... | 1 | 2016-06-08T23:37:24Z | [
"python",
"html",
"web-scraping"
] |
tensorflow gather across multiple dimentions | 37,714,118 | <p><code>gather(params, indices)</code> does the following</p>
<pre><code>output[i, ..., j, :, ... :] = params[indices[i, ..., j], :, ..., :]
</code></pre>
<p>so if you have 4-dimensional params and 2-dimensional indices, you end up having 5-dimensional array as a result</p>
<p>the question is how to do</p>
<pre><c... | 0 | 2016-06-08T22:42:00Z | 37,731,733 | <p>There's an update on <a href="https://github.com/tensorflow/tensorflow/issues/206" rel="nofollow">#206</a> that @ebrevdo is working on generalizing slicing.</p>
<p>Meanwhile, you could flatten your array, construct linear indices for the elements you want, use gather, then reshape back, like was done in <a href="ht... | 1 | 2016-06-09T16:39:58Z | [
"python",
"arrays",
"numpy",
"tensorflow"
] |
Using regex separators with read_csv() in python? | 37,714,202 | <p>I have <em>a lot</em> of csv files formated as such:</p>
<pre><code>date1::tweet1::location1::language1
date2::tweet2::location2::language2
date3::tweet3::location3::language3
</code></pre>
<p>and so on. Some files contain up to 200 000 tweets. I want to extract 4 fields and put them in a pandas dataframe, as we... | 1 | 2016-06-08T22:50:02Z | 37,714,411 | <p>Have you tried <code>read_table</code> instead? I've got this kind of error when I tried to use <code>read_csv</code> before and I solved the problem by using it. Please refer to this <a href="http://stackoverflow.com/questions/18039057/python-pandas-error-tokenizing-data">post</a>, this might give you some ideas ab... | 0 | 2016-06-08T23:09:56Z | [
"python",
"regex",
"separator"
] |
Using regex separators with read_csv() in python? | 37,714,202 | <p>I have <em>a lot</em> of csv files formated as such:</p>
<pre><code>date1::tweet1::location1::language1
date2::tweet2::location2::language2
date3::tweet3::location3::language3
</code></pre>
<p>and so on. Some files contain up to 200 000 tweets. I want to extract 4 fields and put them in a pandas dataframe, as we... | 1 | 2016-06-08T22:50:02Z | 37,714,999 | <p>Start with this:</p>
<pre><code>pd.read_csv(tweets_data_path, sep="::", header = None, usecols = [0,1,2,3])
</code></pre>
<p>The above should bring in 4 columns, then you can figure out how many lines were dropped, and if the data makes sense. </p>
<p>Use this pattern:</p>
<pre><code>data["lang"].unique()
</code... | 0 | 2016-06-09T00:18:21Z | [
"python",
"regex",
"separator"
] |
Populating Insert Statements from a local file | 37,714,226 | <p>I am trying to write user data from a file into a series of insert statements. I feel I am close but just missing one or two things. I am attempting to run a .format, but all I end up with are ?'s</p>
<pre><code>import time, json, sqlite3
def insertsfromfile(file):
results = open(file).readlines()
output =... | 0 | 2016-06-08T22:52:28Z | 37,715,010 | <p>I figured it out after reviewing it. Essentially I was missing that I had to combine the attributes together with my Insert string with the '+'. Also had to convert the variables to str() in case they were int.</p>
| 0 | 2016-06-09T00:19:41Z | [
"python",
"sqlite"
] |
pandas: how to combine matrix with different index and columns? | 37,714,241 | <p>I am using python, pandas and numpy to read a few data.</p>
<p>I have two data frames:</p>
<p>Input 1- Cost matrix(it has the cost per season and region): index = regions and columns = seasons
Input 2- Binary matrix(value 1 when a month "a" belongs to a season "b": index=seasons, columns=months</p>
<p>The output ... | 0 | 2016-06-08T22:53:45Z | 37,714,874 | <p>I believe that there is a mistake in the relationship dataframe from your example, since you clearly state that it should be the relationship between <strong>season</strong> (and not region) and month, so I changed it accordingly.</p>
<pre><code>import pandas as pd
import numpy as np
regions = ['Region A', 'Region... | 0 | 2016-06-09T00:03:55Z | [
"python",
"numpy",
"pandas"
] |
What does the landing time mean in airflow? | 37,714,261 | <p>There is a section called "landing time" in the DAG view on the web console of airflow.</p>
<p><a href="http://i.stack.imgur.com/BCcqp.png" rel="nofollow">An example screen shot taken from airbnb's blog:</a></p>
<p>But what does it mean? There is no definition in the documents or in their repository now (tried to ... | 2 | 2016-06-08T22:56:16Z | 37,739,978 | <p>I directly asked the author Maxime, the answer is
landing_time is when the job completes minutes when the job should have started (for airflow, it's the end of the scheduled period).</p>
<p>source:
<a href="http://gitter.im/apache/incubator-airflow" rel="nofollow">http://gitter.im/apache/incubator-airflow</a>
It i... | 2 | 2016-06-10T04:34:08Z | [
"python",
"airflow"
] |
scrapy middleware for skip some page | 37,714,294 | <p>i want got data only from pages where "name" contains some pattern
other pages i want skip.</p>
<p>Now it is so</p>
<pre><code>def parse_item(self, response):
item=Item()
item['name']=response.xpath('//title//text()').extract().first()
if "pattern" not in item['name']:
return []
else:
return item
<... | 1 | 2016-06-08T22:59:35Z | 37,714,372 | <p>You should use a <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#scrapy.downloadermiddlewares.DownloaderMiddleware.process_response" rel="nofollow"><code>Downloader Middleware</code></a> specifically because of the <code>process_response</code> it offers</p>
<p>from scrapy.exceptions impo... | 2 | 2016-06-08T23:05:30Z | [
"python",
"scrapy"
] |
scrapy middleware for skip some page | 37,714,294 | <p>i want got data only from pages where "name" contains some pattern
other pages i want skip.</p>
<p>Now it is so</p>
<pre><code>def parse_item(self, response):
item=Item()
item['name']=response.xpath('//title//text()').extract().first()
if "pattern" not in item['name']:
return []
else:
return item
<... | 1 | 2016-06-08T22:59:35Z | 37,737,936 | <p>sad to answer my own question, but what can i do...</p>
<pre><code> def process_response(self,request, response, spider):
if not spider._rules:
return response
rule_index=request._meta.get('rule',None)
response_callback=None
if rule_index != None:
rule = sp... | 0 | 2016-06-09T23:49:15Z | [
"python",
"scrapy"
] |
plotting 2 .dat files, string file handle error | 37,714,315 | <p>Hi I am trying to plot data from two .dat files on the same plot.
When I try, I am getting an error message. I show exactly where it comes from below in the code. It has to do with a string or file handle. I am very new to python and do not know how to fix this.</p>
<p>I import both of my .dat files, they are bo... | 1 | 2016-06-08T23:01:08Z | 37,715,040 | <p>You have to plot with <code>plot</code> function:</p>
<pre><code>...
plot1 = plt.plot(*dat_file, linewidth=1.0, marker = 'o', label='solution 1')
plot2 = plt.plot(*dat_file2, linewidth=1.0, marker = 'v', label='solution 2')
ax = plt.gca()
ax.legend(loc='best')
plt.show()
</code></pre>
<p><a href="http://i.stack.... | 1 | 2016-06-09T00:22:49Z | [
"python",
"matplotlib"
] |
New numpy array from attribute of objects in another numpy array | 37,714,320 | <p>Is there a way to do an element-wise attribute extraction from a numpy array? For example, say I have:</p>
<pre><code>import numpy as np
class foo():
def __init__(self, value):
self.bar = value
obj_array = np.empty((2, 2), dtype='object')
for i in range(obj_array.shape[0]):
for j in range(obj_arra... | 0 | 2016-06-08T23:01:33Z | 37,714,552 | <p>You can create your new array as:</p>
<pre><code>bar_array = np.reshape(
np.fromiter((x.bar for x in obj_array.flat), dtype=float),
obj_array.shape)
</code></pre>
<p>Alter the <code>dtype</code> to whatever you'd please.</p>
| 0 | 2016-06-08T23:25:35Z | [
"python",
"numpy"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.