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 |
|---|---|---|---|---|---|---|---|---|---|
Coloring given words in a text with Python | 39,452,744 | <p>I have already read the questions about how coloring text with Python and the Colorama package but I didn't find what I was looking for.</p>
<p>I have some raw text:</p>
<blockquote>
<p>Impossible considered invitation him men instrument saw celebrated unpleasant. Put rest and must set kind next many near nay. H... | 0 | 2016-09-12T14:28:53Z | 39,453,030 | <p>Here is a solution using map. It's definitely no faster than conventional looping :/ </p>
<pre><code>from colorama import Fore, Style
def colourise(s, good, bad):
if s in good:
return Fore.RED + s
elif s in bad:
return Fore.GREEN + s
else:
return Style.RESET_ALL + s
text = "Imp... | 1 | 2016-09-12T14:45:27Z | [
"python"
] |
Cannot cast array data from dtype('O') to dtype('float64') | 39,452,792 | <p>I am using scipy's curve_fit to fit a function to some data, and receive the following error;</p>
<pre><code>Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
</code></pre>
<p>which points me to this line in my code;</p>
<pre><code>popt_r, pcov = curve_fit(
... | 0 | 2016-09-12T14:31:40Z | 39,453,034 | <p>From <a href="https://github.com/numpy/numpy/issues/4384" rel="nofollow">here</a>, apparently numpy struggles with index type. The proposed solution is:</p>
<blockquote>
<p>One thing you can do is use np.intp as dtype whenever things have to do with indexing or are logically related to indexing/array sizes. This... | 0 | 2016-09-12T14:45:44Z | [
"python",
"python-2.7",
"scipy"
] |
Cannot cast array data from dtype('O') to dtype('float64') | 39,452,792 | <p>I am using scipy's curve_fit to fit a function to some data, and receive the following error;</p>
<pre><code>Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'
</code></pre>
<p>which points me to this line in my code;</p>
<pre><code>popt_r, pcov = curve_fit(
... | 0 | 2016-09-12T14:31:40Z | 39,454,698 | <p>Typically these <code>scipy</code> functions require parameters like:</p>
<pre><code>curvefit( function, initial_values, (aux_values,), ...)
</code></pre>
<p>where the tuple of <code>aux_values</code> is passed through to your <code>function</code> along with the current value of the main variable.</p>
<p>Is the ... | 1 | 2016-09-12T16:20:32Z | [
"python",
"python-2.7",
"scipy"
] |
Python: Qt-Gui and several tasks | 39,452,804 | <p>I'm trying to use a Qt-Gui and to implement there several task to do work in the background and to update the content in the gui. Here is the code I'm working on (simplified to the minimum). Without gui, ie printing to the terminal, this code works fine:</p>
<pre><code> #!/usr/bin/env python3
import sys
import asy... | 2 | 2016-09-12T14:32:15Z | 39,455,500 | <p><code>PyQt4</code> is not aware about <code>asyncio</code> existence.
But <a href="https://github.com/harvimt/quamash" rel="nofollow">quamash</a> does, please use it as bridge between Qt and asyncio.</p>
| 0 | 2016-09-12T17:16:40Z | [
"python",
"qt",
"pyqt",
"multitasking",
"python-asyncio"
] |
Python: Qt-Gui and several tasks | 39,452,804 | <p>I'm trying to use a Qt-Gui and to implement there several task to do work in the background and to update the content in the gui. Here is the code I'm working on (simplified to the minimum). Without gui, ie printing to the terminal, this code works fine:</p>
<pre><code> #!/usr/bin/env python3
import sys
import asy... | 2 | 2016-09-12T14:32:15Z | 39,464,406 | <p>Using quamash like proposed by Andrew Svetlov, the working code looks now like this:</p>
<pre><code>#!/usr/bin/env python3
import sys
import asyncio
from PyQt4 import QtCore, QtGui, uic
from quamash import QEventLoop
qtCreatorFile = "gui_mini_task.ui" # Enter file here.
Ui_MainWindow, QtBaseClass = uic.loadUiTy... | 2 | 2016-09-13T07:27:43Z | [
"python",
"qt",
"pyqt",
"multitasking",
"python-asyncio"
] |
Text Pre-processing with NLTK | 39,452,842 | <p>I am practicing on using NLTK to remove certain features from raw tweets and subsequently hoping to remove tweets that are (to me) irelevant (e.g. empty tweet or single word tweets). However, it seems that some of the single word tweets are not removed. I am also facing an issue with not able to remove any stopword ... | 0 | 2016-09-12T14:35:10Z | 39,454,322 | <p>What is df? a list of tweets?
You maybe should consider cleaning the tweet one after the other and not as a list of tweets. It would be easier to have a function <code>tweet_cleaner(single_tweet)</code>.</p>
<p>nltk provides a <a href="http://www.nltk.org/api/nltk.tokenize.html" rel="nofollow">TweetTokenizer</a> t... | 2 | 2016-09-12T15:54:44Z | [
"python",
"twitter",
"nltk"
] |
Text Pre-processing with NLTK | 39,452,842 | <p>I am practicing on using NLTK to remove certain features from raw tweets and subsequently hoping to remove tweets that are (to me) irelevant (e.g. empty tweet or single word tweets). However, it seems that some of the single word tweets are not removed. I am also facing an issue with not able to remove any stopword ... | 0 | 2016-09-12T14:35:10Z | 39,457,094 | <p>With advice from mquantin, I have modified my code to clean tweets individually as a sentence. Here is my amateur attempt with a sample tweet that I believe covers most scenarios (Let me know if you encounter any other cases that deserve a clean up):</p>
<pre><code>import string
import re
from nltk.corpus import st... | 0 | 2016-09-12T19:06:41Z | [
"python",
"twitter",
"nltk"
] |
"In" operator for numpy arrays? | 39,452,843 | <p>How can I do the "in" operation on a numpy array?
(Return True if an element is present in the given numpy array)</p>
<p>For strings, lists and dictionaries, the functionality is intuitive to understand.</p>
<p>Here's what I got when I applied that on a numpy array</p>
<pre><code>a
array([[[2, 3, 0],
[1, 0, 1... | 2 | 2016-09-12T14:35:12Z | 39,452,929 | <p>You could compare the input arrays for <code>equality</code>, which will perform <a href="http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasted</code></a> comparisons across all elements in <code>a</code> at each position in the last two axes against elements at correspondin... | 4 | 2016-09-12T14:40:01Z | [
"python",
"arrays",
"numpy",
"operators"
] |
Enforce precision in decimal python | 39,452,845 | <p>In some environments, exact decimals (numerics, numbers...) are defined with <code>scale</code> and <code>precision</code>, with scale being all significant numbers, and precision being those right of the decimal point. I want to use python's decimal implementation to raise an error, if the precision of the casted s... | 1 | 2016-09-12T14:35:13Z | 39,453,334 | <p>The closest I could find in the <code>decimal</code> <a href="https://docs.python.org/2/library/decimal.html" rel="nofollow">module</a> is in the <code>context.create_decimal_from_float</code> example, using the <code>Inexact</code> <a href="https://docs.python.org/2/library/decimal.html#decimal.Inexact" rel="nofoll... | 2 | 2016-09-12T15:01:17Z | [
"python",
"decimal",
"precision"
] |
Enforce precision in decimal python | 39,452,845 | <p>In some environments, exact decimals (numerics, numbers...) are defined with <code>scale</code> and <code>precision</code>, with scale being all significant numbers, and precision being those right of the decimal point. I want to use python's decimal implementation to raise an error, if the precision of the casted s... | 1 | 2016-09-12T14:35:13Z | 39,453,389 | <p>You could always define a stricter class of Decimal and check the number of decimals in the setter and constructor functions. This should act exactly like the Decimal object, except that it'll raise a ValueError when its created or set with more than two decimals.</p>
<pre><code>class StrictDecimal:
def __init_... | 0 | 2016-09-12T15:03:37Z | [
"python",
"decimal",
"precision"
] |
Print Node Id from Igraph in Python | 39,452,862 | <p>I have text file with the following sample data representing nodes and edges. </p>
<pre><code>a b
b c
d a
b d
</code></pre>
<p>I want to print the node ID in python but I realize that there is no way to achieve this,for example in R once I generate my graph, I get the node attribute name printed along with the pag... | 0 | 2016-09-12T14:36:04Z | 39,459,137 | <p>If anyone is interested, I ended solving my own problem. The values generated by the graph in python are linked by the vertex id. You will need to access the vertex name attribute for your graph and linked that with eh scores produced from the page rank output. </p>
<pre><code>Fin = Graph.Read_Ncol('Node_edge.txt'... | 0 | 2016-09-12T21:34:14Z | [
"python",
"igraph"
] |
Breaking out of one for loop and continuing the other code | 39,452,881 | <p>I currently have an excel sheet checking another excel sheet for certain numbers. Once it finds the matching cell, I want it to move on back to the very first for loop. if it doesn't find the matching cell, but finds the first 6 digits of it, I want it to mark it as checked and then move back to the first for loop a... | -2 | 2016-09-12T14:37:17Z | 39,452,915 | <p>Just use the <code>break</code> statement. It breaks you out of a <code>for</code> loop or <code>while</code> loop. </p>
<p>From the Python docs:</p>
<blockquote>
<p>break may only occur syntactically nested in a for or while loop, but not
nested in a function or class definition within that loop. <strong>It t... | 1 | 2016-09-12T14:39:26Z | [
"python",
"for-loop",
"break"
] |
How to expose a templated class as one class to python with boost::python | 39,453,015 | <p>In many examples about boost::python you see something like:</p>
<pre><code>using namespace boost::python;
typedef class_<std::vector<float>> VectorFloat;
</code></pre>
<p>And then of course if you need a <code>double</code> vector you will have a second class called <code>DoubleVector</code> or so.
In... | 0 | 2016-09-12T14:44:41Z | 39,453,655 | <p>There's a couple sources of confusion here. First, in Python, <code>object</code> is already basically a variant - everything is an <code>object</code>. And in C++, a class template isn't a type - it's a recipe for creating a type. So if you want to expose <code>MyClass<T></code> from C++ to Python, you should... | 1 | 2016-09-12T15:17:45Z | [
"python",
"c++",
"templates",
"boost",
"boost-python"
] |
Label for input field isn't rendered when ends with non ASCII character | 39,453,137 | <p>I encountered a strange behavior while using Django forms. In my <code>forms.py</code> I have a user register form, and for each field I have set a label. Then in view I am passing the form into the context. In html file I'm using the form as follows:</p>
<pre><code>{% for field in UserForm %}
<div class="form-g... | 0 | 2016-09-12T14:50:39Z | 39,454,257 | <p>Python 2.7 have 2 types of string, normal and unicode. Normal string (used by default) can't store any unicode characters. In your form you are using normal strings for label. That is causing issues.</p>
<p>You can either use unicode in that string:</p>
<pre><code> first_name = forms.CharField(
label = ... | 0 | 2016-09-12T15:51:40Z | [
"python",
"html",
"django"
] |
Skimage: group labels with distance condition on outline | 39,453,168 | <p>I have used <em>skimage.measure.label</em> to get labels of my image but i was wondering if there was a function or a best way to group the labels with a distance condition on their outline.</p>
<p>Currently i use <em>skimage.measure.regionprops</em> to analyse each label then <em>skimage.segmentation.find_boundari... | 0 | 2016-09-12T14:52:37Z | 39,454,882 | <p>This code work for grouping and display the result (blue is before, cyan is after):</p>
<p><a href="http://i.stack.imgur.com/j32Bp.png" rel="nofollow"><img src="http://i.stack.imgur.com/j32Bp.png" alt="label grouping"></a></p>
<pre><code>import math
import matplotlib.pyplot as plt
import numpy as np
from skimage.... | 0 | 2016-09-12T16:32:16Z | [
"python",
"image-processing",
"scikit-image",
"skimage"
] |
Unrecognized file type in selenium python | 39,453,184 | <p>So I am testing a web client which communicates with an engine that does something to a text file that I upload. So basically, I choose a file to upload, once this file is uploaded i can press start and the engine does its thing and returns a result. I am trying to test the front end using selenium in python. This w... | 1 | 2016-09-12T14:53:11Z | 39,467,073 | <p>Python + selenium also gives you the option of uploading the file directly.</p>
<p>I am not sure whether this is true in your case, because I don't have the complete html for the "choose" element.</p>
<p>In my case I had an element of input[type=file] and this worked:</p>
<p>driver.find_element_by_css_selector('i... | 0 | 2016-09-13T09:52:13Z | [
"python",
"unit-testing",
"selenium",
"file-upload"
] |
Can I run pdflatex on an in-memory file? | 39,453,227 | <p>I am to generate a series of pdf files whose contents is to be generated in Python (2.7). A regular solution is to save the .tex contents at some directory, call pdflatex on the file, read in the pdf-file afterwards in order to finally place the file somewhere relevant. This is shown below:</p>
<pre><code>import os... | 1 | 2016-09-12T14:55:24Z | 39,453,345 | <p>Have a look at <a href="https://pypi.python.org/pypi/tex" rel="nofollow">tex</a>. It provides an in-memory API to the TeX command line tools. For example:</p>
<pre><code>>>> from tex import latex2pdf
>>> document = ur"""
... \documentclass{article}
... \begin{document}
... Hello, World!
... \end{d... | 0 | 2016-09-12T15:01:37Z | [
"python",
"pdflatex"
] |
How to submit a form to get URL of next webpage using mechanize? | 39,453,333 | <p>I am trying to scrape some data, decided to employ mechanize in conjunction with beautifulsoup. I have to enter the field that I want to search in a form on this webpage, then click the search button to get to the next relevant page whose URL I want to get to scrape data off.</p>
<p>The developer mode shows the fol... | 0 | 2016-09-12T15:01:15Z | 39,585,862 | <p>It seems , at least from my similar problem that mechanize does not handle Javascript at all. Try using selenium it handles javascript well. I am building my script on this I'll update if it solves my issue.</p>
| 0 | 2016-09-20T04:46:18Z | [
"javascript",
"python",
"mechanize"
] |
google search by google api in r or python | 39,453,352 | <p>I want to search some thing (ex:"python language") in google by python or R and it will give me the list of links for that google search
like:</p>
<pre><code>https://en.wikipedia.org/wiki/Python_(programming_language)
https://www.python.org/
https://www.python.org/about/gettingstarted/
</code></pre>
<p>Is there an... | 0 | 2016-09-12T15:02:09Z | 39,453,679 | <p>I have used this <a href="https://github.com/rohithpr/py-web-search" rel="nofollow">python web search api</a> to perform google search in python. Fairly straightforward to use and easy to install.</p>
| 0 | 2016-09-12T15:18:51Z | [
"python",
"web-scraping",
"google-api",
"google-api-python-client"
] |
When to use association, aggregation, composition and inheritance? | 39,453,493 | <p>I've seen plenty of posts on Stackoverflow explaining the difference between the relationships: associations, aggregation, composition and inheritance, with examples. However, I'm more specifically confused more about the pros and cons of each of these approaches, and when one approach is most effective for the task... | 2 | 2016-09-12T15:09:14Z | 39,453,900 | <p>My personal opinion is you should first think about how you would model real world data in ways that help you solve specific real world problems. Assigning things to classes, describing relationships between classes and/or instances, describing properties of things, etc, is the hard part: get this right, and the pat... | 0 | 2016-09-12T15:30:02Z | [
"python",
"inheritance",
"associations",
"aggregation",
"composition"
] |
Dot product between 2D and 3D arrays | 39,453,770 | <p>Assume that I have two arrays <code>V</code> and <code>Q</code>, where <code>V</code> is <code>(i, j, j)</code> and <code>Q</code> is <code>(j, j)</code>. I now wish to compute the dot product of <code>Q</code> with each "row" of <code>V</code> and save the result as an <code>(i, j, j)</code> sized matrix. This is e... | 1 | 2016-09-12T15:23:39Z | 39,454,139 | <p>You can certainly use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html" rel="nofollow"><code>np.tensordot</code></a>, but need to swap axes afterwards, like so -</p>
<pre><code>out = np.tensordot(v,q,axes=(1,1)).swapaxes(1,2)
</code></pre>
<p>With <a href="http://docs.scipy.org/doc... | 1 | 2016-09-12T15:44:26Z | [
"python",
"numpy",
"vectorization"
] |
Numpy: how to apply vectorized functions to array with dtype | 39,453,771 | <p>I'm following <a href="http://www.scipy-lectures.org/advanced/image_processing/" rel="nofollow">this tutorial</a> on how to use numpy to manipulate images. When I load the sample image using scipy, I get a 2D array of RGB tuples, with a dtype value appended on the end.</p>
<pre><code>array([[7, 8, 5],
[3, 5, 7]]... | 0 | 2016-09-12T15:23:49Z | 39,453,937 | <p><code>dtype=uint8</code> is not an element of the array. It is just a thing that gets printed to let you know that the array is of type <code>np.uint8</code>.</p>
<p>The default types <code>np.float_</code> and <code>np.int_</code> do not get a printout like that, which is what you are seeing in the second case. Th... | 0 | 2016-09-12T15:32:16Z | [
"python",
"numpy"
] |
Numpy: how to apply vectorized functions to array with dtype | 39,453,771 | <p>I'm following <a href="http://www.scipy-lectures.org/advanced/image_processing/" rel="nofollow">this tutorial</a> on how to use numpy to manipulate images. When I load the sample image using scipy, I get a 2D array of RGB tuples, with a dtype value appended on the end.</p>
<pre><code>array([[7, 8, 5],
[3, 5, 7]]... | 0 | 2016-09-12T15:23:49Z | 39,454,515 | <p><code>np.vectorize</code> takes an <code>otypes</code> parameter. You can use that to specify the dtype of the return. Without that <code>vectorize</code> does a trial calculation on the 1st element of your array, and uses that return dtype to determine the dtype of the whole reply.</p>
<p>Look at the 3rd example... | 1 | 2016-09-12T16:07:01Z | [
"python",
"numpy"
] |
Extracting Pylint Score | 39,453,828 | <p>Does anyone know how to extract <em>only</em> the pylint score for a repository?</p>
<p>So, assuming pylint produces the following output:</p>
<pre><code>Global evaluation
-----------------
Your code has been rated at 6.67/10 (previous run: 6.67/10, +0.00)
</code></pre>
<p>I would like it to return a value of 6.6... | 1 | 2016-09-12T15:26:03Z | 39,454,034 | <p>You can run <code>pylint</code> <em>programmatically</em> and get to the <code>stats</code> dictionary of the underlying "linter":</p>
<pre><code>from pylint.lint import Run
results = Run(['test.py'], exit=False)
print(results.linter.stats['global_note'])
</code></pre>
| 2 | 2016-09-12T15:38:20Z | [
"python",
"pylint"
] |
Not concatenating in same line | 39,453,829 | <p>This is my code:</p>
<pre><code>with open('test1.txt') as f:
print "printing f"
print f
print '**********************'
for line in f:
print "printing line each"
print line
print '********'
line2=line.upper()+"abc"
print "printing line 2"
print line2
... | 0 | 2016-09-12T15:26:04Z | 39,453,882 | <p>line contains '\n' at the end, you can use this for your goal:</p>
<pre><code>line.strip().upper()
</code></pre>
| 3 | 2016-09-12T15:28:55Z | [
"python",
"python-2.7",
"concatenation"
] |
Not concatenating in same line | 39,453,829 | <p>This is my code:</p>
<pre><code>with open('test1.txt') as f:
print "printing f"
print f
print '**********************'
for line in f:
print "printing line each"
print line
print '********'
line2=line.upper()+"abc"
print "printing line 2"
print line2
... | 0 | 2016-09-12T15:26:04Z | 39,453,897 | <p>Just use a <a href="https://docs.python.org/2/library/string.html#string.strip" rel="nofollow">.strip()</a>, so</p>
<pre><code>print line.strip().upper()
</code></pre>
<p>You're reading a new line separated document. It's got special "\n"s inside.</p>
| 1 | 2016-09-12T15:29:48Z | [
"python",
"python-2.7",
"concatenation"
] |
How to get an element having its relative XPath? | 39,453,891 | <p>I have xml file. After parsing it with <code>lxml</code> as an <code>etree</code>, I can get all of its tags as follows:</p>
<pre><code>root = tree.getroot()
for e in root.iter():
print e.tag
</code></pre>
<p>and the output is something like this:</p>
<pre class="lang-none prettyprint-override"><code>'{http:/... | -1 | 2016-09-12T15:29:29Z | 39,454,096 | <p>BeautifulSoup, does not support XPath expressions, but <strong>lxml</strong> you've mentioned, does. </p>
<p>You can search for elements with XPath like following:</p>
<pre><code>from lxml import etree
htmlparser = etree.HTMLParser()
tree = etree.parse(html_content, htmlparser)
tree.xpath(xpathselector)
</code><... | 0 | 2016-09-12T15:41:56Z | [
"python",
"xml",
"xpath",
"lxml",
"bs4"
] |
How to overload __str__ operation so str("test") returns "test" | 39,454,069 | <p>I'm trying to overload the <strong>str</strong> operation so that when I do str(string) it keeps the quotations.</p>
<p>ex:
str("test")
returns test</p>
<p>I want it to return "test"</p>
<p>Heres what I have written, any help would be very much appreciated!</p>
<pre><code>class Action(MalmoAgent):
def __init... | 0 | 2016-09-12T15:40:18Z | 39,454,138 | <p>Use <code>repr()</code>, this is obviously not an actual string.</p>
<pre><code>repr('Test')
</code></pre>
| 0 | 2016-09-12T15:44:23Z | [
"python",
"string",
"operator-overloading"
] |
How to overload __str__ operation so str("test") returns "test" | 39,454,069 | <p>I'm trying to overload the <strong>str</strong> operation so that when I do str(string) it keeps the quotations.</p>
<p>ex:
str("test")
returns test</p>
<p>I want it to return "test"</p>
<p>Heres what I have written, any help would be very much appreciated!</p>
<pre><code>class Action(MalmoAgent):
def __init... | 0 | 2016-09-12T15:40:18Z | 39,454,165 | <p>Just format your string</p>
<pre><code>... def __str__(self):
... return '"%s"' % self.whatever
</code></pre>
| 0 | 2016-09-12T15:45:58Z | [
"python",
"string",
"operator-overloading"
] |
How to overload __str__ operation so str("test") returns "test" | 39,454,069 | <p>I'm trying to overload the <strong>str</strong> operation so that when I do str(string) it keeps the quotations.</p>
<p>ex:
str("test")
returns test</p>
<p>I want it to return "test"</p>
<p>Heres what I have written, any help would be very much appreciated!</p>
<pre><code>class Action(MalmoAgent):
def __init... | 0 | 2016-09-12T15:40:18Z | 39,463,367 | <pre><code>class MalmoAgent():
pass
class Action(MalmoAgent):
def __init__(self, command='', value=0):
self.__command = command
self.__value = value
def __str__(self):
return '"' + super(Action, self).__str__() + '"'
thing = Action()
print("I have a", thing, "called thing.")
</c... | 0 | 2016-09-13T06:19:01Z | [
"python",
"string",
"operator-overloading"
] |
How to use leveldb and What kind of dataLayer I can use in pycaffe interface? | 39,454,111 | <p>I tried to make train/val.prototxt using leveldb by caffe python interface:</p>
<pre><code>layer {
name: "cifar"
type: "Data"
top: "data"
top: "label"
data_param {
source: "/home/youngwan/data/cifar10/cifar10-gcn-leveldb-splits/cifar10_full_train_leveldb_padded"
batch_size: 100
backend: LEVELD... | 1 | 2016-09-12T15:42:44Z | 39,464,010 | <p>Using <code>caffe.NetSpec()</code> interface, you can have all the layers you want:</p>
<pre><code>from caffe import layers as L, params as P
cifar = L.Data(data_param={'source': '/home/youngwan/data/cifar10/cifar10-gcn-leveldb-splits/cifar10_full_train_leveldb_padded',
'batch_size': 100... | 1 | 2016-09-13T07:03:20Z | [
"python",
"neural-network",
"deep-learning",
"caffe",
"pycaffe"
] |
"FailedParse: [...] Expecting end of text" when trying to parse parenthesized expressions in grako | 39,454,140 | <p>In <code>search_query.ebnf</code>, I have the following grammar definition for <code>grako</code> 3.14.0:</p>
<pre class="lang-none prettyprint-override"><code>@@grammar :: SearchQuery
start = search_query $;
search_query = parenthesized_query | combined_query | search_term;
parenthesized_query = '(' search_query... | 1 | 2016-09-12T15:44:43Z | 39,454,141 | <blockquote>
<p>Am I doing something wrong?</p>
</blockquote>
<p>I don't think so.</p>
<p>This looks like a <a href="https://bitbucket.org/apalala/grako/issues/81/left-recursion" rel="nofollow">known bug</a> in <code>grako</code> concerning "left recursion".</p>
<p>The workaround mentioned in the bug seems to work... | 1 | 2016-09-12T15:44:43Z | [
"python",
"ebnf",
"grako"
] |
Scipy.optimize COBYLA constraint violation | 39,454,203 | <p>I have an optimization problem with constraints, but the COBYLA solver doesn't seem to respect the constraints I specify.</p>
<p>My optimization problem:</p>
<pre><code>cons = ({'type':'ineq', 'fun':lambda t: t},) # all variables must be positive
minimize(lambda t: -stateEst(dict(zip(self.edgeEvents.keys(),t)), (0... | 0 | 2016-09-12T15:48:47Z | 39,455,568 | <p><strong>COBYLA</strong> is technically speaking an <strong>infeasible method</strong>, which means, that the <strong>iterates might not be always feasible in regards to your constraints!</strong> (it's only about the final convergence, where feasibility matters for these algorithms).</p>
<p>Using an objective-funct... | 3 | 2016-09-12T17:22:10Z | [
"python",
"optimization",
"scipy",
"constraints"
] |
xarray.Dataset.where() method force-changes dtype of DataArrays to float | 39,454,205 | <h1>Problem description</h1>
<p>I have a dataset with <code>int</code>s in them, and I'd like to select a subdataset by some criteria but I would like to preserve the integer datatype. It seems to me that Xarray force-changes the integer data to float datatype.</p>
<h1>Example setup</h1>
<h3>Code</h3>
<pre><code>im... | 2 | 2016-09-12T15:48:51Z | 39,454,954 | <p>That's because with numpy (which xarray uses under-the-hood) ints don't have a way of representing <code>NaN</code>s. So with most <code>where</code> results, the type needs to be coerced to floats.</p>
<p>If <code>drop=True</code> and every value that is masked is dropped, that's not actually a constraint - you co... | 3 | 2016-09-12T16:38:17Z | [
"python",
"python-xarray"
] |
How to convert an angle vector to Euclidean coordinates given a fixed amplitude, in n dimension | 39,454,240 | <p>so to convert a polar coordinate (amplitude, angle) to euclidean coordinates in 2D is straight forward. </p>
<p>But in n (say n = 5) dimension, I have a fixed amplitude, and a randomised angle vector. How can I convert it into an euclidean vector of the coordinates?</p>
<pre><code>amp = 0.5
n = 5
ang = np.random.r... | 0 | 2016-09-12T15:50:41Z | 39,454,853 | <p>In 2D, the conversion is:</p>
<pre><code>x = amp * cos(angle)
y = amp * sin(angle)
</code></pre>
<p>In 3D, one option is:</p>
<pre><code>x = amp * cos(angle1) * cos(angle2)
y = amp * sin(angle1) * cos(angle2)
z = amp * sin(angle2)
</code></pre>
<p>You should see a pattern. The dimensions that alrea... | 5 | 2016-09-12T16:30:43Z | [
"python",
"math",
"wolfram-mathematica"
] |
How can I plot my groupby() result? | 39,454,260 | <p>I'm running a <code>groupby()</code> on my data like this:</p>
<pre><code>user.groupby(["DOC_ACC_DT", "DOC_ACTV_CD"]).agg("sum")["SUM_DOC_CNT"]
</code></pre>
<p>which results in this grouped data:</p>
<pre><code>DOC_ACC_DT DOC_ACTV_CD
2015-07-01 BR 1
PT 1
2015-07-02 BR ... | 1 | 2016-09-12T15:51:46Z | 39,454,561 | <p>You can use:</p>
<pre><code>df = user.groupby(["DOC_ACC_DT", "DOC_ACTV_CD"]).agg("sum")["SUM_DOC_CNT"]
df.unstack().resample('D').replace(np.nan,0).plot()
</code></pre>
| 2 | 2016-09-12T16:09:37Z | [
"python",
"pandas",
"plot",
null,
"resampling"
] |
Is there a way to play song from the middle in gstreamer? | 39,454,407 | <p>I've looking for method to play songs not from the begining in python gstreamer, consider this:</p>
<pre><code>import threading
import gst
import gobject
class GobInit(threading.Thread):
...
class BasicPlayer(threading.Thread):
def __init__(self, musiclist):
threading.Thread.__init__(self)
... | 1 | 2016-09-12T15:59:54Z | 39,456,299 | <p>Yes, I guess there should be a few ways, but the one (for non-live streams) that immediately comes to my mind is:</p>
<ul>
<li>Set the pipeline to PAUSED instead of PLAYING</li>
<li>Wait for the GST_MESSSAGE_ASYNC_DONE message to appear in the bus handler.</li>
<li>Query pipeline (gst_element_query()) for the durat... | 3 | 2016-09-12T18:12:34Z | [
"python",
"gstreamer"
] |
Django having issues with django-registration-redux | 39,454,433 | <p>I've been following an online tutorial on django registration. They are using <code>django-registration-redux==1.1</code>, and I have to use <code>django-registration-redux==1.4</code>. I start my local server and go to this: <a href="http://127.0.0.1:8000/accounts/register/" rel="nofollow">http://127.0.0.1:8000/acc... | 0 | 2016-09-12T16:01:50Z | 39,454,475 | <p>It looks like you have a space in line 1 of your template when referencing the file name. If that's not it, you may have another folder locally named registration that django is looking in instead of the registration package.</p>
| 0 | 2016-09-12T16:04:22Z | [
"python",
"django",
"django-registration"
] |
Read (decode) and process an aac stream with python | 39,454,468 | <p>I have an Axis camera that provides an audio stream that is aac encoded. I would like to find a possibility to decode that stream in Python to further process the raw audio data. Does anybody have suggestions how that could be done?</p>
<p>Thanks!</p>
| 0 | 2016-09-12T16:03:53Z | 39,647,478 | <p>You can use <a href="https://github.com/jiaaro/pydub" rel="nofollow">pydub</a> to convert an <code>aac</code> audio to datasegment and then process it further.</p>
<pre><code>from pydub import AudioSegment
from pydub.playback import play
#convert audio to datasegment
sound = AudioSegment.from_file("your/path/to/au... | 0 | 2016-09-22T19:33:20Z | [
"python",
"audio",
"decode",
"aac"
] |
different ways to access pandas.DataFrame columns | 39,454,471 | <p>What is the difference between <code>df[columns]</code> and <code>df.loc[:,columns]</code>, both as lvalue and rvalue?</p>
<p>They seem to be interchangeable from the behavioral POV:</p>
<pre><code>>>> df = pd.DataFrame({'x':[1,2,3],'y':['a','b','c']})
>>> df[['x']].equals(df.loc[:,['x']])
True
&... | 1 | 2016-09-12T16:04:07Z | 39,456,621 | <p>what about timing comparison for a 300K rows DF?</p>
<pre><code>In [22]: big = pd.concat([df] * 10**5, ignore_index=True)
In [23]: %timeit -n 1 -r 1 big['n1'] = big.x.apply(str) + big.y
1 loop, best of 1: 266 ms per loop
In [24]: %timeit -n1 -r 1 big.ix[:, 'n2'] = big.x.apply(str) + big.y
1 loop, best of 1: 317 m... | 0 | 2016-09-12T18:34:30Z | [
"python",
"pandas",
"dataframe"
] |
Add Name and Value in PDF Document Properties \ Custom with Reportlab | 39,454,484 | <p>I am wondering if is possible to add new Names & Values (new attributes) to the PDF Document Properties \ Custom (AKA Metadata).</p>
<p>I've been looking to the documentation but it seems they don't speak about it. Only the metadata Author, Keywords, etc inside Document Properties \ Description.</p>
<p>Thanks ... | 0 | 2016-09-12T16:04:38Z | 39,505,562 | <p>It seems that this is not possible, I checked the source code which actually specifies the reason why:</p>
<blockquote>
<p>PDF documents can have basic information embedded, viewable from
File | Document Info in Acrobat Reader. If this is wrong, you get
Postscript errors while printing, even though i... | 1 | 2016-09-15T07:43:49Z | [
"python",
"reportlab"
] |
How can I run a Jython script with Python | 39,454,526 | <p>I am programming in Python(2.7), processing a bunch of data.
And I've got a software, what I have to use, and I want to start it automatically, and fill it up with data.</p>
<p>The problem is, that I cant open it with Python, because it has API only for Jython. </p>
<p>My question is, that how could I run a Jython... | 0 | 2016-09-12T16:07:51Z | 39,489,547 | <p>You can simply use Jython to run everything.</p>
<p>Having <code>my_script.py</code> and <code>jython_script.py</code> edit <code>my_script.py</code> by adding <code>import jython_script</code> and adding call <code>jython_script.some_function()</code>.</p>
<pre><code># my_script.py
import jython_script
def my_fu... | 2 | 2016-09-14T11:41:12Z | [
"python",
"python-2.7",
"jython"
] |
Divide two dataframes with python | 39,454,542 | <p>I have two dataframes : df1 and df2</p>
<p>df1 : </p>
<pre><code>TIMESTAMP eq1 eq2 eq3
2016-05-10 13:20:00 40 30 10
2016-05-10 13:40:00 40 10 20
</code></pre>
<p>df2 : </p>
<pre><code>TIMESTAMP eq1 eq2 eq3
2016-05-10 13:20:00 10 20 30
2016-05-10 13:40:00 10 20 20
</code></pre>
<p>I would like to divide df1 by d... | 2 | 2016-09-12T16:08:44Z | 39,454,665 | <p>This should work if <code>TIMESTAMP</code> is not the index:</p>
<pre><code>>>> df1.set_index('TIMESTAMP').div(df2.set_index('TIMESTAMP').sum())
eq1 eq2 eq3
TIMESTAMP
2016-05-10 13:20:00 2 0.75 0.2
2016-05-10 13:40:00 2 0.25 0.4
</code></pre>
<p... | 1 | 2016-09-12T16:17:41Z | [
"python",
"pandas",
"dataframe",
"multiple-columns",
"division"
] |
Divide two dataframes with python | 39,454,542 | <p>I have two dataframes : df1 and df2</p>
<p>df1 : </p>
<pre><code>TIMESTAMP eq1 eq2 eq3
2016-05-10 13:20:00 40 30 10
2016-05-10 13:40:00 40 10 20
</code></pre>
<p>df2 : </p>
<pre><code>TIMESTAMP eq1 eq2 eq3
2016-05-10 13:20:00 10 20 30
2016-05-10 13:40:00 10 20 20
</code></pre>
<p>I would like to divide df1 by d... | 2 | 2016-09-12T16:08:44Z | 39,454,901 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.div.html" rel="nofollow"><code>div</code></a>, but before <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.set_index.html" rel="nofollow"><code>set_index</code></a> from both columns <code>TIMES... | 3 | 2016-09-12T16:34:17Z | [
"python",
"pandas",
"dataframe",
"multiple-columns",
"division"
] |
Decorators in class methods: compatibility with 'getattr' | 39,454,560 | <p>I need to make wrappers for class methods, to be executed before and/or after the call of a specific method.</p>
<p>Here is a minimal example:</p>
<pre><code>class MyClass:
def call(self, name):
print "Executing function:", name
getattr(self, name)()
def my_decorator(some_function):
... | 0 | 2016-09-12T16:09:31Z | 39,454,612 | <p>This has nothing to do with <code>getattr()</code>. You get the exact same error when you try to call <code>my_function()</code> directly:</p>
<pre><code>>>> engine.my_function()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callabl... | 2 | 2016-09-12T16:14:03Z | [
"python",
"oop",
"metaprogramming",
"decorator",
"python-decorators"
] |
Single origin value for python matplotlib plot | 39,454,672 | <p>I have a simple plot executed using matplotlib. My x and y axes start at 0,0 respectively. A matplotlib plot shows 2 zeros corresponding to the 2 axes. I want only one zero (somewhere in the middle of the start point, if possible).
How can this be done?</p>
<p>Here's what I used:</p>
<pre><code>import matplotlib.p... | 0 | 2016-09-12T16:18:31Z | 39,464,894 | <p>The keyword is <code>prune</code>, which allows you to kill the <code>upper</code>, <code>lower</code> or <code>both</code> tick labels. Here is a working examples that gets rid of the 0 of the x-axis:</p>
<pre><code>import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
plt.plot([1,2,3], [4,5,6... | 1 | 2016-09-13T07:56:07Z | [
"python",
"matplotlib",
"plot"
] |
How to fetch json response from another url in django? | 39,454,771 | <p>I have created 2 views in django namely</p>
<pre><code> def next_qn_url(request):
test_result1 = 'questionansewrchoice'
return JsonResponse({'test_result':test_result1})
def last_qn_url(request):
test_result2 = 'questionansewrchoice'
return JsonResponse({'test_result':test_r... | 0 | 2016-09-12T16:25:01Z | 39,465,350 | <p>I'm not sure your urls are correct. The first 3 point to the same views.test Django view, which could explain why you get the test html continuously. In my understanding, calling the name of the url in the getJSON function is not the same as calling a view that happen to have a 'similar name'. The first argument in ... | 1 | 2016-09-13T08:22:01Z | [
"jquery",
"python",
"json",
"ajax",
"django"
] |
How to divide a list into a given time step | 39,454,811 | <p>I have a list, e.g.</p>
<pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5]
</code></pre>
<p>Where each item in the list is a event happened at time 0.1, time 0.6 etc.</p>
<p>I want to divide the list into a delta t, but how can this be done? All the other threads I have seen only discussed ab... | 0 | 2016-09-12T16:28:01Z | 39,455,042 | <p>Here is a version that iterates through the list only once: </p>
<pre><code>start = 0
delta = 1
stop = delta
grouped = []
group = []
event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5]
for val in event:
if start < val < stop:
group.append(val)
else:
while val > stop:
... | 0 | 2016-09-12T16:44:10Z | [
"python",
"list"
] |
How to divide a list into a given time step | 39,454,811 | <p>I have a list, e.g.</p>
<pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5]
</code></pre>
<p>Where each item in the list is a event happened at time 0.1, time 0.6 etc.</p>
<p>I want to divide the list into a delta t, but how can this be done? All the other threads I have seen only discussed ab... | 0 | 2016-09-12T16:28:01Z | 39,455,128 | <p>First, make sure you list is sorted. Once you've done this, iterate through the list. Starting from the first value, create a new list containing all values from the first value to the final value that rests within the desired range. Then, jump to the index of that value and repeat. Given a delta t of 1, the list </... | 0 | 2016-09-12T16:50:22Z | [
"python",
"list"
] |
How to divide a list into a given time step | 39,454,811 | <p>I have a list, e.g.</p>
<pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5]
</code></pre>
<p>Where each item in the list is a event happened at time 0.1, time 0.6 etc.</p>
<p>I want to divide the list into a delta t, but how can this be done? All the other threads I have seen only discussed ab... | 0 | 2016-09-12T16:28:01Z | 39,455,213 | <p>It look like you just want a list lists separated by the integers they are above/below. If that is the case then just use your "delta" in an conditional...loop through the list comparing each value to your delta, and keep a record of the index of your "current/active" list that you are inserting into. If the current... | 0 | 2016-09-12T16:56:17Z | [
"python",
"list"
] |
How to divide a list into a given time step | 39,454,811 | <p>I have a list, e.g.</p>
<pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5]
</code></pre>
<p>Where each item in the list is a event happened at time 0.1, time 0.6 etc.</p>
<p>I want to divide the list into a delta t, but how can this be done? All the other threads I have seen only discussed ab... | 0 | 2016-09-12T16:28:01Z | 39,455,236 | <p>you can do this with <code>itertools.groupby</code> pretty easily:</p>
<pre><code>from itertools import groupby
event.sort()
delta_t = 1
r = [list(v) for (k, v) in groupby(event, lambda v: v // delta_t)]
</code></pre>
| 1 | 2016-09-12T16:58:10Z | [
"python",
"list"
] |
How to divide a list into a given time step | 39,454,811 | <p>I have a list, e.g.</p>
<pre><code>event = [0.1, 0.6, 1.5, 3.4, 3.8, 4.1, 6.2, 8.5, 9.1, 9.5]
</code></pre>
<p>Where each item in the list is a event happened at time 0.1, time 0.6 etc.</p>
<p>I want to divide the list into a delta t, but how can this be done? All the other threads I have seen only discussed ab... | 0 | 2016-09-12T16:28:01Z | 39,455,247 | <p>Another possible solution:</p>
<pre><code>from collections import defaultdict
def split_list(lst, delta=1):
start, end = 0, max(event)
result = []
while start < end:
start += delta
group = filter(lambda x: x > (start - delta) and x < start, event)
if group:
... | 1 | 2016-09-12T16:58:38Z | [
"python",
"list"
] |
Openerp workflow doesn't show last transition button | 39,454,832 | <p>I tried to edit my holiday work-flow and up do '<strong>validate</strong>' state it is working fine. But then I have added new node with transition , then the transition button does not appear to validate the work-flow. Please help me with this and relevant codes are bellow.</p>
<p><strong><em>The last two nodes</e... | 0 | 2016-09-12T16:29:36Z | 39,469,251 | <p>It was just I have used a wrong state in the button. </p>
<pre><code><button string="Approved" type="workflow" name="last_validate" states="**new_validate**" class="oe_highlight"/>
</code></pre>
<p>changed in to:</p>
<pre><code><button string="Approved" type="workflow" name="last_validate" states="**vali... | 0 | 2016-09-13T11:46:20Z | [
"python",
"xml",
"openerp"
] |
Python - accessing single database wrapper object from multiple objects | 39,454,993 | <p>I have a simple Python wrapper around a MySQL database, and I need to be able to access it from inside other custom class objects within Python. The wrapper class lives in a separate file to each of the other custom classes. So far I've only been able to find the following ways of doing things:</p>
<ol>
<li>Make th... | 0 | 2016-09-12T16:40:57Z | 39,571,848 | <p>Answering my own question since no one responded, and this might be useful to other people in future. I was recommended to use a "half-way" global, by writing an intermediary module that looks something like this:</p>
<pre><code>from my_db_class import Database
db = Database( 'user', 'password', 'database' )
</code... | 0 | 2016-09-19T11:15:00Z | [
"python",
"mysql",
"database",
"mysql-connector-python"
] |
Python 3 Print Update on multiple lines | 39,455,022 | <p>Is it possible to print and update more than one line?
This works for one line:</p>
<pre><code>print ("Orders: " + str(OrderCount) + " Operations: " + str(OperationCount), end="\r")
</code></pre>
<p>and get this: (Of course the numbers update because its in a loop)</p>
<pre><code>Orders: 25 Operations: 300
</code... | 0 | 2016-09-12T16:42:38Z | 39,455,032 | <p><code>\r</code> is a <em>carriage return</em>, where the cursor moves to the start of the line (column 0). From there, writing more text will overwrite what was written before, so you end up only with the last line (which is long enough to overwrite everything you've written before).</p>
<p>You want <code>\n</code>... | 3 | 2016-09-12T16:43:35Z | [
"python"
] |
Python 3 Print Update on multiple lines | 39,455,022 | <p>Is it possible to print and update more than one line?
This works for one line:</p>
<pre><code>print ("Orders: " + str(OrderCount) + " Operations: " + str(OperationCount), end="\r")
</code></pre>
<p>and get this: (Of course the numbers update because its in a loop)</p>
<pre><code>Orders: 25 Operations: 300
</code... | 0 | 2016-09-12T16:42:38Z | 39,455,043 | <p>You probably want <code>\n</code> instead of <code>\r</code>. <code>\r</code> is "carriage return", a.k.a. "go back to the beginning of the line" -- so you're print "Operations" over "Orders".</p>
| 0 | 2016-09-12T16:44:25Z | [
"python"
] |
sqlalchemy empty schema and no tables | 39,455,048 | <p>I am trying to use sqlalchemy via a Database first approach and generate the models for the existing database structure. The db is a standard SQLServer(express).</p>
<p>I can connect to my database and query it via the following</p>
<pre><code>from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.o... | 0 | 2016-09-12T16:44:35Z | 39,455,113 | <p>This is because <code>debug.BasicTable</code> is most likley not the name of your table. The name of your table is <code>BasicTable</code> and <code>debug</code> is its schema. So:</p>
<pre><code>Table('BasicTable', meta, schema="debug", autoload=True, autoload_with=db_engine)
</code></pre>
| 1 | 2016-09-12T16:49:36Z | [
"python",
"sql-server",
"sqlalchemy"
] |
.py config file with fallback data? | 39,455,068 | <p>I have a <code>settings.py</code> file in my project:</p>
<pre><code>"Nickname of the user to check the games for"
USERNAME = "user"
</code></pre>
<p>Unfortunately, it will be overwritten by each upgrade. So, I'd like to allow the user to override the default settings by creating a <code>.py</code> file <code>$XDG... | 0 | 2016-09-12T16:46:02Z | 39,455,595 | <p>I assume the way you get the values from the <code>settings.py</code> file is by <code>import</code>ing it:</p>
<pre><code>import settings
print(settings.USERNAME)
</code></pre>
<p>Then you could change it by adding something like this to the end which will do what you want.</p>
<p><strong><code>settings.py</cod... | 1 | 2016-09-12T17:23:56Z | [
"python",
"python-3.x",
"settings"
] |
Python zip - Why do we need to unpack the argument? | 39,455,100 | <p>I'm trying to understand the need to unpack the arguments using <code>*</code> when the input to <code>zip</code> is a 2D list. The <a href="https://docs.python.org/3/library/functions.html#zip" rel="nofollow">docs</a> state,</p>
<blockquote>
<p>[zip] Returns an iterator of tuples, where the i-th tuple contains ... | 0 | 2016-09-12T16:47:54Z | 39,455,396 | <p>Consider this example:</p>
<pre><code>>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> z = [7, 8, 9]
>>> zip(x,y,z)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> zip(x,y)
[(1, 4), (2, 5), (3, 6)]
>>> zip(x)
[(1,), (2,), (3,)]
>>> zip()
[]
</code></pre>
<p>Observe that ... | 5 | 2016-09-12T17:08:27Z | [
"python"
] |
Increase the number of columns in a list of dictionaries | 39,455,106 | <p>I don't know the exact words to phrase this in a more scientific way, so please feel free to help me out with my poor grammar.</p>
<p>My problem is the following: I have constructed a table out of a list of dictionaries like so:</p>
<pre><code>for d in listDictionary:
print d
{'key1':'value11', 'key2':'value1... | 0 | 2016-09-12T16:48:54Z | 39,455,816 | <p>Firstly, the simple answer:</p>
<p>If you want to set only unset values, there's a <code>dict.setdefault</code> method. For example, given <code>dict5</code> as the fifth row (containing <code>value51</code>, <code>value52</code>, etc.), and that you want to update the column <code>root1</code>:</p>
<pre><code># r... | 0 | 2016-09-12T17:40:01Z | [
"python",
"dictionary"
] |
Increase the number of columns in a list of dictionaries | 39,455,106 | <p>I don't know the exact words to phrase this in a more scientific way, so please feel free to help me out with my poor grammar.</p>
<p>My problem is the following: I have constructed a table out of a list of dictionaries like so:</p>
<pre><code>for d in listDictionary:
print d
{'key1':'value11', 'key2':'value1... | 0 | 2016-09-12T16:48:54Z | 39,456,148 | <p>If I've understood the question correctly, perhaps this might work:</p>
<pre><code>data = [
{ 'k1': 'root3>rv11;root1>rv12', 'k2': 'v12', 'k3': 'v13'},
{ 'k1': 'v21', 'k2': 'root1>rv21;root2>rv22;', 'k3': 'v23'},
{ 'k1': 'v31', 'k2': 'v32', 'k3': 'root2>rv32;'}
]
newkeys = set()
for item... | 0 | 2016-09-12T18:01:47Z | [
"python",
"dictionary"
] |
Kivy non-GUI events | 39,455,119 | <p>i am trying to start an animation when the app is first loaded. I.E. immediately after the loading screen has closed. I have tired the "on_enter" event but it doesn't seem to work, any help would be much appreciated.</p>
<pre><code>from kivy.base import runTouchApp
from kivy.lang import Builder
from kivy.uix.widget... | 0 | 2016-09-12T16:49:49Z | 39,455,849 | <p>The <code>on_enter</code> method is defined in the <code>Screen</code>, not in the <code>Widget</code>. You should put that rectangle on a screen (the <code>Root</code> widget should be a screen here), and once the screen's <code>on_enter</code> event fires, start the rectangle animation.</p>
<p>Also, you are calli... | 0 | 2016-09-12T17:42:41Z | [
"python",
"events",
"event-handling",
"kivy",
"kivy-language"
] |
How to make a pdb set_trace the first breakpoint | 39,455,167 | <p>I have pdb.set_trace() in two spots of my code. The problem is that I get multiple stops in the second area when I want it to start somewhere specific. Here is an example:</p>
<pre><code>def function():
#some code in here
pdb.set_trace()
#some more code
def main():
#some code
function()
#come mo... | 0 | 2016-09-12T16:53:11Z | 39,459,884 | <p>You need not modify your code (by adding calls to <code>pdb.set_trace()</code>) in order to debug it with <code>pdb</code> (the advice to do that has always seemed misguided to me). <a href="http://stackoverflow.com/q/34914704/5384908">This question</a> is another example of a problem this approach can cause.</p>
<... | 0 | 2016-09-12T22:51:42Z | [
"python",
"pdb"
] |
Odoo - Change domain on inherited view | 39,455,189 | <p>I am currently working on building a custom module, and I extended the unit of measure class (product.uom). I want some uom entries to be removed from the list/tree views, based on a specific value for one of my new variables.</p>
<p>I am not entirely sure how to modify this view. I seem to be reading that I need... | 1 | 2016-09-12T16:54:59Z | 39,459,866 | <p>In order to do what Nross2781 is looking for you have to override the ir.actions.act_window for the record. </p>
<pre><code><record model="ir.actions.act_window" id="uom_list_action">
<field name="name">Units Of Measurement</field>
<field name="res_model">product.uom</field>
... | 1 | 2016-09-12T22:48:19Z | [
"python",
"filter",
"openerp"
] |
Difficulties in installation of pysparse and superlu | 39,455,263 | <p>I want to run a python2.7 program (<a href="https://github.com/williamhunter/topy" rel="nofollow">this one</a>). I'm having a lot of trouble (I spend my whole aftenoon on this), because of the installation of the python 2.7 dependencies.</p>
<p><strong>Config</strong></p>
<p>I am running an Ubuntu 16.04 64bits ([M... | 0 | 2016-09-12T17:00:02Z | 39,471,269 | <p>I did get an <a href="https://github.com/williamhunter/topy/issues/9" rel="nofollow">answer</a>, thanks to <a href="https://github.com/williamhunter" rel="nofollow" title="William Hunter's profile on Github">William Hunter</a>.</p>
<p>The procedure to install it is the following :</p>
<pre><code>sudo apt-get i... | 0 | 2016-09-13T13:24:46Z | [
"python",
"python-2.7",
"pip",
"python-module",
"finite-element-analysis"
] |
Normalisation of data | 39,455,299 | <p>I am trying to plot the data below in a pie chart. I split the pie chart based on the group first and then based on the Id. But since for some rows, the count is very small, I am not able to see it in the pie chart. </p>
<p>I am trying to normalise the data. I am not sure on how to do that. Any help would be sincer... | 1 | 2016-09-12T17:02:16Z | 39,455,469 | <p>Don't pie chart what doesn't fit a visual representation in a pie chart</p>
<pre><code>(
df.groupby(['Group', 'Id'])
.sum().Count.sort_values(ascending=False)
.plot.bar(logy=True, subplots=True)
)
</code></pre>
| 3 | 2016-09-12T17:14:13Z | [
"python",
"pandas",
"normalization"
] |
Error in reading and writing files in Python | 39,455,343 | <p>I am trying to convert files from one format to other in Python. The current format is DAQ (data acquisition format), which is read in first. Then I use <code>undaq Tools</code> module to write the files to hdf5 format. </p>
<pre><code>import glob
ctnames = glob.glob('*.daq')
</code></pre>
<p>Following are the fe... | 0 | 2016-09-12T17:04:42Z | 39,455,492 | <p>Wrap the <code>read()</code> call in a try/except block. If you get an exception, print the current filename and skip to the next one.</p>
<pre><code>for n in ctnames:
try:
x = daq.read(n)
except AssertionError:
print 'Could not process file %s. Skipping.' % n
continue
daq... | 1 | 2016-09-12T17:15:56Z | [
"python"
] |
wxPython: pause main script and wait for button press | 39,455,361 | <p>I am working on a GUI using wxPython. This GUI should dynamically ask to the user several sets of inputs in the same window, updating the window with the new set of inputs after a button "ok" is pressed.</p>
<p>To do this I have a for loop which calls a function that prompts the input controls on the window. I have... | 0 | 2016-09-12T17:05:45Z | 39,466,326 | <p>It's not really clear what you intend to do here. Your Script doesnt crash, it just waits indefinatly on the event at line 40. You did not start any additional thread which could set the event, so the other script would continue.</p>
<p>Also be aware that wxPython is not thread safe - so if you start adding widgets... | 1 | 2016-09-13T09:14:40Z | [
"python",
"user-interface",
"dynamic",
"wxpython"
] |
extract a sentence that contains a list of keywords or phrase using python | 39,455,363 | <p>I have used the following code to extract a sentence from file(the sentence should contain some or all of the search keywords)</p>
<pre><code>search_keywords=['mother','sing','song']
with open('text.txt', 'r') as in_file:
text = in_file.read()
sentences = text.split(".")
for sentence in sentences:
if (... | 0 | 2016-09-12T17:05:49Z | 39,455,515 | <p>So you want to find sentences that contain at least one keyword. You can use <a href="https://docs.python.org/3/library/functions.html?highlight=any#any" rel="nofollow">any()</a> instead of <a href="https://docs.python.org/3/library/functions.html?highlight=all#all" rel="nofollow">all()</a>.</p>
<p>EDIT:
If you wan... | 0 | 2016-09-12T17:17:55Z | [
"python",
"file",
"search",
"text"
] |
extract a sentence that contains a list of keywords or phrase using python | 39,455,363 | <p>I have used the following code to extract a sentence from file(the sentence should contain some or all of the search keywords)</p>
<pre><code>search_keywords=['mother','sing','song']
with open('text.txt', 'r') as in_file:
text = in_file.read()
sentences = text.split(".")
for sentence in sentences:
if (... | 0 | 2016-09-12T17:05:49Z | 39,455,516 | <p>If I understand correctly, you should be using <a href="https://docs.python.org/3/library/functions.html#any" rel="nofollow"><code>any()</code></a> instead of <code>all()</code>.</p>
<pre><code>if (any(map(lambda word: word in sentence, search_keywords))):
print sentence
</code></pre>
| 0 | 2016-09-12T17:17:59Z | [
"python",
"file",
"search",
"text"
] |
extract a sentence that contains a list of keywords or phrase using python | 39,455,363 | <p>I have used the following code to extract a sentence from file(the sentence should contain some or all of the search keywords)</p>
<pre><code>search_keywords=['mother','sing','song']
with open('text.txt', 'r') as in_file:
text = in_file.read()
sentences = text.split(".")
for sentence in sentences:
if (... | 0 | 2016-09-12T17:05:49Z | 39,455,804 | <p>It seems like you want to count the number of <code>search_keyboards</code> in each sentence. You can do this as follows:</p>
<pre><code>sentences = "My name is sing song. I am a mother. I am happy. You sing like my mother".split(".")
search_keywords=['mother','sing','song']
for sentence in sentences:
print("{... | 2 | 2016-09-12T17:39:11Z | [
"python",
"file",
"search",
"text"
] |
Python: read regexps from JSON | 39,455,366 | <p>I have a JSON file where I store a mapping, which contains regexes, like the ones below:</p>
<pre><code>"F(\\d)": "field-\\\\1",
"FLR[ ]*(\\w)": "floor-\\\\1",
</code></pre>
<p>To comply with the standard I escape the backslashes, the actually regexps should contain <code>\d</code>, <code>\w</code>, and <code>\\1<... | 1 | 2016-09-12T17:05:55Z | 39,455,454 | <p>It does produce a single backslash - that backslash is escaped when displayed. This is done so that characters without a non-escaped way to display them can still be unambiguously printed - otherwise, you wouldn't know whether a backslash was meant to be escaping the following character or not.</p>
<p>This can be d... | 1 | 2016-09-12T17:13:16Z | [
"python",
"json",
"regex",
"python-2.7"
] |
Python relative imports using setuptools with scripts | 39,455,388 | <p>I am transitioning to a package-based workflow for a project I've been working on. I want to be able to separate development and production environments and I think setuptools offers this possibility with some degree of ease.</p>
<p>I have a project structured as follows:</p>
<pre><code>modulename/
setup.py
... | 0 | 2016-09-12T17:07:27Z | 39,483,698 | <p>The problem is not related with <code>setuptools</code>. Using relative imports inside the module being executed as <code>__main__</code> does not work out of the box. There are workarounds / hacks, but the most common solutions seems to be moving the script out of the package or using absolute imports in the script... | 1 | 2016-09-14T06:20:54Z | [
"python",
"python-3.x",
"import",
"package"
] |
shell shift in exel using python | 39,455,474 | <p>i wrote the following python script that reads the contents of "prom output.csv" file" and after does some processing it writes the output to the file "sorted output."</p>
<pre><code>import collections
import csv
import sys
with open("prom output.csv","r") as f:
cr = csv.reader(f,delimiter=",")
d=collecti... | 2 | 2016-09-12T17:14:23Z | 39,455,538 | <p>Don't use <code>join</code> for your row content; just combine the header w/ the data into a single list:</p>
<pre><code>cr.writerow([k]+v)
</code></pre>
| 3 | 2016-09-12T17:19:36Z | [
"python",
"excel"
] |
Python 2.7 MySQLdb to save last row read from database into text file | 39,455,484 | <p>So bare with me, I have been doing python for a little over a week now. I have been tasked with getting a MySQL database to send data into Salesforce and create a ticket. I currently have python downloading the required tables from the database and saving that information into a .xlsx sheet. Then I have another pyth... | 0 | 2016-09-12T17:15:38Z | 39,489,791 | <ol>
<li>Add a <code>row</code> in the <code>table</code>you pull your information from. </li>
<li>Pull the <code>id</code> (0th's row) as unique identifier</li>
<li>Update <code>row</code> which has <code>id</code> with something like <code>True</code> or <code>False</code>.</li>
<li>Give your query a <code>condition... | 0 | 2016-09-14T11:53:14Z | [
"python",
"mysql",
"excel",
"python-2.7"
] |
SQLAlchemy Core bulk insert slow | 39,455,518 | <p>I'm trying to truncate a table and insert only ~3000 rows of data using SQLAlchemy, and it's very slow (~10 minutes). </p>
<p>I followed the recommendations on this <a href="http://docs.sqlalchemy.org/en/latest/faq/performance.html" rel="nofollow">doc</a> and leveraged sqlalchemy core to do my inserts, but it's sti... | 0 | 2016-09-12T17:18:02Z | 39,755,105 | <p>I was bummed when I saw this didn't have an answer... I ran into the exact same problem the other day: Trying to bulk-insert about millions of rows to a Postgres RDS Instance using CORE. It was taking <em>hours</em>.</p>
<p>As a workaround, I ended up writing my own bulk-insert script that generated the raw sql its... | 0 | 2016-09-28T18:30:12Z | [
"python",
"postgresql",
"orm",
"sqlalchemy"
] |
Custom user model and custom authentication not working in django. Authentication form is not passing validation tests | 39,455,546 | <p>I am trying to implement the custom User model and custom authentication for my application.<br>
I am able to create models and make migrations. But when I created a form and implemented the login template, I am getting this error - </p>
<pre><code>login
User model with this Login already exists.
</code></pre>
<p... | 0 | 2016-09-12T17:20:38Z | 39,456,300 | <p>Firstly, you are storing passwords in plain text in your overwritten <code>create_superuser</code> method. You <strong>must absolutely not do this</strong>. Quite apart from the security issues, it won't actually work, as the authentication backend will hash a submitted password before comparing it with the saved ve... | 1 | 2016-09-12T18:12:39Z | [
"python",
"django",
"authentication"
] |
map items from list using list comprehension? | 39,455,561 | <p>I have a problem with a list comprehension inside a loop. I want to add items from one list to an other.</p>
<p>I'm using <code>map class</code> and <code>zip</code> inside the list comprehension.</p>
<pre><code>from pandas import Series, DataFrame
import pandas
x = ['a', 'b', 'c', 'd', 'e']
y = [2, 3, 6, 7, 4]
se... | 2 | 2016-09-12T17:21:13Z | 39,456,594 | <p>Replace gap = with this</p>
<pre><code>[list((x,y[0])) for x,y in zip(years,temp)]
</code></pre>
| 2 | 2016-09-12T18:32:39Z | [
"python",
"list",
"python-3.x",
"loops"
] |
django login_required defaults request.LANGUAGE_CODE to default language in settings | 39,455,603 | <p><strong>login_required</strong> decorator sets <strong>request.LANGUAGE_CODE</strong> to default language that has been set in <strong>settings.py</strong>. How can I bypass this behavior ?</p>
<p>thanks! </p>
| 1 | 2016-09-12T17:24:27Z | 39,457,089 | <p>I had this issue in the past and found that setting your LOGIN_URL in the settings file to use reverse_lazy works:</p>
<pre><code>LOGIN_URL = reverse_lazy('log_in')
</code></pre>
| 0 | 2016-09-12T19:06:29Z | [
"python",
"django"
] |
My labels aren't moving to the column and rows I want them to | 39,455,718 | <p>I want my labels and entry widgets and different rows but they automatically move to the top. What do I do to do that? Is there a simple function I could use?</p>
<pre><code>from tkinter import *
root = Tk()
root.resizable(width = False, height = False)
label_1 = Label(root, text="Text")
label_2 = Label(root, te... | -1 | 2016-09-12T17:32:55Z | 39,458,554 | <p>Empty rows and columns have size 0. Blank labels can be used to create blank space.</p>
<pre><code>from tkinter import *
root = Tk()
dummy = Label(root, text='\n')
label_1 = Label(root, text="Text")
label_2 = Label(root, text="Text2")
entry1 = Entry(root)
entry2 = Entry(root)
dummy.grid()
label_1.grid(row=4, colu... | 0 | 2016-09-12T20:47:18Z | [
"python",
"tkinter"
] |
gcc: error trying to exec 'cc1plus': execvp: No such file or directory | 39,455,741 | <p>I'm trying to install this python module, which requires compilation (on Ubuntu 16.04). I'm struggling to understand exactly what's causing it stall; what am I missing?</p>
<pre><code>(xenial)chris@localhost:~$ pip install swigibpy
Collecting swigibpy
Using cached swigibpy-0.4.1.tar.gz
Building wheels for collect... | 0 | 2016-09-12T17:34:37Z | 39,458,229 | <p>The routine commands that saved me time after time for such errors:</p>
<pre><code>sudo apt install upgrade
sudo apt install update
sudo apt install gcc python3-dev python3-pip libxml2-dev libxslt1-dev zlib1g-dev
</code></pre>
<p>Hope it works.</p>
| 0 | 2016-09-12T20:22:30Z | [
"python",
"gcc"
] |
How to store mySQL query as python dictionary and call later in script? | 39,455,758 | <p>I have a table called "<strong>uid</strong>" which has two fields, <strong>rfid</strong> and <strong>empid</strong>:</p>
<ul>
<li><strong>EXAMPLE RECORD 1</strong> rfid = 88 999 33 555 empid = 1 </li>
<li><strong>EXAMPLE RECORD 2</strong> rfid = 64 344 77 222 empid = 2</li>
</ul>
<p>I would like to run a query ... | 1 | 2016-09-12T17:35:44Z | 39,456,216 | <p>I think you're looking for the fetchall method. After you call </p>
<p><code>cur.execute("""SELECT number, empid FROM rfid """)</code></p>
<p>you would do:</p>
<p><code>rows = cur.fetchall()</code></p>
<p>and then rows would contain a list of tuples. If you specifically need it to be a dictionary, you could ju... | 0 | 2016-09-12T18:06:31Z | [
"python",
"mysql",
"dictionary"
] |
Find a character from a string without using find method? | 39,455,784 | <p>As I am a newbie ... not understanding why it's not working properly ?
expecting the cause and solution and also tips
thanks</p>
<pre><code>str = "gram chara oi ranga matir poth"
find ='p'
l = len(str)
for x in range(0,l):
if str[x]==find:
flag = x
#break
if flag == x:
print "foun... | 1 | 2016-09-12T17:37:55Z | 39,455,839 | <p><code>if flag == x</code> looks strange. What value of <code>x</code> are you expecting there?</p>
<p>I'd suggest instead initializing <code>flag</code> to <code>None</code> and then checking for it not being <code>None</code> at the end of the loop.</p>
<pre><code>flag = None # assign a "sentinel" value here
str ... | 1 | 2016-09-12T17:41:48Z | [
"python",
"string"
] |
Find a character from a string without using find method? | 39,455,784 | <p>As I am a newbie ... not understanding why it's not working properly ?
expecting the cause and solution and also tips
thanks</p>
<pre><code>str = "gram chara oi ranga matir poth"
find ='p'
l = len(str)
for x in range(0,l):
if str[x]==find:
flag = x
#break
if flag == x:
print "foun... | 1 | 2016-09-12T17:37:55Z | 39,455,879 | <p>You're trying to have flag be the location of the index of the (first) matching character. Good!</p>
<pre><code>if str[x]==find:
flag = x
break
</code></pre>
<p>But how to tell if nothing was found? Testing against x won't help! Try initializing flag to a testable value:</p>
<pre><code>flag = -1
for x in ra... | 0 | 2016-09-12T17:44:45Z | [
"python",
"string"
] |
Find a character from a string without using find method? | 39,455,784 | <p>As I am a newbie ... not understanding why it's not working properly ?
expecting the cause and solution and also tips
thanks</p>
<pre><code>str = "gram chara oi ranga matir poth"
find ='p'
l = len(str)
for x in range(0,l):
if str[x]==find:
flag = x
#break
if flag == x:
print "foun... | 1 | 2016-09-12T17:37:55Z | 39,456,005 | <p>Your method of searching is valid (iterating through the characters in the string). However, your problem is at the end when you're evaluating whether or not you've found the character. You're comparing <code>flag</code> to <code>x</code>, but when you do the comparison, <code>x</code> is <a href="http://stackover... | 0 | 2016-09-12T17:52:36Z | [
"python",
"string"
] |
Issue with Flask-Marshmallow exposing DB contents via API | 39,455,814 | <p>I am developing a API which will return entries from a Database. I am using Flask-SQLAlchemy, Flask-Marshmallow, Flask-Admin and Docker to package it all up. </p>
<p>In one file Packages.py I have the following code regarding the database. The class PckagesSchema is the class I've added when trying to get Flash-Mar... | 1 | 2016-09-12T17:39:57Z | 39,458,289 | <p>I just brushed up a little on marshmallow:</p>
<pre><code>@app.route('/packages', methods=['GET'])
def get_packages():
packages = Packages.query.all()
result = packages_schema.dump(packages).data
return jsonify(result)
</code></pre>
<p>Should give you everything in there. If you are returning many rec... | 0 | 2016-09-12T20:25:27Z | [
"python",
"flask",
"flask-sqlalchemy",
"marshmallow"
] |
pyspark: convert a bytearray field to string in data frame | 39,455,836 | <p>I am reading a parquet file to a dataframe:</p>
<pre><code>my_df = sqlContext.read.parquet('hdfs://my_server/user/hive/warehouse/my_db.db/my_table')
</code></pre>
<p>if I do:</p>
<pre><code>my_df.head()
</code></pre>
<p>I got:</p>
<pre><code>Row(id=bytearray(b'00000000000000000000000000000000'), numcores=8, ...... | 0 | 2016-09-12T17:41:41Z | 39,455,876 | <p>If you mean to change what <code>head()</code> returns to you, that's not gonna happen, since the <a href="https://spark.apache.org/docs/1.6.2/api/python/pyspark.sql.html#pyspark.sql.DataFrame.head" rel="nofollow">prototype</a> doesn't provide any such functionality:</p>
<blockquote>
<p>head(n=None)</p>
</blockqu... | 1 | 2016-09-12T17:44:27Z | [
"python",
"apache-spark",
"pyspark",
"spark-dataframe"
] |
What is the benefit of a dataframe view or copy | 39,455,863 | <p>I've seen many questions about the infamous <code>SettingWithCopy</code> warning. I've even ventured to answer a few of them. Recently, I was putting together an answer that involved this topic and I wanted to present the benefit of a dataframe view. I failed to produce a tangible demonstration of why it is a goo... | 2 | 2016-09-12T17:43:28Z | 39,456,035 | <p>There is a lot of existing discussion on this, see <a href="https://github.com/pydata/pandas/issues/10954" rel="nofollow">here</a> for instance, including the attempted PRs. It's also worth noting that true copy-on-write for views is being considered as part of the "pandas 2.0" refactor, see <a href="https://github... | 3 | 2016-09-12T17:54:17Z | [
"python",
"pandas"
] |
How to merge lists of tuples? | 39,455,901 | <p>I use python 3</p>
<p>I have a list L, which contains another lists, which contains turples of point (x,y):</p>
<pre><code>L=[A, B, C, D ...]
A = [(1,1),(3,3),(4,5)...]
B=[(1,2),..(6,7)]
</code></pre>
<p>I want to merge all lists from L, which have a adjacent points.
As above: we must to union A,B because they ha... | -2 | 2016-09-12T17:46:17Z | 39,456,990 | <p>This is my crack at your algorithm:</p>
<pre><code>def adjacent(list_1, list_2):
for elem_1 in list_1:
for elem_2 in list_2:
if abs(elem_1[0] - elem_2[0]) == 1 or\
abs(elem_1[1] - elem_2[1]) == 1:
return True
return False
def join_adjacent_points(L):
... | 0 | 2016-09-12T18:59:48Z | [
"python",
"python-3.x"
] |
A simple case of struct, but getting a "bad char" error | 39,455,984 | <p>I'm attempting to read a section of a binary file, and decode it as a string of characters using the struct. module. </p>
<p>It's a simple enough case. Here is the bytes argument:</p>
<pre><code>b'11:10:00\x00ng '
</code></pre>
<p>and here is the function I am attempting to use: </p>
<pre><code>struct.unpack('ut... | -3 | 2016-09-12T17:51:18Z | 39,456,314 | <h1>EDIT</h1>
<ol>
<li>no <code>"i"</code> is not a valid encoding to use <code>str.decode</code>
<ul>
<li>see <a href="https://docs.python.org/2/library/codecs.html#standard-encodings" rel="nofollow">https://docs.python.org/2/library/codecs.html#standard-encodings</a></li>
</ul></li>
<li>no <code>"utf-8"</code> is ... | 1 | 2016-09-12T18:13:17Z | [
"python",
"struct"
] |
A simple case of struct, but getting a "bad char" error | 39,455,984 | <p>I'm attempting to read a section of a binary file, and decode it as a string of characters using the struct. module. </p>
<p>It's a simple enough case. Here is the bytes argument:</p>
<pre><code>b'11:10:00\x00ng '
</code></pre>
<p>and here is the function I am attempting to use: </p>
<pre><code>struct.unpack('ut... | -3 | 2016-09-12T17:51:18Z | 39,456,358 | <p>The struct module does a completely different job from what you're trying to do. It's for deserializing data that looks like serialized C structs (hence the name). <code>int</code>s, <code>double</code>s, fixed-size <code>char</code> arrays, things like that, packed together in a rigid layout with fixed alignment an... | 1 | 2016-09-12T18:16:27Z | [
"python",
"struct"
] |
Data from socket.recv() printing as a mixture of \x and printable ASCII, how to force raw hex? | 39,455,997 | <p>I have some simple code which is listening to data on a TCP socket:</p>
<pre><code> data = client_socket.recv(4096)
print("RECEIVED:",data)
</code></pre>
<p>It works great, but the output looks like this:</p>
<pre><code>RECEIVED: b'\xd8\xff\xfe\x00$\xe3J\xda*\x00
</code></pre>
<p>and so on.</p>
<p>What I... | 0 | 2016-09-12T17:52:27Z | 39,456,059 | <pre><code>import binascii
binascii.hexlify('\xd8\xff\xfe\x00$\xe3J\xda*\x00').upper()
</code></pre>
<p>gets you most of the way ...</p>
| 0 | 2016-09-12T17:55:41Z | [
"python",
"tcp"
] |
Python Recursion vs Iteration | 39,456,149 | <p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p>
<blockquote>
<p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the numbe... | -1 | 2016-09-12T18:01:52Z | 39,456,272 | <pre><code>def replicate(c,times):
return [c]*times
def replicate2(c,times):
return [c for i in range(times)]
def replicate3(c,times):
result = []
for i in range(times): result.append(c)
return result
def replicate4(c,times):
return [c] + (replicate4(c,times-1) if times > 0 else [])
</code... | 1 | 2016-09-12T18:10:51Z | [
"python",
"recursion",
"iteration"
] |
Python Recursion vs Iteration | 39,456,149 | <p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p>
<blockquote>
<p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the numbe... | -1 | 2016-09-12T18:01:52Z | 39,456,289 | <pre><code>def replicate_iter(times, data):
if not isinstance(data, int) and not isinstance(data, str):
raise ValueError('Must be int or str')
if times <= 0:
return []
return [data for _ in range(times)]
def replicate_recur(times, data):
if not isinstance(data, int) and not isinstanc... | 0 | 2016-09-12T18:12:01Z | [
"python",
"recursion",
"iteration"
] |
Python Recursion vs Iteration | 39,456,149 | <p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p>
<blockquote>
<p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the numbe... | -1 | 2016-09-12T18:01:52Z | 39,456,450 | <p>Basic implementation for both (although they are not good Python to be honest) would be:</p>
<pre><code>def replicate_iter(times, data):
result = []
for _ in range(times): # xrange in Python2
result.append(data)
return result
def replicate_recur(times, data):
if times <= 0:
ret... | 1 | 2016-09-12T18:22:21Z | [
"python",
"recursion",
"iteration"
] |
Python Recursion vs Iteration | 39,456,149 | <p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p>
<blockquote>
<p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the numbe... | -1 | 2016-09-12T18:01:52Z | 39,456,972 | <p>I think your code is closer to being correct than other folks are saying -- you just need to rearrange some elements:</p>
<pre><code>def replicate_iter(times, data):
if type(data) != int and type(data) != str:
raise TypeError('Invalid Argument')
try:
my_list = []
if times > 0:
... | 1 | 2016-09-12T18:58:45Z | [
"python",
"recursion",
"iteration"
] |
Python Recursion vs Iteration | 39,456,149 | <p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p>
<blockquote>
<p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the numbe... | -1 | 2016-09-12T18:01:52Z | 39,457,423 | <p>for the recursive version I recommend <a href="https://en.wikipedia.org/wiki/Tail_call" rel="nofollow">tail recursion</a> as you are already doing, the other examples even if simplest use list concatenation (<code>+</code>) which produce a new list with a copy of the elements of each, that is too much waste of time ... | 1 | 2016-09-12T19:28:02Z | [
"python",
"recursion",
"iteration"
] |
Python Recursion vs Iteration | 39,456,149 | <p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p>
<blockquote>
<p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the numbe... | -1 | 2016-09-12T18:01:52Z | 39,459,754 | <p>This works!</p>
<pre><code>def replicate_iter(times, data):
if((not isinstance(times, int)) or (not isinstance(data, (int, float, long, complex, str)))):
raise ValueError("Invalid arguments")
elif(times <= 0):
return []
else:
array = []
for x in range(t... | 2 | 2016-09-12T22:34:30Z | [
"python",
"recursion",
"iteration"
] |
Python Recursion vs Iteration | 39,456,149 | <p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p>
<blockquote>
<p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the numbe... | -1 | 2016-09-12T18:01:52Z | 39,462,465 | <p>I think the iterative version is straightforward, and others have provided good answers. As for the recursion, I always like to see if I can come up with a divide and conquer strategy rather than whittle the problem down one step at a time, to avoid blowing out the stack. The following does that:</p>
<pre><code>d... | 1 | 2016-09-13T04:59:37Z | [
"python",
"recursion",
"iteration"
] |
Python Recursion vs Iteration | 39,456,149 | <p>I can't find the error in my code. It runs just fine on my cmd but won't pass the lab platform tests. Here is the question:</p>
<blockquote>
<p>You need to design an iterative and a recursive function called replicate_iter and replicate_recur respectively which will receive two arguments: times which is the numbe... | -1 | 2016-09-12T18:01:52Z | 39,563,723 | <p>def replicate_recur(times, data):
list = []
if (times <= 0):
return []
elif(type(times) != int and type(data) != str):
raise ValueError ("invalid")</p>
<pre><code>elif(times > 0):
list.append(data)
return list + replicate_recur(times -1, data)
</code></pre>
<p>def repli... | 0 | 2016-09-18T23:57:43Z | [
"python",
"recursion",
"iteration"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.