title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
How to concatenate two numpy ndarrays without using concatenate | 38,705,094 | <p>I am writing code which utilizes Numba to JIT compile my python code.
The function takes in two arrays of same length as input, randomly selects a slicing point and returns a tuple with two Frankenstein array formed by parts of the two input strings.
Numba however does not yet support the numpy.concatenate function ... | 2 | 2016-08-01T17:48:06Z | 38,705,440 | <p>This might work for you:</p>
<pre><code>import numpy as np
import numba as nb
@nb.jit(nopython=True)
def randomSlice_nb(str1, str2):
lenstr = len(str1)
rnd = np.random.randint(1, lenstr)
out1 = np.empty_like(str1)
out2 = np.empty_like(str1)
out1[:rnd] = str1[:rnd]
out1[rnd:] = str2[rnd:]
... | 1 | 2016-08-01T18:11:23Z | [
"python",
"numpy",
"numba"
] |
using MultiSelect widget to hide and show lines in bokeh | 38,705,123 | <p>i'm working with four sets of data, each of them have several number of time series. i'm using bokeh for plotting all of them together, the result looks like this:</p>
<p><a href="http://i.stack.imgur.com/u0Azi.png" rel="nofollow">multiline graph bokeh with widget </a></p>
<pre><code>from bokeh.plotting import fig... | 1 | 2016-08-01T17:50:17Z | 38,706,613 | <p>Support for doing exactly that (using a MultiSelect widget to hide/show lines) was just added in version 0.12.1 in this PR: <a href="https://github.com/bokeh/bokeh/pull/4868" rel="nofollow">https://github.com/bokeh/bokeh/pull/4868</a></p>
<p>There's an example here (copied below): <a href="https://github.com/bokeh/... | 0 | 2016-08-01T19:24:25Z | [
"python",
"python-2.7",
"widget",
"bokeh"
] |
Django using custom SQL instead of models to return JSON object to template | 38,705,147 | <p>I currently am able to retrieve JSON data/object from my models.py and MySQL database and send that JSON object to my template. How would I be able to use custom SQL to retrieve data from MySQL then make it into a JSON object to send to my template. I basically don't want to use models.py at all. Here is what I have... | 1 | 2016-08-01T17:51:21Z | 38,705,372 | <p>If you want instances of the Model, you're looking for the <a href="https://docs.djangoproject.com/en/1.9/topics/db/sql/" rel="nofollow"><code>raw</code></a> method on the objects property.</p>
<pre><code>platforms = Platform.objects.raw('SELECT * FROM Platform')
</code></pre>
<p>If you're just looking for content... | 1 | 2016-08-01T18:06:46Z | [
"python",
"mysql",
"json",
"django"
] |
redis not working in my python django app | 38,705,235 | <p>I first followed the tutorial on the heroku site. I did this</p>
<pre><code>pip install rq
</code></pre>
<p>then in a worker.py file</p>
<pre><code>import os
import redis
from rq import Worker, Queue, Connection
listen = ['high', 'default', 'low']
redis_url = os.getenv('REDISTOGO_URL', 'redis:/... | 0 | 2016-08-01T17:57:29Z | 38,710,498 | <p>You need to run the redis server. Type redis-server on you console to start the server(Mac OSX).</p>
<pre><code>$redis-server
</code></pre>
<p>Remember that the worker needs a broker(redis) in order to communicate with your app. </p>
| 0 | 2016-08-02T01:33:31Z | [
"python",
"django",
"heroku",
"redis"
] |
How to give sns.clustermap a precomputed distance matrix? | 38,705,359 | <p>Usually when I do dendrograms and heatmaps, I use a distance matrix and do a bunch of <code>SciPy</code> stuff. I want to try out <code>Seaborn</code> but <code>Seaborn</code> wants my data in rectangular form (rows=samples, cols=attributes, not a distance matrix)? </p>
<p>I essentially want to use <code>seaborn</... | 8 | 2016-08-01T18:05:36Z | 38,858,404 | <p>You can pass the precomputed distance matrix as linkage to <code>clustermap()</code>:</p>
<pre><code>import pandas as pd, seaborn as sns
import scipy.spatial as sp, scipy.cluster.hierarchy as hc
from sklearn.datasets import load_iris
sns.set(font="monospace")
iris = load_iris()
X, y = iris.data, iris.target
DF = p... | 1 | 2016-08-09T18:55:33Z | [
"python",
"matplotlib",
"heatmap",
"seaborn",
"hierarchical-clustering"
] |
Django sorting by date(day) | 38,705,451 | <p>I want to sort models by day first and then by score, meaning I'd like to see the the highest scoring Articles in each day. </p>
<pre><code>class Article(models.Model):
date_modified = models.DateTimeField(blank=True, null=True)
score = models.DecimalField(max_digits=5, decimal_places=3, blank=True, null=True)
</c... | 1 | 2016-08-01T18:11:55Z | 38,705,818 | <p>I guess you should use the standar date ordering, without extra method. Format processing is a template responsability.</p>
<pre><code>Article.objects.filter(category='Art').order_by=('-date_modified', '-score')
</code></pre>
<p>Then in you template, you can show the date in the format you want. I leave you an exa... | 1 | 2016-08-01T18:36:39Z | [
"python",
"django",
"sorting"
] |
Django sorting by date(day) | 38,705,451 | <p>I want to sort models by day first and then by score, meaning I'd like to see the the highest scoring Articles in each day. </p>
<pre><code>class Article(models.Model):
date_modified = models.DateTimeField(blank=True, null=True)
score = models.DecimalField(max_digits=5, decimal_places=3, blank=True, null=True)
</c... | 1 | 2016-08-01T18:11:55Z | 38,707,048 | <p>If you're using Django >= 1.8 you can use a <a href="https://docs.djangoproject.com/en/1.9/ref/models/expressions/#func-expressions" rel="nofollow"><code>Func</code></a> expression. The problem you're experiencing is that the <code>%</code> notation is passed directly to the database adapter, which is trying to repl... | 1 | 2016-08-01T19:52:45Z | [
"python",
"django",
"sorting"
] |
Django sorting by date(day) | 38,705,451 | <p>I want to sort models by day first and then by score, meaning I'd like to see the the highest scoring Articles in each day. </p>
<pre><code>class Article(models.Model):
date_modified = models.DateTimeField(blank=True, null=True)
score = models.DecimalField(max_digits=5, decimal_places=3, blank=True, null=True)
</c... | 1 | 2016-08-01T18:11:55Z | 38,709,728 | <pre><code>from django.db.models import DateTimeField
from django.db.models.functions import Trunc
Article.objects.order_by(
Trunc('date_modified', 'date', output_field=DateTimeField()).desc(),
'-score')
</code></pre>
<ul>
<li><a href="https://docs.djangoproject.com/en/1.10/ref/models/database-functions/#trun... | 1 | 2016-08-01T23:49:11Z | [
"python",
"django",
"sorting"
] |
how to update to a specific versionh of pyserial 2.6 | 38,705,458 | <p>I want to update to pyserial 2.6,I normally install using pip install pyserial,is there a pip command to install to a specific version</p>
| 0 | 2016-08-01T18:12:31Z | 38,707,186 | <pre><code>pip install pyserial==2.6
</code></pre>
<p>or you can as well use >= and <=</p>
<p>Also, try <code>pip help install</code> to get more help on pip installation options</p>
| 0 | 2016-08-01T20:02:22Z | [
"python",
"pip",
"pyserial"
] |
Regex to match only part of certain line | 38,705,502 | <p>I have some config file from which I need to extract only some values. For example, I have this:</p>
<pre><code>PART
{
title = Some Title
description = Some description here. // this 2 params are needed
tags = qwe rty // don't need this param
...
}
</code></pre>
<p>I need to extract value of... | -1 | 2016-08-01T18:16:18Z | 38,705,605 | <p>This is a pretty simple regex, you just need a positive lookbehind, and optionally something to remove the comments. (do this by appending <code>?(//)?</code> to the regex)</p>
<pre><code>r"(?<=description = ).*"
</code></pre>
<p><a href="https://regex101.com/r/bL4dQ9/1" rel="nofollow">Regex101 demo</a></p>
| -1 | 2016-08-01T18:23:01Z | [
"python",
"regex",
"python-3.x"
] |
Regex to match only part of certain line | 38,705,502 | <p>I have some config file from which I need to extract only some values. For example, I have this:</p>
<pre><code>PART
{
title = Some Title
description = Some description here. // this 2 params are needed
tags = qwe rty // don't need this param
...
}
</code></pre>
<p>I need to extract value of... | -1 | 2016-08-01T18:16:18Z | 38,705,715 | <p>The better approach would be to use an established configuration file system. Python has built-in support for INI-like files in the <a href="https://docs.python.org/3/library/configparser.html" rel="nofollow"><code>configparser</code></a> module.</p>
<p>However, if you just <em>desperately</em> need to get the stri... | 0 | 2016-08-01T18:30:50Z | [
"python",
"regex",
"python-3.x"
] |
Regex to match only part of certain line | 38,705,502 | <p>I have some config file from which I need to extract only some values. For example, I have this:</p>
<pre><code>PART
{
title = Some Title
description = Some description here. // this 2 params are needed
tags = qwe rty // don't need this param
...
}
</code></pre>
<p>I need to extract value of... | -1 | 2016-08-01T18:16:18Z | 38,705,796 | <p>Here is the regex, assuming that the file text is in <code>txt</code>:</p>
<pre><code>import re
m = re.search(r'^\s*description\s*=\s*(.*?)(?=(//)|$)', txt, re.M)
print(m.group(1))
</code></pre>
<p>Let me explain.
<code>^</code> matches at beginning of line.
Then <code>\s*</code> means zero or more spaces (or tab... | 1 | 2016-08-01T18:35:44Z | [
"python",
"regex",
"python-3.x"
] |
Beginning Python: Find greatest number from function that gives input list of positive integers | 38,705,555 | <ol>
<li><p>New to python, having trouble getting the function to display the greatest number, for some reason I have the number display the least.
The quiz I am using used this code as the final solution, I think it is wrong, any help appreciated. </p>
<pre><code># Define a procedure, greatest,
# that takes as input... | 0 | 2016-08-01T18:19:54Z | 38,705,576 | <p>You are returning on the first iteration. Move your return out one level:</p>
<pre><code>def greatest(list_of_numbers):
big = 0
for i in list_of_numbers:
if i > big:
big = i
return big
</code></pre>
<p>However this is entirely unnecessary as Python has this built in:</p>
<pre... | 3 | 2016-08-01T18:21:33Z | [
"python"
] |
Split a unicode string into components containing numbers and letters | 38,705,622 | <p>I'd like to split the string <code>u'123K</code> into <code>123</code> and <code>K</code>. I've tried <code>re.match("u'123K", "\d+")</code> to match the number and <code>re.match("u'123K", "K")</code> to match the letter but they don't work. What is a Pythonic way to do this?</p>
| 0 | 2016-08-01T18:24:40Z | 38,705,649 | <p>Use <code>re.findall()</code> to find all numbers and characters:</p>
<pre><code>>>> s = u'123K'
>>> re.findall(r'\d+|[a-zA-Z]+', s) # or use r'\d+|\D+' as mentioned in comment in order to match all numbers and non-numbers.
['123', 'K']
</code></pre>
<p>If you are just dealing with this string or... | 2 | 2016-08-01T18:26:50Z | [
"python",
"regex"
] |
Split a unicode string into components containing numbers and letters | 38,705,622 | <p>I'd like to split the string <code>u'123K</code> into <code>123</code> and <code>K</code>. I've tried <code>re.match("u'123K", "\d+")</code> to match the number and <code>re.match("u'123K", "K")</code> to match the letter but they don't work. What is a Pythonic way to do this?</p>
| 0 | 2016-08-01T18:24:40Z | 38,705,819 | <p>You can also use <a href="https://docs.python.org/3.4/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> method, grouping digits:</p>
<pre><code>>>> import itertools as it
>>> for _,v in it.groupby(s, key=str.isdigit):
print(''.join(v))
123
K
</co... | 0 | 2016-08-01T18:36:40Z | [
"python",
"regex"
] |
In advanced collections module in python 2.7. What is the difference between Counter(dict(c.items)) and dict(c) | 38,705,698 | <pre><code>//This is the code
sen = 'How many times does each word show up in the sentence word word shows up up shows'
words = sen.split()
c = Counter(words)
dict(c)
Counter(dict(c.items()))
</code></pre>
<p>//Output</p>
<pre><code>//output of dict(c)
{'How': 1,
'does': 1,
'each': 1,
'in': 1,
'many': 1,
'... | -5 | 2016-08-01T18:29:33Z | 38,705,782 | <p>Read the docs about <a href="https://docs.python.org/2/library/collections.html#collections.Counter" rel="nofollow">Counters</a>. They're generally used for tallying only. It provides other operations that aren't available with vanilla <code>dict</code>'s. </p>
| 0 | 2016-08-01T18:35:14Z | [
"python"
] |
In python, how do I scan a text file with one long row and separate the items into different columns? | 38,705,701 | <p>I have a text file that looks like this:</p>
<pre><code>âDistance 1: Distance XYâ 1 2 4 5 9 âDistance 2: Distance XYâ 3 6 8 10 5 âDistance 3: Distance XYâ 88 45 36 12 4
</code></pre>
<p>It is all on one big line like this. My question is how do I take this and separate the distance measurements ... | 3 | 2016-08-01T18:29:53Z | 38,705,784 | <p>You can use <code>re.split</code> to split the string with regular expressions:</p>
<pre><code>import re
s = '\"Distance 1: Distance XY\" 1 2 4 5 9 \"Distance 2: Distance XY\" 3 6 8 10 5 \"Distance 3: Distance XY\" 88 45 36 12 4'
re.split(r'(?<=\d)\s+(?=\")', s)
# ['"Distance 1: Distance XY" 1 2 4 5 9',
# ... | 5 | 2016-08-01T18:35:21Z | [
"python"
] |
In python, how do I scan a text file with one long row and separate the items into different columns? | 38,705,701 | <p>I have a text file that looks like this:</p>
<pre><code>âDistance 1: Distance XYâ 1 2 4 5 9 âDistance 2: Distance XYâ 3 6 8 10 5 âDistance 3: Distance XYâ 88 45 36 12 4
</code></pre>
<p>It is all on one big line like this. My question is how do I take this and separate the distance measurements ... | 3 | 2016-08-01T18:29:53Z | 38,705,928 | <p>A perhaps less elegant solution than Psidom's, assuming the lines have the same format every time:</p>
<pre><code>with open("input.txt", 'r') as file:
line = file.read()
line = line.split()
count = 0
output = open("output.txt", 'w')
for i in line:
output.write(i)
output.write(" "... | 1 | 2016-08-01T18:42:47Z | [
"python"
] |
In python, how do I scan a text file with one long row and separate the items into different columns? | 38,705,701 | <p>I have a text file that looks like this:</p>
<pre><code>âDistance 1: Distance XYâ 1 2 4 5 9 âDistance 2: Distance XYâ 3 6 8 10 5 âDistance 3: Distance XYâ 88 45 36 12 4
</code></pre>
<p>It is all on one big line like this. My question is how do I take this and separate the distance measurements ... | 3 | 2016-08-01T18:29:53Z | 38,706,140 | <p>A attempt to better Andrew's fine answer.</p>
<pre><code>with open("input.txt", 'r') as file:
output = open("output.txt", 'w')
for line in file:
line = line.split()
relevant_line = line[0:9]
relevant_line_as_string = " ".join(relevant_line)
output.write(relevant_line_as_strin... | 1 | 2016-08-01T18:56:06Z | [
"python"
] |
Scrape data from a page that requires a login | 38,705,748 | <p>I am new to Python and Web Scapping and I am trying to write a very basic script that will get data from a webpage that can only be accessed after logging in. I have looked at a bunch of different examples but none are fixing the issue. This is what I have so far: </p>
<pre><code>from bs4 import BeautifulSoup
imp... | 1 | 2016-08-01T18:32:36Z | 38,705,775 | <p>You can use the <code>requests</code> module.</p>
<p>Take a look at this answer that i've linked below.</p>
<p><a href="http://stackoverflow.com/a/8316989/6464893">http://stackoverflow.com/a/8316989/6464893</a></p>
| 0 | 2016-08-01T18:34:47Z | [
"python",
"cookies",
"login",
"web-scraping",
"beautifulsoup"
] |
setting qml property from Python? | 38,705,765 | <p>I'm trying to use Python, PySide and a sample QML file to make a simple ui.
How can I set the "value" property available in the QML control from my Python app? As of now, the "SpeedDial" show up, but can't figure out how to change it's value.</p>
<p><strong>Python file:</strong></p>
<pre><code>import sys
from PySi... | 1 | 2016-08-01T18:34:07Z | 38,714,550 | <p>You're not supposed to control QML properties directly from Python or C++.</p>
<p>Define a Python class that will represent a car with a property <code>speed</code>. Instantiate it in QML like that:</p>
<pre><code>Car {
id: car
}
</code></pre>
<p>and then use its speed:</p>
<pre><code>angle: car.speed
</cod... | 0 | 2016-08-02T07:43:30Z | [
"python",
"qt",
"qml",
"pyside"
] |
How to approach this multithreading task, problems with logical structure | 38,705,778 | <p>I have two ICs which convert sensor signals connected to a Raspberry Pi:</p>
<ul>
<li>IC1 sends his data every 2 seconds as a serial telegram.</li>
<li>IC2 is an ADC that sends its data after receiving a certain control signal.</li>
</ul>
<p>I have written separate codes that let me extract the measurement values ... | 0 | 2016-08-01T18:34:59Z | 38,709,083 | <p>I found my mistake:</p>
<pre><code>interrupt = threading.Thread(target=self.stopAvg())
recording = threading.Thread(target=self._record())
</code></pre>
<p>The brackets inside target's argument don't belong there!</p>
<pre><code>interrupt = threading.Thread(target=self.stopAvg)
recording = threading.Thread(target... | 0 | 2016-08-01T22:29:30Z | [
"python",
"multithreading",
"python-2.7"
] |
how to use find all method from BS4 to scrape certain strings | 38,705,805 | <pre><code><li class="sre" data-tn-component="asdf-search-result" id="85e08291696a3726" itemscope="" itemtype="http://schema.org/puppies">
<div class="sre-entry">
<div class="sre-side-bar">
</div>
<div class="sre-content">
<div class="clickable_asdf_card" onclick="wi... | 3 | 2016-08-01T18:36:16Z | 38,705,856 | <p>Use <code>BeautifulSoup</code>'s <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#a-regular-expression" rel="nofollow">built-in regular expression search</a> to find and extract the desired substring from an <code>onclick</code> attribute value:</p>
<pre><code>import re
pattern = re.compile(r"window... | 2 | 2016-08-01T18:38:42Z | [
"python",
"python-3.x",
"web-scraping",
"beautifulsoup",
"bs4"
] |
Merge Sorted Array in leetcode: The in-place modification of list doesn't work | 38,705,954 | <p>The link to the question: <a href="https://leetcode.com/problems/merge-sorted-array/" rel="nofollow">merge sorted array</a></p>
<p>I don't know why my solution doesn't modify the list nums1 when exiting the function <strong>merge</strong>. Here is the code:</p>
<pre><code>def merge(self, nums1, m, nums2, n):
"... | 1 | 2016-08-01T18:44:33Z | 38,706,080 | <p>lists are mutable, so you can create the behavior that you are looking for. What you need to do is to assign new values to specific indices in nums1. When you use splicing you are in fact creating new lists. Use list functions like <code>[].insert()</code>, <code>[].pop()</code>, <code>[].extend()</code> to achie... | 0 | 2016-08-01T18:52:47Z | [
"python",
"arrays"
] |
fastest format to load saved graph structure into python-igraph | 38,706,050 | <p>I have a very large network structure which I am working with in igraph. There are many different file formats which igraph Graph objects can write to and then be loaded from. I ran into memory problems when using g.write_picklez, and Graph.Read_Lgl() takes about 5 minutes to finish. I was wondering if anyone had al... | 0 | 2016-08-01T18:50:55Z | 38,720,955 | <p>If you don't have vertex or edge attributes, your best bet is a simple edge list, i.e. <code>Graph.Read_Edgelist()</code>. The disadvantage is that it assumes that vertex IDs are in the range [0; |V|-1], so you'll need to have an additional file next to it where line <em>i</em> contains the name of the vertex with I... | 1 | 2016-08-02T12:51:30Z | [
"python",
"profiling",
"igraph"
] |
Creating a Python list or dictionary with a set number of rows, but variable number of columns per row | 38,706,095 | <p>I'm working with images and want to create a list of lists of arrays. For example, a list with 5 rows, where each row has a variable number of images (3x200x100) stored in them ranging from 2 images to 10 images.</p>
<p>I've ruled out numpy and concatenation since they need the matrix to be uniform. I've tried appe... | 0 | 2016-08-01T18:54:01Z | 38,706,158 | <p>How about something like this?</p>
<pre><code>row1 = [1,2,3,4,5,6]
row2 = [1,2,3]
matrix = [row1, row2]
row3 = [1,2,4,5,6,7,8,9]
matrix.append(row3)
</code></pre>
| 0 | 2016-08-01T18:57:01Z | [
"python",
"list",
"numpy"
] |
python imap not calling function for all items in list | 38,706,132 | <p>I am trying to use python3.5 to parallelize CodeML by calling separate instances on different threads. I've gotten everything to work up to a point. If I provide <code>Pool.imap</code> (or <code>Pool.map</code>) with an iterable that contains more variables than cores the program has available, it will only run one... | -1 | 2016-08-01T18:55:45Z | 38,839,518 | <p>I figured out the problem was with another program I was calling. I set that to run in a different step, so it runs on one thread before Pool.imap is called.</p>
| 0 | 2016-08-08T22:36:59Z | [
"python",
"python-multiprocessing"
] |
Pandas Dataframe - Lookup Error | 38,706,196 | <p>I am attempting to lookup a row in a pandas (version 0.14.1) dataframe using a date and stock ticker combination and am receiving a strange error.</p>
<p>My pandas dataframe that looks like this:</p>
<pre><code> AAPL IBM GOOG XOM Date
2011-01-10 16:00:00 340.99 143.41 614... | 1 | 2016-08-01T18:58:59Z | 38,706,311 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.lookup.html" rel="nofollow"><code>df.lookup</code></a> expects 2 array-likes (instead of scalars) as arguments:</p>
<pre><code>In [25]: df.lookup(row_labels=[DT.datetime(2011,1,10,16,0)], col_labels=['AAPL'])
Out[25]: array([ 340.99])
<... | 4 | 2016-08-01T19:05:27Z | [
"python",
"pandas"
] |
How can I inline every n objects within a loop in html with flask using jinja | 38,706,259 | <p>Let us say I have 30 numbers 1-30. If I loop through the list in flask and print out the numbers (<p>{{ num }}</p>), It will print out like so:</p>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>...</p>
<p>What I want to do is to have it print out like this:</p>
<p>1 2 3</p>
<p>4 5 6</p>
<p>7 8 9</p>
<p>so that 3 ... | 0 | 2016-08-01T19:02:33Z | 38,706,377 | <p>Maybe something like this?</p>
<pre><code>{% if num % 3 == 0 %}
{{ num }} <br>
{% else %}
{{ num }}
{% endif %}
</code></pre>
<p>Assuming you're using <code>jinja2</code> for templates</p>
| 1 | 2016-08-01T19:09:52Z | [
"python",
"flask"
] |
pandas.HDFStore: How do I modify "data_columns" for an existing store? I'd like to add an index to a column not in data columns | 38,706,359 | <p>I have created a large (120GB; 1 billion rows) HDF5 file using pandas. After an initial creation of the hdf file, I added to the file like so:</p>
<pre><code>with pd.get_store(path_output) as hdf_output:
for i in range(BIG_LOOP):
df = ...
hdf_output.append('all', df, data_columns=[])
</code></pre>
<p>I p... | 1 | 2016-08-01T19:08:55Z | 38,707,659 | <p>I'd do it bit differently - <a href="http://stackoverflow.com/a/38472574/5741205">take a look at this small example</a>:</p>
<pre><code>for chunk in ... # reading data in chunks:
# specify `data_columns`, but don't index (`index=False`)
hdf_output.append('all', chunk, data_columns=[cols_to_index], index=Fa... | 1 | 2016-08-01T20:35:37Z | [
"python",
"pandas",
"hdf5",
"pytables",
"hdfstore"
] |
Python Challenge- #3: it prints random letters instead of 7 | 38,706,413 | <pre><code>import re
b=re.findall('[A-Z]+[a-z]+[A-Z]',k)
for i in b:
print (i)
</code></pre>
<p>I have written this code. The string in k is too long to print here.
I need to find all sets of sub strings where the middle later is in lower case and three letters exactly on each side is upper case.
I think this ... | 0 | 2016-08-01T19:11:57Z | 38,706,604 | <p>Your regexp shouldn't contain <code>+</code>, which matches 1 or more uppercase letters. If you need to get something like <code>AAAbCCC</code> just try:</p>
<pre><code>b=re.findall('[A-Z]{3}[a-z][A-Z]{3}',k)
</code></pre>
| 0 | 2016-08-01T19:23:42Z | [
"python"
] |
Python Challenge- #3: it prints random letters instead of 7 | 38,706,413 | <pre><code>import re
b=re.findall('[A-Z]+[a-z]+[A-Z]',k)
for i in b:
print (i)
</code></pre>
<p>I have written this code. The string in k is too long to print here.
I need to find all sets of sub strings where the middle later is in lower case and three letters exactly on each side is upper case.
I think this ... | 0 | 2016-08-01T19:11:57Z | 38,706,653 | <p>You can specify repetitions of a atom/range/group with <code>{n}</code> where n is an integer.</p>
<p>I'd change your regexp to <code>[A-Z]{3}[a-z]+[A-Z]{3}</code>, or better, if the middle substring must be only one letter, remove the <code>+</code>, because that would match 1 <em>or more</em> lowercase characters... | 0 | 2016-08-01T19:27:00Z | [
"python"
] |
looping through user input with an if condition | 38,706,631 | <p>Hi I want to loop through this input if balance does not match the sum of book balances(pp, bfair, sky, freds wh)</p>
<pre><code>while True:
try:
balance = float(raw_input('Balance:'))
print balance
except ValueError:
print"That's not a number"
continu... | 0 | 2016-08-01T19:25:48Z | 38,706,831 | <p>Yes.</p>
<p>And consider using functions to avoid repetitions in your code:</p>
<pre><code>def ask_float(msg):
while True:
try:
x = float(raw_input(msg))
print x
return x
except ValueError:
print "That's not a number"
continue
while ... | 0 | 2016-08-01T19:39:11Z | [
"python",
"loops",
"input",
"user"
] |
How to ignore path when extracting zip file in python | 38,706,644 | <p>I want to ignore the path of a file stored in a zip.
I use the following:</p>
<pre><code>ZipFile.extract('/ignorepath/filename.txt', '/mygoodpath')
</code></pre>
<p>This will create the followng:</p>
<blockquote>
<p>/mygoodpath/ignorepath/filename.txt</p>
</blockquote>
<p>I would prefer </p>
<blockquote>
<... | 0 | 2016-08-01T19:26:33Z | 38,707,240 | <p>Try using <a href="https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.open" rel="nofollow">Zipfile.open</a></p>
<pre><code>with ZipFile('spam.zip') as myzip:
with myzip.open('/ignorepath/filename.txt') as infile:
with open('/mygoodpath/filename.txt', 'w') as outfile:
outfile.writ... | 0 | 2016-08-01T20:06:28Z | [
"python",
"path",
"zip"
] |
html5 websockets closing connect when a link is clicked | 38,706,655 | <p>I use the javascript websocket to connect to the websocket server. I use python flask framework to navigate through webpages.</p>
<p>my project is as below:</p>
<ol>
<li>the route "/" renders index.html page. In this page, I create a
websocket connection.</li>
<li>when I receive data from the server, I navigate to... | 0 | 2016-08-01T19:27:07Z | 38,720,960 | <p>The WebSocket connection only persists as long as the page it was established for is open. Loading another page closes the WebSocket, so storing a reference to the object does not help (what it references no longer exists). You need to establish a new WebSocket connection after each page load.
(For an older look in... | 0 | 2016-08-02T12:51:58Z | [
"javascript",
"python",
"html5",
"google-chrome",
"websocket"
] |
Create new folder with timestamp and then move files to new folder | 38,706,664 | <p>I'm having trouble with this ... I want to create a new folder with a time stamped name. Then I want to move a bunch of files into it.</p>
<p>I can't figure it out!</p>
<pre><code>import shutil, os, time
timestr = time.strftime("%Y%m%d")
Sourcepath = r'Z:\\test'
if not os.path.exists(Sourcepath):
os.mak... | 0 | 2016-08-01T19:27:46Z | 38,706,878 | <p>Does this fix your problem. Notice indentation of last line</p>
<pre><code>import shutil, os, time
timestr = time.strftime("%Y%m%d")
Sourcepath = r'Z:\\test'
if not os.path.exists(Sourcepath):
os.makedirs(Sourcepath+timestr)
source = os.listdir(Sourcepath)
destinationpath = (Sourcepath+timestr) ... | 0 | 2016-08-01T19:41:48Z | [
"python",
"timestamp",
"shutil"
] |
Is it possible to use SQL Server in python without external libs? | 38,706,720 | <p>I'm developing on an environment which I'm not allowed to install anything. It's a monitoring server and I'm making a script to work with logs and etc.</p>
<p>So, I need to connect to a SQL Server with Python 2.7 without any lib like pyodbc installed. Is it possible to make this? I've found nothing I could use to c... | -1 | 2016-08-01T19:32:04Z | 38,706,901 | <p>There are certain things you can do to run sql from the command line from python:</p>
<pre><code>import subprocess
x = subprocess.check_output('sqlcmd -Q "SELECT * FROM db.table"')
print x
</code></pre>
| 2 | 2016-08-01T19:43:30Z | [
"python",
"sql-server"
] |
Obfuscate Data in .csv from a .txt file | 38,706,754 | <p>I would like to obfuscate words that occur in a column of a .csv file based on a list of data to remove that are in a different .txt file. </p>
<p>Ideally I will be able to ignore the case of my data and then in the .csv file, replace the matching words from the "to remove" file with an <code>'*'</code>. I am not s... | 0 | 2016-08-01T19:34:17Z | 38,707,475 | <p>I would start by constructing a set of censor words. My input is basically a plain text file of newline separated words. If your text file is different you might need to parse separately. </p>
<p>Other thoughts:</p>
<p>Create a separate censored file output instead of trying to overwrite your input file. That way ... | 0 | 2016-08-01T20:23:47Z | [
"python",
"csv"
] |
Student - np.random.choice: How to isolate and tally hit frequency within a np.random.choice range | 38,706,796 | <p>Currently learning Python and very new to Numpy & Panda</p>
<p>I have pieced together a random generator with a range. It uses Numpy and I am unable to isolate each individual result to count the iterations within a range within my random's range.</p>
<p>Goal: Count the iterations of "Random >= 1000" and then... | 0 | 2016-08-01T19:36:36Z | 38,707,934 | <p>I believe you are mixing up iterations and generations. It sounds like you want 4 iterations for N numbers of generations, but your bottom piece of code does not express the "4" anywhere. If you pull all your variables out to the top of your script it can help you organize better. Panda is great for parsing complica... | 0 | 2016-08-01T20:53:41Z | [
"python",
"pandas",
"numpy",
"random",
"range"
] |
How to Remove a Substring of String in a Dataframe Column? | 38,706,813 | <p>I have this simplified dataframe:</p>
<pre><code>ID, Date
1 8/24/1995
2 8/1/1899 :00
</code></pre>
<p>How can I use the power of pandas to recognize any date in the dataframe which has extra <code>:00</code> and removes it. </p>
<p>Any idea how to solve this problem?</p>
<p>I have tried this syntax but did not h... | 2 | 2016-08-01T19:37:39Z | 38,706,893 | <p>You need to assign the trimmed column back to the original column instead of doing subsetting, and also the <code>str.replace</code> method doesn't seem to have the <code>to_replace</code> and <code>value</code> parameter. It has <code>pat</code> and <code>repl</code> parameter instead:</p>
<pre><code>df["Date"] = ... | 3 | 2016-08-01T19:42:49Z | [
"python",
"regex",
"string",
"pandas",
"dataframe"
] |
How to Remove a Substring of String in a Dataframe Column? | 38,706,813 | <p>I have this simplified dataframe:</p>
<pre><code>ID, Date
1 8/24/1995
2 8/1/1899 :00
</code></pre>
<p>How can I use the power of pandas to recognize any date in the dataframe which has extra <code>:00</code> and removes it. </p>
<p>Any idea how to solve this problem?</p>
<p>I have tried this syntax but did not h... | 2 | 2016-08-01T19:37:39Z | 38,706,935 | <p>To apply this to an entire dataframe, I'd <code>stack</code> then <code>unstack</code></p>
<pre><code>df.stack().str.replace(r'\s:00', '').unstack()
</code></pre>
<p><a href="http://i.stack.imgur.com/MmbsN.png" rel="nofollow"><img src="http://i.stack.imgur.com/MmbsN.png" alt="enter image description here"></a></p>... | 2 | 2016-08-01T19:45:34Z | [
"python",
"regex",
"string",
"pandas",
"dataframe"
] |
Edit & save dictionary in another python file | 38,706,855 | <p>I have 2 python files, file1.py has only 1 dictionary and I would like to read & write to that dictionary from file2.py. Both files are in same directory.</p>
<p>I'm able to read from it using <strong>import file1</strong> but how do I write to that file.</p>
<p>Snippet:</p>
<p>file1.py (nothing additional in... | 0 | 2016-08-01T19:40:18Z | 38,706,923 | <p>You should use the pickle library to save and load the dictionary <a href="https://wiki.python.org/moin/UsingPickle" rel="nofollow">https://wiki.python.org/moin/UsingPickle</a></p>
<p>Here is the basic usage of pickle</p>
<pre><code> 1 # Save a dictionary into a pickle file.
2 import pickle
3
4 favorit... | 0 | 2016-08-01T19:44:59Z | [
"python",
"file",
"dictionary",
"fileupdate"
] |
Edit & save dictionary in another python file | 38,706,855 | <p>I have 2 python files, file1.py has only 1 dictionary and I would like to read & write to that dictionary from file2.py. Both files are in same directory.</p>
<p>I'm able to read from it using <strong>import file1</strong> but how do I write to that file.</p>
<p>Snippet:</p>
<p>file1.py (nothing additional in... | 0 | 2016-08-01T19:40:18Z | 38,706,973 | <p>I think you want to save the data from <code>file1</code> into a separate <code>.json</code> file, then read the <code>.json</code> file in your second file. Here is what you can do:</p>
<p><strong>file1.py</strong></p>
<pre><code>import json
dict1 = {
'a' : 1, # value is integer
'b' : '5xy', ... | 0 | 2016-08-01T19:47:51Z | [
"python",
"file",
"dictionary",
"fileupdate"
] |
Edit & save dictionary in another python file | 38,706,855 | <p>I have 2 python files, file1.py has only 1 dictionary and I would like to read & write to that dictionary from file2.py. Both files are in same directory.</p>
<p>I'm able to read from it using <strong>import file1</strong> but how do I write to that file.</p>
<p>Snippet:</p>
<p>file1.py (nothing additional in... | 0 | 2016-08-01T19:40:18Z | 38,707,046 | <p>If you are attempting to print the dictionary back to the file, you could use something like...</p>
<pre><code>outFile = open("file1.py","w")
outFile.writeline("dict1 = " % (str(dict2)))
outFile.close()
</code></pre>
<p>You might be better off having a json file, then loading the object from and writing the object... | 0 | 2016-08-01T19:52:42Z | [
"python",
"file",
"dictionary",
"fileupdate"
] |
Edit & save dictionary in another python file | 38,706,855 | <p>I have 2 python files, file1.py has only 1 dictionary and I would like to read & write to that dictionary from file2.py. Both files are in same directory.</p>
<p>I'm able to read from it using <strong>import file1</strong> but how do I write to that file.</p>
<p>Snippet:</p>
<p>file1.py (nothing additional in... | 0 | 2016-08-01T19:40:18Z | 38,710,044 | <p>Finally as @Zaren suggested, I used a json file instead of dictionary in python file.</p>
<p>Here's what I did:</p>
<ol>
<li><p>Modified <strong>file1.py</strong> to <strong>file1.json</strong> and store the data with appropriate formatting.</p></li>
<li><p>From <strong>file2.py</strong>, I opened <strong>file1.js... | 0 | 2016-08-02T00:29:51Z | [
"python",
"file",
"dictionary",
"fileupdate"
] |
Difference between get_lines() method of axes and legend | 38,706,857 | <p>In the code</p>
<pre><code>from matplotlib.figure import Figure
fig1 = Figure()
ax1 = fig1.add_subplot(111)
p1 = ax1.plot([1,2,3], label='123')
lg1 = ax1.legend()
</code></pre>
<p><code>lg1.get_lines()[0] == ax1.get_lines()[0]</code> evaluates to false even though they should be referring to the same line. May I ... | 0 | 2016-08-01T19:40:26Z | 38,711,329 | <p>The short answer is that they are different instances of objects in memory. </p>
<pre><code>In [6]: lg1.get_lines()
Out[6]: [<matplotlib.lines.Line2D at 0x10e355828>]
In [7]: ax1.get_lines()
Out[7]: <a list of 1 Line2D objects>
In [8]: list(ax1.get_lines())
Out[8]: [<matplotlib.lines.Line2D at 0x10... | 0 | 2016-08-02T03:28:56Z | [
"python",
"matplotlib",
"legend"
] |
search a 2GB WAV file for dropouts using wave module | 38,706,926 | <p>`What is the best way to analyze a 2GB WAV file (1khz Tone) for audio dropouts using wave module? </p>
| 2 | 2016-08-01T19:45:10Z | 38,707,088 | <p>I think a simple solution to this would be to consider that the frame rate on audio files is pretty high. A sample file on my computer happens to have a framerate of 8,000. That means for every second of audio, I have 8,000 samples. If you have missing audio, I'm sure it will exist across multiple frames within a se... | 1 | 2016-08-01T19:56:25Z | [
"python",
"wav"
] |
search a 2GB WAV file for dropouts using wave module | 38,706,926 | <p>`What is the best way to analyze a 2GB WAV file (1khz Tone) for audio dropouts using wave module? </p>
| 2 | 2016-08-01T19:45:10Z | 38,707,693 | <p>At the moment, you're reading the entire file into memory, which is not ideal. If you look at the methods available for a "Wave_read" object, one of them is <code>setpos(pos)</code>, which sets the position of the file pointer to <em>pos</em>. If you update this position, you should be able to only keep the frame ... | 1 | 2016-08-01T20:37:58Z | [
"python",
"wav"
] |
search a 2GB WAV file for dropouts using wave module | 38,706,926 | <p>`What is the best way to analyze a 2GB WAV file (1khz Tone) for audio dropouts using wave module? </p>
| 2 | 2016-08-01T19:45:10Z | 38,708,236 | <p>I haven't used the <code>wave</code> module before, but <code>file1.readframes(i)</code> looks like it's reading 1 frame when you're at the first frame, 2 frames when you're at the second frame, 10 frames when you're in the tenth frame, and a 2Gb CD quality file might have a million frames - by the time you're at fr... | 1 | 2016-08-01T21:14:51Z | [
"python",
"wav"
] |
Cannot compile pyethash python package which requires C99 compiler (AFAIU). Error - Cannot open include file: 'alloca.h' | 38,706,927 | <h1>Problem</h1>
<p>When installing pyethash manually or with pip I get the same kind of error:</p>
<blockquote>
<p>fatal error C1083: Cannot open include file: 'alloca.h': No such file
or directory error: command 'C:\Program Files (x86)\Microsoft Visual
Studio 9.0\VC\BIN\amd64\cl.exe' failed with exit status 2... | 0 | 2016-08-01T19:45:16Z | 38,709,510 | <p><code>alloca</code> <strong>alloc</strong>ates <strong>a</strong>utomatic memory and as Jens Gustedt noted is not standardised.</p>
<p>MSVCRT declares it in the <a href="https://msdn.microsoft.com/en-us/library/wb1s57t5.aspx" rel="nofollow"><code><malloc.h></code> header</a>. Its implementation on Windows ali... | 0 | 2016-08-01T23:19:37Z | [
"python",
"c++",
"c",
"compiler-errors",
"c99"
] |
Pandas Dataframe and Converting DateTime Objects | 38,706,932 | <p>I have multiple datettime columns in my dataframe and when I export the datetime to csv, I need to convert the datetime from Month/Day/Year to Month/Year. Is it possible to do this?</p>
<p>I was trying this:</p>
<pre><code>if date_mask == "MMM":
df[name].apply(lambda x: x.strftime('%b %Y'))
else:
df[name]... | 0 | 2016-08-01T19:45:25Z | 38,717,978 | <p>Solution</p>
<pre><code>def modify_date(x):
try:
if pd.isnull(x) == False:
return x.strftime('%b %Y')
else:
print pd.NaT
except:
return pd.NaT
df = pd.DateFrame.from_records(<some list from database>)
df[name] = df[name].apply(modify_date)
</code></pre... | 0 | 2016-08-02T10:30:17Z | [
"python",
"csv",
"datetime",
"pandas"
] |
Setting up a PyCharm environment for a GTK Hello World on Windows | 38,706,946 | <p>I'm just trying to make a simple GTK Hello World app run in Pycharm.</p>
<ul>
<li>I have installed <a href="https://www.jetbrains.com/pycharm/download/#section=windows" rel="nofollow">PyCharm Community Edition</a> 2016.2. </li>
<li>I have installed any combination of <a href="https://www.continuum.io/downloads" rel... | 0 | 2016-08-01T19:46:18Z | 39,975,986 | <p>You need to download the latest installer for windows from: <a href="https://sourceforge.net/projects/pygobjectwin32/files/?source=navbar" rel="nofollow">https://sourceforge.net/projects/pygobjectwin32/files/?source=navbar</a></p>
<p>Also, you must make sure you are not running python 3.5 or newer, the last support... | 0 | 2016-10-11T11:13:54Z | [
"python",
"pycharm",
"pygtk"
] |
How to add more than one feature into the same cell using the grid method, Python Tkinter | 38,707,017 | <p>There might be question like this, but I can't find it.
I want to have more than one entry or label etc. in the same cell without them overlapping. I hope you know what I mean.
Any ideas?</p>
| 0 | 2016-08-01T19:50:52Z | 38,708,108 | <p>Put as many items as you want in a frame, and then put the frame in the grid cell.</p>
<h2>Example</h2>
<pre><code>import tkinter as tk
root = tk.Tk()
# some random widgets, for illustrative purposes
l0 = tk.Label(root, text="Cell 0,0", borderwidth=1, relief="solid")
l1 = tk.Label(root, text="Cell 0,1", borderwi... | 0 | 2016-08-01T21:06:09Z | [
"python",
"tkinter",
"grid"
] |
calling functions via grequests | 38,707,023 | <p>I realize there have been many posts on grequests such as <a href="http://stackoverflow.com/questions/9110593/asynchronous-requests-with-python-requests">Asynchronous Requests with Python requests</a>
which describes the basic usage of grequests and how to send hooks via <code>grequests.get()</code> I pulled this bi... | 0 | 2016-08-01T19:51:12Z | 38,707,579 | <p>I need to check sources yet, but if you rewrite your hook function as </p>
<pre><code># A simple task to do to each response object
def do_something(response, *args, **kwargs):
print ('print_test')
</code></pre>
<p>it puts output. So it's probably failing to call you original hook(because it passes more argume... | 1 | 2016-08-01T20:30:27Z | [
"python",
"asynchronous",
"request",
"grequests"
] |
Running executable that takes arguments using Python | 38,707,087 | <p>I am writing a small python script where I open an existing executable (.exe) and I send a string as an argument.</p>
<p>I am using the subprocess.call method and I get the following error:</p>
<pre><code>File "C:\Python34\lib\subprocess.py", line 537, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Pyt... | 1 | 2016-08-01T19:56:02Z | 38,707,175 | <p>Put the program and any arguments you want into an array first.</p>
<pre><code>import os
import subprocess
x = subprocess.call(["C:\\Users\\Desktop\\Program\\Program.exe", y])
</code></pre>
| 4 | 2016-08-01T20:01:54Z | [
"python",
"exe"
] |
Running executable that takes arguments using Python | 38,707,087 | <p>I am writing a small python script where I open an existing executable (.exe) and I send a string as an argument.</p>
<p>I am using the subprocess.call method and I get the following error:</p>
<pre><code>File "C:\Python34\lib\subprocess.py", line 537, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Pyt... | 1 | 2016-08-01T19:56:02Z | 38,707,183 | <p>The command and arguments should be in a list</p>
<pre><code>x = subprocess.call(["C:\\Users\\Desktop\\Program\\Program.exe", y])
</code></pre>
<p><a href="https://docs.python.org/2/library/subprocess.html#using-the-subprocess-module" rel="nofollow">Documentation</a></p>
| 3 | 2016-08-01T20:02:14Z | [
"python",
"exe"
] |
A novice's hangman project: Dealing with duplicate letters | 38,707,200 | <p>First, I realize the following code is probably not very good, so apologies for anything that makes you cringe, I'm just trying to code as much as I can in hopes of getting better.</p>
<p>This is part of a small hangman game project, I'm trying to figure the best way to deal with duplicate letters in strings.</p>
... | -3 | 2016-08-01T20:03:20Z | 38,707,644 | <p>Based on what you've described in the comments, it seems reasonable to use a <code>dictionary</code> object in this case. You don't just want to store the letter, you want to store <em>where</em> those letters occur. </p>
<p>Dictionaries have a key and a value. For example:</p>
<p><code>{'jack': 4095, 'jill': 12}<... | 1 | 2016-08-01T20:34:19Z | [
"python",
"pygame"
] |
Pandas DataFrame: Cannot convert string into a float | 38,707,242 | <p>I have a column <code>Column1</code> in a pandas dataframe which is of type <code>str</code>, values which are in the following form: </p>
<pre><code>import pandas as pd
df = pd.read_table("filename.dat")
type(df["Column1"].ix[0]) #outputs 'str'
print(df["Column1"].ix[0])
</code></pre>
<p>which outputs <code>'1/... | 3 | 2016-08-01T20:06:34Z | 38,707,340 | <p>You can do it by applying <code>eval</code> to the column:</p>
<pre><code>data = {'one':['1/20', '2/30']}
df = pd.DataFrame(data)
In [8]: df['one'].apply(eval)
Out[8]:
0 0.050000
1 0.066667
Name: one, dtype: float64
</code></pre>
| 2 | 2016-08-01T20:13:49Z | [
"python",
"string",
"pandas",
"valueconverter"
] |
Pandas DataFrame: Cannot convert string into a float | 38,707,242 | <p>I have a column <code>Column1</code> in a pandas dataframe which is of type <code>str</code>, values which are in the following form: </p>
<pre><code>import pandas as pd
df = pd.read_table("filename.dat")
type(df["Column1"].ix[0]) #outputs 'str'
print(df["Column1"].ix[0])
</code></pre>
<p>which outputs <code>'1/... | 3 | 2016-08-01T20:06:34Z | 38,707,400 | <p>You need to evaluate the expression (e.g. '1/350') in order to get the result, for which you can use Python's <a href="https://docs.python.org/3.5/library/functions.html#eval" rel="nofollow"><code>eval()</code></a> function.</p>
<p>By wrapping Panda's <code>apply()</code> function around it, you can then execute th... | 4 | 2016-08-01T20:19:05Z | [
"python",
"string",
"pandas",
"valueconverter"
] |
Pandas DataFrame: Cannot convert string into a float | 38,707,242 | <p>I have a column <code>Column1</code> in a pandas dataframe which is of type <code>str</code>, values which are in the following form: </p>
<pre><code>import pandas as pd
df = pd.read_table("filename.dat")
type(df["Column1"].ix[0]) #outputs 'str'
print(df["Column1"].ix[0])
</code></pre>
<p>which outputs <code>'1/... | 3 | 2016-08-01T20:06:34Z | 38,707,719 | <p>I hate advocating for the use of <code>eval</code>. I didn't want to spend time on this answer but I was compelled because I don't want you to use <code>eval</code>.</p>
<p>So I wrote this function that works on a <code>pd.Series</code></p>
<pre><code>def do_math_in_string(s):
op_map = {'/': '__div__', '*': '... | 3 | 2016-08-01T20:39:31Z | [
"python",
"string",
"pandas",
"valueconverter"
] |
GPU Kernel Blocksize/Gridsize without Threads | 38,707,318 | <p>I'm currently programming some numerical methods on a gpu via pycuda/cuda and am writing my own kernels. At some point, i need to estimate error for at least 1000 coupled ODE's. I don't want to have to copy a couple of vectors with over 1000 entries, so i created a kernel (at the bottom of the post) that is a basi... | 0 | 2016-08-01T20:12:25Z | 38,708,656 | <p>In a kernel launch, the total number of threads that will be spun up on the GPU is equal to the product of the grid size and block size specified for the launch.</p>
<p>Both of these values must be positive integers, therefore the only possible combination of these is 1,1 to create a launch of a single thread.</p>
... | 1 | 2016-08-01T21:47:28Z | [
"python",
"cuda",
"gpu"
] |
Does PeeWee support interaction with MySQL Views? | 38,707,331 | <p>I am trying to access pre-created MySQL View in the database via. peewee treating it as a table [peewee.model], however I am still prompted with Operational Error 1054 unknown column.</p>
<p>Does PeeWee Supports interactions with database view ?</p>
| 0 | 2016-08-01T20:13:01Z | 38,714,847 | <p>Peewee has been able to query against views when I've tried it, but while typing up a simple proof-of-concept I ran into two potential gotcha's.</p>
<p>First, the code:</p>
<pre><code>from peewee import *
db = SqliteDatabase(':memory:')
class Foo(Model):
name = TextField()
class Meta: database = db
db.c... | 1 | 2016-08-02T07:59:12Z | [
"python",
"views",
"peewee"
] |
Decorate two functions? | 38,707,393 | <p>Is it possible to make such test cases shorter by using decorator or whatever else?</p>
<pre><code> def test_login_invalid_pwd(self):
password = '12345'
response = self._login(pwd=password)
self.assertEqual(status_code, 200)
self.assertEqual(response['resultText'],
... | 0 | 2016-08-01T20:18:29Z | 38,707,449 | <p>Yes. Try this:</p>
<pre><code>def helper(self, response):
self.assertEqual(status_code, 200)
self.assertEqual(response['resultText'],
'invalid password or login')
self.assertEqual(response['resultCode'], 55)
def test_login_invalid_pwd(self):
password = '12345'
response = se... | 3 | 2016-08-01T20:21:40Z | [
"python",
"python-unittest",
"web-api-testing"
] |
Handling bad URLs with requests | 38,707,394 | <p>Sorry in advance for the beginner question. I'm just learning how to access web data in Python, and I'm having trouble understanding exception handling in the <code>requests</code> package.</p>
<p>So far, when accessing web data using the <code>urllib</code> package, I wrap the <code>urlopen</code> call in a try/ex... | 2 | 2016-08-01T20:18:38Z | 38,708,680 | <p>You can specify a kind of exception after the keyword <strong>except</strong>. So to catch just errors that come from bad connections, you can do:</p>
<pre><code>import urllib, sys
url = 'https://httpbinTYPO.org/' # Note the typo in my URL
try: uh=urllib.urlopen(url)
except IOError:
print 'Failed to open url... | 1 | 2016-08-01T21:49:08Z | [
"python",
"python-2.7",
"python-requests"
] |
Handling bad URLs with requests | 38,707,394 | <p>Sorry in advance for the beginner question. I'm just learning how to access web data in Python, and I'm having trouble understanding exception handling in the <code>requests</code> package.</p>
<p>So far, when accessing web data using the <code>urllib</code> package, I wrap the <code>urlopen</code> call in a try/ex... | 2 | 2016-08-01T20:18:38Z | 38,715,911 | <p>Try to catch connection error:</p>
<pre><code>from requests.exceptions import ConnectionError
try:
requests.get('https://httpbinTYPO.org/')
except ConnectionError:
print 'Failed to open url.'
</code></pre>
| 1 | 2016-08-02T08:53:26Z | [
"python",
"python-2.7",
"python-requests"
] |
Skipped If Statement/unstripped input data in Python | 38,707,588 | <p>I'm updating a crack the code game I made in Python so that you can play a single-player game against the computer. For some reason, the interpreter either doesn't use the data stripped from the input used to determine player count or skips the if statement that uses the stripped data from the input. Either way, aft... | 0 | 2016-08-01T20:31:02Z | 38,707,622 | <p><code>plyrs</code> is a string, and you're comparing it to an int. <code>"2" == 2</code> will always be false. Same with <code>plyrs == 1</code>, this will be false throughout.</p>
| 2 | 2016-08-01T20:33:03Z | [
"python",
"python-3.x",
"if-statement"
] |
filling cells in DataFrame | 38,707,628 | <p>I created the DataFrame and faced a problem:</p>
<pre><code> r value
0 0.8 2.5058
1 0.9 -1.9320
2 1.0 -2.6097
3 1.2 -1.6840
4 1.4 -0.8906
5 0.8 2.6955
6 0.9 -1.9552
7 1.0 -2.6641
8 1.2 -1.7169
9 1.4 -0.9056
... ... ...
</code></pre>
... | 2 | 2016-08-01T20:33:26Z | 38,707,670 | <p>Starting with this: </p>
<pre><code> r value
0 0.8 -2.6097
1 0.9 -2.6097
2 1.0 -2.6097
3 1.2 -2.6097
4 1.4 -2.6097
5 0.8 -2.6641
6 0.9 -2.6641
7 1.0 -2.6641
8 1.2 -2.6641
9 1.4 -2.6641
df3['grp'] = (df3['r'] ==.8).cumsum()
grpd = dict(df3[['grp','value']][df3['r'] == 1].values)
df3["val... | 1 | 2016-08-01T20:36:47Z | [
"python",
"pandas"
] |
filling cells in DataFrame | 38,707,628 | <p>I created the DataFrame and faced a problem:</p>
<pre><code> r value
0 0.8 2.5058
1 0.9 -1.9320
2 1.0 -2.6097
3 1.2 -1.6840
4 1.4 -0.8906
5 0.8 2.6955
6 0.9 -1.9552
7 1.0 -2.6641
8 1.2 -1.7169
9 1.4 -0.9056
... ... ...
</code></pre>
... | 2 | 2016-08-01T20:33:26Z | 38,708,106 | <p>Try this:</p>
<pre><code>def subr(df):
isone = df.r == 1.0
if isone.any():
atone = df.value[isone].iloc[0]
# Improvement suggested by @root
df.loc[df.r.between(0.8, 1.4), 'value'] = atone
# df.loc[(df.r >= .8) & (df.r <= 1.4), 'value'] = atone
return df
df.grou... | 2 | 2016-08-01T21:06:08Z | [
"python",
"pandas"
] |
Not getting the desired output in python | 38,707,679 | <p><a href="http://i.stack.imgur.com/Uv6bI.png" rel="nofollow">enter image description here</a>I want to reverse a number. If 92 is typed the result should be 29. The code is given below</p>
<pre><code>def intreverse(n) :
a=str(n)
b=a[::-1]
c=int(b)
print (c)
</code></pre>
<p>But i am getting the resu... | -2 | 2016-08-01T20:37:09Z | 38,707,767 | <p>It looks like you are getting newlines in your text input (possibly two?). I would fix this with</p>
<pre><code> a=str(n).strip()
</code></pre>
<p>also, you are printing the result, I think you want to return it. Since the function does not return anything, <code>a = intreverse('29')</code> will assign <code>Non... | 1 | 2016-08-01T20:42:03Z | [
"python",
"python-3.x"
] |
Not getting the desired output in python | 38,707,679 | <p><a href="http://i.stack.imgur.com/Uv6bI.png" rel="nofollow">enter image description here</a>I want to reverse a number. If 92 is typed the result should be 29. The code is given below</p>
<pre><code>def intreverse(n) :
a=str(n)
b=a[::-1]
c=int(b)
print (c)
</code></pre>
<p>But i am getting the resu... | -2 | 2016-08-01T20:37:09Z | 38,715,627 | <p>The course you use probably wants you to write functions with returns. As your function has no return, you get None in the end. And for the newline character <code>\n</code>: As you print your answer, print puts a newline character after what you print. If you delete the print statement and put a return statement in... | 2 | 2016-08-02T08:40:43Z | [
"python",
"python-3.x"
] |
Python extract occurence of a string with regex | 38,707,699 | <p>I need a python regular expression to extract all the occurrences of a string from the line . </p>
<p>So for example,</p>
<pre><code>line = 'TokenRange(start_token:5835456583056758754, end_token:5867789857766669245, rack:brikbrik0),EndpointDetails(host:192.168.210.183, datacenter:DC1, rack:brikbrikadfdas), Endpoin... | 1 | 2016-08-01T20:38:15Z | 38,707,724 | <p>You can capture alphanumerics coming after the <code>rack:</code>:</p>
<pre><code>>>> re.findall(r"rack:(\w+)", line)
['brikbrik0', 'brikbrikadfdas', 'brikbrik1adf']
</code></pre>
| 3 | 2016-08-01T20:39:42Z | [
"python",
"regex"
] |
Python extract occurence of a string with regex | 38,707,699 | <p>I need a python regular expression to extract all the occurrences of a string from the line . </p>
<p>So for example,</p>
<pre><code>line = 'TokenRange(start_token:5835456583056758754, end_token:5867789857766669245, rack:brikbrik0),EndpointDetails(host:192.168.210.183, datacenter:DC1, rack:brikbrikadfdas), Endpoin... | 1 | 2016-08-01T20:38:15Z | 38,708,183 | <p>Add a <strong>word boundary</strong> to <code>rack</code>:</p>
<pre><code>\brack:(\w+)
</code></pre>
<p>See <a href="https://regex101.com/r/iW9dX2/1" rel="nofollow"><strong>a demo on regex101.com</strong></a>.<br>
<hr>
In <code>Python</code> (<a href="http://ideone.com/BveiOn" rel="nofollow"><strong>demo on ideone... | 2 | 2016-08-01T21:10:27Z | [
"python",
"regex"
] |
Can numpy diagonalise a skew-symmetric matrix with real arithmetic? | 38,707,758 | <p>Any skew-symmetric matrix (<strong><em>A^T = -A</em></strong>) can be turned into a Hermitian matrix (<strong><em>iA</em></strong>) and diagonalised with complex numbers. But it is <a href="http://link.springer.com/article/10.1007/BF01436375" rel="nofollow">also possible</a> to bring it into <a href="https://en.wiki... | 2 | 2016-08-01T20:41:20Z | 39,047,400 | <p>Let's take a look at the <a href="http://www.netlib.org/lapack/explore-html/d9/d28/dgeev_8f_source.html" rel="nofollow"><code>dgeev()</code></a> function of the LAPACK librarie. This routine computes the eigenvalues of any real double-precison square matrix. Moreover, this routine is right behind the python function... | 1 | 2016-08-19T20:44:11Z | [
"python",
"numpy",
"matrix",
"linear-algebra",
"lapack"
] |
Can numpy diagonalise a skew-symmetric matrix with real arithmetic? | 38,707,758 | <p>Any skew-symmetric matrix (<strong><em>A^T = -A</em></strong>) can be turned into a Hermitian matrix (<strong><em>iA</em></strong>) and diagonalised with complex numbers. But it is <a href="http://link.springer.com/article/10.1007/BF01436375" rel="nofollow">also possible</a> to bring it into <a href="https://en.wiki... | 2 | 2016-08-01T20:41:20Z | 39,087,904 | <p>Yes you can do it via sticking a unitary transformation in the middle of the product hence we get </p>
<blockquote>
<p><strong><em>A = V * U * V^-1 = V * T' * T * U * T' * T * V^{-1}</em></strong>. </p>
</blockquote>
<p>Once you get the idea you can optimize the code by tiling things but let's do it the naive wa... | 0 | 2016-08-22T20:10:15Z | [
"python",
"numpy",
"matrix",
"linear-algebra",
"lapack"
] |
Python Encoding that ignores leading 0s | 38,707,772 | <p>I'm writing code in python 3.5 that uses hashlib to spit out MD5 encryption for each packet once it is is given a pcap file and the password. I am traversing through the pcap file using pyshark. Currently, the values it is spitting out are not the same as the MD5 encryptions on the packets in the pcap file. </p>
<p... | 1 | 2016-08-01T20:42:18Z | 38,708,581 | <p>Hashing <code>b'06'</code> and <code>b'6'</code> gives different results because, in this context, '06' and '6' are different.</p>
<p>The <code>b</code> string prefix in Python tells the Python interpreter to convert each character in the string into a byte. Thus, <code>b'06'</code> will be converted into the two b... | 0 | 2016-08-01T21:41:15Z | [
"python",
"encryption",
"hex",
"md5",
"encode"
] |
How to clear matplotlib labels in legend? | 38,707,853 | <p>Is there a way to clear matplotlib labels inside a graph's legend? <a href="http://stackoverflow.com/questions/5735208/remove-the-legend-on-a-matplotlib-figure">This post</a> explains how to remove the legend itself, but the labels themselves still remain, and appear again if you plot a new figure. I tried the follo... | 2 | 2016-08-01T20:48:17Z | 38,708,097 | <p>Use <code>set_visible()</code> method:</p>
<pre><code>import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca()
ax.scatter([1,2,3], [4,5,6], label = "a")
legend = ax.legend()
for text in legend.texts:
if (text.get_text() == 'a'): text.set_text('b') # change label text
text.set_visible(False) # dis... | 2 | 2016-08-01T21:05:35Z | [
"python",
"matplotlib",
"legend"
] |
"Expected an indented block" error explanation | 38,707,867 | <p>So yes I know that there is an answer on how to fix this but can someone explain to me what the hell it means?Because I don't know where it comes from and I also don't know what indented means in programming (as you can understand dear reader English is not my native tongue).</p>
<p>P.S I found that error from a fo... | -4 | 2016-08-01T20:49:04Z | 38,708,032 | <p>An indent in Python is 4 spaces. Would have commented this, but I don't have enough reputation. Here's a link: <a href="http://stackoverflow.com/questions/1125653/python-4-whitespaces-indention-why">Python 4 whitespaces indention. Why?</a></p>
| -1 | 2016-08-01T20:59:52Z | [
"python",
"for-loop",
"image-processing"
] |
"Expected an indented block" error explanation | 38,707,867 | <p>So yes I know that there is an answer on how to fix this but can someone explain to me what the hell it means?Because I don't know where it comes from and I also don't know what indented means in programming (as you can understand dear reader English is not my native tongue).</p>
<p>P.S I found that error from a fo... | -4 | 2016-08-01T20:49:04Z | 38,708,162 | <p>In python syntax, if statements, loops, and functions must be followed by indented lines. It's just python syntax. You have to put 4 spaces or use a tab before each line to indent them. In many other scripting languages, { } are used to enclose the code blocks. Without correct indenting, python doesn't know when a b... | 0 | 2016-08-01T21:09:02Z | [
"python",
"for-loop",
"image-processing"
] |
python xarray select by lat/long and extract point data to dataframe | 38,707,926 | <p>I would like to select all grid cells within a lat/long range, and for each grid cell, export it as a dateframe and then to an csv file (i.e. <code>df.to_csv</code>). My dataset is below. I can use <code>xr.where(...)</code> to mask out grid cells outside my input, but not sure how to loop through remaining grids th... | 0 | 2016-08-01T20:53:13Z | 38,709,078 | <p>The simplest way to do this is probably to loop through every grid point, with something like the following:</p>
<pre><code># (optionally) create a grid dataset so we don't need to pull out all
# the data from the main dataset before looking at each point
grid = ds[['gridlat_0', 'gridlon_0']]
for i in range(ds.coo... | 0 | 2016-08-01T22:29:04Z | [
"python",
"python-xarray"
] |
Python Pandas -- how to select minimum amount of columns that contain 1s in all their columns across a set of rows | 38,708,020 | <p>Given a document-term pandas Dataframe. Where each cell is represented by an occurrence matrix.</p>
<pre><code> clover seed sowing stolon
1489 1 0 0 0
1488 1 0 0 0
9677 0 0 1 0
9996 1 0 0 1
0557 ... | 2 | 2016-08-01T20:59:27Z | 38,708,321 | <p>I'd do it like this:</p>
<pre><code>relevant = ['clover', 'seed', 'sowing']
df[df[relevant].all(1)][relevant]
</code></pre>
<p><a href="http://i.stack.imgur.com/vpFog.png" rel="nofollow"><img src="http://i.stack.imgur.com/vpFog.png" alt="enter image description here"></a></p>
| 1 | 2016-08-01T21:20:37Z | [
"python",
"pandas",
"dataframe",
"selection"
] |
Python Pandas -- how to select minimum amount of columns that contain 1s in all their columns across a set of rows | 38,708,020 | <p>Given a document-term pandas Dataframe. Where each cell is represented by an occurrence matrix.</p>
<pre><code> clover seed sowing stolon
1489 1 0 0 0
1488 1 0 0 0
9677 0 0 1 0
9996 1 0 0 1
0557 ... | 2 | 2016-08-01T20:59:27Z | 38,709,409 | <p>Another possibility is to use <code>df.sum(axis=1)>=3</code> as a mask. Chain <code>drop</code> to this:</p>
<pre><code>>>> df[df.sum(axis=1)>=3].drop('stolon', axis=1)
clover seed sowing
1965 1 1 1
4326 1 1 1
4531 1 1 1
</code></pre>
<p>To mak... | 0 | 2016-08-01T23:07:42Z | [
"python",
"pandas",
"dataframe",
"selection"
] |
Retrieving the sender of PyQt4 QLabel mousepressevent | 38,708,039 | <p>I'm programming an interface in PyQt4 and I am using QLabels and making them clickable using the mousepressevent function. I have multiple labels (signals) that have the same mousepressevent slot. Here is the gist of what I'm trying to do.</p>
<pre><code>class Example(QtGui.QWidget):
def __init__(self):
... | 0 | 2016-08-01T21:00:19Z | 38,709,722 | <p>You can use <a href="http://doc.qt.io/qt-4.8/qobject.html#installEventFilter" rel="nofollow">event-filtering</a> to do this:</p>
<pre><code>class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
lbl1 = QtGui.QLabel(self)
... | 0 | 2016-08-01T23:47:43Z | [
"python",
"pyqt",
"pyqt4"
] |
Python if/elif conditional | 38,708,056 | <p>Is there a way to execute code in an if/elif structure so it evaluates all the code up to the elif? Here is an example:</p>
<pre><code>i = 1 # this can be anything depending on what to user chooses
x = 5
y = 10
if i == 1:
z = x + y
elif i == 2:
# Here I want to return what would have happened if i == 1, ... | 1 | 2016-08-01T21:01:59Z | 38,708,085 | <p>How an if works is it will execute if the condition passes. Else if is only executed if none of the prior if/elif statements conditions pass. So you want all if statements not elif statements</p>
<pre><code> i = 1 # this can be anything depending on what to user chooses
x = 5
y = 10
if i >= 1:
z = x + y
i... | 1 | 2016-08-01T21:04:17Z | [
"python"
] |
Python if/elif conditional | 38,708,056 | <p>Is there a way to execute code in an if/elif structure so it evaluates all the code up to the elif? Here is an example:</p>
<pre><code>i = 1 # this can be anything depending on what to user chooses
x = 5
y = 10
if i == 1:
z = x + y
elif i == 2:
# Here I want to return what would have happened if i == 1, ... | 1 | 2016-08-01T21:01:59Z | 38,708,109 | <p>Perhaps something like this:</p>
<pre><code>if i in (1, 2, 3):
z = x + y
if i in (2, 3):
r = x^3 - y
if i == 3:
s = i^3 + y^2
</code></pre>
<p>You can replace the tuples with <code>range(...)</code> when you have many cases.</p>
| 1 | 2016-08-01T21:06:14Z | [
"python"
] |
Python if/elif conditional | 38,708,056 | <p>Is there a way to execute code in an if/elif structure so it evaluates all the code up to the elif? Here is an example:</p>
<pre><code>i = 1 # this can be anything depending on what to user chooses
x = 5
y = 10
if i == 1:
z = x + y
elif i == 2:
# Here I want to return what would have happened if i == 1, ... | 1 | 2016-08-01T21:01:59Z | 38,708,115 | <p>Try this:</p>
<pre><code>i = 1 # this can be anything depending on what to user chooses
x = 5
y = 10
if i >= 1:
z = x + y
if i >= 2:
# Here I want to return what would have happened if i == 1, in addition other stuff:
r = x^3 - y
if i == 3:
# Again, execute all the stuff that would have ha... | 3 | 2016-08-01T21:06:35Z | [
"python"
] |
Rewriting on a specific line while other lines behave normaly | 38,708,128 | <p>I have a python program with which I have to update the last line of a terminal while on the rest of them I print data as if the last line is non-existent. Here's an example. Suppose we have this (pseudo)code:</p>
<pre><code>1. print("test1")
2. updateLastLine("79 percent")
3. print("test2")
4. updateLastLine("80 p... | 0 | 2016-08-01T21:07:04Z | 38,708,251 | <p>The percentage part put me on the way of a screen refreshing :
In a (almost) endless loop, clear the user screen with </p>
<pre><code>os.system('clear')
</code></pre>
<p>and then display your "test" list, the current percentage and the current user input (if there was one being typed).
Refresh the display every ti... | 0 | 2016-08-01T21:15:38Z | [
"python",
"terminal"
] |
Rewriting on a specific line while other lines behave normaly | 38,708,128 | <p>I have a python program with which I have to update the last line of a terminal while on the rest of them I print data as if the last line is non-existent. Here's an example. Suppose we have this (pseudo)code:</p>
<pre><code>1. print("test1")
2. updateLastLine("79 percent")
3. print("test2")
4. updateLastLine("80 p... | 0 | 2016-08-01T21:07:04Z | 38,716,103 | <pre><code>import shutil
class Printer(object):
def __init__(self):
self.last_line = ''
def print(self, line):
(w, h) = shutil.get_terminal_size()
print(' '*(w-1), end='\r')
print(line)
self.update_last_line(self.last_line)
def update_last_line(self, line):
... | 1 | 2016-08-02T09:02:29Z | [
"python",
"terminal"
] |
Spark - Unable to access S3 file if master parameter set | 38,708,269 | <p>I'm having issues accessing a file sitting on AWS S3 when I launch the job specifying --master parameter - either as a parameter in the terminal </p>
<pre><code>spark-submit --master spark://myIP:port
</code></pre>
<p>or in the actual code </p>
<pre><code>conf = SparkConf().setAppName("test").setMaster("spark://m... | 0 | 2016-08-01T21:16:58Z | 38,725,609 | <p>By installing java version 1.8, as required in the documentation, the issue gets solved.</p>
| 0 | 2016-08-02T16:11:09Z | [
"python",
"apache-spark",
"pyspark",
"rdd"
] |
TKinter - How do you use variables in hex to color widgets? | 38,708,404 | <p>I'm trying to set a frame's background color a hex value which I've stored in a variable. I did something wrong and it's giving me this error "unknown color name 'hex_value'." What am I doing wrong?</p>
<pre><code>hex_value = "#f35123"
root = Tk()
top_frame = Frame(root, bg="hex_value")
top_frame.pack(side=TOP, fil... | -1 | 2016-08-01T21:27:34Z | 38,708,435 | <p>I would assume you want the <em>content</em> of the variable?!</p>
<pre><code>hex_value = "#f35123"
root = Tk()
top_frame = Frame(root, bg=hex_value)
top_frame.pack(side=TOP, fill=X)
root.mainloop()
</code></pre>
| 0 | 2016-08-01T21:30:32Z | [
"python",
"tkinter",
"hex"
] |
TKinter - How do you use variables in hex to color widgets? | 38,708,404 | <p>I'm trying to set a frame's background color a hex value which I've stored in a variable. I did something wrong and it's giving me this error "unknown color name 'hex_value'." What am I doing wrong?</p>
<pre><code>hex_value = "#f35123"
root = Tk()
top_frame = Frame(root, bg="hex_value")
top_frame.pack(side=TOP, fil... | -1 | 2016-08-01T21:27:34Z | 38,708,441 | <p>You're getting this error because you passed in the <em>string</em> "hex_value". Instead of the variable containing the string you want. Remove the <code>"</code></p>
| 2 | 2016-08-01T21:30:48Z | [
"python",
"tkinter",
"hex"
] |
Having a constantly changing variable in a python loop | 38,708,426 | <p>I'm trying to write a program that would ask for a students name, a couple other numerical values, and assign them to groups, via their numerical value, to have all groups as close to equal as possible (by taking the the highest next value in the list, and assigning it to the next group and so on).</p>
<p>However, ... | -1 | 2016-08-01T21:29:52Z | 38,709,353 | <p>I believe it would be nice to create a Student class that holds all variables associated with a student. Then you could add each student to a list which you could sort by the values you want and divide to how many groups you want.</p>
<pre><code>from easygui import *
from operator import attrgetter
class Student(... | 0 | 2016-08-01T23:00:48Z | [
"python",
"variables",
"input"
] |
Can we use SWIG to make python bindings for Qt application? | 38,708,475 | <p>How to use SWIG to binding to QT application, our situation is almost the same as the situation in this <a href="http://lists.qt-project.org/pipermail/pyside/2013-January/000957.html" rel="nofollow">post</a>, which says:</p>
<blockquote>
<ul>
<li>We have a big C++/Qt application with a Swig binding of the core.... | 2 | 2016-08-01T21:33:01Z | 38,747,415 | <blockquote>
<p>Can we use SWIG to make python bindings for Qt application?</p>
</blockquote>
<p><strong>YES</strong>!</p>
<p>The error happens because your header file uses macros that SWIG doesn't know about. A C++ compiler wouldn't know about them either, of course.</p>
<p>SWIG needs to preprocess your input. T... | 2 | 2016-08-03T15:10:19Z | [
"python",
"c++",
"qt",
"swig"
] |
Getting the timezone offset in Python from a timezone ignoring DST | 38,708,572 | <p>What is the correct way to get an UTC offset from a timezone in python?
I need a function to send a pytz timezone and get the timezone offset ignoring the Daylight Saving Time.</p>
<pre><code>import pytz
tz = pytz.timezone('Europe/Madrid')
getOffset(tz) #datetime.timedelta(0, 3600)
</code></pre>
| 0 | 2016-08-01T21:40:31Z | 38,708,944 | <p><code>pytz</code> timezone objects obey <code>tzinfo</code> <a href="https://docs.python.org/3/library/datetime.html#datetime.tzinfo.dst" rel="nofollow">API specification</a> defined in the <code>datetime</code> module. Therefore you can use their <code>.utcoffset()</code> and <code>.dst()</code> methods:</p>
<pre>... | 2 | 2016-08-01T22:15:30Z | [
"python",
"datetime",
"timezone"
] |
python opencv panorama blacklines | 38,708,596 | <p>I am working on panorama with Python OpenCV. Can someone show me how to get rid of the black lines in my final images? I am thinking of maybe I should first check for the color I.e. 0,0,0 before copying it to the atlas image, but I am not quite sure how to do that.</p>
<pre><code>def warpTwoImages(img1, img2, H):
... | 0 | 2016-08-01T21:42:32Z | 38,788,954 | <p>This answer depends on warpPrespicteve function to work with RGBA.
You can try to use the alpha channel of each image.
Before wrapping convert each image to RGBA (See the code below) were the alpha channel will be 0 for the black lines and for all other pixels it will be 255.</p>
<pre><code>import cv2
import numpy... | 0 | 2016-08-05T12:11:36Z | [
"python",
"opencv",
"image-processing",
"computer-vision",
"panoramas"
] |
How to calculate percentage of sparsity for a numpy array/matrix? | 38,708,621 | <p>I have the following 10 by 5 numpy array/matrix, which has a number of <code>NaN</code> values:</p>
<pre><code>array([[ 0., 0., 0., 0., 1.],
[ 1., 1., 0., nan, nan],
[ 0., nan, 1., nan, nan],
[ 1., 1., 1., 1., 0.],
[ 0., 0., 0., 1., 0.],
[ ... | 4 | 2016-08-01T21:44:34Z | 38,709,042 | <pre><code>np.isnan(a).sum()
</code></pre>
<p>gives the number of <code>nan</code> values, in this example 8. </p>
<pre><code>np.prod(a.shape)
</code></pre>
<p>is the number of values, here 50. Their ratio should give the desired value.</p>
<pre><code>In [1081]: np.isnan(a).sum()/np.prod(a.shape)
Out[1081]: 0.16
... | 3 | 2016-08-01T22:25:58Z | [
"python",
"arrays",
"numpy",
"matrix",
"sparse-matrix"
] |
How to make combinations nCr from x to y (nCx -nCy) | 38,708,625 | <p>I want to make some combinations of all 160 elements in my list, but I don't want to make all possible combinations or it will never end. I just want some, lets say 1,2,3,4.</p>
<p>Instead of doing one by one:</p>
<pre><code>combination = itertools.combinations(lst, 1)
combination = itertools.combinations(lst, 2)
... | 0 | 2016-08-01T21:45:05Z | 38,708,684 | <p>How about this simple <code>for</code> loop:</p>
<pre><code>comb = []
for i in range (1,5): # (start, end + 1)
comb[i] = itertools.combinations(lst, i)
</code></pre>
| 0 | 2016-08-01T21:49:31Z | [
"python",
"list",
"combinations",
"itertools"
] |
How to make combinations nCr from x to y (nCx -nCy) | 38,708,625 | <p>I want to make some combinations of all 160 elements in my list, but I don't want to make all possible combinations or it will never end. I just want some, lets say 1,2,3,4.</p>
<p>Instead of doing one by one:</p>
<pre><code>combination = itertools.combinations(lst, 1)
combination = itertools.combinations(lst, 2)
... | 0 | 2016-08-01T21:45:05Z | 38,708,770 | <p>You can create single iterator containing all the combinations with <a href="https://docs.python.org/3.5/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain.from_iterable</code></a>:</p>
<pre><code>combination = chain.from_iterable(combinations(lst, i) for i in range(1,5))
</c... | 0 | 2016-08-01T21:56:56Z | [
"python",
"list",
"combinations",
"itertools"
] |
How do I filter SQLAlchemy results based on a columns' value? | 38,708,645 | <p>I'm trying to serialize results from a SQLAlchemy query. I'm new to the ORM so I'm not sure how to filter a result set after I've retrieved it. The result set looks like this, if I were to flatten the objects:</p>
<blockquote>
<p>A1 B1 V1</p>
<p>A1 B1 V2</p>
<p>A2 B2 V3</p>
</blockquote>
<p>I nee... | 0 | 2016-08-01T21:46:44Z | 38,806,913 | <p>Yup just use <code>func.array_agg</code> and <code>group_by</code></p>
<pre><code>import sqlalchemy.sql.functions as func
session.query(Object.col1, Object.col2, func.array_agg(Object.col3))
.group_by(Object.col1)
.group_by(Object.col2)
.all()
</code></pre>
<p>But this will only work with database b... | 0 | 2016-08-06T17:25:09Z | [
"python",
"orm",
"sqlalchemy"
] |
How do I filter SQLAlchemy results based on a columns' value? | 38,708,645 | <p>I'm trying to serialize results from a SQLAlchemy query. I'm new to the ORM so I'm not sure how to filter a result set after I've retrieved it. The result set looks like this, if I were to flatten the objects:</p>
<blockquote>
<p>A1 B1 V1</p>
<p>A1 B1 V2</p>
<p>A2 B2 V3</p>
</blockquote>
<p>I nee... | 0 | 2016-08-01T21:46:44Z | 38,882,242 | <p>Turns out I needed to use association tables and the joinedload() function. The documentation is a bit wonky but I got there after playing with it for a while.</p>
| 0 | 2016-08-10T19:45:24Z | [
"python",
"orm",
"sqlalchemy"
] |
Remove ns0 from XML | 38,708,658 | <p>I have an XML file where I would like to edit certain attributes. I am able to properly edit the attributes but when I write the changes to the file, the tags have a strange "ns0" added onto them. How can I get rid of this? This is what I have tried and have been unsuccessful. I am working in python and using lxml.<... | 0 | 2016-08-01T21:47:39Z | 38,709,043 | <p>Actually the way to do it seemed to be a combination of two things. </p>
<ol>
<li>The import statement is import xml.etree.ElementTree as ET</li>
<li>ET.register_namespace("", NAMESPACE) is the correct call, where NAMESPACE is the namespace listed in the input xml, ie the url after xmlns.</li>
</ol>
| 0 | 2016-08-01T22:26:06Z | [
"python",
"xml",
"lxml"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.