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 |
|---|---|---|---|---|---|---|---|---|---|
Inherit field from one model to another model - Odoo v9 Community | 40,099,291 | <p>I'm trying to add a field from a table, into another table, through a module.</p>
<p>Specifically, trying to inherit a field from <code>product.product</code>, the <code>price</code> field, to add it into <code>stock.move</code> model.</p>
<p>So, I've created a model into this new module I'm making.</p>
<p>Like t... | 1 | 2016-10-18T04:02:06Z | 40,104,725 | <p>The problem you have is that you're inheriting <code>product.product</code> and linking back to it again with a <code>One2many</code> field</p>
<p>If you want to add the product price to <code>stock.move</code> just delete the extra model that extends <code>product.product</code> and make a Many2one link like you'v... | 1 | 2016-10-18T09:38:46Z | [
"python",
"openerp",
"odoo-9",
"qweb"
] |
Inherit field from one model to another model - Odoo v9 Community | 40,099,291 | <p>I'm trying to add a field from a table, into another table, through a module.</p>
<p>Specifically, trying to inherit a field from <code>product.product</code>, the <code>price</code> field, to add it into <code>stock.move</code> model.</p>
<p>So, I've created a model into this new module I'm making.</p>
<p>Like t... | 1 | 2016-10-18T04:02:06Z | 40,104,986 | <p>What about a related field on <code>stock.move</code>?</p>
<pre class="lang-py prettyprint-override"><code>class StockMove(models.Model):
_inherit = "stock.move"
price_unity = fields.Float(
string="Precio", related="product_id.price", readonly=True)
</code></pre>
| 1 | 2016-10-18T09:50:59Z | [
"python",
"openerp",
"odoo-9",
"qweb"
] |
Why isn't readline() working properly? | 40,099,351 | <p>I have a file called untitled.txt with the following lines:</p>
<pre><code>Line 1: ATTCTGGA
Line 2: CGCCCGAATCCAGAACGCATTCCCATATTTCGGGACCACTGGCCTCCACGGTACGGACGTCAATCAAAT
</code></pre>
<p>When I enter code for finding the positions where sp (line 1) appears in p (line 2) with a maximum of d errors, I get the outpu... | -5 | 2016-10-18T04:09:20Z | 40,099,384 | <p>Because <code>readline()</code> provides the whole line, including the trailing newline character. You should strip the trailing newline:</p>
<pre><code>sp = text.readline().rstrip("\n")
p = text.readline().rstrip("\n")
</code></pre>
| 0 | 2016-10-18T04:13:26Z | [
"python",
"python-3.x",
"bioinformatics",
"jupyter",
"jupyter-notebook"
] |
How to use REGEX with multiple filters | 40,099,363 | <p>There are three DAYs described by <code>text</code> variable: </p>
<pre><code>text = """
DAY {
foo 12 5 A
foo
12345
}
DAY {
day 1
day 2
file = "/Users/Shared/docs/doc.txt"
day 3
end of the month
}
DAY {
01.03.2016 11:15
01.03.2016 11:16
01.03.2016 11:17
}"""
</code></pre>
<p>All three DAY definitions b... | 0 | 2016-10-18T04:11:08Z | 40,099,981 | <p>To perform regular expression matching on multiline text, you need to compile your regex with parameter <code>re.MULTILINE</code>.</p>
<p>This piece of code should work as you requested.</p>
<pre><code>regex = re.compile("""(DAY\s*\{[^\{\}]*file\ \=\ \"/Users/Shared/docs/doc\.txt\"[^\{\}]*\})""", re.MULTILINE)
reg... | 1 | 2016-10-18T05:10:08Z | [
"python",
"regex"
] |
Python multi-precision rational comparison: Fraction, mpq and mpfr | 40,099,422 | <p>I understand that floating-point calculation is not accurate due to its nature. I'm trying to find out the best library/way to do multi-precision ration comparison. I'm comparing Fraction, mpq and mpfr. The later two are from gmpy2 library. The first one is from fractions package. I'm using python3.3</p>
<p>This is... | 0 | 2016-10-18T04:17:27Z | 40,101,899 | <p><code>float(mpq)</code> calls the GMP library function <code>mpq_get_q</code>. I checked the GMP source and <code>mpq_get_d</code> rounds the intermediate result towards 0. It does not calculate a correctly rounded result. (In this case, correctly rounded implies round to nearest with ties to even.) So it will occas... | 1 | 2016-10-18T07:18:00Z | [
"python",
"fractions",
"mpfr",
"gmpy"
] |
python (deI) statement and python behavior | 40,099,427 | <p>When a del statement is issued:</p>
<blockquote>
<p>del var</p>
</blockquote>
<p>Shouldn't it be removed from the list of known variable and shouldn't the python interpreter spit out "unresolved reference" error?</p>
<p>Or is it simply just deleting the object and leaving the name (var) not pointing anywhere? W... | 4 | 2016-10-18T04:17:57Z | 40,099,489 | <p>Not sure what you're asking, as clearly thats what happens...</p>
<pre><code>>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
>>> x = 10
>>> 'x' in vars()
True
>>> vars()['x']
10
>>> del x
>&... | 2 | 2016-10-18T04:24:57Z | [
"python"
] |
python (deI) statement and python behavior | 40,099,427 | <p>When a del statement is issued:</p>
<blockquote>
<p>del var</p>
</blockquote>
<p>Shouldn't it be removed from the list of known variable and shouldn't the python interpreter spit out "unresolved reference" error?</p>
<p>Or is it simply just deleting the object and leaving the name (var) not pointing anywhere? W... | 4 | 2016-10-18T04:17:57Z | 40,099,819 | <blockquote>
<p>Shouldn't it be removed from the list of known variable and shouldn't
the python interpreter spit out "unresolved reference" error?</p>
</blockquote>
<p>This is exactly what happens. Once you <code>del</code> something, the next reference to it will raise <code>NameError</code>.</p>
<blockquote>
... | 1 | 2016-10-18T04:56:02Z | [
"python"
] |
python (deI) statement and python behavior | 40,099,427 | <p>When a del statement is issued:</p>
<blockquote>
<p>del var</p>
</blockquote>
<p>Shouldn't it be removed from the list of known variable and shouldn't the python interpreter spit out "unresolved reference" error?</p>
<p>Or is it simply just deleting the object and leaving the name (var) not pointing anywhere? W... | 4 | 2016-10-18T04:17:57Z | 40,099,844 | <p>The "del" removes the name from the current namespace. If the underlying object has its reference count drop to zero, then the object itself is freed.</p>
<pre><code>>>> import sys
>>> x = 123456
>>> y = x # create a second reference to the number
>>> dir() ... | 1 | 2016-10-18T04:58:17Z | [
"python"
] |
Is it possible to use DictVectorizer on chunked data? | 40,099,432 | <p>I am trying to import chunked data using python pandas csv reader,to overcome memory error, and use DicVectorizer to transform string to float dtypes. But I could see two different strings are having same codes after transformation. Do we have alternative/option to do the data type transformation on chunked data?</p... | 2 | 2016-10-18T04:18:22Z | 40,099,483 | <p>In Pandas 0.19, you can declare columns as Categorial in read_csv. See <a href="http://pandas.pydata.org/pandas-docs/version/0.19.0/whatsnew.html#whatsnew-0190-enhancements-read-csv-categorical" rel="nofollow">documentaion</a>.</p>
<p>So as an example for the doc, you can type a column named <code>col1</code> in yo... | 2 | 2016-10-18T04:24:23Z | [
"python",
"pandas"
] |
Python Scrambler Program | 40,099,459 | <p>This program takes words in a sentence and scrambles them.
The rules are:
- first and last letter remain the same
- punctuation at the end of a word stays the same
- punctuation with a word is scrambled like the middle letters</p>
<p>My problem is that if I have multiple punctuation at the end of a word it does not... | 1 | 2016-10-18T04:22:00Z | 40,099,696 | <p>The problem is that you don't add in the punctuation to the shuffle; see the two amended lines below:</p>
<pre><code>if word[-1] in punctuation:
x = -1
while word[x] in punctuation:
end_punctuation += word[x]
x -= 1
omega = word[x]
middle = word[1: x] + end_punctuation[1:] # Include ... | 0 | 2016-10-18T04:46:26Z | [
"python",
"python-3.x"
] |
Python Scrambler Program | 40,099,459 | <p>This program takes words in a sentence and scrambles them.
The rules are:
- first and last letter remain the same
- punctuation at the end of a word stays the same
- punctuation with a word is scrambled like the middle letters</p>
<p>My problem is that if I have multiple punctuation at the end of a word it does not... | 1 | 2016-10-18T04:22:00Z | 40,104,195 | <p>My take on it, can shorten the code a bit. (In Python 3.5.1)</p>
<pre><code>import random
words = input("Enter your text: ")
def scramble(words):
for x in words.split():
middle = x[1:-1]
middle_list = list(middle)
random.shuffle(middle_list)
shuffled = "".join(middle_list)
... | 0 | 2016-10-18T09:15:58Z | [
"python",
"python-3.x"
] |
Check row by row in QTableWidget to affect QCombobox | 40,099,498 | <p>I have a QTableWidget, 2 Columns in which the first column contains the name of items while the second column is populated with qcomboboxes (created using cellwidgets) which contains a list of color options (eg. "", RED, BLUE, GREEN)</p>
<p>For example, in the following table, items denoted with * has a variable ca... | 0 | 2016-10-18T04:26:16Z | 40,108,203 | <p>If you look at the code you posted, it doesn't show the loop over the rows to put the combo boxes in each cell, but I will assume there is one otherwise it wouldn't work at all. </p>
<p>What you should do is one of two things:
- if you have a separate loop to create your combo boxes then in that loop don't create ... | 0 | 2016-10-18T12:24:34Z | [
"python",
"pyqt",
"maya",
"qtablewidget",
"qcombobox"
] |
Check row by row in QTableWidget to affect QCombobox | 40,099,498 | <p>I have a QTableWidget, 2 Columns in which the first column contains the name of items while the second column is populated with qcomboboxes (created using cellwidgets) which contains a list of color options (eg. "", RED, BLUE, GREEN)</p>
<p>For example, in the following table, items denoted with * has a variable ca... | 0 | 2016-10-18T04:26:16Z | 40,112,961 | <p>If the color variable doesn't exist, your code needs to explicitly set the color combo to a blank item:</p>
<pre><code>def populate_data(self):
geo_name = self.all_mesh
for row_index, geo_item in enumerate(geo_name):
new_item = QtGui.QTableWidgetItem(geo_item)
# Add in each and every mesh f... | 1 | 2016-10-18T16:01:27Z | [
"python",
"pyqt",
"maya",
"qtablewidget",
"qcombobox"
] |
Check row by row in QTableWidget to affect QCombobox | 40,099,498 | <p>I have a QTableWidget, 2 Columns in which the first column contains the name of items while the second column is populated with qcomboboxes (created using cellwidgets) which contains a list of color options (eg. "", RED, BLUE, GREEN)</p>
<p>For example, in the following table, items denoted with * has a variable ca... | 0 | 2016-10-18T04:26:16Z | 40,121,592 | <p>Ok, so the problem was in <code>color_value_to_combobox</code>. Instead of setting the combobox for ALL objects, you need to specify what object and combobox the function needs to work on. The major flaw was that you were using <code>self.color_combobox</code> to set with every time, so every object would keep setti... | 1 | 2016-10-19T03:26:10Z | [
"python",
"pyqt",
"maya",
"qtablewidget",
"qcombobox"
] |
SQLAlchemy ORM update value by checking if other table value in list | 40,099,500 | <p>I have a Kanji (Japanese characters) list which looks like:</p>
<pre><code>kanji_n3 = ['æ¿', 'è°', 'æ°', 'é£'] # But then with 367 Kanji
</code></pre>
<p>and I have 2 tables: <code>TableKanji</code> and <code>TableMisc</code>. <code>TableMisc</code> has a column called 'jlpt', from which some currently have t... | 1 | 2016-10-18T04:26:26Z | 40,101,090 | <p>Seems like that your intention is to make an update on joined tables. Not all databases support this.</p>
<p>First of all you should use <a href="http://stackoverflow.com/questions/8603088/sqlalchemy-in-clause"><code>in_</code></a> method instead of <code>in</code> operator.</p>
<p>You can make select first and th... | 1 | 2016-10-18T06:31:53Z | [
"python",
"sqlalchemy"
] |
Python Multiprocessing data output wrong | 40,099,585 | <p>I am trying Multiprocessing in Python. I have written some code which does vector add, but couldn't get the output out of the function. Which mean, the output Z prints out 0 rather than 2.</p>
<pre><code>from multiprocessing import Process
import numpy as np
numThreads = 16
num = 16
numIter = num/numThreads
X = ... | 0 | 2016-10-18T04:35:52Z | 40,100,670 | <p>The reason your last line <code>print Z[0]</code> returns [0] instead of [2] is that each of the processes makes an independent copy of Z (or may be <code>Z[j]</code> - not completely sure about that) before modifying it. Either way, a separate process run will guarantee that your original version will be unchanged.... | 0 | 2016-10-18T06:03:35Z | [
"python",
"numpy",
"multiprocessing"
] |
How to convert nested OrderedDict to Object | 40,099,614 | <p>I have dictionary like this</p>
<pre><code>data = OrderedDict([('name', 'NewIsland'), ('Residents', [OrderedDict([('name', 'paul'), ('age', '23')])])])
</code></pre>
<p>and I want to convert it to class object.</p>
<p>Here are my django models.</p>
<pre><code>class Country(models.Model):
name = models.CharFi... | 0 | 2016-10-18T04:38:55Z | 40,099,789 | <p>You can do it by manually creating child objects</p>
<pre><code>residents_data = data.pop('Residents')
result = Country(**data)
for rdata in residents_data:
result.residents.add(Residents(**rdata), bulk=False)
</code></pre>
| 0 | 2016-10-18T04:53:21Z | [
"python",
"django"
] |
??? .head() displays 5 rows without mentioning it | 40,099,777 | <p><em>I'm confused here.
Below is command to view the dataset shape:</em></p>
<pre><code> In[] df_faa_dataset.shape
Out[] (83, 42)
</code></pre>
<p><em>Now I want to see first 5 rows and entered command:</em></p>
<pre><code>In[] df_faa_dataset.head()
Out[] (displayed output with 5 rows à 42 columns)
</code><... | -2 | 2016-10-18T04:52:00Z | 40,099,887 | <p><a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.head.html" rel="nofollow">link to official docs</a></p>
<p><a class='doc-link' href="http://stackoverflow.com/documentation/pandas/1751/indexing-and-selecting-data/21739/slice-dataframe-from-beginning-or-end#t=201610180457416242455">lin... | 1 | 2016-10-18T05:01:05Z | [
"python",
"pandas",
"dataframe"
] |
What is the best way to "force" users to use a certain file extension with argparse? | 40,099,817 | <p>I have a script which users include the pathnames for the input and output files. </p>
<pre><code>import argparse
parser = argparse.ArgumentParser()
parser.add_argument("i", help = "input path")
parser.add_argument("o", help = "output path")
args = parser.parse_args()
file_input = args.input
file_output = args.out... | 3 | 2016-10-18T04:55:42Z | 40,120,714 | <p>You could define a <code>type</code> function that adds the required extension, e.g.</p>
<pre><code>def txtname(astr):
if not astr.endswith('.txt'):
astr += '.txt'
return astr
In [724]: parser=argparse.ArgumentParser()
In [725]: parser.add_argument('-i',type=txtname);
In [726]: parser.add_argument(... | 2 | 2016-10-19T01:41:38Z | [
"python",
"python-3.x",
"argparse",
"file-extension"
] |
slicing the last second word in python | 40,099,866 | <p>i need to write a python script that will count the next-to-last word . my code is:</p>
<pre><code>with open('/tmp/values.txt') as f:
for sentence in f:
list_sentecne = [sen for sen in sentence.rstrip().split(' ')]
print (list_sentecne)
op = list_sentecne[-2:-2]
print (op)
</code></pre>
<p>output i go... | -3 | 2016-10-18T04:59:33Z | 40,100,154 | <p>Yo need to print from 2nd last element from list - </p>
<pre><code>>>> list_sentecne = ['some', 'line', 'with', 'text']
>>> op = list_sentecne[-2:]
>>> print (op)
['with', 'text']
</code></pre>
<p>if only the 2nd last element </p>
<pre><code>>>> list_sentecne = ['some', 'line',... | 1 | 2016-10-18T05:25:48Z | [
"python",
"python-2.7",
"python-3.x"
] |
Are asyncio's EventLoop tasks created with loop.create_task a FIFO | 40,099,885 | <p>I can not find any documentation on this, but empirically it <em>seems</em> that it is.</p>
<p>In what order will the coroutines 1 and 2 run in the following three examples and is the order always guaranteed?</p>
<p><strong>A</strong></p>
<pre><code>loop.run_until_complete(coro1)
loop.run_until_complete(coro2)
lo... | 1 | 2016-10-18T05:00:48Z | 40,107,051 | <p>In your first example, <code>coro1</code> will run until it is complete. Then <code>coro2</code> will run. This is essentially the same as if they were both synchronous functions. </p>
<p>In your second example, <code>coro1</code> will run until it's told to await. At that point control is yielded to <code>coro2</c... | 1 | 2016-10-18T11:29:07Z | [
"python",
"python-asyncio"
] |
Drop "faulty" lines of pandas dataframe based on their type and value | 40,099,924 | <p>I have a dataset that includes a column of date and time values and another column containing some measured values (float). However, during some measurements, an error occured, resulting in some weird entries - example below (these include a repeated part of the datetime object which is interpreted as string, incomp... | 3 | 2016-10-18T05:04:23Z | 40,099,956 | <p>I think you need <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> for filtering, instead <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html" rel="nofollow"><code>dropna</code></a> you can add... | 2 | 2016-10-18T05:07:44Z | [
"python",
"pandas"
] |
First django project,showing error no module named 'polls' | 40,099,936 | <p>I followed the Django official document,and I am writing the poll app.</p>
<p>And in the mysite package, it says No module named 'polls' when I run it,how can I solve it?</p>
<p>my python is 3.6,my Django is 1.10.2,</p>
<p>this is my directory</p>
<pre><code>âââ db.sqlite3
âââ manage.py
âââ ... | -4 | 2016-10-18T05:05:51Z | 40,100,210 | <p>Sounds like you don't have the <code>polls</code> app installed.</p>
<p>Go to <code>settings.py</code>, inside it find <code>INSTALLED_APPS = [...]</code> and add <code>'polls',</code> to that list.</p>
| 2 | 2016-10-18T05:30:07Z | [
"python",
"django"
] |
First django project,showing error no module named 'polls' | 40,099,936 | <p>I followed the Django official document,and I am writing the poll app.</p>
<p>And in the mysite package, it says No module named 'polls' when I run it,how can I solve it?</p>
<p>my python is 3.6,my Django is 1.10.2,</p>
<p>this is my directory</p>
<pre><code>âââ db.sqlite3
âââ manage.py
âââ ... | -4 | 2016-10-18T05:05:51Z | 40,105,338 | <p>I have a feeling this problem is related to the setup environment. </p>
<p>For your first problem, try <code>url(r'^polls/', include('mysite.polls.urls')),</code></p>
<p>For your second problem try <code>from polls import views</code>, or just stick with <code>import views</code>.</p>
<p>If this doesn't work, I s... | 0 | 2016-10-18T10:07:25Z | [
"python",
"django"
] |
SPA webapp for plotting data with angular and python | 40,100,083 | <p>I want to write an app for plotting various data (cpu, ram,disk etc.) from Linux machines.</p>
<p>On the client side:
Data will be collected via a <code>python script</code> and saved to a <code>database</code> (on a remote server) eg.: In each second create an entry in a <code>mongodb</code> collection with: sessi... | 1 | 2016-10-18T05:18:38Z | 40,100,193 | <p>I don't see a problem with your approach except that because you have real-time data, I would encourage you to go with some kind of WebSockets approach, like Socket.io on Node and the front end. The reason why I say this is because the alternative approach, which is long-polling, involved a lot of HTTP traffic back ... | 0 | 2016-10-18T05:29:06Z | [
"python",
"angularjs",
"mongodb"
] |
Python: multithreading setting the variable once | 40,100,159 | <p>Does the following code thread-safe?<br>
Will only one/first thread set the variable, set_this_var_only_once? </p>
<pre><code>set_this_var_only_once = None
def worker():
global set_this_var_only_once
if set_this_var_only_once is None:
set_this_var_only_once = "not None"
for i in range(10):
t ... | 2 | 2016-10-18T05:26:05Z | 40,100,269 | <p>Absolutely not.</p>
<p>It is quite possible that two threads execute this line before executing the next one:</p>
<pre><code> if set_this_var_only_once is None:
</code></pre>
<p>After that, both threads will execute the next line:</p>
<pre><code> set_this_var_only_once = "not None"
</code></pre>
<p>Yo... | 3 | 2016-10-18T05:34:17Z | [
"python",
"multithreading",
"python-2.7"
] |
Python: multithreading setting the variable once | 40,100,159 | <p>Does the following code thread-safe?<br>
Will only one/first thread set the variable, set_this_var_only_once? </p>
<pre><code>set_this_var_only_once = None
def worker():
global set_this_var_only_once
if set_this_var_only_once is None:
set_this_var_only_once = "not None"
for i in range(10):
t ... | 2 | 2016-10-18T05:26:05Z | 40,100,311 | <p>No it's not. </p>
<blockquote>
<p>If another thread gets control after the current thread has fetched
the variable, it may fetch the variable, increment it, and write it
back, before the current thread does the same thing. And since theyâre
both seeing the same original value, only one item will be accoun... | 1 | 2016-10-18T05:37:16Z | [
"python",
"multithreading",
"python-2.7"
] |
Python: multithreading setting the variable once | 40,100,159 | <p>Does the following code thread-safe?<br>
Will only one/first thread set the variable, set_this_var_only_once? </p>
<pre><code>set_this_var_only_once = None
def worker():
global set_this_var_only_once
if set_this_var_only_once is None:
set_this_var_only_once = "not None"
for i in range(10):
t ... | 2 | 2016-10-18T05:26:05Z | 40,100,334 | <p>You need to lock the variable like this:</p>
<pre><code>from threading import Lock
lock = Lock()
set_this_var_only_once = None
def worker():
with lock:
if set_this_var_only_once is None:
set_this_var_only_once = "not None
</code></pre>
| 4 | 2016-10-18T05:39:07Z | [
"python",
"multithreading",
"python-2.7"
] |
Can dask parralelize reading fom a csv file? | 40,100,176 | <p>I'm converting a large textfile to a hdf storage in hopes of a faster data access. The conversion works allright, however reading from the csv file is not done in parallel. It is really slow (takes about 30min for a 1GB textfile on an SSD, so my guess is that it is not IO-bound). </p>
<p>Is there a way to have it r... | 1 | 2016-10-18T05:27:31Z | 40,107,654 | <p>Yes, dask.dataframe can read in parallel. However you're running into two problems:</p>
<h3>Pandas.read_csv only partially releases the GIL</h3>
<p>By default dask.dataframe parallelizes with threads because most of Pandas can run in parallel in multiple threads (releases the GIL). Pandas.read_csv is an exceptio... | 1 | 2016-10-18T11:58:11Z | [
"python",
"csv",
"pandas",
"dask"
] |
Django display a photo from a model | 40,100,199 | <p>I've tried several of methods on how to retrieve an image from a model with no luck, this is where I'm at so far. I'd like to have the image show and when the user clicks on it, it opens a modal showing a projects detail.</p>
<p>models.py</p>
<pre><code>class Project(models.Model):
author = models.ForeignKey('a... | 0 | 2016-10-18T05:29:30Z | 40,100,452 | <p>Look at your <code>img</code> tag. In the src attribute, you are using <code>{{ projects.photo.url }}</code>. So, you cannot get image from a queryset, you can only do so from an object of <code>Project</code> model. Use <code>{{ project.photo.url }}</code></p>
| 1 | 2016-10-18T05:47:13Z | [
"python",
"django"
] |
Django where in queryset with comma separated slug in url | 40,100,341 | <p>I have a Post Model</p>
<p><strong>models.py</strong></p>
<pre><code>class Category(models.Model):
title = models.CharField(max_length=100,null=True,blank=False)
slug = models.SlugField(max_length=150,null=True,blank=False)
class Post(models.Model):
title = models.CharField(max_length=256,null=True,bl... | 1 | 2016-10-18T05:39:27Z | 40,100,591 | <p>Comma separated you're going to have to do this by hand:</p>
<p><code>categories = request.GET.get('category').split(',')</code></p>
<p>The more Django way to do this it so change your query string to be</p>
<p><code>?category=slug1&category=slug2</code>. </p>
<p>Then you could use</p>
<p><code>categories ... | 2 | 2016-10-18T05:57:54Z | [
"python",
"django"
] |
Python 2.7: Variable "is not defined" | 40,100,405 | <p>I'm using <a href="https://physionet.org/cgi-bin/atm/ATM" rel="nofollow">Physionet's data base</a> for some tasks related to ECG signal analysis. I wanted to read .MAT files, extract the MLII readings on the file (located throughout row 1), adjust the signal to mV using "gain" and "base" (located in the .INFO filed ... | 1 | 2016-10-18T05:43:49Z | 40,112,595 | <p>Use two loops and extract the <em>info</em> before processing the data files</p>
<pre><code>for filepath in os.listdir('C:blablablablabla\Multiple .mat files'):
if filepath.endswith(".info"):
Fs, gain, base = get_info(filepath)
break
for file in os.listdir('C:blablablablabla\Multiple .mat files'... | 2 | 2016-10-18T15:42:32Z | [
"python",
"python-2.7",
"nested"
] |
Variables in import statement python | 40,100,419 | <p>I'm trying to convert a script I had from bash to python. The way the program worked is that it had a Master script in the top folder and then in the subfolder Scripts a series of smaller, more specialised scripts. These smaller scripts might have names such as foo_bar.x, bar_foo.x, foo_baz.x, foo_qux.x, bar_qux.x, ... | 1 | 2016-10-18T05:44:49Z | 40,100,677 | <p>If you want to import a module whose name is in a variable, you need to use <code>__import__</code>.</p>
<p>For example, let's create a dictionary whose values are the names of modules:</p>
<pre><code>>>> d = { 1:'re', 2:'numpy' }
</code></pre>
<p>Now, let's import one of them:</p>
<pre><code>>>&g... | 0 | 2016-10-18T06:04:02Z | [
"python",
"python-2.7"
] |
Variables in import statement python | 40,100,419 | <p>I'm trying to convert a script I had from bash to python. The way the program worked is that it had a Master script in the top folder and then in the subfolder Scripts a series of smaller, more specialised scripts. These smaller scripts might have names such as foo_bar.x, bar_foo.x, foo_baz.x, foo_qux.x, bar_qux.x, ... | 1 | 2016-10-18T05:44:49Z | 40,100,746 | <p>You can use the <code>importlib</code> library. And use like this:</p>
<pre><code>...
import importlib
...
function_call = 'Modules.' + var1 + dict['var2']
function_call = importlib.import_module(function_call)
function_call.test()
</code></pre>
| 3 | 2016-10-18T06:08:21Z | [
"python",
"python-2.7"
] |
Variables in import statement python | 40,100,419 | <p>I'm trying to convert a script I had from bash to python. The way the program worked is that it had a Master script in the top folder and then in the subfolder Scripts a series of smaller, more specialised scripts. These smaller scripts might have names such as foo_bar.x, bar_foo.x, foo_baz.x, foo_qux.x, bar_qux.x, ... | 1 | 2016-10-18T05:44:49Z | 40,100,853 | <p>How about executing your import statement dynamically? </p>
<p>Dummy example :</p>
<pre><code>d = {"a" : "path"}
exec("import os.%s"%d["a"])
print os.path.abspath(__file__)
</code></pre>
| 0 | 2016-10-18T06:16:11Z | [
"python",
"python-2.7"
] |
Shortest Path Algorithm: Label correcting algorithm | 40,100,518 | <p>I am trying to make a program for the shortest path algorithm.</p>
<p>What I have done,
I am reading a excel file in python add creating a dictionary look like this:</p>
<pre><code>{1: {2: 6, 3: 4}, 2: {1: 6, 6: 5}, 3: {1: 4, 4: 4, 12: 4}, 4: {11: 6, 3: 4, 5: 2}, 5: {9: 5, 4: 2, 6: 4}, 6: {8: 2, 2: 5, 5: 4}, 7: {... | 1 | 2016-10-18T05:52:38Z | 40,100,905 | <p>You need to change your for loop to something like this:</p>
<pre><code>while SEL:
a = SEL.pop(0) # removes the first element in SEL and assigns it to a
print(a)
print(SEL)
for b, c in graph[a].items():
print('checking' + str(b))
if (label[b] > label[a] + c):
label[b]... | 0 | 2016-10-18T06:19:38Z | [
"python",
"networking",
"shortest-path"
] |
u'å§'.encode('gb2312') throws UnicodeEncodeError | 40,100,596 | <p>Firefox can display <code>'å§'</code> in gb2312 encoded HTML. But <code>u'å§'.encode('gb2312')</code> throws <code>UnicodeEncodeError</code>.</p>
<p>1.Is there a map, so firefox can lookup gb2312 encoded characters in that map, find 01 display matrix and display <code>å§</code>.</p>
<p>2.Is there a map for tran... | 0 | 2016-10-18T05:58:06Z | 40,100,834 | <p>å§ not in gb2312, use gb18030 instead. I guess firefox may extends encode method when she face unknown characters.</p>
| 1 | 2016-10-18T06:14:45Z | [
"python",
"unicode",
"encode",
"gb2312"
] |
Unable to visualize graph in tensorboard | 40,100,608 | <p>While writing the summary, </p>
<pre><code>summary_writer1 = tf.train.SummaryWriter(logs_path, graph=tf.get_default_graph())
</code></pre>
<p>works fine and produces graph on tensorboard but doing </p>
<pre><code>summary_writer2 = tf.train.SummaryWriter(logs_path, sess.graph())
</code></pre>
<p>produces the foll... | 0 | 2016-10-18T05:59:12Z | 40,102,633 | <p>There's no difference between the default graph and the <code>sess.graph</code>, they're the same exact graph.</p>
<p>The error is clear: </p>
<blockquote>
<p>'Graph' object is not callable</p>
</blockquote>
<p>The session object has a <code>graph</code> <strong>member</strong>, not a graph <strong>method</stro... | 0 | 2016-10-18T07:56:36Z | [
"python",
"machine-learning",
"tensorflow",
"tensorboard"
] |
TypeError: must be string without null bytes, not str in os.system() | 40,100,623 | <p>I am trying to write a python code which executes a C executable using the following line </p>
<pre><code>os.system("./a.out \"%s\"" % payload)
</code></pre>
<p>where ./a.out is a C executable, and payload is a string (without spaces) given as command line argument. (The link is <a href="http://codearcana.com/post... | 0 | 2016-10-18T06:00:32Z | 40,100,691 | <p>Put an <code>r</code> in the <code>os.system</code> call. </p>
<pre><code>os.system(r"./a.out \"%s\"" % p)
</code></pre>
| 0 | 2016-10-18T06:04:52Z | [
"python",
"string"
] |
TypeError: must be string without null bytes, not str in os.system() | 40,100,623 | <p>I am trying to write a python code which executes a C executable using the following line </p>
<pre><code>os.system("./a.out \"%s\"" % payload)
</code></pre>
<p>where ./a.out is a C executable, and payload is a string (without spaces) given as command line argument. (The link is <a href="http://codearcana.com/post... | 0 | 2016-10-18T06:00:32Z | 40,100,804 | <p>Why don't you use call for this purpose. I guess it will do the work
You can provide the arguments in the list
Example:</p>
<pre><code>from subprocess import call
call(["./a.out","10","10","string without spaces which I need as payload"])
</code></pre>
<p>here in your case it is equivalent to </p>
<pre><code>call... | 0 | 2016-10-18T06:12:31Z | [
"python",
"string"
] |
RuntimeError: maximum recursion depth exceeded while calling a Python object while using split() function in odoo | 40,100,626 | <p><strong>RuntimeError: maximum recursion depth exceeded while calling a Python object</strong>
I got this Error when I use split function of python for Selection field or Many2one field in odoo 9.</p>
<p>I want to to split string and concate with other string but first I've to split it other one. but it showing ab... | 0 | 2016-10-18T06:00:47Z | 40,100,734 | <p>You can increase the recursion depth with</p>
<pre><code>import sys
sys.setrecursionlimit($) # replace $ with any number greater than 1000
</code></pre>
<p>`</p>
| 0 | 2016-10-18T06:07:37Z | [
"python",
"xml",
"odoo-9"
] |
Finding if a QPolygon contains a QPoint - Not giving expected results | 40,100,733 | <p>I am working on a program in PyQt and creating a widget that displays a grid and a set of polygons on that grid that you are able to move around and click on. When I try to implement the clicking of the polygon, it does not seem to work. Below is the function that does not work: </p>
<pre><code>def mouseMoveCustom(... | 3 | 2016-10-18T06:07:33Z | 40,101,012 | <p>The reason this is not working is because bool <code>QPolygon.contains( QPoint )</code> returns true if the point is one of the vertices of the polygon, or if the point falls on the edges of the polygon. Some examples of points that would return true with your setup would be <code>QPoint(0,0)</code>, <code>QPoint(0,... | 3 | 2016-10-18T06:27:29Z | [
"python",
"pyqt",
"qpolygon"
] |
More pythonic way of updating an existing value in a dictionary | 40,100,856 | <p>Lets assume I got a dictionary <code>_dict</code> and a variable <code>n</code>.</p>
<pre><code>_dict = {'a': 9, 'b': 7, 'c': 'someValue'}
n = 8
</code></pre>
<p>I want to update just a single entry e.g. <code>{'b': 7}</code> only if the value of <code>n</code> is greater than the actual value of <code>b</code>.
T... | 2 | 2016-10-18T06:16:31Z | 40,100,868 | <p>Its as simple as that</p>
<pre><code>if n > _dict['b']:
_dict['b'] = n
</code></pre>
| 0 | 2016-10-18T06:17:37Z | [
"python",
"dictionary"
] |
More pythonic way of updating an existing value in a dictionary | 40,100,856 | <p>Lets assume I got a dictionary <code>_dict</code> and a variable <code>n</code>.</p>
<pre><code>_dict = {'a': 9, 'b': 7, 'c': 'someValue'}
n = 8
</code></pre>
<p>I want to update just a single entry e.g. <code>{'b': 7}</code> only if the value of <code>n</code> is greater than the actual value of <code>b</code>.
T... | 2 | 2016-10-18T06:16:31Z | 40,100,896 | <pre><code>if n > _dict['b']:
_dict['b'] = n
</code></pre>
| 1 | 2016-10-18T06:19:08Z | [
"python",
"dictionary"
] |
More pythonic way of updating an existing value in a dictionary | 40,100,856 | <p>Lets assume I got a dictionary <code>_dict</code> and a variable <code>n</code>.</p>
<pre><code>_dict = {'a': 9, 'b': 7, 'c': 'someValue'}
n = 8
</code></pre>
<p>I want to update just a single entry e.g. <code>{'b': 7}</code> only if the value of <code>n</code> is greater than the actual value of <code>b</code>.
T... | 2 | 2016-10-18T06:16:31Z | 40,100,901 | <p>There is no point in looping if you just need to update one key:</p>
<pre><code>_dict['b'] = max(_dict['b'], n)
</code></pre>
<p>The above sets <code>'b'</code> to the highest value of the two.</p>
| 12 | 2016-10-18T06:19:33Z | [
"python",
"dictionary"
] |
Search and Replace in a Text File In Flask | 40,101,016 | <p>I want to search and replace in a text file in flask. </p>
<pre><code>@app.route('/links', methods=['POST'])
def get_links():
search_line= "blah blah"
try:
for line in fileinput.input(os.path.join(APP_STATIC, u'links.txt')):
x = line.replace(search_line,
search_lin... | -1 | 2016-10-18T06:28:02Z | 40,101,274 | <p>Your code will always delete all lines since you are not writing lines back to files in both case i.e when search_line is present and when search_line is not present.</p>
<p><strong>Please check the below code with comments inline.</strong></p>
<pre><code>@app.route('/links', methods=['POST'])
def get_links():
... | 1 | 2016-10-18T06:44:06Z | [
"python",
"flask"
] |
Model development choice | 40,101,049 | <p>Lets say, that I'm want to develop a game (RTS-like, with economy orientation) in which player, as well as AI, can posses almost every in-game object. For example: player posses a land and some buildings on it; other players, or AI can also have some buildings, or else, on this land piece; also, someone can posses a... | 1 | 2016-10-18T06:29:41Z | 40,101,170 | <p>The questions you should ask are the following:</p>
<ol>
<li><strong>Can</strong> A be linked to at most 1 or many (more than 1) B?</li>
<li><strong>Can</strong> B be linked to at most 1 or many A?</li>
</ol>
<p>If A can be linked to many B and B can be linked to many A, you need a many-to-many link.</p>
<p>If A ... | 1 | 2016-10-18T06:37:47Z | [
"python",
"django-models"
] |
uploading an image file to aws s3 using python | 40,101,085 | <pre><code>import tinys3
conn =tinys3.Connection(aws_key_id,aws_secrert_key)
f = open('c:/Users/Akhil/Downloads/New/img033.jpg','rb')
conn.upload('c:/Users/Akhil/Downloads/New/img033.jpg',f,'matt3r')
</code></pre>
<p>I am trying to upload an image present in local directory shown below to aws s3 matt3r bucket. wh... | 0 | 2016-10-18T06:31:32Z | 40,101,881 | <p>You need to add policy for AWS S3 to your IAM user. </p>
| 0 | 2016-10-18T07:17:04Z | [
"python",
"amazon-web-services",
"amazon-s3"
] |
Deploying Python Flask App on Apache with Python version installed in Virtual Environment Only | 40,101,094 | <p>I am working on a CentOS7 development environment. The machine came with Python 2.7.5 pre-installed. I have developed a web application using Python 3.5.1 which along with it's dependencies was installed in the virtual environment only. Python 3 is not installed machine-wide. I am now trying to deploy the applicatio... | 0 | 2016-10-18T06:32:17Z | 40,106,680 | <p>Check out the Software Collections Library (SCL) at <a href="https://www.softwarecollections.org" rel="nofollow">https://www.softwarecollections.org</a> for CentOS/RHEL, don't use any default system Python, Apache or mod_wsgi packages. The SCL provides newer versions of Python and Apache than the default system vers... | 0 | 2016-10-18T11:11:49Z | [
"python",
"apache",
"flask",
"mod-wsgi",
"python-3.5"
] |
how do I calculate a rolling idxmax | 40,101,130 | <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
s = pd.Series(np.random.randint(0, 10, 10), list('abcdefghij'))
s
a 0
b 2
c 7
d 3
e 8
f 7
g 0
h 6
i 8
j 6
dtype: int64
</code></pre>
<p>I want to get the... | 4 | 2016-10-18T06:35:34Z | 40,101,614 | <p>There is no simple way to do that, because the argument that is passed to the rolling-applied function is a plain numpy array, not a pandas Series, so it doesn't know about the index. Moreover, the rolling functions must return a float result, so they can't directly return the index values if they're not floats.</p... | 6 | 2016-10-18T07:02:08Z | [
"python",
"pandas",
"numpy",
"dataframe",
"series"
] |
how do I calculate a rolling idxmax | 40,101,130 | <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
s = pd.Series(np.random.randint(0, 10, 10), list('abcdefghij'))
s
a 0
b 2
c 7
d 3
e 8
f 7
g 0
h 6
i 8
j 6
dtype: int64
</code></pre>
<p>I want to get the... | 4 | 2016-10-18T06:35:34Z | 40,102,656 | <p>Here's an approach using <a href="https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html" rel="nofollow"><code>broadcasting</code></a> -</p>
<pre><code>maxidx = (s.values[np.arange(s.size-3+1)[:,None] + np.arange(3)]).argmax(1)
out = s.index[maxidx+np.arange(maxidx.size)]
</code></pre>
<p>This generates al... | 2 | 2016-10-18T07:58:03Z | [
"python",
"pandas",
"numpy",
"dataframe",
"series"
] |
how do I calculate a rolling idxmax | 40,101,130 | <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
s = pd.Series(np.random.randint(0, 10, 10), list('abcdefghij'))
s
a 0
b 2
c 7
d 3
e 8
f 7
g 0
h 6
i 8
j 6
dtype: int64
</code></pre>
<p>I want to get the... | 4 | 2016-10-18T06:35:34Z | 40,103,020 | <p>I used a generator</p>
<pre><code>def idxmax(s, w):
i = 0
while i + w <= len(s):
yield(s.iloc[i:i+w].idxmax())
i += 1
pd.Series(idxmax(s, 3), s.index[2:])
c c
d c
e e
f e
g e
h f
i i
j i
dtype: object
</code></pre>
| 3 | 2016-10-18T08:16:52Z | [
"python",
"pandas",
"numpy",
"dataframe",
"series"
] |
how do I calculate a rolling idxmax | 40,101,130 | <p>consider the <code>pd.Series</code> <code>s</code></p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed([3,1415])
s = pd.Series(np.random.randint(0, 10, 10), list('abcdefghij'))
s
a 0
b 2
c 7
d 3
e 8
f 7
g 0
h 6
i 8
j 6
dtype: int64
</code></pre>
<p>I want to get the... | 4 | 2016-10-18T06:35:34Z | 40,107,590 | <p>You can also simulate the rolling window by creating a <code>DataFrame</code> and use <code>idxmax</code> as follows: </p>
<pre><code>window_values = pd.DataFrame({0: s, 1: s.shift(), 2: s.shift(2)})
s.index[np.arange(len(s)) - window_values.idxmax(1)]
Index(['a', 'b', 'c', 'c', 'e', 'e', 'e', 'f', 'i', 'i'], dtyp... | 1 | 2016-10-18T11:55:06Z | [
"python",
"pandas",
"numpy",
"dataframe",
"series"
] |
Python - change all specific values in a dictionary | 40,101,329 | <p>I have some problem with constructing a phonebook, I have a function that adds names and number, a function that makes an alias for the person (two numbers have two diffrent names). And a change function which im having problems with. I want the function to change the number for one person and all its aliases. My co... | 0 | 2016-10-18T06:46:51Z | 40,101,613 | <p>If I understood you correctly you need to replace old number for some name, then add the new number as an alias, set it to the name and then remove the old number as alias:</p>
<pre><code>def change(self,namn,nummer):
old_number = ''
if namn in self.pb:
for godtyckligt in self.pb:
if se... | 0 | 2016-10-18T07:02:08Z | [
"python",
"dictionary",
"value"
] |
How to replace each array element by 4 copies in Python? | 40,101,371 | <p>How do I use numpy / python array routines to do this ?</p>
<p>E.g. If I have array <code>[ [1,2,3,4,]]</code> , the output should be </p>
<pre><code>[[1,1,2,2,],
[1,1,2,2,],
[3,3,4,4,],
[3,3,4,4]]
</code></pre>
<p>Thus, the output is array of double the row and column dimensions. And each element from origina... | 5 | 2016-10-18T06:49:08Z | 40,101,592 | <p>Use <code>np.repeat()</code>:</p>
<pre><code>In [9]: A = np.array([[1, 2, 3, 4]])
In [10]: np.repeat(np.repeat(A, 2).reshape(2, 4), 2, 0)
Out[10]:
array([[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4]])
</code></pre>
<p><strong><em>Explanation:</em></strong> </p>
<p>First off you can... | 3 | 2016-10-18T07:00:57Z | [
"python",
"arrays",
"numpy"
] |
How to replace each array element by 4 copies in Python? | 40,101,371 | <p>How do I use numpy / python array routines to do this ?</p>
<p>E.g. If I have array <code>[ [1,2,3,4,]]</code> , the output should be </p>
<pre><code>[[1,1,2,2,],
[1,1,2,2,],
[3,3,4,4,],
[3,3,4,4]]
</code></pre>
<p>Thus, the output is array of double the row and column dimensions. And each element from origina... | 5 | 2016-10-18T06:49:08Z | 40,102,380 | <p>Another approach could be with <a href="https://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.kron.html" rel="nofollow"><code>np.kron</code></a> -</p>
<pre><code>np.kron(a.reshape(-1,2),np.ones((2,2),dtype=int))
</code></pre>
<p>Basically, we reshape input array into a <code>2D</code> array keeping the... | 1 | 2016-10-18T07:42:20Z | [
"python",
"arrays",
"numpy"
] |
How to replace each array element by 4 copies in Python? | 40,101,371 | <p>How do I use numpy / python array routines to do this ?</p>
<p>E.g. If I have array <code>[ [1,2,3,4,]]</code> , the output should be </p>
<pre><code>[[1,1,2,2,],
[1,1,2,2,],
[3,3,4,4,],
[3,3,4,4]]
</code></pre>
<p>Thus, the output is array of double the row and column dimensions. And each element from origina... | 5 | 2016-10-18T06:49:08Z | 40,111,415 | <p>The better solution is to use numpy but you could use iteration also:</p>
<pre class="lang-python prettyprint-override"><code>a = [[1, 2, 3, 4]]
v = iter(a[0])
b = []
for i in v:
n = next(v)
[b.append([i for k in range(2)] + [n for k in range(2)]) for j in range(2)]
print b
>>> [[1, 1, 2, 2], [... | 0 | 2016-10-18T14:47:47Z | [
"python",
"arrays",
"numpy"
] |
Test setup and teardown for each testcase in a test suite in robot frame work using python | 40,101,372 | <p>Hi I'm new to robot frame-work. Can someone help me to find if it's possible to have to a test setup and a teardown for each test case in test suite containing around 20 testcases. </p>
<p>Can someone explain this with a example?</p>
| -1 | 2016-10-18T06:49:12Z | 40,131,075 | <p>Here's an example. A testsuite containing teardown. You can miss the teardown from each testcase if you want to execute it at last.
Please read the corresponding documentation: </p>
<p><a href="http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-setup-and-teardown" rel="nofollow">http... | 0 | 2016-10-19T12:11:38Z | [
"python",
"robotframework"
] |
Python error with flattening list of lists | 40,101,544 | <p>Hi I'm trying to flatten the following list of lists but I always get the following error:</p>
<p>'int' object is not iterable </p>
<p>I also tried chain from itertools but still not working. I guess the solution is easy but I really cannot see it! Anybody can help?</p>
<p>Thanks</p>
<pre><code> from itertools i... | 0 | 2016-10-18T06:58:03Z | 40,101,694 | <p>Is this what you need?</p>
<pre><code>lista = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]
listb = []
for sub in lista:
listb.extend(sub) # Modification suggested by @Dinesh Pundkar
print(listb)
print(sum(listb))
</code></pre>
| 0 | 2016-10-18T07:06:21Z | [
"python",
"list",
"flatten"
] |
Python combinations with list and items in other lists | 40,101,598 | <p>I try the code below, is there a efficent way to do this?</p>
<pre><code>c = []
l = [['A1','A2'], ['B1','B2'], ['C1','C2'] ]
for i in range(0, len(l) - 1):
for j in range(i+1, len(l)):
c.append(sorted([l[i][0],l[i][1],l[j][0]]))
c.append(sorted([l[i][0],l[i][1],l[j][1]]))
c.append(sor... | 0 | 2016-10-18T07:01:18Z | 40,102,111 | <p>Try this:</p>
<pre><code># group every 2 lists in list l
ll = list(itertools.combinations(l, 2))
# generate all combinations of 3 elements out from each 2 lists
c = [list(itertools.combinations(a + b, 3)) for (a, b) in ll]
# concate all elements
c = sum(c, [])
</code></pre>
| 1 | 2016-10-18T07:29:29Z | [
"python"
] |
Python combinations with list and items in other lists | 40,101,598 | <p>I try the code below, is there a efficent way to do this?</p>
<pre><code>c = []
l = [['A1','A2'], ['B1','B2'], ['C1','C2'] ]
for i in range(0, len(l) - 1):
for j in range(i+1, len(l)):
c.append(sorted([l[i][0],l[i][1],l[j][0]]))
c.append(sorted([l[i][0],l[i][1],l[j][1]]))
c.append(sor... | 0 | 2016-10-18T07:01:18Z | 40,102,341 | <p>Or in one line</p>
<pre><code>from itertools import product
c = [[k] + i for i, j in product(l, l) if j!=i for k in j]
</code></pre>
| 0 | 2016-10-18T07:40:45Z | [
"python"
] |
Python (win10): python35.dll and VCRUNTIME140.dll missing | 40,101,662 | <p>I have installed <code>WinPython-64bit-3.5.2.2Qt5</code>
I try to access Python from the command line. It accesses the <code>symlink</code> </p>
<pre><code>C:\Users\usr>where python
C:\Windows\System32\python.exe
</code></pre>
<p>when I execute</p>
<pre><code>C:\Users\usr>python
</code></pre>
<p>I got the... | -1 | 2016-10-18T07:04:50Z | 40,102,133 | <p>Add the path to Environment variable , This may help you : <a href="https://www.youtube.com/watch?v=q5MchIy7r1o" rel="nofollow">https://www.youtube.com/watch?v=q5MchIy7r1o</a> </p>
<p>This is download linkt to fix VCRUNTIME140.dll missing error: <a href="http://download.microsoft.com/download/0/4/1/041224F6-A7DC-48... | 0 | 2016-10-18T07:30:30Z | [
"python",
"dll",
"command-line"
] |
Python (win10): python35.dll and VCRUNTIME140.dll missing | 40,101,662 | <p>I have installed <code>WinPython-64bit-3.5.2.2Qt5</code>
I try to access Python from the command line. It accesses the <code>symlink</code> </p>
<pre><code>C:\Users\usr>where python
C:\Windows\System32\python.exe
</code></pre>
<p>when I execute</p>
<pre><code>C:\Users\usr>python
</code></pre>
<p>I got the... | -1 | 2016-10-18T07:04:50Z | 40,137,184 | <p>Thanks for your help</p>
<p>I discovered that executing
C:\Windows\System32\python.exe
just doesn't work</p>
<p>so I just erased python.exe symlink in the system32 folder
and added
C:\Users\usr\Documents\MyExes\WinPython-64bit-3.5.2.2Qt5\python-3.5.2.amd64\
to PATH</p>
<p>and it works</p>
<p>Thank you again !!... | 0 | 2016-10-19T16:43:30Z | [
"python",
"dll",
"command-line"
] |
How to create random default value in ndb model in GAE? | 40,101,698 | <p>I have a ndb model</p>
<pre><code>import os
class ProblemInvite(ndb.Model):
email = nab.StringProperty(required=True)
token = ndb.StringProperty(required=True, default=os.urandom(16).encode('hex'))
</code></pre>
<p>When I create a list of the model, the token is same:</p>
<pre><code>import logging
for ema... | 1 | 2016-10-18T07:06:32Z | 40,107,371 | <p>There can only be <strong>one</strong> default value for a property type in the datastore at a time. From the <a href="https://cloud.google.com/appengine/docs/python/ndb/entity-property-reference#options" rel="nofollow">Property Options</a> table:</p>
<p><a href="https://i.stack.imgur.com/k2kBU.png" rel="nofollow">... | 2 | 2016-10-18T11:45:30Z | [
"python",
"google-app-engine",
"app-engine-ndb",
"python-os"
] |
how to analyze the value of tfidf matrix in sklearn? | 40,101,873 | <p>I am using sklearn KMeans algorithm for document clustering as guided in
<a href="http://brandonrose.org/clustering" rel="nofollow">http://brandonrose.org/clustering</a></p>
<p>Here There is a calculation of TFIDF matrix. I have understood the concept behind the TFIDF technique.
But, when I printed this Matrix in ... | 3 | 2016-10-18T07:16:15Z | 40,105,858 | <p>The first column contains the tuples <code>(ind_document, ind_word)</code> where <code>ind_document</code> is the index of your document (in your case a <code>string</code>) contained in your data set, and <code>ind_word</code> the index of the word in the dictionary of words generated by the <code>TfidfVectorizer</... | 0 | 2016-10-18T10:31:51Z | [
"python",
"scikit-learn",
"nltk",
"k-means",
"tf-idf"
] |
How to match rows based on certain columns in pandas? | 40,101,925 | <p>I have a dataframe like this:</p>
<pre><code>id date event name time
1 2016-10-01 A leader 12:45
2 2016-10-01 A AA 12:87
3 2016-10-01 A BB 12:45
</code></pre>
<p>There are rows for each member in the event, but one row has the leader da... | 2 | 2016-10-18T07:19:08Z | 40,102,325 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> with custom function <code>f</code> which return new column <code>is_leader</code> with <code>True</code> for all rows where is same <code>time</code> as <code>time</code>... | 3 | 2016-10-18T07:40:11Z | [
"python",
"pandas",
"feature-extraction"
] |
Performance issues in simulation with python lists | 40,102,141 | <p>I'm currently writing a simulation in python 3.4 (miniconda).
The entire simulation is quite fast but the measurement of some simulation data is bloody slow and takes about 35% of the entire simulation time. I hope I can increase the performance of the entire simulation if I could get rid of that bottleneck. I spend... | 0 | 2016-10-18T07:30:46Z | 40,107,660 | <p>The code looks basic enough that there aren't any obvious gaps for optimisation without substantial restructuring (which I don't know enough about your overall architecture to suggest).</p>
<p>Try installing <a href="http://cython.org/" rel="nofollow"><code>cython</code></a> - I believe nowadays you can install it ... | 0 | 2016-10-18T11:58:24Z | [
"python",
"performance",
"list",
"python-3.x",
"simulation"
] |
Performance issues in simulation with python lists | 40,102,141 | <p>I'm currently writing a simulation in python 3.4 (miniconda).
The entire simulation is quite fast but the measurement of some simulation data is bloody slow and takes about 35% of the entire simulation time. I hope I can increase the performance of the entire simulation if I could get rid of that bottleneck. I spend... | 0 | 2016-10-18T07:30:46Z | 40,119,476 | <p>As stated in the comments the function is quite simple, and with the provided code I don't see a way to change optimize it directly.</p>
<p>You can try different approaches:</p>
<ol>
<li><a href="http://pypy.org/" rel="nofollow">PyPy</a>, this may works depending on your current codebase and external dependecies.<... | 0 | 2016-10-18T23:07:01Z | [
"python",
"performance",
"list",
"python-3.x",
"simulation"
] |
Interpolate between elements in an array of floats | 40,102,160 | <p>I'm getting a list of 5 floats which I would like to use as values to send pwm to an LED. I want to ramp smoothly in a variable amount of milliseconds between the elements in the array.</p>
<p>So if this is my array...</p>
<pre><code>list = [1.222, 3.111, 0.456, 9.222, 22.333]
</code></pre>
<p>I want to ramp from... | 0 | 2016-10-18T07:32:08Z | 40,102,994 | <p>do you think about something like that?</p>
<pre><code>import time
l = [1.222, 3.111, 0.456, 9.222, 22.333]
def play_led(value):
#here should be the led- code
print value
def calc_ramp(given_list, interval_count):
new_list = []
len_list = len(given_list)
for i in range(len_list):
first... | 0 | 2016-10-18T08:15:32Z | [
"python",
"arrays",
"linear-interpolation"
] |
Interpolate between elements in an array of floats | 40,102,160 | <p>I'm getting a list of 5 floats which I would like to use as values to send pwm to an LED. I want to ramp smoothly in a variable amount of milliseconds between the elements in the array.</p>
<p>So if this is my array...</p>
<pre><code>list = [1.222, 3.111, 0.456, 9.222, 22.333]
</code></pre>
<p>I want to ramp from... | 0 | 2016-10-18T07:32:08Z | 40,103,084 | <p>Like this :</p>
<pre><code>import time
_ramplist = [1.222, 3.111, 0.456, 9.222, 22.333]
def set_pwm(_ramplist,_time,_sensitivy):
for i in range(len(_ramplist)) :
if i + 1 != len(_ramplist) :
init_time = time.time()
_from = _ramplist[i]
_to = _ramplist[i+1]
... | 0 | 2016-10-18T08:19:32Z | [
"python",
"arrays",
"linear-interpolation"
] |
Interpolate between elements in an array of floats | 40,102,160 | <p>I'm getting a list of 5 floats which I would like to use as values to send pwm to an LED. I want to ramp smoothly in a variable amount of milliseconds between the elements in the array.</p>
<p>So if this is my array...</p>
<pre><code>list = [1.222, 3.111, 0.456, 9.222, 22.333]
</code></pre>
<p>I want to ramp from... | 0 | 2016-10-18T07:32:08Z | 40,107,065 | <p>another version, similar to the version of dsgdfg (based on his/her idea), but without timing lag:</p>
<pre><code>import time
list_of_ramp = [1.222, 3.111, 0.456, 9.222, 22.333]
def play_LED(value):
s = ''
for i in range(int(value*4)):
s += '*'
print s, value
def interpol(first, sec... | 0 | 2016-10-18T11:29:52Z | [
"python",
"arrays",
"linear-interpolation"
] |
Howe to get ORDSYS.ORDIMAGE field value in python | 40,102,187 | <p>Using cx_Oracle 5.2.1 with Oracle client library 11.2 and Oracle server 11.2, I am unable to retrieve the content of an <code>ORDSYS.ORDIMAGE</code> field.
The following code raises <code>attribute read not found exception</code>:</p>
<pre><code>import cx_Oracle
db = cx_Oracle.Connection('user/pass@ip/t')
cursor = ... | 0 | 2016-10-18T07:34:03Z | 40,111,607 | <p>The problem is that cx_Oracle.OBJECT does not have a read() method. Instead, it has attributes which you can read/write just like any other Python object.</p>
<p>Using the unreleased version of cx_Oracle the following generic code will work:</p>
<pre><code>def ObjectRepr(obj):
if obj.type.iscollection:
... | 1 | 2016-10-18T14:55:25Z | [
"python",
"oracle",
"cx-oracle"
] |
flask-sqlalchemy group_by with max id | 40,102,193 | <p>I have a table like this
<a href="https://i.stack.imgur.com/6Y6EV.png" rel="nofollow"><img src="https://i.stack.imgur.com/6Y6EV.png" alt="enter image description here"></a></p>
<p>Now I want to get data which ip is uniq and id is max.</p>
<pre><code>In [53]: ModuleInfo.query.group_by(ModuleInfo.ip).all()
Out[53]:
... | 0 | 2016-10-18T07:34:26Z | 40,104,853 | <p>You can try this:</p>
<pre><code>from sqlalchemy import func
foo = Session.query(func.max(ModuleInfo.id),ModuleInfo.ip).\
group_by(ModuleInfo.ip).order_by(ModuleInfo.ip).all()
</code></pre>
<p>I used declarative base and scoped Session to run a test here but the idea is the same. You should receive a list of t... | 0 | 2016-10-18T09:44:46Z | [
"python",
"mysql",
"sqlalchemy"
] |
How to configure YAML to create fresh log files instead of appending them? | 40,102,223 | <p>In a python logger implementation given below, each time I run my program, the logs are <em>appended</em> each time to the existing log files. How do I ensure that each time I run my application code, they are written to the fresh log file? </p>
<p>Is it happening because I have set the RotatingFileHandler with bac... | 0 | 2016-10-18T07:35:58Z | 40,102,353 | <p>Set the <a href="https://docs.python.org/3.5/library/logging.html#logging.basicConfig" rel="nofollow"><code>filemode</code></a> to <code>w</code>, the default is <code>a</code> (append). </p>
<p>Or alternatively just add the following line to overwrite your old log file (after reading the yaml file):</p>
<pre><cod... | 1 | 2016-10-18T07:41:19Z | [
"python",
"pyyaml"
] |
Using a C function in Python | 40,102,274 | <p>I've tried all the solutions mentioned on the internet so far nothing worked for me.</p>
<p>I have a python code, to speed it up, I want that my code runs the heavy calculations in a C function.
I already wrote this C function.</p>
<p>Then, to share the library, I did this in the terminal :</p>
<pre><code>gcc -sh... | 10 | 2016-10-18T07:38:00Z | 40,102,473 | <p>You need to specify <code>restype</code>, <code>argtypes</code> of the function:</p>
<pre><code>zelib = ctypes.CDLL('...')
zelib.multiplier.restype = ctypes.c_float # return type
zelib.multiplier.argtypes = [ctypes.c_float, ctypes.c_float] # argument types
</code></pre>
<p>According to <a href="https://docs.pyt... | 4 | 2016-10-18T07:47:40Z | [
"python",
"c",
"python-3.x",
"ctypes"
] |
Using a C function in Python | 40,102,274 | <p>I've tried all the solutions mentioned on the internet so far nothing worked for me.</p>
<p>I have a python code, to speed it up, I want that my code runs the heavy calculations in a C function.
I already wrote this C function.</p>
<p>Then, to share the library, I did this in the terminal :</p>
<pre><code>gcc -sh... | 10 | 2016-10-18T07:38:00Z | 40,103,282 | <p>While @falsetru's answer is the better way of doing it an alternative is to simply write your C function to use doubles.</p>
<p>Floats are automatically promoted to double when calling a function without a parameter list.</p>
| 1 | 2016-10-18T08:30:52Z | [
"python",
"c",
"python-3.x",
"ctypes"
] |
Python Matplotlib: Clear figure when figure window is not open | 40,102,311 | <p>I'm working with matplotlib plotting and use <code>ioff()</code> to switch interactive mode off to suppress the automatic opening of the plotting window on figrue creation. I want to have full control over the figure and only see it when explicitely using the <code>show()</code> command.</p>
<p>Now apparently the b... | 1 | 2016-10-18T07:39:29Z | 40,103,652 | <p>If you add a call to <code>plt.draw()</code> after <code>P.fig.clear()</code> it clears the figure. From the <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.draw" rel="nofollow">docs</a>,</p>
<blockquote>
<p>This is used in interactive mode to update a figure that has been altered, but not au... | 1 | 2016-10-18T08:49:11Z | [
"python",
"matplotlib",
"plot"
] |
Windows Side-by-side assembly default version (msvcr90.dll) | 40,102,318 | <p>Where is the default version of assemblies stored?</p>
<p>When I run python.exe (2.6 or 2.7) and check it out using Process Explorer, I see that it loads the newest version of msvcr90.dll (9.0.30729.9247 on my PC). Python has an internal manifest that specifies version 9.0.21022.8 of msvcr90.dll, but the newer vers... | 0 | 2016-10-18T07:39:45Z | 40,133,807 | <p>The default Windows side-by-side assembly version is specified in the registry</p>
<p>For microsoft.vc90.crt the version is specified at:</p>
<pre><code> HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\SideBySide\Winners\x86_policy.9.0.microsoft.vc90.crt_
</code></pre>
<p>Change the default versio... | 0 | 2016-10-19T14:10:17Z | [
"python",
"windows",
"visual-studio",
"dll",
"winsxs"
] |
Selenium FireFox Driver stops responding after pop-up disappears | 40,102,383 | <p>I would appreciate some thoughts on a problem at hand that I've been trying to solve for 1-2 days.</p>
<p>I am running a Python script with Selenium 2.53.6 on FireFox 49.0.1. The script is supposed to click a series of document-download links on a page (I have set the browser to automatically download these file t... | 0 | 2016-10-18T07:42:26Z | 40,102,796 | <p>You need to keep on waiting until the pop-up disappears. One way you might do this is making below changes in your code: </p>
<pre><code>file_link = tr.find_element_by_xpath('td[5]/a')
file_link.click()
time.sleep(7) # Allows the blank pop-up to disappear automatically under Event2
agree_button = None
# Checks f... | 0 | 2016-10-18T08:04:39Z | [
"python",
"selenium",
"selenium-firefoxdriver"
] |
I have a list of IDs, each of which is again associated with several IDS and some values. How to code in python to save this data? | 40,102,572 | <p>I am reading in data of the following type from a file, and I need a method to store it for further calculations.</p>
<p>ID1 , ID2 , value</p>
<p>A , 1 , 520</p>
<p>A , 2 , 180</p>
<p>A , 3 , 80</p>
<p>B , 1 ,... | 1 | 2016-10-18T07:52:39Z | 40,106,374 | <p>If you've loaded your data with Python, and your next program down the line is also written in Python, you can simply use the <code>pickle</code> module, like this:</p>
<pre><code>big_list_list = [["A", 1, 520], ["A", 2, 180], ["B", 1, 49]]
import pickle
# Storing the data
with open("data.pickle", "wb") as outfil... | 0 | 2016-10-18T10:57:19Z | [
"python"
] |
Remove the parentheses around the very first element in an expression tree and in each of its sub-expression trees in Python | 40,102,595 | <p>The goal is to implement a simplification operation: remove the parentheses around the very first element in an expression tree and in each of its sub-expression trees, where the expression is given as a string input enclosed in various parentheses. This must work for an arbitrary number of parentheses, so for examp... | 2 | 2016-10-18T07:53:58Z | 40,103,695 | <p>I would be providing a general idea as to how to go about solving the problem and then you can implement it in any language easily( <em>especially python</em> ).</p>
<p>Just traverse the given string (<em>say</em> <code>str</code> ).</p>
<p>Keep a stack <code>leftstk</code> of integers and whenever you encounter a... | 0 | 2016-10-18T08:51:40Z | [
"python",
"algorithm",
"tree",
"expression"
] |
Remove the parentheses around the very first element in an expression tree and in each of its sub-expression trees in Python | 40,102,595 | <p>The goal is to implement a simplification operation: remove the parentheses around the very first element in an expression tree and in each of its sub-expression trees, where the expression is given as a string input enclosed in various parentheses. This must work for an arbitrary number of parentheses, so for examp... | 2 | 2016-10-18T07:53:58Z | 40,142,863 | <p>This can be viewed as a finite state machine (with three states) which you instantiate once per level, where each <code>(</code> symbol creates a new level. Alternatively, it is a deterministic <a href="https://en.wikipedia.org/wiki/Pushdown_automaton" rel="nofollow">pushdown automaton</a> with two trivial states (a... | 0 | 2016-10-19T23:01:30Z | [
"python",
"algorithm",
"tree",
"expression"
] |
Python: Dynamically import modules and objects | 40,102,605 | <p>I want import dynamically some class through variable like:</p>
<pre><code>classes = ['AaaBc', 'AccsAs', 'Asswwqq']
for class in classes:
from file.models import class
</code></pre>
<p>How can I do it ?</p>
| 0 | 2016-10-18T07:55:00Z | 40,102,668 | <p>use <code>__import__</code></p>
<pre><code>spam = __import__('spam', globals(), locals(), [], 0)
</code></pre>
<p>The statement import spam.ham results in this call:</p>
<pre><code>spam = __import__('spam.ham', globals(), locals(), [], 0)
</code></pre>
<p>Note how <strong>import</strong>() returns the toplevel m... | 1 | 2016-10-18T07:58:24Z | [
"python",
"python-import"
] |
Percentage format in elements of python graph | 40,102,711 | <p>Im executing the below code and I would like the numbers in the second graph to be percentage format with a two digit precision (0.3333 --> 33.33%). I have tried a ton of different version where I use '{percent, .2%}'.format() in lambda functions on the arrays, etc, but I dont get it all the way. All input is appric... | 0 | 2016-10-18T08:00:06Z | 40,103,504 | <p>There are (at least) two problems in your code: </p>
<ul>
<li><p>What is <code>iris_x</code> in <code>line 14</code>? I think you meant <code>x[:, :2]</code> instead of <code>iris_x[:, :2]</code></p></li>
<li><p><code>conf_mat_prc</code> should be defined as <code>conf_mat_prc = conf_mat/float(len(y))</code> instea... | 0 | 2016-10-18T08:41:56Z | [
"python",
"numpy"
] |
Prevent initializing model form when creating | 40,102,757 | <p>In a Django form, I encountered a strange python behavior. I have a model form which I want to populate with some existing data. Because one field is meant to be a comma separated list of an m2m field I have to initialize it separately.</p>
<pre><code>class SomeModel(models.Model):
confirming_stuff = models.Man... | 0 | 2016-10-18T08:02:19Z | 40,103,081 | <p>You will always have an <code>instance</code> object, just check if its saved.</p>
<pre><code>if self.instance.id:
#do stuff
</code></pre>
<p>Thanks.</p>
| 3 | 2016-10-18T08:19:29Z | [
"python",
"django",
"initialization",
"modelform"
] |
subprocess.call with sed pass variable | 40,102,766 | <p>I am trying to run Python script with <code>subprocess.call</code> to add a line after matching pattern. Here's the ways :</p>
<p><code>addline1</code> is variable and has the value say <code>"hello world1"</code></p>
<p><code>filename1</code> is the variable containing path and file name for example <code>"/tmp/p... | 1 | 2016-10-18T08:02:52Z | 40,122,084 | <p>Correcting the <code>sed</code> issue:</p>
<pre><code>sed_cmd = '/ReWriteEngine On/a' + addline1
subprocess.call(['sed', '-i', sed_cmd, filename1])
</code></pre>
<p><strong>Note:</strong> Use <code>/^ReWriteEngine On/a</code> if the string has to match at start of line</p>
<p><br>
With <code>fileinput</code>:</p>... | 0 | 2016-10-19T04:22:19Z | [
"python",
"sed",
"subprocess"
] |
Python: Applying function to list of tems | 40,102,772 | <p>I have following code snippet that helps me to get Google Trends data (see <a href="https://github.com/GeneralMills/pytrends" rel="nofollow">https://github.com/GeneralMills/pytrends</a>):</p>
<pre><code>trend_payload = {'q': 'Dogs, Cats, Catfood, Dogfood','date': '01/2015 12m'}
trend = pytrend.trend(trend_payload)
... | 0 | 2016-10-18T08:03:11Z | 40,102,936 | <p>You can work on this: </p>
<pre><code>queries = ['Cats', 'Dogs', 'Catfood','Dogfood']
def function(queries):
trend_payload = {'q': queries, 'date': '01/2015 12m'}
trend = pytrend.trend(trend_payload)
df = pytrend.trend(trend_payload, return_type='dataframe')
return df
list_of_df = [function([quer... | 1 | 2016-10-18T08:12:04Z | [
"python",
"function",
"pandas",
"dataframe"
] |
Python: Applying function to list of tems | 40,102,772 | <p>I have following code snippet that helps me to get Google Trends data (see <a href="https://github.com/GeneralMills/pytrends" rel="nofollow">https://github.com/GeneralMills/pytrends</a>):</p>
<pre><code>trend_payload = {'q': 'Dogs, Cats, Catfood, Dogfood','date': '01/2015 12m'}
trend = pytrend.trend(trend_payload)
... | 0 | 2016-10-18T08:03:11Z | 40,103,379 | <p>I would simply concatenate DFs as <a href="http://stackoverflow.com/questions/40102772/python-applying-function-to-list-of-tems#comment67478072_40102772">jimifiki has already proposed</a>:</p>
<pre><code>df = pd.concat([pytrend.trend({'q': x, 'date': '01/2015 12m'},
return_type='datafr... | 1 | 2016-10-18T08:35:37Z | [
"python",
"function",
"pandas",
"dataframe"
] |
How not to stop the execution of other function in python in case of Exception/Error | 40,102,786 | <p>I have a script in python which works as shown below. Each function performs a completely different task and not related to each other. My problem is if <strong>function2()</strong> is having an issue during the execution process then <strong>function3()</strong>, <strong>function4()</strong>, <strong>function5()</s... | 2 | 2016-10-18T08:04:12Z | 40,102,885 | <p>No need to write multiple <code>try/except</code>. Create a list of your function and execute them. For example, you code should be like:</p>
<pre><code>if __name__ == '__main__':
func_list = [function1, function2, function3, function4, function5]
for my_func in func_list:
try:
my_func(... | 5 | 2016-10-18T08:09:28Z | [
"python",
"python-2.7"
] |
How not to stop the execution of other function in python in case of Exception/Error | 40,102,786 | <p>I have a script in python which works as shown below. Each function performs a completely different task and not related to each other. My problem is if <strong>function2()</strong> is having an issue during the execution process then <strong>function3()</strong>, <strong>function4()</strong>, <strong>function5()</s... | 2 | 2016-10-18T08:04:12Z | 40,102,887 | <p>You can use exception and catch all sort of exceptions like this</p>
<pre><code>if __name__ == '__main__':
try:
function1()
except:
pass
try:
function2()
except:
pass
try:
function3()
except:
pass
try:
function4()
except... | 1 | 2016-10-18T08:09:29Z | [
"python",
"python-2.7"
] |
Pycharm warns "Local variable <variable> value is not used" in "if" block though it actually used | 40,102,854 | <p>Pycharm 2016.2 warns me that "Local variable 'message' value is not used" in <code>if</code> block.</p>
<p>Why this?</p>
<pre><code>def build_message(result, action, data, time_stamp, error_message=None, path=None, line=None):
"""
Result message format:
Success message format: {'result', 'action', 'tar... | 0 | 2016-10-18T08:08:08Z | 40,102,942 | <p>Your <code>try</code> clause is under <code>else</code> branch so <code>message</code> variable under <code>if</code> branch is never being used.</p>
<p>What you wanted to achieve is probably</p>
<pre><code>if result == 'success':
# *** I'm getting warning on this one
message = {'result': result, 'actio... | 4 | 2016-10-18T08:12:18Z | [
"python",
"pycharm"
] |
Do imported modules have the same working directory as the file being executed? | 40,102,865 | <p>Suppose I have a file called <code>myfile.py</code> in <code>/Users/joe/Documents</code>:</p>
<pre><code>import mymodule
mymodule.foobar()
</code></pre>
<p>Now let's say that I need to fetch the current working directory of <code>myfile.py</code> in <code>mymodule</code> (which is in another location). Do they bo... | 0 | 2016-10-18T08:08:47Z | 40,102,866 | <p>Because you are importing the module, they both have the same working directory, meaning that completing operations with <code>os</code> will be successful (or whatever other purpose you are using the current working directory for).</p>
| 0 | 2016-10-18T08:08:47Z | [
"python",
"working-directory"
] |
lxml fromstring() yields HTML code with everywhere | 40,102,872 | <p>I'm reading in a webpage from the intranet via</p>
<pre><code> webpage = urllib2.urlopen(urllib2.Request(self.URL))
doc = webpage.read()
root = html.fromstring(doc)
</code></pre>
<p>I noticed that I can't read anything via findall() from this root Object, I then looked into the root Object ... | 0 | 2016-10-18T08:08:57Z | 40,103,958 | <p>Nevermind, that wasn't the issue.</p>
<p>The problem was that I downloaded the site and parsed it offline, where it sneaked in </p>
<p>< tbody ></p>
<p>tags that I used in my Xpath queries. This caused my script not to work when downloading the website fresh via lxml.</p>
| 0 | 2016-10-18T09:04:44Z | [
"python",
"lxml",
"elementtree"
] |
Python: Finding the longest path | 40,102,975 | <p>I have a simple graph created as such in the below</p>
<pre><code>class Job():
def __init__(self, name, weight):
self.name = name
self.weight = weight
self.depends = []
def add_dependent(self, dependent):
self.depends.append(dependent)
jobA = Job('A', 0)
jobB = Job('B', 4)... | 1 | 2016-10-18T08:14:18Z | 40,106,783 | <p>Not the most efficient solution, but here is one that should work:</p>
<pre><code>import operator
def longest_path(root):
def _find_longest(job):
costs = [_find_longest(depend) for depend in job.depends]
if costs:
# Find most expensive:
path, cost = max(costs, key=operat... | 1 | 2016-10-18T11:16:45Z | [
"python",
"python-2.7",
"longest-path"
] |
Python: Finding the longest path | 40,102,975 | <p>I have a simple graph created as such in the below</p>
<pre><code>class Job():
def __init__(self, name, weight):
self.name = name
self.weight = weight
self.depends = []
def add_dependent(self, dependent):
self.depends.append(dependent)
jobA = Job('A', 0)
jobB = Job('B', 4)... | 1 | 2016-10-18T08:14:18Z | 40,108,901 | <p>If you use OO solution, it's easy to provide a way to store only the heaviest path.
This is the solution I came up with - using a callable class</p>
<pre><code>In [111]: class Heaviest(object):
...: def __init__(self, job):
...: self.path = ''
...: self.weight = 0
...: ... | 1 | 2016-10-18T12:55:37Z | [
"python",
"python-2.7",
"longest-path"
] |
trying to change the state of button after the all the entry are updated | 40,102,984 | <p>trying to get my head around how to enable the state of the button after the entries are written. I am trying to get a new window Toplevel. Wherein, there are three entry widgets. After they are filled with values the RUN button should be enabled. I know i gotta use the trace method to attach observer callbacks to t... | 0 | 2016-10-18T08:14:49Z | 40,104,492 | <p>Your code is almost working except:</p>
<pre><code>self.ent = tk.Button( self.newWindow, text='ENTER', state='disabled', command=self.validate_check ).grid(row=3, column=1 )
</code></pre>
<p>should be:</p>
<pre><code>self.ent = tk.Button( self.newWindow, text='ENTER', state='disabled', command=self.validate_check... | 3 | 2016-10-18T09:29:05Z | [
"python",
"tkinter"
] |
.recv function Socket programming TCP Server in Python | 40,103,042 | <p>Im having trouble getting my very basic and simple TCP Server to properly work with http requests. This is what I have so far</p>
<pre><code>from socket import *
import sys
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('', 4567))
serverSocket.listen(1)
while True:
print('Ready to serve...')... | 0 | 2016-10-18T08:17:34Z | 40,103,170 | <p>There are numerous problems with your code and since you don't state what specific issues you are concerned about, here is what I see:</p>
<pre><code> connectionSocket.send(outputdata[i].encode())
connectionSocket.send("\r\n".encode())
</code></pre>
<p>That appears to send a newline after every char... | 0 | 2016-10-18T08:24:18Z | [
"python",
"sockets",
"http",
"tcp",
"decode"
] |
what is a for loop doing on file objects? | 40,103,053 | <p>I have a question related to Python for loops and files. </p>
<p>In this code: </p>
<pre><code>file = raw_input("input a text file ")
f = open(file) # creates a file object of file
for line in f:
# prints each line in the file
print line
print f
# prints <open file 'MVL_ref.txt', mode 'r' at 0x0... | 0 | 2016-10-18T08:17:59Z | 40,103,124 | <p>Since file object in Python is <a href="https://docs.python.org/2/glossary.html#term-iterable" rel="nofollow">iterable</a> you can iterate over it to get lines of file one-by-one. </p>
<p>However File is not a collection but object - you won't see all lines by printing this like when outputting collection</p>
<pre... | 2 | 2016-10-18T08:21:44Z | [
"python",
"python-2.7"
] |
Plot decision boundaries of classifier, ValueError: X has 2 features per sample; expecting 908430" | 40,103,060 | <p>Based on the scikit-learn document <a href="http://scikit-learn.org/stable/auto_examples/svm/plot_iris.html#sphx-glr-auto-examples-svm-plot-iris-py" rel="nofollow">http://scikit-learn.org/stable/auto_examples/svm/plot_iris.html#sphx-glr-auto-examples-svm-plot-iris-py</a>.
I try to plot a decision boundaries of the c... | 0 | 2016-10-18T08:18:29Z | 40,141,574 | <p>The thing is you <strong>cannot</strong> plot decision boundary for a classifier for data which is not <strong>2 dimensional</strong>. Your data is clearly high dimensional, it has 908430 dimensions (NLP task I assume). There is no way to plot actual decision boundary for such a model. Example that you are using is ... | 0 | 2016-10-19T21:09:20Z | [
"python",
"machine-learning",
"scikit-learn"
] |
Python 2.7 encoding from csv file | 40,103,127 | <p>I have a problem with Python 2.7 encoding I have a csv file with some french characters (mangé, parlé, prêtre ...), the code I'm using is the following:</p>
<pre><code>import pandas as pd
path_dataset = 'P:\\Version_python\\Dataset\\data_set - Copy.csv'
dataset = pd.read_csv(path_dataset, sep=';')
for lab, row ... | 1 | 2016-10-18T08:21:55Z | 40,103,314 | <p>You can use codecs in python2.7</p>
<pre><code>import codecs
file = codecs.open(filename, encoding="utf-8")
</code></pre>
| 0 | 2016-10-18T08:32:02Z | [
"python",
"python-2.7",
"pandas"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.