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
sequence
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 this:</p> <pre><code># -*- coding: utf-8 -*- from openerp import models, fields, api import openerp.addons.decimal_precision as dp class product(models.Model): _inherit = 'product.product' _rec_name = 'price_unidad' price_unidad = fields.One2many('product.product','price', string="Precio", readonly=True) class StockMove(models.Model): _inherit = 'stock.move' price_unity = fields.Many2one("product", string="Precio", readonly=True) </code></pre> <p>Then, on my views:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;openerp&gt; &lt;data&gt; &lt;record id="view_stock_move_tree" model="ir.ui.view"&gt; &lt;field name="name"&gt;Stock Move Price Tree&lt;/field&gt; &lt;field name="model"&gt;stock.move&lt;/field&gt; &lt;field name="inherit_id" ref="stock.view_move_picking_tree"/&gt; &lt;field name="arch" type="xml"&gt; &lt;field name="state" position="before"&gt; &lt;field name="price_unity"/&gt; &lt;/field&gt; &lt;/field&gt; &lt;/record&gt; &lt;record id="view_stock_move_form" model="ir.ui.view"&gt; &lt;field name="name"&gt;Stock Move Price Form&lt;/field&gt; &lt;field name="model"&gt;stock.move&lt;/field&gt; &lt;field name="inherit_id" ref="stock.view_move_picking_form"/&gt; &lt;field name="arch" type="xml"&gt; &lt;field name="state" position="before"&gt; &lt;field name="price_unity"/&gt; &lt;/field&gt; &lt;/field&gt; &lt;/record&gt; &lt;/data&gt; &lt;/openerp&gt; </code></pre> <p>I'm not really sure, but it seems like it enters into a neverending loop when I call it from the form view.</p> <p>So, I don't really know what's wrong with it.</p> <p>Any ideas on how to accomplish this?</p> <p>Thanks in advance!</p>
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've done in your <code>stock.move</code> model except that the model name is <code>product.product</code></p> <pre><code>class StockMove(models.Model): _inherit = 'stock.move' price_unity = fields.Many2one("product.product", string="Precio", readonly=True) </code></pre> <p>This picks the object as a whole, but if you want only the price, then you'll have to use a related field</p> <pre><code>class StockMove(models.Model): _inherit = 'stock.move' product_id = fields.Many2one("product.product", "Product") price_unity = fields.Float(string="Precio", store=True, readonly=True, related="product_id.price") </code></pre> <p><strong>Note: you don't need the product_id (the <code>stock.move</code> model already has a link to product.product with the same name), i just put it there to show you how related fields work</strong></p>
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 this:</p> <pre><code># -*- coding: utf-8 -*- from openerp import models, fields, api import openerp.addons.decimal_precision as dp class product(models.Model): _inherit = 'product.product' _rec_name = 'price_unidad' price_unidad = fields.One2many('product.product','price', string="Precio", readonly=True) class StockMove(models.Model): _inherit = 'stock.move' price_unity = fields.Many2one("product", string="Precio", readonly=True) </code></pre> <p>Then, on my views:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;openerp&gt; &lt;data&gt; &lt;record id="view_stock_move_tree" model="ir.ui.view"&gt; &lt;field name="name"&gt;Stock Move Price Tree&lt;/field&gt; &lt;field name="model"&gt;stock.move&lt;/field&gt; &lt;field name="inherit_id" ref="stock.view_move_picking_tree"/&gt; &lt;field name="arch" type="xml"&gt; &lt;field name="state" position="before"&gt; &lt;field name="price_unity"/&gt; &lt;/field&gt; &lt;/field&gt; &lt;/record&gt; &lt;record id="view_stock_move_form" model="ir.ui.view"&gt; &lt;field name="name"&gt;Stock Move Price Form&lt;/field&gt; &lt;field name="model"&gt;stock.move&lt;/field&gt; &lt;field name="inherit_id" ref="stock.view_move_picking_form"/&gt; &lt;field name="arch" type="xml"&gt; &lt;field name="state" position="before"&gt; &lt;field name="price_unity"/&gt; &lt;/field&gt; &lt;/field&gt; &lt;/record&gt; &lt;/data&gt; &lt;/openerp&gt; </code></pre> <p>I'm not really sure, but it seems like it enters into a neverending loop when I call it from the form view.</p> <p>So, I don't really know what's wrong with it.</p> <p>Any ideas on how to accomplish this?</p> <p>Thanks in advance!</p>
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 output [27], which is only one of the correct positions.</p> <p>code using only readline(): <a href="https://i.stack.imgur.com/CO5EF.png" rel="nofollow"><img src="https://i.stack.imgur.com/CO5EF.png" alt="enter image description here"></a></p> <p>When I define <code>"sp = 'ATTCTGGA'"</code> directly within the code, however, I get <code>[6, 7, 26, 27]</code>, which is the correct answer.</p> <p><a href="https://i.stack.imgur.com/LLtEX.png" rel="nofollow"><img src="https://i.stack.imgur.com/LLtEX.png" alt="enter image description here"></a></p> <p>Why does <code>"sp = text.readline()"</code> not get the same result?</p>
-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 begin with the word DAY (at the beginning of line), then a space and a curly bracket. The end is indicated with the closing bracket always placed at the beginning of the line. So we can say the boundaries of each DAY is defined within the curly brackets {}. </p> <p>Using <code>regex</code> I need to "find" the DAY that contains <code>file = "/Users/Shared/docs/doc.txt"</code> line inside of its boundary. </p> <p>I started writing a regex expression:</p> <p><code>string = """DAY {\n [A-Za-z0-9]+}"""</code></p> <p><code>result = re.findall(string, text)</code></p> <p>But the expression stops finding the text at the end of <code>foo</code> right before the white space character. How to modify the expression so it returns the second DAY that has <code>file = "/Users/Shared/docs/doc.txt"</code> in its body, so the result would look like:</p> <pre><code>DAY { day 1 day 2 file = "/Users/Shared/docs/doc.txt" day 3 end of the month } </code></pre>
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) regex.findall(text) </code></pre> <p>Result:</p> <pre><code>['DAY {\n day 1\n day 2\n file = "/Users/Shared/docs/doc.txt"\n day 3\n end of the month\n}'] </code></pre>
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 the script I used to compare. Not very well written, a very simple one.</p> <pre><code>from fractions import Fraction from gmpy2 import mpq, mpfr import time # This script compares gmpy2 library and Fraction library total_pass_mpq = 0 total_pass_mpfr = 0 total_pass_frc = 0 a = mpq("-3.232429") a_ = Fraction("-3.232429") a__ = mpfr("-3.232429") if str(float(a)) == "-3.232429": total_pass_mpq +=1 if str(float(a_)) == "-3.232429": total_pass_frc += 1 if str(float(a__)) == "-3.232429": total_pass_mpfr += 1 b = mpq("604.08") c = mpq("1.979") b_ = Fraction("604.08") c_ = Fraction("1.979") b__ = mpfr("604.08") c__ = mpfr("1.979") if str(float(b*c)) == "1195.47432": total_pass_mpq += 1 if str(float(b_*c_)) == "1195.47432": total_pass_frc += 1 if str(float(b__*c__)) == "1195.47432": total_pass_mpfr += 1 d = mpq(604.08) e = mpq(1.979) d_ = Fraction(604.08) e_ = Fraction(1.979) d__ = mpfr(604.08) e__ = mpfr(1.979) if str(float(d*e)) == "1195.47432": total_pass_mpq += 1 if str(float(d_*e_)) == "1195.47432": total_pass_frc += 1 if str(float(d__*e__)) == "1195.47432": total_pass_mpfr += 1 f = mpq(-3.232429) f_ = Fraction(-3.232429) f__ = mpfr(-3.232429) if str(float(f)) == "-3.232429": total_pass_mpq +=1 if str(float(f_)) == "-3.232429": total_pass_frc += 1 if str(float(f__)) == "-3.232429": total_pass_mpfr +=1 g = mpq(503.79) g_ = Fraction(503.79) g__ = mpfr(503.79) h = mpq(0.07) h_ = Fraction(0.07) h__ = mpfr(0.07) if str(float(g*(1+h))) == "539.0553": total_pass_mpq += 1 if str(float(g_*(1+h_))) == "539.0553": total_pass_frc += 1 if str(float(g__*(1+h__))) == "539.0553": total_pass_mpfr += 1 print("Total passed mpq: " + str(total_pass_mpq)) print("Total passed Fraction: " + str(total_pass_frc)) print("Total passed mpfr: " + str(total_pass_mpfr)) start_mpq = time.time() for i in range(0, 50000): y = mpq(0.32329) z = mpq(-1) yz = y*z end_mpq = time.time() print("Time for executing mpq: " + str(end_mpq - start_mpq)) start_frc = time.time() for j in range(0, 50000): y = Fraction(0.32329) z = Fraction(-1) yz_ = y*z end_frc = time.time() print("Time for executing frc: " + str(end_frc - start_frc)) start_frc_2 = time.time() for j_ in range(0, 50000): y = Fraction(0.32329) z = Fraction(-1) yz_2 = y*z end_frc_2 = time.time() print("Time for executing frc str: " + str(end_frc_2 - start_frc_2)) start_mpfr = time.time() for k in range(0, 50000): y = mpfr(0.32329) z = mpfr(-1) yz__ = y*z end_mpfr = time.time() print("Time for executing mpfr: " + str(end_mpfr - start_mpfr)) start_mpfr_2 = time.time() for k_ in range(0, 50000): y = mpfr("0.32329") z = mpfr("-1") yz__2 = y*z end_mpfr_2 = time.time() print("Time for executing mpfr str: " + str(end_mpfr_2 - start_mpfr_2)) </code></pre> <p>This is the result:</p> <pre><code>Total passed mpq: 3 Total passed Fraction: 5 Total passed mpfr: 4 Time for executing mpq: 0.04700875282287598 Time for executing frc: 2.1327619552612305 Time for executing frc str: 2.0934295654296875 Time for executing mpfr: 0.05441713333129883 Time for executing mpfr str: 0.12844634056091309 </code></pre> <p>So basically I've got the result that Fraction is the <strong>most accurate</strong> one, but it's super slow. For this question, I wanted to ask, </p> <ol> <li>is there any other case that you think I should also try?</li> <li>any other library?</li> <li>If speed matters, is there a way to improve precision using gmpy2 library?</li> </ol>
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 occasionally be different than <code>float(Fraction)</code>.</p> <p>The GMP library is not optimized for floating point calculations. To get correctly rounded floating values, you should use the MFPR libary (aka the <code>mpfr</code> type in <code>gmpy2</code>).</p> <p>The most accurate way to convert an <code>mpq</code> to a <code>float</code> is to convert it to an <code>mpfr</code> first. To avoid double-rounding, you should convert from <code>mpq</code> to <code>mpfr</code> with a precision of exactly 53 bits. So <code>float(mpfr(mpq, 53))</code>. (The default precision is currently 53 bits but that might change in the future. Specifying the desired precision, or ensuring the default context's precision is set to 53, is recommended.) This change makes <code>mpq</code> and <code>Fraction</code> return the same results in your example.</p> <p>There is still one <code>mpfr</code> result that is different. That is just inherent in the fact that intermediate <code>mpfr</code>calculations are rounding to the current precision (53 bits in this case).</p> <p><strong>Update to answer a question by @mattsun.</strong></p> <p>Why does <code>mpfr("503.79")*(mpfr("1")+mpfr("0.07"))</code> not equal "539.0553"?</p> <p>Both Python's <code>float</code> type and gmpy2's <code>mpfr</code> type use a binary, or radix-2, representation. We normally use decimal, or radix-10, representation when we work with numbers. Just like <code>1/3</code> cannon be represented exactly in decimal arithmetic, most decimal numbers cannot be represented exactly with a binary representation. The calculations are done with values that are close, but not exactly equal, to the values given. The errors can accumulate, and the result will be just a little different than your expected value.</p> <p>There are two options:</p> <p>1) Format the string to the desired decimal format.</p> <p>2) Use the <code>decimal</code> library.</p> <p>Disclaimer: I maintain <code>gmpy2</code>.</p>
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? Why would that kind of behavior be useful? In what cases?</p> <p>Also I am talking simply about deleting a single variable. Not del list[3] or alike.</p> <p>note: I am asking if this python's behavior is meant that way. And in what cases, it would be still useful.</p> <p>EDIT: Charles Addis gave a detailed explanation. I also admit my mistake that I mistook the pycharm behavior as official python's. I am now trying out ipython along with official python interactive shell. Despite this being my mistake, I am glad that I learnt a lot about python variables along with some python debug commands.</p>
4
2016-10-18T04:17:57Z
40,099,489
<p>Not sure what you're asking, as clearly thats what happens...</p> <pre><code>&gt;&gt;&gt; x Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined &gt;&gt;&gt; x = 10 &gt;&gt;&gt; 'x' in vars() True &gt;&gt;&gt; vars()['x'] 10 &gt;&gt;&gt; del x &gt;&gt;&gt; 'x' in vars() False &gt;&gt;&gt; x Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined </code></pre> <p>As you can see, Python stores valid identifiers in <code>vars()</code> and <code>locals()</code>... So del essentially removes it from memory, removing it from these data structures as well. So the identifier is no longer valid. It's not like in C where you might free some memory and set the value to <code>NULL</code>.</p> <pre><code>&gt;&gt;&gt; x = 10 &gt;&gt;&gt; def func(): ... global x ... del x ... &gt;&gt;&gt; x 10 &gt;&gt;&gt; func() &gt;&gt;&gt; x Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined &gt;&gt;&gt; </code></pre> <h2>Update:</h2> <p>Raymond made a good point when he mentioned that the object itself (read: the actual data in memory that the identifier points too, for lack of a more detailed explanation) is only freed when it's reference count goes to 0. IMO he could have done a better job detailing this in the python interpreter, so I'll have a go at it.</p> <p>We'll use the ID function to prove this:</p> <pre><code>Help on built-in function id in module __builtin__: id(...) id(object) -&gt; integer Return the identity of an object. This is guaranteed to be unique among simultaneously existing objects. (Hint: it's the object's memory address.) </code></pre> <p>Pay attention to whats going on here, you'll see that for immutable types, different values reference the same memory (strings are immutable in python and are interned, which means only one copy of each unique string is stored -- in ruby, symbols are interned strings).</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; x = 10 # 10 is a common value, probably exists in memory already &gt;&gt;&gt; sys.getrefcount(x) 26 &gt;&gt;&gt; id(x) # memory location of x 140266396760096 &gt;&gt;&gt; y = x &gt;&gt;&gt; id(y) == id(x) True &gt;&gt;&gt; z = 10 &gt;&gt;&gt; id(z) == id(y) == id(x) True &gt;&gt;&gt; sys.getrefcount(y) 28 &gt;&gt;&gt; sys.getrefcount(z) 28 &gt;&gt;&gt; del y, z &gt;&gt;&gt; sys.getrefcount(x) 26 &gt;&gt;&gt; del x &gt;&gt;&gt; x = 'charlie' &gt;&gt;&gt; id(x) 4442795056 &gt;&gt;&gt; y = 'charlie' &gt;&gt;&gt; z = x &gt;&gt;&gt; id(x) == id(y) == id(z) True &gt;&gt;&gt; sys.getrefcount(x) 4 &gt;&gt;&gt; sys.getrefcount(y) 4 &gt;&gt;&gt; sys.getrefcount(z) 4 &gt;&gt;&gt; del y &gt;&gt;&gt; del x &gt;&gt;&gt; sys.getrefcount(z) # will be two because this line is an additional reference 2 &gt;&gt;&gt; id(z) # pay attention to this memory location because this 4442795056 # is the last remaining reference to 'charlie', and &gt;&gt;&gt; del z # when it goes out of scope 'charlie' is removed from &gt;&gt;&gt; # memory. &gt;&gt;&gt; id('charlie') # This has a different memory location because 'charlie' 4442795104 # had to be re-created. </code></pre> <p>First we set the identifier 'x' == 10, a common integer value. Since 10 is such a common value, it's almost guaranteed that something in the processes memory already has that value. Since integers are immutable in python, we only ever need one copy of each unique value stored in memory. In this case, there are 24 other references to 10 in memory. Setting <code>x = 10</code> creates the 25th reference, and calling <code>sys.getrefcount(x)</code> is the 26th reference (though it quickly goes out of scope). When we set <code>y = 10</code> and <code>z = x</code>, we know that they all point to the same data because they all have the same memory location. Calling <code>del</code> alters the reference count, but even when all 3 are deleted the integer 10 still exists in memory.</p> <p>Next we create set <code>x = 'charlie'</code>, followed by <code>y = 'charlie'</code>, and finally <code>z = x</code>. You can see all of these variables have the same memory address. Once we delete all of these variables there are no more references to <code>'charlie'</code>. We can verify this by calling <code>id('charlie')</code> which will produce a different memory address meaning the string did not exist in memory when we called that function. </p> <p>One more thing to note is the location of <code>'charlie'</code> and <code>10</code> in memory. <code>10</code> has a significantly higher memory address than Charlie does. This is because they exist in different locations of memory. <code>'charlie'</code> exists on the heap whereas <code>10</code> exists on the stack.</p> <pre><code>&gt;&gt;&gt; hex(id(10)) # high address, this is on the stack '0x7f9250c0b820' &gt;&gt;&gt; hex(id('charlie')) # lower address, this is on the heap '0x108cfac60 </code></pre>
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? Why would that kind of behavior be useful? In what cases?</p> <p>Also I am talking simply about deleting a single variable. Not del list[3] or alike.</p> <p>note: I am asking if this python's behavior is meant that way. And in what cases, it would be still useful.</p> <p>EDIT: Charles Addis gave a detailed explanation. I also admit my mistake that I mistook the pycharm behavior as official python's. I am now trying out ipython along with official python interactive shell. Despite this being my mistake, I am glad that I learnt a lot about python variables along with some python debug commands.</p>
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> <p>Or is it simply just deleting the object and leaving the name (var) not pointing anywhere? Why would that kind of behavior be useful? In what cases?</p> </blockquote> <p>In Python, things are a bit different. There are no "variables" as you might be used to in other languages.</p> <p>There is the object space, where data lives - and the namespace, where <em>names</em> live.</p> <p><em>names</em> are what we normally refer to in other languages as <em>variables</em> but in Python they are simply labels to an object in the data space.</p> <p>Once the label (name) is removed with <code>del</code>, its simply taking away the label that points to the object. The object (which has the value) remains; unless its not referred to by any other name, in which case Python will then garbage collect it. Names are just lightweight labels that point to objects in the object space, and are the only way we can access those objects.</p> <p>Here is an example to illustrate this:</p> <pre><code>&gt;&gt;&gt; x = 5 &gt;&gt;&gt; y = x &gt;&gt;&gt; del x &gt;&gt;&gt; y 5 </code></pre> <p>Now I deleted <code>x</code>, but since <code>y</code> is still pointing to the same object as <code>x</code> (the integer <code>5</code>), it remains and I can access it again; but if I try to access <code>x</code>:</p> <pre><code>&gt;&gt;&gt; x Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; NameError: name 'x' is not defined </code></pre>
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? Why would that kind of behavior be useful? In what cases?</p> <p>Also I am talking simply about deleting a single variable. Not del list[3] or alike.</p> <p>note: I am asking if this python's behavior is meant that way. And in what cases, it would be still useful.</p> <p>EDIT: Charles Addis gave a detailed explanation. I also admit my mistake that I mistook the pycharm behavior as official python's. I am now trying out ipython along with official python interactive shell. Despite this being my mistake, I am glad that I learnt a lot about python variables along with some python debug commands.</p>
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>&gt;&gt;&gt; import sys &gt;&gt;&gt; x = 123456 &gt;&gt;&gt; y = x # create a second reference to the number &gt;&gt;&gt; dir() # known variables include "x" and "y" ['__builtins__', '__doc__', '__name__', '__package__', 'sys', 'x', 'y'] &gt;&gt;&gt; sys.getrefcount(x) 3 &gt;&gt;&gt; del x # remove "x" as a known variable &gt;&gt;&gt; dir() # known variables includes only "y" ['__builtins__', '__doc__', '__name__', '__package__', 'sys', 'y'] &gt;&gt;&gt; sys.getrefcount(y) # reference count is now lower by 1 2 &gt;&gt;&gt; del y # remove "y" as a known variable &gt;&gt;&gt; dir() # known variables no longer include "x" and "y" ['__builtins__', '__doc__', '__name__', '__package__', 'sys'] &gt;&gt;&gt; x # unresolved variable raises a "NameError" Traceback (most recent call last): File "&lt;pyshell#12&gt;", line 1, in &lt;module&gt; x # unresolved variable raises a "NameError" NameError: name 'x' is not defined </code></pre>
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 your csv like this and reduce memory footprint:</p> <pre><code>pd.read_csv(StringIO(data), dtype={'col1': 'category'}) </code></pre>
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 scramble it.</p> <p>Ex) testing!!! should be something like t!ste!nig! or t!est!nig! but not tstenig!!!</p> <p>How can I fix that?</p> <pre><code>import random import string original_text = input("Enter your text: ").split(' ') seed = int(input("Enter a seed (0 for random): ")) punctuation = [] for c in string.punctuation: punctuation.append(c) if seed is not 0: random.seed(seed) randomized_list = [] def scramble_word(word): alpha = word[0] end_punctuation = '' 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] else: omega = word[-1] middle = word[1:-1] end_punctuation = "" middle_list = list(middle) random.shuffle(middle_list) shuffled_text = "".join(middle_list) new_words = alpha + shuffled_text + omega + end_punctuation return new_words for item in original_text: if len(item) &lt;= 3: randomized_list.append(item) else: randomized_list.append(scramble_word(item)) new_words = " ".join(randomized_list) print(new_words) </code></pre>
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 all except the final character end_punctuation = end_punctuation[0] # Just use the final character else: omega = word[-1] middle = word[1:-1] end_punctuation = "" </code></pre> <p>That does the trick for me:</p> <pre><code>In [63]: scramble_word('hello!?$') Out[63]: 'hle?l!o$' In [64]: scramble_word('hello!?$') Out[64]: 'h?!ello$' In [65]: scramble_word('hello!?$') Out[65]: 'hlel!?o$' In [66]: scramble_word('hello!') Out[66]: 'hlleo!' In [67]: scramble_word('hello!') Out[67]: 'hello!' In [68]: scramble_word('hello!') Out[68]: 'hlleo!' In [69]: scramble_word('hello') Out[69]: 'hlelo' </code></pre> <p>By the way, you don't need the <code>punctuation</code> variable; <code>word[x] in string.punctuation</code> will work the same.</p>
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 scramble it.</p> <p>Ex) testing!!! should be something like t!ste!nig! or t!est!nig! but not tstenig!!!</p> <p>How can I fix that?</p> <pre><code>import random import string original_text = input("Enter your text: ").split(' ') seed = int(input("Enter a seed (0 for random): ")) punctuation = [] for c in string.punctuation: punctuation.append(c) if seed is not 0: random.seed(seed) randomized_list = [] def scramble_word(word): alpha = word[0] end_punctuation = '' 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] else: omega = word[-1] middle = word[1:-1] end_punctuation = "" middle_list = list(middle) random.shuffle(middle_list) shuffled_text = "".join(middle_list) new_words = alpha + shuffled_text + omega + end_punctuation return new_words for item in original_text: if len(item) &lt;= 3: randomized_list.append(item) else: randomized_list.append(scramble_word(item)) new_words = " ".join(randomized_list) print(new_words) </code></pre>
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) print ("".join(x[0]+shuffled+x[-1]),"", end="") scramble(words) </code></pre> <p>My output was for example from:</p> <p>Masterson!!%&amp; makes baking%$ potatoes great!</p> <p>to Ment!osrs!a%&amp; mkeas bigkna%$ patooets gerat! </p> <p>I'm sure someone could shorten it even more dramatically.</p>
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 called <code>color_set</code>, I am trying to achieve as follows:</p> <ul> <li>it will lookup the names of items in the scene</li> <li>then it will go through a function to check and see if the item <code>shirt_01</code> contains a variable called <code>color_set</code></li> <li>If the variable exists, say if it is RED, it will then lookup the list of options in the combobox and display RED as the value</li> <li>If the variable does not exists, it will displays a blank field instead</li> <li><p>this function/values populate the table with information before the ui is launched, it is not a button clicked function etc.</p> <pre><code>Name of items | Color Options shirt_01* | RED shirt_02 | pants* | GREEN </code></pre></li> </ul> <p>However, instead of getting my ui to output as above, I got the following result:</p> <pre><code> Name of items | Color Options shirt_01* | RED shirt_02 | RED pants* | GREEN </code></pre> <p>For some reasons, the <code>shirt_02</code> seems to got 'tangled' and displayed the same result as <code>shirt_01</code>. And I think it could possibly be due to how my logic was written but I could not figure it out or because I keep tying my output result to <code>self.color_combobox</code> as my code initially checks through the first column then find the matching text in the second column. But I keep getting error at the line - item_name has no attribute .text()</p> <pre><code>import maya.cmds as cmds from PyQt4 import QtGui, QtCore import json def get_all_mesh(): all_mesh = cmds.listRelatives(cmds.ls(type = 'mesh'), parent=True) return all_mesh def read_json(node_name): # checks if the node_name exists in the json file with open('/Desktop/car_colors.json') as data_file: data = json.load(data_file) items = set() for index, name in enumerate(data): # if the name is in the json, it will states the color if node_name in name: for item in (data[name]): #print "{0} - {1}".format(name, item) items.add(item) return items def attrToPy(objAttr): stringAttrData = str(cmds.getAttr(objAttr)) loadedData = cPickle.loads(stringAttrData) return loadedData class testTableView(QtGui.QDialog): def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.setWindowTitle('Color Test') self.setModal(False) self.all_mesh = get_all_mesh() # Build the GUI self.init_ui() self.populate_data() def init_ui(self): # Table setup self.mesh_table = QtGui.QTableWidget() self.mesh_table.setRowCount(len(self.all_mesh)) self.mesh_table.setColumnCount(3) self.mesh_table.setHorizontalHeaderLabels(['Mesh Found', 'Color for Mesh']) self.md_insert_color_btn = QtGui.QPushButton('Apply color') # Layout self.layout = QtGui.QVBoxLayout() self.layout.addWidget(self.mesh_table) self.layout.addWidget(self.md_insert_color_btn) self.setLayout(self.layout) 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 found in scene and append them into rows self.mesh_table.setItem(row_index, 0, new_item) geo_exclude_num = ''.join(i for i in geo_item if not i.isdigit()) color_list = read_json(geo_exclude_num) color_list.add("") # Insert in the color self.color_combobox = QtGui.QComboBox() #color_list = get_color() self.color_combobox.addItems(list(sorted(color_list))) self.mesh_table.setCellWidget(row_index, 1, self.color_combobox) self.color_value_to_combobox() def color_value_to_combobox(self): obj_nodes = get_all_mesh() for node in obj_nodes: # This attribute is stored in the Extra Attributes objAttr = '%s.pyPickle'%node storedData = attrToPy(objAttr) if 'color_set' in storedData: color_variant = storedData['color_set'] combo_index = self.color_combobox.findText(color_variant, QtCore.Qt.MatchFixedString) self.color_combobox.setCurrentIndex(0 if combo_index &lt; 0 else combo_index) # To opent the dialog window dialog = testTableView() dialog.show() </code></pre> <p>Is there anyway in which I can make my ui to check for the list of item in scene, tallies which name and combobox it should go (in terms of which rows/columns)? Otherwise what other ways can i approach?</p> <p>EDIT: This is the attachment that I did it quick - <a href="https://www.mediafire.com/?fy67i4105j6z1tp" rel="nofollow">Link</a> If you run the UI, you will notice that pCube1 has the color "red" while pCube2 is "blue", however both the comboboxes will turn up as blue instead</p>
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 a combo box if the item does not have colors; then in the second loop you check if the cell has a combo box and only if it does do you configure it. - Second option is to move the first loop into the rows loop, ie you as loop through each row you determine if the item has colors, and only if it does, do you create the combo box and configure it; if no colors, just leave that sell empty.</p>
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 called <code>color_set</code>, I am trying to achieve as follows:</p> <ul> <li>it will lookup the names of items in the scene</li> <li>then it will go through a function to check and see if the item <code>shirt_01</code> contains a variable called <code>color_set</code></li> <li>If the variable exists, say if it is RED, it will then lookup the list of options in the combobox and display RED as the value</li> <li>If the variable does not exists, it will displays a blank field instead</li> <li><p>this function/values populate the table with information before the ui is launched, it is not a button clicked function etc.</p> <pre><code>Name of items | Color Options shirt_01* | RED shirt_02 | pants* | GREEN </code></pre></li> </ul> <p>However, instead of getting my ui to output as above, I got the following result:</p> <pre><code> Name of items | Color Options shirt_01* | RED shirt_02 | RED pants* | GREEN </code></pre> <p>For some reasons, the <code>shirt_02</code> seems to got 'tangled' and displayed the same result as <code>shirt_01</code>. And I think it could possibly be due to how my logic was written but I could not figure it out or because I keep tying my output result to <code>self.color_combobox</code> as my code initially checks through the first column then find the matching text in the second column. But I keep getting error at the line - item_name has no attribute .text()</p> <pre><code>import maya.cmds as cmds from PyQt4 import QtGui, QtCore import json def get_all_mesh(): all_mesh = cmds.listRelatives(cmds.ls(type = 'mesh'), parent=True) return all_mesh def read_json(node_name): # checks if the node_name exists in the json file with open('/Desktop/car_colors.json') as data_file: data = json.load(data_file) items = set() for index, name in enumerate(data): # if the name is in the json, it will states the color if node_name in name: for item in (data[name]): #print "{0} - {1}".format(name, item) items.add(item) return items def attrToPy(objAttr): stringAttrData = str(cmds.getAttr(objAttr)) loadedData = cPickle.loads(stringAttrData) return loadedData class testTableView(QtGui.QDialog): def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.setWindowTitle('Color Test') self.setModal(False) self.all_mesh = get_all_mesh() # Build the GUI self.init_ui() self.populate_data() def init_ui(self): # Table setup self.mesh_table = QtGui.QTableWidget() self.mesh_table.setRowCount(len(self.all_mesh)) self.mesh_table.setColumnCount(3) self.mesh_table.setHorizontalHeaderLabels(['Mesh Found', 'Color for Mesh']) self.md_insert_color_btn = QtGui.QPushButton('Apply color') # Layout self.layout = QtGui.QVBoxLayout() self.layout.addWidget(self.mesh_table) self.layout.addWidget(self.md_insert_color_btn) self.setLayout(self.layout) 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 found in scene and append them into rows self.mesh_table.setItem(row_index, 0, new_item) geo_exclude_num = ''.join(i for i in geo_item if not i.isdigit()) color_list = read_json(geo_exclude_num) color_list.add("") # Insert in the color self.color_combobox = QtGui.QComboBox() #color_list = get_color() self.color_combobox.addItems(list(sorted(color_list))) self.mesh_table.setCellWidget(row_index, 1, self.color_combobox) self.color_value_to_combobox() def color_value_to_combobox(self): obj_nodes = get_all_mesh() for node in obj_nodes: # This attribute is stored in the Extra Attributes objAttr = '%s.pyPickle'%node storedData = attrToPy(objAttr) if 'color_set' in storedData: color_variant = storedData['color_set'] combo_index = self.color_combobox.findText(color_variant, QtCore.Qt.MatchFixedString) self.color_combobox.setCurrentIndex(0 if combo_index &lt; 0 else combo_index) # To opent the dialog window dialog = testTableView() dialog.show() </code></pre> <p>Is there anyway in which I can make my ui to check for the list of item in scene, tallies which name and combobox it should go (in terms of which rows/columns)? Otherwise what other ways can i approach?</p> <p>EDIT: This is the attachment that I did it quick - <a href="https://www.mediafire.com/?fy67i4105j6z1tp" rel="nofollow">Link</a> If you run the UI, you will notice that pCube1 has the color "red" while pCube2 is "blue", however both the comboboxes will turn up as blue instead</p>
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 found in scene and append them into rows self.mesh_table.setItem(row_index, 0, new_item) geo_exclude_num = ''.join(i for i in geo_item if not i.isdigit()) color_list = read_json(geo_exclude_num) color_list.add("") # Insert in the color color_combobox = QtGui.QComboBox() #color_list = get_color() color_combobox.addItems(list(sorted(color_list))) self.mesh_table.setCellWidget(row_index, 1, color_combobox) # This attribute is stored in the Extra Attributes objAttr = '%s.pyPickle' % geo_item storedData = attrToPy(objAttr) if 'color_set' in storedData: color_variant = storedData['color_set'] else: color_variant = '' combo_index = color_combobox.findText(color_variant, QtCore.Qt.MatchFixedString) color_combobox.setCurrentIndex(0 if combo_index &lt; 0 else combo_index) </code></pre> <p>(NB: for this to work, you obviously must make sure the first entry in the combo-boxes is a blank item).</p>
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 called <code>color_set</code>, I am trying to achieve as follows:</p> <ul> <li>it will lookup the names of items in the scene</li> <li>then it will go through a function to check and see if the item <code>shirt_01</code> contains a variable called <code>color_set</code></li> <li>If the variable exists, say if it is RED, it will then lookup the list of options in the combobox and display RED as the value</li> <li>If the variable does not exists, it will displays a blank field instead</li> <li><p>this function/values populate the table with information before the ui is launched, it is not a button clicked function etc.</p> <pre><code>Name of items | Color Options shirt_01* | RED shirt_02 | pants* | GREEN </code></pre></li> </ul> <p>However, instead of getting my ui to output as above, I got the following result:</p> <pre><code> Name of items | Color Options shirt_01* | RED shirt_02 | RED pants* | GREEN </code></pre> <p>For some reasons, the <code>shirt_02</code> seems to got 'tangled' and displayed the same result as <code>shirt_01</code>. And I think it could possibly be due to how my logic was written but I could not figure it out or because I keep tying my output result to <code>self.color_combobox</code> as my code initially checks through the first column then find the matching text in the second column. But I keep getting error at the line - item_name has no attribute .text()</p> <pre><code>import maya.cmds as cmds from PyQt4 import QtGui, QtCore import json def get_all_mesh(): all_mesh = cmds.listRelatives(cmds.ls(type = 'mesh'), parent=True) return all_mesh def read_json(node_name): # checks if the node_name exists in the json file with open('/Desktop/car_colors.json') as data_file: data = json.load(data_file) items = set() for index, name in enumerate(data): # if the name is in the json, it will states the color if node_name in name: for item in (data[name]): #print "{0} - {1}".format(name, item) items.add(item) return items def attrToPy(objAttr): stringAttrData = str(cmds.getAttr(objAttr)) loadedData = cPickle.loads(stringAttrData) return loadedData class testTableView(QtGui.QDialog): def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.setWindowTitle('Color Test') self.setModal(False) self.all_mesh = get_all_mesh() # Build the GUI self.init_ui() self.populate_data() def init_ui(self): # Table setup self.mesh_table = QtGui.QTableWidget() self.mesh_table.setRowCount(len(self.all_mesh)) self.mesh_table.setColumnCount(3) self.mesh_table.setHorizontalHeaderLabels(['Mesh Found', 'Color for Mesh']) self.md_insert_color_btn = QtGui.QPushButton('Apply color') # Layout self.layout = QtGui.QVBoxLayout() self.layout.addWidget(self.mesh_table) self.layout.addWidget(self.md_insert_color_btn) self.setLayout(self.layout) 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 found in scene and append them into rows self.mesh_table.setItem(row_index, 0, new_item) geo_exclude_num = ''.join(i for i in geo_item if not i.isdigit()) color_list = read_json(geo_exclude_num) color_list.add("") # Insert in the color self.color_combobox = QtGui.QComboBox() #color_list = get_color() self.color_combobox.addItems(list(sorted(color_list))) self.mesh_table.setCellWidget(row_index, 1, self.color_combobox) self.color_value_to_combobox() def color_value_to_combobox(self): obj_nodes = get_all_mesh() for node in obj_nodes: # This attribute is stored in the Extra Attributes objAttr = '%s.pyPickle'%node storedData = attrToPy(objAttr) if 'color_set' in storedData: color_variant = storedData['color_set'] combo_index = self.color_combobox.findText(color_variant, QtCore.Qt.MatchFixedString) self.color_combobox.setCurrentIndex(0 if combo_index &lt; 0 else combo_index) # To opent the dialog window dialog = testTableView() dialog.show() </code></pre> <p>Is there anyway in which I can make my ui to check for the list of item in scene, tallies which name and combobox it should go (in terms of which rows/columns)? Otherwise what other ways can i approach?</p> <p>EDIT: This is the attachment that I did it quick - <a href="https://www.mediafire.com/?fy67i4105j6z1tp" rel="nofollow">Link</a> If you run the UI, you will notice that pCube1 has the color "red" while pCube2 is "blue", however both the comboboxes will turn up as blue instead</p>
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 setting the same combobox! It needs to be more generic. Instead of storing the combobox to <code>self.color_combobox</code> I would normally store it in a list, otherwise you can't access all of them anymore, but I leave that to you.</p> <p>Anyways, I just had to change the end of <code>populate_data</code> and <code>color_value_to_combobox</code>. Now <code>cube1</code> shows <code>red</code>, and <code>cube2</code> shows <code>blue</code>.</p> <pre><code>import maya.cmds as cmds from PyQt4 import QtGui, QtCore import json import cPickle def get_all_mesh(): all_mesh = cmds.listRelatives(cmds.ls(type = 'mesh'), parent=True) return all_mesh def read_json(node_name): # checks if the node_name exists in the json file with open('/Desktop/car_colors.json') as data_file: data = json.load(data_file) items = set() for index, name in enumerate(data): # if the name is in the json, it will states the color if node_name in name: for item in (data[name]): #print "{0} - {1}".format(name, item) items.add(item) return items def attrToPy(objAttr): stringAttrData = str(cmds.getAttr(objAttr)) loadedData = cPickle.loads(stringAttrData) return loadedData class testTableView(QtGui.QDialog): def __init__(self, parent=None): QtGui.QDialog.__init__(self, parent) self.setWindowTitle('Color Test') #self.setModal(False) self.all_mesh = get_all_mesh() # Build the GUI self.init_ui() self.populate_data() def init_ui(self): # Table setup self.mesh_table = QtGui.QTableWidget() self.mesh_table.setRowCount(len(self.all_mesh)) self.mesh_table.setColumnCount(3) self.mesh_table.setHorizontalHeaderLabels(['Mesh Found', 'Color for Mesh']) self.md_insert_color_btn = QtGui.QPushButton('Apply color') # Layout self.layout = QtGui.QVBoxLayout() self.layout.addWidget(self.mesh_table) self.layout.addWidget(self.md_insert_color_btn) self.setLayout(self.layout) 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 found in scene and append them into rows self.mesh_table.setItem(row_index, 0, new_item) geo_exclude_num = ''.join(i for i in geo_item if not i.isdigit()) color_list = read_json(geo_exclude_num) color_list.add("") # Insert in the color color_combobox = QtGui.QComboBox() #color_list = get_color() color_combobox.addItems(list(sorted(color_list))) self.mesh_table.setCellWidget(row_index, 1, color_combobox) self.color_value_to_combobox(geo_item, color_combobox) # Pass the object and combobox you want to set # This use to work on all mesh objects, but only edits a single combobox. This is wrong! def color_value_to_combobox(self, node, combobox): # This attribute is stored in the Extra Attributes objAttr = '%s.pyPickle'%node storedData = attrToPy(objAttr) if 'color_set' in storedData: color_variant = storedData['color_set'] combo_index = combobox.findText(color_variant, QtCore.Qt.MatchFixedString) combobox.setCurrentIndex(0 if combo_index &lt; 0 else combo_index) # Needs to work on the proper combobox! # To opent the dialog window dialog = testTableView() dialog.show() </code></pre>
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 the value <code>2</code>, but this has to be updated to value <code>3</code>, if the Kanji is in <code>kanji_n3</code>.</p> <p>tableclass.py</p> <pre><code>import sqlalchemy as sqla from sqlalchemy.orm import relationship import sqlalchemy.ext.declarative as sqld sqla_base = sqld.declarative_base() class TableKanji(sqla_base): __tablename__ = 'Kanji' id = sqla.Column(sqla.Integer, primary_key=True) character = sqla.Column(sqla.String, nullable=False) misc = relationship("TableMisc", back_populates='kanji') class TableMisc(sqla_base): __tablename__ = 'Misc' kanji_id = sqla.Column(sqla.Integer, sqla.ForeignKey('Kanji.id'), primary_key=True) jlpt = sqla.Column(sqla.Integer) kanji = relationship("TableKanji", back_populates="misc") </code></pre> <p>So the query I came up with is, kanjiorigin_index.py:</p> <pre><code>import sqlalchemy as sqla import sqlalchemy.orm as sqlo from tableclass import TableKanji, TableMisc kanji_n3 = ['政', '議', '民', '連'] # But then with 367 Kanji session.query(TableMisc)\ .filter(TableMisc.jlpt == 2).filter(TableKanji.character in kanji_n3)\ .update({TableMisc.jlpt: TableMisc.jlpt + 1}, synchronize_session='fetch') </code></pre> <p>This runs succesfully, but doesn't update anything. The output:</p> <pre><code>2016-10-18 04:05:53,908 INFO sqlalchemy.engine.base.Engine SELECT CAST('test plain returns' AS VARCHAR(60)) AS anon_1 2016-10-18 04:05:53,908 INFO sqlalchemy.engine.base.Engine () 2016-10-18 04:05:53,908 INFO sqlalchemy.engine.base.Engine SELECT CAST('test unicode returns' AS VARCHAR(60)) AS anon_1 2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine () 2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine BEGIN (implicit) 2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine SELECT "Misc".kanji_id AS "Misc_kanji_id" FROM "Misc" WHERE 0 = 1 2016-10-18 04:05:53,909 INFO sqlalchemy.engine.base.Engine () 2016-10-18 04:05:53,910 INFO sqlalchemy.engine.base.Engine UPDATE "Misc" SET jlpt=("Misc".jlpt + ?) WHERE 0 = 1 2016-10-18 04:05:53,910 INFO sqlalchemy.engine.base.Engine (1,) 2016-10-18 04:05:53,911 INFO sqlalchemy.engine.base.Engine COMMIT </code></pre> <h2>Question</h2> <p>How do I update <code>TableMisc.jlpt</code> where the current value is 2 and where TableKanji.character is in <code>kanji_n3</code>? Does my <code>in kanji_n3</code> statement not work like this? I also tried to add an <code>.outerjoin(TableKanji)</code>, but this results in:</p> <pre><code>sqlalchemy.exc.InvalidRequestError: Can't call Query.update() or Query.delete() when join(), outerjoin(), select_from(), or from_self() has been called </code></pre>
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 than update all selected records like this:</p> <pre><code>records = session.query(TableMisc).\ join(TableKanji).\ filter(TableMisc.jlpt == 2).\ filter(TableKanji.character.in_(kanji_n3)).\ all() for record in records: record.jlpt += 1 session.commit() </code></pre>
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 = np.ones((num, 1)) Y = np.ones((num, 1)) Z = np.zeros((num, 1)) def add(X,Y,Z,j): Z[j] = X[j] + Y[j] if __name__ == '__main__': jobs = [] for i in range(numThreads): p = Process(target=add, args=(X, Y, Z, i,)) jobs.append(p) for i in range(numThreads): jobs[i].start() for i in range(numThreads): jobs[i].join() print Z[0] </code></pre> <p>Edit: Took advice of clocker, and changed my code to this:</p> <pre><code>import multiprocessing import numpy as np numThreads = 16 numRows = 32000 numCols = 2 numOut = 3 stride = numRows / numThreads X = np.ones((numRows, numCols)) W = np.ones((numCols, numOut)) B = np.ones((numRows, numOut)) Y = np.ones((numRows, numOut)) def conv(idx): Y[idx*stride:idx*stride+stride] = X[idx*stride:idx*stride+stride].dot(W) + B[idx*stride:idx*stride+stride] if __name__=='__main__': pool = multiprocessing.Pool(numThreads) pool.map(conv, range(numThreads)) print Y </code></pre> <p>And the output is Y instead of a Saxp.</p>
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.</p> <p>If you were to use the <code>threading module</code> instead the last line would indeed return [2] as expected, but that is not multi-processing. </p> <p>So, you probably want to use <code>multiprocessing.Pool</code> instead. Going along your experiment purely for illustration, one could do the following:</p> <pre><code>In [40]: pool = multiprocessing.Pool() In [41]: def add_func(j): ....: return X[j] + Y[j] In [42]: pool = multiprocessing.Pool(numThreads) In [43]: pool.map(add_func, range(numThreads)) Out[43]: [array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.]), array([ 2.])] </code></pre> <p>Have fun!</p> <p>For your second part to your question, the problem is that the conv() function does not return any value. While the process pool gets a copy of X, B and W for pulling values from, the Y inside conv() is local to each process that is launched. To get the new computed value of Y, you would use something like this:</p> <pre><code>def conv(idx): Ylocal_section = X[idx*stride:idx*stride+stride].dot(W) + B[idx*stride:idx*stride+stride] return Ylocal_section results = pool.map(conv, range(numThreads)) # then apply each result to Y for idx in range(numThreads): Y[idx*stride:idx*stride+stride] = results[idx] </code></pre> <p>Parallelism can get complicated really fast, and at this point I would evaluate existing libraries that can perform fast 2D convolution. numpy and scipy libraries can be super efficient and might serve your needs better.</p>
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.CharField(max_length=20) class Residents(models.Model): name = models.CharField(max_length=20) age = models.PositiveSmallIntegerField() country = models.ForeignKey('Country', related_name='residents') </code></pre> <p>When I code like this</p> <pre><code>result = Country(**data) </code></pre> <p>I got exception </p> <blockquote> <p>'residents' is an invalid keyword argument for this function</p> </blockquote> <p>How can I convert it to class object that I can access residents with result.residents[idx]?</p>
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></pre> <p><em>How come by default <code>.head()</code> method took 5 rows without mentioning in the bracket?</em> </p>
-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">link to stackoverflow docs</a></p> <p><strong><em>copied from documentation</em></strong> </p> <blockquote> <pre><code>DataFrame.head(n=5) Returns first n rows </code></pre> </blockquote> <p>It is how we establish default parameter values in python. For the <code>head</code> method, <code>n=5</code> means that the default value is 5 and consequently, if you do not pass a parameter value yourself, then 5 is used.</p>
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.output </code></pre> <p>Now, I want to make sure that users create an output file that is a text file, with extension <code>.txt</code>. </p> <p>(1) I could possible through an error, telling users that they <em>must</em> use a txt extension. </p> <p>(2) I could check whether a <code>.txt</code> extension has been used. If not, I would simply add it. </p> <p>The first is relatively easy:</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.output if file_output.endswith("txt") != True: raise argparse.ArgumentTypeError('File must end in extension .txt!') </code></pre> <p>How would one accomplish the latter? </p>
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('-o',type=txtname); In [728]: parser.parse_args(['-i','inname','-o','oname.txt']) Out[728]: Namespace(i='inname.txt', o='oname.txt') </code></pre> <p>That function could also raise a ValueError if you don't like certain extensions or forms of filename.</p>
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 got is:-</p> <pre><code>['some', 'line', 'with', 'text'] [] </code></pre> <p>output that i need to get is :</p> <pre><code>with </code></pre> <p>My idea is to use slicing , so i used [-2:-2] such that it will print 2nd word from last in the list but when i run the script, i am getting 'empty list' at the output.</p>
-3
2016-10-18T04:59:33Z
40,100,154
<p>Yo need to print from 2nd last element from list - </p> <pre><code>&gt;&gt;&gt; list_sentecne = ['some', 'line', 'with', 'text'] &gt;&gt;&gt; op = list_sentecne[-2:] &gt;&gt;&gt; print (op) ['with', 'text'] </code></pre> <p>if only the 2nd last element </p> <pre><code>&gt;&gt;&gt; list_sentecne = ['some', 'line', 'with', 'text'] &gt;&gt;&gt; op = list_sentecne[-2] &gt;&gt;&gt; print (op) 'with' </code></pre>
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) loop.run_forever() </code></pre> <p><strong>B</strong></p> <pre><code>loop.create_task(coro1) loop.create_task(coro2) loop.run_forever() </code></pre> <p><strong>C</strong></p> <pre><code>loop.create_task(coro1) loop.run_until_complete(coro2) loop.run_forever() </code></pre> <p>etc.</p>
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</code>. <code>coro2</code> will run until it's told to await. At that point the loop will check to see if <code>coro1</code> is ready to resume. This will repeat until both are finished and then the loop will just wait. </p> <p>In your final example, <code>coro2</code> starts first, following the same back and forth as the previous example, and then the process will stop once it, <code>coro2</code>, is done. Then <code>coro1</code> will resume until it's done and then the loop will just wait. </p> <p>A fourth example is</p> <pre><code>loop.run_until_complete( asyncio.gather( asyncio.ensure_future(coro1), asyncio.ensure_future(coro2), ) ) </code></pre> <p>It will behave like the second example except it will stop once both are complete. </p>
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, incomplete datetime object, a completely random string, a missing value or a value for the other column which is way out of range (measured values are mostly between 10 and 50, but sometimes I get a zero or a value like 100).</p> <p>extract from the large dataset (loaded as pandas dataframe):</p> <pre><code> t baaa 0 13/11/2014 23:43 17.6 1 13/11/2014 23:44 17.7 2 2014-11-13 23:452014-11-13 23:45:00 17.7 3 13/11/2014 23:46 17.7 4 14/11/2014 00:34 16 5 14/11/2014 00:35 15.9 6 :00 17.7 7 14/11/2014 01:25 14.9 8 14/11/2014 01:26 14.9 9 0 80 10 14/11/2014 02:16 14.3 11 14/11/2014 02:17 14.3 12 NaN AA550112209500080009002855AA 13 14/11/2014 03:09 13 14 009000B002B55AA NaN 15 14/11/2014 02:19 14.3 16 14/11/2014 03:59 12.6 17 14/11/2014 04:00 12.6 18 14/11/2014 05:41 11.7 19 14/11/2014 05:42 11.7 20 0 140 21 14/11/2014 04:53 12.2 </code></pre> <p>examples of all types of faulty entries are here. How can I get rid of the faulty lines? My idea was to do an if loop, setting the condition that the 't' column should be a datetime object and the 'baaa' columns should be a float > 0 and &lt; 60. If the condition is not fulfilled, I would replace the value with <code>np.nan</code> and eventually use the <code>dropna</code> function. </p> <pre><code>df['t'] = pd.to_datetime(df['t'], format = '%d/%m/%Y %H:%M', errors='coerce') df.iloc[:,1] = pd.to_numeric(df.iloc[:,1], errors='coerce') for line in df.iloc[:,1]: if (line &lt; 60) &amp; (line &gt; 0): line = line else: line = np.nan # not assigning this new value! :( df = df.dropna(subset = df.columns.values, how='any', inplace=True) </code></pre> <p>This seems to have solved most of the problems except the condition that the line needs to be lower than 60. I must have a wrong syntax? Or what is wrong here? Thanks!</p>
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 new (third) condition with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.notnull.html" rel="nofollow"><code>notnull</code></a> - get all not <code>NaN</code> values in column <code>t</code>. <code>NaN</code> values in first column are filtered by first and second condition:</p> <pre><code>df['t'] = pd.to_datetime(df['t'], format = '%d/%m/%Y %H:%M', errors='coerce') df.iloc[:,1] = pd.to_numeric(df.iloc[:,1], errors='coerce') df = df[(df.iloc[:,1] &lt; 60) &amp; (df.iloc[:,1] &gt; 0) &amp; (df['t'].notnull())] print (df) t baaa 0 2014-11-13 23:43:00 17.6 1 2014-11-13 23:44:00 17.7 3 2014-11-13 23:46:00 17.7 4 2014-11-14 00:34:00 16.0 5 2014-11-14 00:35:00 15.9 7 2014-11-14 01:25:00 14.9 8 2014-11-14 01:26:00 14.9 10 2014-11-14 02:16:00 14.3 11 2014-11-14 02:17:00 14.3 13 2014-11-14 03:09:00 13.0 15 2014-11-14 02:19:00 14.3 16 2014-11-14 03:59:00 12.6 17 2014-11-14 04:00:00 12.6 18 2014-11-14 05:41:00 11.7 19 2014-11-14 05:42:00 11.7 21 2014-11-14 04:53:00 12.2 </code></pre>
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 ├── mysite │ ├── __init__.py │ │ ├── __pycache__ │ ├── settings.py │ │ ├── urls.py │ └── wsgi.py └── polls ├── __init__.py ├── __pycache__ ├── admin.py ├── models.py ├── tests.py ├── urls.py ├── views.py └── apps.py </code></pre> <p>mysite\urls.py</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin import polls urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>INSTALLED_APPS in settings.py</p> <pre><code> INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ] </code></pre> <p>And there is another problem in the document,the document types:</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] </code></pre> <p>When i run it,it says cannot import name 'views',i delete the from .,then it works.But the problem above still don't solve,can anyone tell me why??</p>
-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 ├── mysite │ ├── __init__.py │ │ ├── __pycache__ │ ├── settings.py │ │ ├── urls.py │ └── wsgi.py └── polls ├── __init__.py ├── __pycache__ ├── admin.py ├── models.py ├── tests.py ├── urls.py ├── views.py └── apps.py </code></pre> <p>mysite\urls.py</p> <pre><code>from django.conf.urls import include, url from django.contrib import admin import polls urlpatterns = [ url(r'^polls/', include('polls.urls')), url(r'^admin/', admin.site.urls), ] </code></pre> <p>INSTALLED_APPS in settings.py</p> <pre><code> INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ] </code></pre> <p>And there is another problem in the document,the document types:</p> <pre><code>from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] </code></pre> <p>When i run it,it says cannot import name 'views',i delete the from .,then it works.But the problem above still don't solve,can anyone tell me why??</p>
-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 suggest restarting the tutorial, because clearly the environment has not been setup accordingly. The code is perfectly fine in the other hand.</p>
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: session identifier,cpu used, ram,iops and their values. This data will be written in sessions of a few hours (so ~25K-50K entries per session)</p> <p>On the server side: Data will be processed having the <code>'session'</code> identified, plotted and saved to a <code>cpu graph png/ram graph png</code> etc. Also it will write to a separate collection in <code>mongodb</code> identification that will be used to gather and present this data in a webpage. The page will have the possibility to start the client on the remote machine.</p> <p>Is this approach optimal? Is there a better but simple way to store the data ? Can I make the page construct and display the session dynamically to be used for example to zoom. Will mongo be able to store/save hundreds of millions of entries like this ? </p> <p>I was thinking on using <code>angular + nodejs</code> or <code>angular + flask</code> on the server and mongodb. I don't know flask or node, which will be easier to use for creating a simple REST.</p> <p>My skill levels: python advanced, javascript/html/css medium, angularjs 1 beginner. </p>
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 and forth between your server and client, which is a performance bottleneck.</p> <p>Angular is perfectly fine for this, as you will not need to manually update your model data on the front end, thanks to two-way data binding.</p> <p>There are many charting frameworks and libraries like D3.js and HighCharts that can be plugged into your front end to chart your data, use it according to your liking. </p>
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 = threading.Thread( target=worker ) t.daemon=True t.start() </code></pre>
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>You can use <a href="https://docs.python.org/3/library/threading.html#threading.Lock" rel="nofollow">locks</a> to prevent that:</p> <pre><code>lock = threading.Lock() def worker(): lock.acquire() if set_this_var_only_once is None: set_this_var_only_once = "not None" lock.release() </code></pre> <p>Only one thread will be able to <em>acquire</em> the lock. If another thread tries to acquire it while it is locked, the call to <code>lock.acquire()</code> will block and wait until the lock is <em>released</em> by the first thread. Then the lock will be acquired by the other thread.</p> <p>That way it is ensured that the code between <code>lock.acquire()</code> and <code>lock.release()</code> is executed in one thread at a time.</p> <p><strong>EDIT</strong></p> <p>As Gerhard pointed in <a href="http://stackoverflow.com/a/40100334/389289">the other answer</a>, you can use the <a href="https://docs.python.org/3/library/threading.html#with-locks" rel="nofollow">context management protocol</a> with locks:</p> <pre><code>with lock: if set_this_var_only_once is None: set_this_var_only_once = "not None" </code></pre> <p>That will also make sure the lock is correctly released in case of an exception within the locked block.</p>
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 = threading.Thread( target=worker ) t.daemon=True t.start() </code></pre>
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 accounted for.</p> </blockquote> <p><a href="http://effbot.org/zone/thread-synchronization.htm" rel="nofollow">Here's</a> this good article about it. </p> <p>P.S. Also the following line is needed in the worker(): </p> <pre><code>global set_this_var_only_once </code></pre>
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 = threading.Thread( target=worker ) t.daemon=True t.start() </code></pre>
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 read in multiple threads in parralel? Sice it might be important, I'm currently forced to run under Windows -- just in case that makes any difference.</p> <pre><code>from dask import dataframe as ddf df = ddf.read_csv("data/Measurements*.csv", sep=';', parse_dates=["DATETIME"], blocksize=1000000, ) df.categorize([ 'Type', 'Condition', ]) df.to_hdf("data/data.hdf", "Measurements", 'w') </code></pre>
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 exception, especially if your resulting dataframes use object dtypes for text</p> <h3>dask.dataframe.to_hdf(filename) forces sequential computation</h3> <p>Writing to a single HDF file will force sequential computation (it's very hard to write to a single file in parallel.)</p> <h3>Solution</h3> <p>Because your dataset likely fits in memory, use dask.dataframe.read_csv to load in parallel with multiple processes, then switch immediately to Pandas.</p> <pre><code>import dask.dataframe as dd import dask.multiprocessing df = df = ddf.read_csv("data/Measurements*.csv", # read in parallel sep=';', parse_dates=["DATETIME"], blocksize=1000000, ) df = df.compute(get=dask.multiprocessing.get) # convert to pandas df['Type'] = df['Type'].astype('category') df['Condition'] = df['Condition'].astype('category') df.to_hdf('data/data.hdf', 'Measurements', format='table', mode='w') </code></pre>
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('auth.User') title = models.CharField(max_length=200) client = models.CharField(max_length=200) date = models.DateField(timezone.now()) service = models.CharField(max_length=200) info = models.TextField() photo = models.ImageField(upload_to='ports/static/img/', default='ports/static/img/port_photo.png', height_field='photo_height', width_field='photo_width',) photo_height = models.PositiveIntegerField(blank=True, default=900) photo_width = models.PositiveIntegerField(blank=True, default=650) created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) </code></pre> <p><br></p> <p>index.html</p> <pre><code>&lt;section id="portfolio"&gt; {% for project in projects %} &lt;div class="row"&gt; &lt;div class="col-lg-12 text-center"&gt; &lt;h2&gt;Portfolio&lt;/h2&gt; &lt;hr class="star-primary"&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div class="col-sm-4 portfolio-item"&gt; &lt;a href="#portfolioModal1" class="portfolio-link" data-toggle="modal"&gt; &lt;div class="caption"&gt; &lt;div class="caption-content"&gt; &lt;i class="fa fa-search-plus fa-3x"&gt;&lt;/i&gt; &lt;/div&gt; &lt;/div&gt; &lt;img src="{{ projects.photo.url }}" class="img-responsive" alt=""&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; {% endfor %} &lt;/section&gt; </code></pre> <p>views.py</p> <pre><code>from django.shortcuts import render from .forms import ContactForm from django.utils import timezone from .models import Project # Create your views here. def index(request): form_class = ContactForm projects = Project.objects.filter(published_date__lte=timezone.now()).order_by('-published_date') return render(request, 'ports/index.html', {'form': form_class, 'projects': projects}) </code></pre>
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,blank=False) categories = models.ManyToManyField(Category) </code></pre> <p>So in view I need to query all the posts with specific category for example This is the url <a href="http://example.com/?category=slug1,slug2" rel="nofollow">http://example.com/?category=slug1,slug2</a> or <a href="http://example.com/?category=1,2" rel="nofollow">http://example.com/?category=1,2</a> - PK or slug will be used</p> <p><strong>views.py</strong></p> <pre><code>class PostList(TemplateView): ... def get(self,request,*args,**kwargs): categories = request.GET.get('category') post_list = Post.objects().filter(categories__in=categories) ... </code></pre> <p>The above view throws error as <code>invalid literal for int() with base 10: ','</code> because of passing comma separated strings, but how can I achieve this?</p>
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&amp;category=slug2</code>. </p> <p>Then you could use</p> <p><code>categories = request.GET.getlist('category')</code></p>
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 also supplied by Physionet) and finally print the signal values and its period.</p> <p>I wanted to write a script that could do all of those things to all the files in one folder. Before this, I wrote one in which I could do everythin mentioned above and it worked nicely. </p> <p>But the script that would manage all the .mat and .info files in my folder is giving me problems with the variables. I tried using the 'global' command in the very beginning of my succession of IFs, but it kept sending a similar error message. </p> <p>This is the code:</p> <pre><code>import os import scipy.io as sio import numpy as np import re import matplotlib.pyplot as plt for file in os.listdir('C:blablablablabla\Multiple .mat files'): if file.endswith(".mat"): file_name=os.path.splitext(file) ext_txt=".txt" ext_info=".info" if file.endswith(".info"): f=open(file_name[0]+ext_info,'r') k=f.read() f.close() j=re.findall('\d+', k) Fs=j[9] gain=j[13] base=j[14] RawData=sio.loadmat(file) signalVectors=RawData['val'] [a,b]=signalVectors.shape signalVectors_2=np.true_divide((signalVectors-gain),base) ecgSignal=signalVectors_2[1,1:] T=np.true_divide(np.linspace(1,b,num=b-1),Fs) txt_data=np.array([ecgSignal, T]) txt_data=txt_data.T f=open(file_name[0]+ext_name,'w') np.savetxt(file_name[0]+ext_txt,txt_data,fmt=['%.8f','%.8f']) f.close() </code></pre> <p>The error message I get is: </p> <pre><code>&gt; File "C:blablablablabla\Multiple .mat files\ecg_mat_multi.py", line 24, in &lt;module&gt; signalVectors_2=np.true_divide((signalVectors-gain),base) NameError: name 'gain' is not defined </code></pre> <p>The problem comes with the variables 'gain', 'base' and 'Fs'. I tried to define them as global variables, but that didn't make a difference. Can you help me fix this error, please?</p> <p>Thanks a lot for your time and help.</p> <p>EDIT 1: copied the error message below the script. EDIT 2: Changed the post title and erased additional questions. </p>
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'): if file.endswith(".mat"): file_name=os.path.splitext(file) ... RawData=sio.loadmat(file) signalVectors=RawData['val'] ... </code></pre> <hr> <p>I was working off your first edit so I'll include this even though the question has been <em>streamlined</em></p> <pre><code># foo.info Source: record mitdb/100 Start: [00:00:10.000] val has 2 rows (signals) and 3600 columns (samples/signal) Duration: 0:10 Sampling frequency: 360 Hz Sampling interval: 0.002777777778 sec Row Signal Gain Base Units 1 MLII 200 1024 mV 2 V5 200 1024 mV To convert from raw units to the physical units shown above, subtract 'base' and divide by 'gain'. </code></pre> <p>I would also write a function that returns the info you want. Using a function to extract the info makes the code in your <em>loop</em> more readable and it makes it easier to test the extraction.</p> <p>Since the file is well structured, you could probably iterate over the lines and extract the info by counting lines and using <code>str.split</code> and slices.</p> <p>This function uses regex patterns to extract the info:</p> <pre><code># regex patterns hz_pattern = r'frequency: (\d+) Hz' mlii_pattern = r'MLII\t(\d+)\t(\d+)' def get_info(filepath): with open(filepath) as f: info = f.read() match = re.search(hz_pattern, info) Fs = match.group(1) match = re.search(mlii_pattern, info) gain, base = match.groups() return map(int, (Fs, gain, base)) </code></pre> <hr> <p>If there are multiple .info and .mat files in a directory, you want to ensure you extract the correct info for the data. Since the .info file has the same name as the .mat file that it <em>belongs</em> to, sort the directory list by name then group by name -this will ensure you are operating on the two files that are related to each other.</p> <pre><code>import itertools def name(filename): name, extension = filename.split('.') return name files = os.listdir('C:blablablablabla\Multiple .mat files') files.sort(key = name) for fname, _ in itertools.groupby(files, key = name): fname_info = name + '.info' fname_data = name + '.mat' Fs, gain, base = get_info(fname_info) # process datafile </code></pre>
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, and so on. The Master script would collect the variables (as defined in files or from command line arguments) and execute the appropriate script with this sort of syntax:</p> <pre><code>VAR1=foo VAR2=bar ./Scripts/${VAR1}_${VAR2}.x </code></pre> <p>This would execute Scripts/foo_bar.x</p> <p>Now I'm trying to do the same but in python. The scripts are now modules in the folder Modules named foo_bar.py, foo_qux.py and so on. For now, the only thing they have is:</p> <pre><code>def test(): print "This is foo_bar." </code></pre> <p>(or whichever).</p> <p>If use these commands, this happens:</p> <pre><code>&gt;&gt;&gt; import Modules.foo_bar &gt;&gt;&gt; Modules.foo_bar.test() This is foo_bar. &gt;&gt;&gt; import Modules.foo_qux &gt;&gt;&gt; Modules.foo_qux.test() This is foo_qux. &gt;&gt;&gt; a = Modules.foo_bar &gt;&gt;&gt; a.test() This is foo_bar. </code></pre> <p>Which is fine. However, I can't get the syntax right if I want to use variables in the import statement. The first variable is defined as the string output of a command, and the second is a dictionary entry. Trying to use them in an import command gives an error.</p> <pre><code>&gt;&gt;&gt; var1 = a_file.read_value() &gt;&gt;&gt; print var1 foo &gt;&gt;&gt; print dict['var2'] bar &gt;&gt;&gt; import Modules.var1_dict['var2'] File "&lt;stdin&gt;", line 1 import Modules.var1_dict['var2'] ^ SyntaxError: invalid syntax </code></pre> <p>I assume it's a question of having the correct quotes or parentheses to properly invoke the variables. I've tried a bunch of combinations involving single quotes, curly brackets, square brackets, whatever, but no dice. What am I missing?</p>
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>&gt;&gt;&gt; d = { 1:'re', 2:'numpy' } </code></pre> <p>Now, let's import one of them:</p> <pre><code>&gt;&gt;&gt; x = __import__(d[1]) &gt;&gt;&gt; x &lt;module 're' from '/usr/lib/python2.7/re.pyc'&gt; </code></pre> <p>We can use the module as long as we refer to it by the name we have given it:</p> <pre><code>&gt;&gt;&gt; s='jerry'; x.sub('j', 'J', s) 'Jerry </code></pre> <p>And, to import the other:</p> <pre><code>&gt;&gt;&gt; y = __import__(d[2]) &gt;&gt;&gt; y &lt;module 'numpy' from '/home/jll/.local/lib/python2.7/site-packages/numpy/__init__.pyc'&gt; &gt;&gt;&gt; y.array([1,3,2]) array([1, 3, 2]) </code></pre>
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, and so on. The Master script would collect the variables (as defined in files or from command line arguments) and execute the appropriate script with this sort of syntax:</p> <pre><code>VAR1=foo VAR2=bar ./Scripts/${VAR1}_${VAR2}.x </code></pre> <p>This would execute Scripts/foo_bar.x</p> <p>Now I'm trying to do the same but in python. The scripts are now modules in the folder Modules named foo_bar.py, foo_qux.py and so on. For now, the only thing they have is:</p> <pre><code>def test(): print "This is foo_bar." </code></pre> <p>(or whichever).</p> <p>If use these commands, this happens:</p> <pre><code>&gt;&gt;&gt; import Modules.foo_bar &gt;&gt;&gt; Modules.foo_bar.test() This is foo_bar. &gt;&gt;&gt; import Modules.foo_qux &gt;&gt;&gt; Modules.foo_qux.test() This is foo_qux. &gt;&gt;&gt; a = Modules.foo_bar &gt;&gt;&gt; a.test() This is foo_bar. </code></pre> <p>Which is fine. However, I can't get the syntax right if I want to use variables in the import statement. The first variable is defined as the string output of a command, and the second is a dictionary entry. Trying to use them in an import command gives an error.</p> <pre><code>&gt;&gt;&gt; var1 = a_file.read_value() &gt;&gt;&gt; print var1 foo &gt;&gt;&gt; print dict['var2'] bar &gt;&gt;&gt; import Modules.var1_dict['var2'] File "&lt;stdin&gt;", line 1 import Modules.var1_dict['var2'] ^ SyntaxError: invalid syntax </code></pre> <p>I assume it's a question of having the correct quotes or parentheses to properly invoke the variables. I've tried a bunch of combinations involving single quotes, curly brackets, square brackets, whatever, but no dice. What am I missing?</p>
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, and so on. The Master script would collect the variables (as defined in files or from command line arguments) and execute the appropriate script with this sort of syntax:</p> <pre><code>VAR1=foo VAR2=bar ./Scripts/${VAR1}_${VAR2}.x </code></pre> <p>This would execute Scripts/foo_bar.x</p> <p>Now I'm trying to do the same but in python. The scripts are now modules in the folder Modules named foo_bar.py, foo_qux.py and so on. For now, the only thing they have is:</p> <pre><code>def test(): print "This is foo_bar." </code></pre> <p>(or whichever).</p> <p>If use these commands, this happens:</p> <pre><code>&gt;&gt;&gt; import Modules.foo_bar &gt;&gt;&gt; Modules.foo_bar.test() This is foo_bar. &gt;&gt;&gt; import Modules.foo_qux &gt;&gt;&gt; Modules.foo_qux.test() This is foo_qux. &gt;&gt;&gt; a = Modules.foo_bar &gt;&gt;&gt; a.test() This is foo_bar. </code></pre> <p>Which is fine. However, I can't get the syntax right if I want to use variables in the import statement. The first variable is defined as the string output of a command, and the second is a dictionary entry. Trying to use them in an import command gives an error.</p> <pre><code>&gt;&gt;&gt; var1 = a_file.read_value() &gt;&gt;&gt; print var1 foo &gt;&gt;&gt; print dict['var2'] bar &gt;&gt;&gt; import Modules.var1_dict['var2'] File "&lt;stdin&gt;", line 1 import Modules.var1_dict['var2'] ^ SyntaxError: invalid syntax </code></pre> <p>I assume it's a question of having the correct quotes or parentheses to properly invoke the variables. I've tried a bunch of combinations involving single quotes, curly brackets, square brackets, whatever, but no dice. What am I missing?</p>
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: {8: 3, 18: 2}, 8: {16: 5, 9: 10, 6: 2, 7: 3}, 9: {8: 10, 10: 3, 5: 5}, 10: {16: 4, 9: 3, 11: 5, 17: 8, 15: 6}, 11: {12: 6, 10: 5, 4: 6, 14: 4}, 12: {11: 6, 3: 4, 13: 3}, 13: {24: 4, 12: 3}, 14: {23: 4, 11: 4, 15: 5}, 15: {10: 6, 19: 3, 22: 3, 14: 5}, 16: {8: 5, 17: 2, 10: 4, 18: 3}, 17: {16: 2, 10: 8, 19: 2}, 18: {16: 3, 20: 4, 7: 2}, 19: {17: 2, 20: 4, 15: 3}, 20: {18: 4, 19: 4, 21: 6, 22: 5}, 21: {24: 3, 20: 6, 22: 2}, 22: {23: 4, 20: 5, 21: 2, 15: 3}, 23: {24: 2, 22: 4, 14: 4}, 24: {23: 2, 13: 4, 21: 3}} </code></pre> <p>So, every node is connected to some other nodes having a travel time associated with it. </p> <p>So I started by creating a program by defining node lables and node predecessor. While going through the loop, my node label updates if my previous node label + current travel time is less than than the current node label. I also update the predecessor if I update this travel time. </p> <pre><code>import xlrd # import xlrd python package to play with excel files file_location = "C:/Users/12/Desktop/SiouxFalls_net1.xlsx" #defining excel file location workbook = xlrd.open_workbook(file_location) #assigning workbook sheet = workbook.sheet_by_index(0) #assigning sheet of that workbook graph = {} #initializing dictionary for graph # as dataset includes a header file then skip the first step by setting rows!=0 for rows in range(sheet.nrows): #This will read no. of rows if(rows != 0): a = int(sheet.cell_value(rows, 0)) b = int(sheet.cell_value(rows, 1)) c = int(sheet.cell_value(rows, 4)) #etdefault() creates a new entry (empty dictionary in this case) only if there is no such entry associated with the # given key. Then it returns the entry (either the newly created empty or the existing one), # so we add into the entry (which is nested dictionary) the new relation. graph.setdefault(a, {})[b] = c graph.setdefault(b, {})[a] = c # Reading Nodes nodes = [] label = {} for rows in range(sheet.nrows): if(rows != 0): x = int(sheet.cell_value(rows, 0)) if x not in nodes: #to get unique values from the column nodes.append(x) start_node = int(input('Enter the origin')) end_node = int(input('Enter the destination')) SEL = [start_node] pred = {start_node: 0 } for i in nodes: if(i == start_node): label[i] = 0 else: label[i] = 100000000 for a in SEL: print(a) SEL.remove(a) print(SEL) for b, c in graph[a].items(): print('checking' + str(b)) if (label[b] &gt; label[a] + c): label[b] = label[a] + c pred[b] = a SEL.append(b) print(SEL) </code></pre> <p>So I remove SEL every time, in order to check labels and predecessor, and add a node to SEL, if something is updated. So, at the end my SEL should be empty, but my for loop stop arbitrarily in the middle without finishing SEL list. I don't know why?he </p> <p>I can show you one example, I am giving start node 15 and end node 5 as the destination, and just to check out I am printing everything within the loop. This is the output:</p> <pre><code>Enter the origin15 Enter the destination5 15 [] checking10 [10] checking19 [10, 19] checking22 [10, 19, 22] checking14 [10, 19, 22, 14] 19 [10, 22, 14] checking17 [10, 22, 14, 17] checking20 [10, 22, 14, 17, 20] checking15 14 [10, 22, 17, 20] checking23 [10, 22, 17, 20, 23] checking11 [10, 22, 17, 20, 23, 11] checking15 20 [10, 22, 17, 23, 11] checking18 [10, 22, 17, 23, 11, 18] checking19 checking21 [10, 22, 17, 23, 11, 18, 21] checking22 11 [10, 22, 17, 23, 18, 21] checking12 [10, 22, 17, 23, 18, 21, 12] checking10 checking4 [10, 22, 17, 23, 18, 21, 12, 4] checking14 21 [10, 22, 17, 23, 18, 12, 4] checking24 [10, 22, 17, 23, 18, 12, 4, 24] checking20 checking22 4 [10, 22, 17, 23, 18, 12, 24] checking11 checking3 [10, 22, 17, 23, 18, 12, 24, 3] checking5 [10, 22, 17, 23, 18, 12, 24, 3, 5] 3 [10, 22, 17, 23, 18, 12, 24, 5] checking1 [10, 22, 17, 23, 18, 12, 24, 5, 1] checking4 checking12 1 [10, 22, 17, 23, 18, 12, 24, 5] checking2 [10, 22, 17, 23, 18, 12, 24, 5, 2] checking3 Process finished with exit code 0 </code></pre> <p>I want my for loop to continue until my SEL is empty. Please help</p>
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] &gt; label[a] + c): label[b] = label[a] + c pred[b] = a SEL.append(b) print(SEL) </code></pre> <p>You are appending SEL inside the loop in your code. This change does not get picked up inside <code>for a in SEL</code>. That's the reason why your loop finishes early.</p>
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 tranlating unicode to gb2312 but <code>u'囧'</code> is not in that map?</p>
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 following error while running the code to train the model, </p> <pre><code>Traceback (most recent call last): File "MultiLayerPerceptron.py", line 121, in &lt;module&gt; summary_writer2 = tf.train.SummaryWriter(logs_path, graph=sess.graph()) TypeError: 'Graph' object is not callable </code></pre> <p>also what's the difference between the default graph as in <code>summary_writer1</code> and graph in <code>summar_writer2</code></p>
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</strong>. Just remove the <code>()</code> from <code>graph=sess.graph()</code> and everything will work as you expect.</p>
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/posts/2013/05/28/introduction-to-return-oriented-programming-rop.html" rel="nofollow">this</a>. I am trying to follow example under section chaining functions) <br> Now I have written another C code but it takes 3 command line arguments. So my string should be arg[1] + " " + arg[2] + " " + payloadString. (The c code is converting the arg[1] and arg[2] into integer to use it in its functions). Here is the snippet of my python code:</p> <pre><code>p = "10 " #arg[1] p += "10 " #arg[2] p += "string without spaces which I need as payload" #arg[3] os.system("./a.out \"%s\"" % p) </code></pre> <p><br> where ./a.out is executable of my C code which takes 3 command line arguments. When I run the python code I get error:</p> <pre><code>Traceback (most recent call last): File "this_file.py", line XX, in &lt;module&gt; os.system("./a.out \"%s\"" % p) TypeError: must be string without null bytes, not str </code></pre> <p><br>Can anyone help me? <br>P.S. I am new to python. Similar questions were there in stack overflow, but I am not sure how to use their answers to solve my problem.</p>
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/posts/2013/05/28/introduction-to-return-oriented-programming-rop.html" rel="nofollow">this</a>. I am trying to follow example under section chaining functions) <br> Now I have written another C code but it takes 3 command line arguments. So my string should be arg[1] + " " + arg[2] + " " + payloadString. (The c code is converting the arg[1] and arg[2] into integer to use it in its functions). Here is the snippet of my python code:</p> <pre><code>p = "10 " #arg[1] p += "10 " #arg[2] p += "string without spaces which I need as payload" #arg[3] os.system("./a.out \"%s\"" % p) </code></pre> <p><br> where ./a.out is executable of my C code which takes 3 command line arguments. When I run the python code I get error:</p> <pre><code>Traceback (most recent call last): File "this_file.py", line XX, in &lt;module&gt; os.system("./a.out \"%s\"" % p) TypeError: must be string without null bytes, not str </code></pre> <p><br>Can anyone help me? <br>P.S. I am new to python. Similar questions were there in stack overflow, but I am not sure how to use their answers to solve my problem.</p>
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(["./a.out",arg[0],arg[1],arg[2]]) </code></pre> <p>I think this should work</p>
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 above error for split(). Please help me to get out of it..... </p> <p>This is .py file</p> <pre><code>from openerp import models, fields, api import sys sys.setrecursionlimit(1500) class erp_product_template(models.Model): _name='product.template' _inherit='product.template' erp_sub=fields.Many2one("product.sub11",string="Sub Category") erp_cats=fields.Many2one("product.maincats",string="Main Category") temp1=fields.Char("Testing Char Field") temp1=erp_sub.split("/") class erp_MainModal(models.Model): _name="product.maincats" name=fields.Selection([('SL0','SL0'),('SL1','SL1'),('SL2','SL2'),('SL3','SL3'),('SL4','SL4'),('SL5','SL5'),('SL6','SL6'),('SL7','SL7'),('SL8','SL8')]) class erp_sub11(models.Model): _name="product.sub11" name=fields.Selection([('ECDS0','SL0/ECDS0'),('ECDS1','SL0/ECDS1'),('ECDS2','SL0/ECDS2'),('ECDS3','SL0/ECDS3')]) class erp_sub_sub1(models.Model): _name="product.sub_sub1" name=fields.Selection([('08','ECDS0/08'),('09','ECDS0/09'),('10','ECDS2/10'),('11','ECDS3/11')]) </code></pre> <p>This is xml file</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;openerp&gt; &lt;data&gt; &lt;record id="erp_product_template_tree_view" model="ir.ui.view"&gt; &lt;field name="inherit_id" ref="product.product_template_tree_view" /&gt; &lt;field name="model"&gt;product.template&lt;/field&gt; &lt;field name="arch" type="xml"&gt; &lt;field name="type" position="after"&gt; &lt;field name="erp_cats"/&gt; &lt;/field&gt; &lt;/field&gt; &lt;/record&gt; &lt;record id="erp_product_template_only_form_view" model="ir.ui.view"&gt; &lt;field name="inherit_id" ref="product.product_template_only_form_view" /&gt; &lt;field name="model"&gt;product.template&lt;/field&gt; &lt;field name="arch" type="xml"&gt; &lt;field name="type" position="after"&gt; &lt;field name="erp_cats"/&gt; &lt;field name="erp_sub"/&gt; &lt;/field&gt; &lt;/field&gt; &lt;/record&gt; &lt;/data&gt; &lt;/openerp&gt; </code></pre>
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(self, e): for poly in reversed(self.polys): if poly.contains(e.pos()): self.cur_poly = poly self.setCursor(Qt.PointingHandCursor) print('mouse cursor in polygon') break else: self.setCursor(Qt.CrossCursor) </code></pre> <p>For context, <code>self.polys</code> is a list of <code>QPolygons</code> and <code>e.pos()</code> is the mouse position. I have tried entering </p> <pre><code>print(poly) print(poly.contains(QPoint(1,1))) </code></pre> <p>to test if it would work for a control point, but in the console, it only gives me this:</p> <pre><code>&lt;PySide.QtGui.QPolygon(QPoint(50,350) QPoint(50,0) QPoint(0,0) QPoint(0,350) ) at 0x000000000547D608&gt; False </code></pre> <p>Is there something I am doing wrong here, or how can I convert the above "polygon" into an actual <code>QPolygon</code> that I can work with?</p> <p><strong>EDIT:</strong></p> <p>This is the code used to generate the list <code>self.polys</code>:</p> <pre><code>self.polys.append(QPolygon([QPoint(points[i][X]+self.transform[X], points[i][Y]+self.transform[Y]) for i in range(len(points))])) </code></pre> <p>Could it perhaps be a problem with using an inline for loop to add the <code>QPolygons</code> to the list?</p>
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,200)</code>, or anything that does match either of those criteria.</p> <p>What you are looking for, presumably, is a function that returns true if the point resides within the polygon, rather than on it. The function you are looking for is <code>QPolygon.containsPoint ( QPoint , Qt.FillRule )</code>. The point is as you think it is, and the second value is either a 1 or a 0 (represented as either Qt.OddEvenFill or Qt.WindingFill respectively), which determine what method of finding whether or not a point is inside a polygon. Information about Qt.FillRule can be found here: <a href="https://doc.qt.io/archives/qtjambi-4.5.2_01/com/trolltech/qt/core/Qt.FillRule.html" rel="nofollow">https://doc.qt.io/archives/qtjambi-4.5.2_01/com/trolltech/qt/core/Qt.FillRule.html</a></p> <p>corrected code:</p> <pre><code>print(poly) print(poly.containsPoint(QPoint(1,1), Qt.OddEvenFill)) </code></pre>
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>. The solution I got so far is</p> <pre><code>_dict.update({'b': n for key, value in _dict.items() if key == 'b' and n &gt; value}) </code></pre> <p>Which provides the desired result of <code>{'a': 9, 'b': 8, 'c': 'someValue'}</code>. So now to my question: Is there a shorter, more pythonic way of doing this? (preferably without importing additional modules)</p>
2
2016-10-18T06:16:31Z
40,100,868
<p>Its as simple as that</p> <pre><code>if n &gt; _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>. The solution I got so far is</p> <pre><code>_dict.update({'b': n for key, value in _dict.items() if key == 'b' and n &gt; value}) </code></pre> <p>Which provides the desired result of <code>{'a': 9, 'b': 8, 'c': 'someValue'}</code>. So now to my question: Is there a shorter, more pythonic way of doing this? (preferably without importing additional modules)</p>
2
2016-10-18T06:16:31Z
40,100,896
<pre><code>if n &gt; _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>. The solution I got so far is</p> <pre><code>_dict.update({'b': n for key, value in _dict.items() if key == 'b' and n &gt; value}) </code></pre> <p>Which provides the desired result of <code>{'a': 9, 'b': 8, 'c': 'someValue'}</code>. So now to my question: Is there a shorter, more pythonic way of doing this? (preferably without importing additional modules)</p>
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_line + "\n" + request.form.get(u'query')) except BaseException as e: print e return render_template('index.html') </code></pre> <p>This code always deletes all lines in my txt file. And I have unicode and "input() already active" erros. </p> <p>Is this a correct way to do this? I have to work with python 2.6</p>
-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(): search_line= "blah blah" try: for line in fileinput.input(os.path.join(APP_STATIC, u'links.txt'),inplace=1): #Search line if search_line in line: #If yes Modify it x = line.replace(search_line,search_line + "\n" + request.form.get(u'query')) #Write to file print (x) else: #Write as it is print (x) except BaseException as e: print e return render_template('index.html') </code></pre>
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 an entire region with such land pieces and sell some of it to others. Possesable objects can be movable, or immovable, but all of them have common attributes, such as owner, title, world coords and so on. What DB structure with respect to Django models will be most suitable for this description? </p> <ul> <li>Owner_Table - (one-to-many) - PossesableObject_Table</li> <li>PossesableObject_Table - (many-to-many) - PossesableObject_Table (in example, building linked to land piece where it is)</li> </ul> <p>or</p> <ul> <li>Owner_Table - (one-to-many) - PossesableObjectType_Table (table for each type of possible object)</li> <li>PossesableObjectType_Table - (one-to-many) -<br> PossesableObjectType_Table (for already explained above type of<br> linking)</li> </ul>
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 can be linked to at most 1 B and B can be linked to many A, you need a one-to-many link, where the link column is in table A.</p> <p>If A can linked to at most 1 B and B can be linked to at most 1 A, you need a one-to-one link. At this point you should consider whether is viable to join them into 1 single table, though this may not be possible or good from other considerations.</p> <p>In your case, you ask yourself the question: Can a PossessableObject be linked to only at most 1 other PossessableObject or many other PossessableObject? Or in other words: Can a PossessableObject be owned by only at most 1 other PossessableObject or many other PossessableObject? If the answer is at most 1, use a one-to-many link, if the answer is many, use a many to many link. </p> <p>Also with regard to your question on a PossesableObject_Table for each possible type of object: I think it is best to put the things they have in common in a single table and then specify types. Than create a seperate table for each type of object that has the unique properties of an object and connect those, but your way will work as well. It depends on how many different types you have and what <strong>you</strong> find the easiest to work with. Remember: as long as is works it is fine.</p>
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. when I run this I am getting the following error :</p> <pre><code>Traceback (most recent call last): File "conn.py", line 6, in &lt;module&gt; conn.upload('c:/Users/Akhil/Downloads/New/img033.jpg',f,'matt3r') File "C:\Python27\lib\site-packages\tinys3\connection.py", line 171, in upload return self.run(r) File "C:\Python27\lib\site-packages\tinys3\connection.py", line 262, in run return self._handle_request(request) File "C:\Python27\lib\site-packages\tinys3\connection.py", line 356, in _handle_request return request.run() File "C:\Python27\lib\site-packages\tinys3\request_factory.py", line 346, in run auth=self.auth) File "C:\Python27\lib\site-packages\requests\api.py", line 123, in put return request('put', url, data=data, **kwargs) File "C:\Python27\lib\site-packages\requests\api.py", line 56, in request return session.request(method=method, url=url, **kwargs) File "C:\Python27\lib\site-packages\requests\sessions.py", line 475, in request resp = self.send(prep, **send_kwargs) File "C:\Python27\lib\site-packages\requests\sessions.py", line 596, in send r = adapter.send(request, **kwargs) File "C:\Python27\lib\site-packages\requests\adapters.py", line 473, in send raise ConnectionError(err, request=request) requests.exceptions.ConnectionError: ('Connection aborted.', error(10054, 'An existing connection was forcibly closed by the remote host')) </code></pre>
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 application on an Apache server but have run into trouble. Here is what I have done.</p> <p>I installed mod_wsgi using yum.</p> <p>I configured the virtualhost as shown below:</p> <pre><code>&lt;VirtualHost *:80&gt; ServerName myapp.myserver.com WSGIDaemonProcess myapp user=myuser group=mygroup threads=5 python-path=/var/www/myapp.myserver.com/html:/var/www/myapp.myserver.com/venv/lib:/var/www/myapp.myserver.com/venv/lib/python3.5/site-packages python-home=/var/www/myapp.myserver.com/html/venv WSGIScriptAlias / /var/www/myapp.myserver.com/html/myapp.wsgi &lt;Directory /var/www/myapp.myserver.com/html&gt; WSGIProcessGroup smex WSGIApplicationGroup %{GLOBAL} Order deny,allow Allow from all &lt;/Directory&gt; &lt;/VirtualHost&gt; </code></pre> <p>My wsgi file is configured as shown below:</p> <pre><code>import sys sys.path.insert(0, '/var/www/myapp.myserver.com/html') activate_this = '/var/www/myapp.myserver.com/html/venv/bin/activate_this.py' with open(activate_this) as file_: exec(file_.read(), dict(__file__=activate_this)) from myapp import app as application </code></pre> <p>However, I am getting an internal server error when I try to open the site. The error log reveals the following:</p> <pre><code>Tue Oct 18 14:24:50.174740 2016] [mpm_prefork:notice] [pid 27810] AH00163: Apache/2.4.6 (CentOS) PHP/5.4.16 mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations [Tue Oct 18 14:24:50.174784 2016] [core:notice] [pid 27810] AH00094: Command line: '/usr/sbin/httpd -D FOREGROUND' ImportError: No module named site ImportError: No module named site ImportError: No module named site ImportError: No module named site </code></pre> <p>The last error keeps repeating for most of the log file. The first thing that catches my eye is the Python version which seems to be 2.7.5. This brings me to my questions:</p> <ol> <li>Do I need to have Python 3.5.1 installed in /usr/local or can I just have it in the virtual environment.</li> <li>Do I need to install a specific mod_wsgi version for this version of Python? If so should I install it via pip instead of yum?</li> <li>What else am I missing to get this to work?</li> </ol> <p>Thanks in advance for your help.</p>
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 versions. Then build mod_wsgi from source code against the SCL versions of Python and Apache. You cannot force mod_wsgi to use a Python virtual environment for a different version of Python than what mod_wsgi was compiled for.</p>
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 index for the max value for the rolling window of 3</p> <pre><code>s.rolling(3).max() a NaN b NaN c 7.0 d 7.0 e 8.0 f 8.0 g 8.0 h 7.0 i 8.0 j 8.0 dtype: float64 </code></pre> <p>What I want is</p> <pre><code>a None b None c c d c e e f e g e h f i i j i dtype: object </code></pre> <p>What I've done</p> <pre><code>s.rolling(3).apply(np.argmax) a NaN b NaN c 2.0 d 1.0 e 2.0 f 1.0 g 0.0 h 0.0 i 2.0 j 1.0 dtype: float64 </code></pre> <p>which is obviously not what I want</p>
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> <p>Here is one approach:</p> <pre><code>&gt;&gt;&gt; s.index[s.rolling(3).apply(np.argmax)[2:].astype(int)+np.arange(len(s)-2)] Index([u'c', u'c', u'e', u'e', u'e', u'f', u'i', u'i'], dtype='object') </code></pre> <p>The idea is to take the argmax values and align them with the series by adding a value indicating how far along in the series we are. (That is, for the first argmax value we add zero, because it is giving us the index into a subsequence starting at index 0 in the original series; for the second argmax value we add one, because it is giving us the index into a subsequence starting at index 1 in the original series; etc.)</p> <p>This gives the correct results, but doesn't include the two "None" values at the beginning; you'd have to add those back manually if you wanted them.</p> <p>There is <a href="https://github.com/pandas-dev/pandas/issues/9481">an open pandas issue</a> to add rolling idxmax.</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 index for the max value for the rolling window of 3</p> <pre><code>s.rolling(3).max() a NaN b NaN c 7.0 d 7.0 e 8.0 f 8.0 g 8.0 h 7.0 i 8.0 j 8.0 dtype: float64 </code></pre> <p>What I want is</p> <pre><code>a None b None c c d c e e f e g e h f i i j i dtype: object </code></pre> <p>What I've done</p> <pre><code>s.rolling(3).apply(np.argmax) a NaN b NaN c 2.0 d 1.0 e 2.0 f 1.0 g 0.0 h 0.0 i 2.0 j 1.0 dtype: float64 </code></pre> <p>which is obviously not what I want</p>
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 all the indices corresponding to the rolling windows, indexes into the extracted array version with those and thus gets the max indices for each window. For a more efficient indexing, we can use <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html" rel="nofollow"><code>NumPy strides</code></a>, like so -</p> <pre><code>arr = s.values n = arr.strides[0] maxidx = np.lib.stride_tricks.as_strided(arr, \ shape=(s.size-3+1,3), strides=(n,n)).argmax(1) </code></pre>
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 index for the max value for the rolling window of 3</p> <pre><code>s.rolling(3).max() a NaN b NaN c 7.0 d 7.0 e 8.0 f 8.0 g 8.0 h 7.0 i 8.0 j 8.0 dtype: float64 </code></pre> <p>What I want is</p> <pre><code>a None b None c c d c e e f e g e h f i i j i dtype: object </code></pre> <p>What I've done</p> <pre><code>s.rolling(3).apply(np.argmax) a NaN b NaN c 2.0 d 1.0 e 2.0 f 1.0 g 0.0 h 0.0 i 2.0 j 1.0 dtype: float64 </code></pre> <p>which is obviously not what I want</p>
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 &lt;= 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 index for the max value for the rolling window of 3</p> <pre><code>s.rolling(3).max() a NaN b NaN c 7.0 d 7.0 e 8.0 f 8.0 g 8.0 h 7.0 i 8.0 j 8.0 dtype: float64 </code></pre> <p>What I want is</p> <pre><code>a None b None c c d c e e f e g e h f i i j i dtype: object </code></pre> <p>What I've done</p> <pre><code>s.rolling(3).apply(np.argmax) a NaN b NaN c 2.0 d 1.0 e 2.0 f 1.0 g 0.0 h 0.0 i 2.0 j 1.0 dtype: float64 </code></pre> <p>which is obviously not what I want</p>
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'], dtype='object', name=0) </code></pre> <p>As you can see, the first two terms are the <code>idxmax</code> as applied to the initial windows of lengths 1 and 2 rather than null values. It's not as efficient as the accepted answer and probably not a good idea for large windows but just another perspective. </p>
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 code looks like this:</p> <pre><code>class Phonebook: #vi skapar en klass def __init__(self): #för att initiera scriptet (constructor) self.pb={} #dictionary def add(self,namn,nummer): if namn in self.pb: print "Name already in contacts!" #kolla om namnet finns elif nummer in self.pb.viewvalues(): #kolla om numret finns print "Number already exists for a contact!" else: self.pb[namn]=nummer #lägga till namn med tel.nr def lookup(self,namn): if namn in self.pb: print print self.pb[namn] #skriver ut numret till namnet print else: print "Name is not in contacts" print def alias(self,namn,nummer): self.pb[nummer]=self.pb[namn] #två namn får samma nummer def change(self,namn,nummer): if namn in self.pb: for godtyckligt in self.pb: if self.pb[namn]==self.pb[godtyckligt]: self.pb[godtyckligt]=nummer </code></pre> <p>What can I change in my change function and/or in my alias function? Thanks.</p>
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 self.pb[namn]==self.pb[godtyckligt]: old_nummer = self.pb[godtyckligt] self.pb[godtyckligt]=nummer self.pb[nummer]=godtyckligt del self.pb.pop(old_nummer) </code></pre> <p>Your <code>alias</code> method should be like this:</p> <pre><code>#You need to define another dict aliases #aliases = {} def alias(self, name0, name1): self.aliases[name0].append(name1) </code></pre> <p>And then change the <code>lookup</code> method:</p> <pre><code>def lookup(self,namn): if namn in self.pb: print print self.pb[namn] #skriver ut numret till namnet print return else: for name in aliases: if namn in aliases[name]: print print self.pb[namn] #skriver ut numret till namnet print return print "Name is not in contacts" print return </code></pre>
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 original array is repeated three times. </p> <p>What I have so far is this</p> <pre><code>def operation(mat,step=2): result = np.array(mat,copy=True) result[::2,::2] = mat return result </code></pre> <p>This gives me array </p> <pre><code>[[ 98.+0.j 0.+0.j 40.+0.j 0.+0.j] [ 0.+0.j 0.+0.j 0.+0.j 0.+0.j] [ 29.+0.j 0.+0.j 54.+0.j 0.+0.j] [ 0.+0.j 0.+0.j 0.+0.j 0.+0.j]] </code></pre> <p>for the input</p> <pre><code>[[98 40] [29 54]] </code></pre> <p>The array will always be of even dimensions.</p>
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 repeat the arrya items:</p> <pre><code> In [30]: np.repeat(A, 3) Out[30]: array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]) </code></pre> <p>then all you need is reshaping the result (based on your expected result this can be different):</p> <pre><code> In [32]: np.repeat(A, 3).reshape(2, 3*2) array([[1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4]]) </code></pre> <p>And now you should repeat the result along the the first axis:</p> <pre><code> In [34]: np.repeat(np.repeat(A, 3).reshape(2, 3*2), 3, 0) Out[34]: array([[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4]]) </code></pre>
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 original array is repeated three times. </p> <p>What I have so far is this</p> <pre><code>def operation(mat,step=2): result = np.array(mat,copy=True) result[::2,::2] = mat return result </code></pre> <p>This gives me array </p> <pre><code>[[ 98.+0.j 0.+0.j 40.+0.j 0.+0.j] [ 0.+0.j 0.+0.j 0.+0.j 0.+0.j] [ 29.+0.j 0.+0.j 54.+0.j 0.+0.j] [ 0.+0.j 0.+0.j 0.+0.j 0.+0.j]] </code></pre> <p>for the input</p> <pre><code>[[98 40] [29 54]] </code></pre> <p>The array will always be of even dimensions.</p>
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 second axis of <code>length=2</code>. Then <code>np.kron</code> essentially replicates the elements along both rows and columns for a length of <code>2</code> each with that array : <code>np.ones((2,2),dtype=int)</code>.</p> <p>Sample run -</p> <pre><code>In [45]: a Out[45]: array([7, 5, 4, 2, 8, 6]) In [46]: np.kron(a.reshape(-1,2),np.ones((2,2),dtype=int)) Out[46]: array([[7, 7, 5, 5], [7, 7, 5, 5], [4, 4, 2, 2], [4, 4, 2, 2], [8, 8, 6, 6], [8, 8, 6, 6]]) </code></pre> <p>If you would like to have <code>4</code> rows, use <code>a.reshape(2,-1)</code> instead.</p>
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 original array is repeated three times. </p> <p>What I have so far is this</p> <pre><code>def operation(mat,step=2): result = np.array(mat,copy=True) result[::2,::2] = mat return result </code></pre> <p>This gives me array </p> <pre><code>[[ 98.+0.j 0.+0.j 40.+0.j 0.+0.j] [ 0.+0.j 0.+0.j 0.+0.j 0.+0.j] [ 29.+0.j 0.+0.j 54.+0.j 0.+0.j] [ 0.+0.j 0.+0.j 0.+0.j 0.+0.j]] </code></pre> <p>for the input</p> <pre><code>[[98 40] [29 54]] </code></pre> <p>The array will always be of even dimensions.</p>
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 &gt;&gt;&gt; [[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]] </code></pre>
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://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#test-setup-and-teardown</a></p> <pre><code>*** Settings *** Test Setup Open Application App A Test Teardown Close Application *** Test Cases *** Default values [Documentation] Setup and teardown from setting table Do Something Overridden setup [Documentation] Own setup, teardown from setting table [Setup] Open Application App B Do Something No teardown [Documentation] Default setup, no teardown at all Do Something [Teardown] No teardown 2 [Documentation] Setup and teardown can be disabled also with special value NONE Do Something [Teardown] NONE Using variables [Documentation] Setup and teardown specified using variables [Setup] ${SETUP} Do Something [Teardown] ${TEARDOWN} </code></pre>
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 import chain import operator lista = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]] listone = lista[0][0],[-x[0] for x in lista[:2]] #sumlistone = chain.from_iterable(listone) sumlistone = [x for sublist in listone for x in sublist] print listone print sumlistone </code></pre>
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(sorted([l[i][0],l[j][0],l[j][1]])) c.append(sorted([l[i][1],l[j][0],l[j][1]])) print(c) </code></pre> <p>Out put:</p> <pre><code>[['A1', 'A2', 'B1'], ['A1', 'A2', 'B2'], ['A1', 'B1', 'B2'], ['A2', 'B1', 'B2'], ['A1', 'A2', 'C1'], ['A1', 'A2', 'C2'], ['A1', 'C1', 'C2'], ['A2', 'C1', 'C2'], ['B1', 'B2', 'C1'], ['B1', 'B2', 'C2'], ['B1', 'C1', 'C2'], ['B2', 'C1', 'C2'] </code></pre>
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(sorted([l[i][0],l[j][0],l[j][1]])) c.append(sorted([l[i][1],l[j][0],l[j][1]])) print(c) </code></pre> <p>Out put:</p> <pre><code>[['A1', 'A2', 'B1'], ['A1', 'A2', 'B2'], ['A1', 'B1', 'B2'], ['A2', 'B1', 'B2'], ['A1', 'A2', 'C1'], ['A1', 'A2', 'C2'], ['A1', 'C1', 'C2'], ['A2', 'C1', 'C2'], ['B1', 'B2', 'C1'], ['B1', 'B2', 'C2'], ['B1', 'C1', 'C2'], ['B2', 'C1', 'C2'] </code></pre>
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&gt;where python C:\Windows\System32\python.exe </code></pre> <p>when I execute</p> <pre><code>C:\Users\usr&gt;python </code></pre> <p>I got the error:</p> <blockquote> <p>The program can't start because VCRUNTIME140.dll is missing from your computer. Try reinstalling to fix this problem The program can't start because python35.dll is missing from your computer. Try reinstalling to fix this problem</p> </blockquote> <p>if I execute </p> <pre><code>C:\Users\usr\Documents\MyExes\WinPython-64bit-3.5.2.2Qt5\python-3.5.2.amd64\python.exe </code></pre> <p>everything runs smoothly</p> <p>what can I do to call Python simply by python instead of <code>python_path\python</code>?</p>
-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-486B-BD66-BCAAF74B6919/vc_redist.x86.exe" rel="nofollow">http://download.microsoft.com/download/0/4/1/041224F6-A7DC-486B-BD66-BCAAF74B6919/vc_redist.x86.exe</a></p>
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&gt;where python C:\Windows\System32\python.exe </code></pre> <p>when I execute</p> <pre><code>C:\Users\usr&gt;python </code></pre> <p>I got the error:</p> <blockquote> <p>The program can't start because VCRUNTIME140.dll is missing from your computer. Try reinstalling to fix this problem The program can't start because python35.dll is missing from your computer. Try reinstalling to fix this problem</p> </blockquote> <p>if I execute </p> <pre><code>C:\Users\usr\Documents\MyExes\WinPython-64bit-3.5.2.2Qt5\python-3.5.2.amd64\python.exe </code></pre> <p>everything runs smoothly</p> <p>what can I do to call Python simply by python instead of <code>python_path\python</code>?</p>
-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 !!!</p>
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 email in emails: problem_invite = ProblemInvite(email=email_address) logging.exception(problem_invite.token) </code></pre> <p>The weird thing is, the invite token for each email is same, what's wrong with it? Thanks.</p>
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"><img src="https://i.stack.imgur.com/k2kBU.png" alt="enter image description here"></a></p> <p>So your <code>os.urandom(16).encode('hex')</code> expression is evaluated only once. I'm not 100% certain when, but I suspect it'd be at app deployment time - when the datastore models are uploaded.</p> <p>To address the problem just drop the default value and explicitly specify the property value when you create the entity.</p> <p><strong>Side note:</strong> when using default values in ndb models you need to be extra careful at <strong>changing these default values</strong> as the behaviour (i.e. the data returned for the affected properties) <strong>may change</strong> for the entities already existing in the datastore at app deployment/update time.</p>
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 the given program, The matrix is like this,</p> <pre><code> (0, 11) 0.238317554822 (0, 34) 0.355850989305 (0, 7) 0.355850989305 (0, 21) 0.238317554822 (0, 16) 0.355850989305 (0, 35) 0.355850989305 (0, 8) 0.355850989305 (0, 17) 0.355850989305 (0, 36) 0.355850989305 (1, 11) 0.238317554822 (1, 21) 0.238317554822 (1, 23) 0.355850989305 (1, 0) 0.355850989305 (1, 24) 0.355850989305 (1, 12) 0.355850989305 (1, 22) 0.355850989305 (1, 25) 0.355850989305 (1, 13) 0.355850989305 (2, 2) 0.27430356415 (2, 18) 0.339992197465 (2, 26) 0.339992197465 (2, 39) 0.339992197465 (2, 3) 0.339992197465 (2, 19) 0.339992197465 (2, 27) 0.339992197465 (2, 4) 0.339992197465 (2, 20) 0.339992197465 (3, 2) 0.27430356415 (3, 40) 0.339992197465 (3, 9) 0.339992197465 (3, 1) 0.339992197465 (3, 5) 0.339992197465 (3, 41) 0.339992197465 (3, 10) 0.339992197465 (3, 6) 0.339992197465 (3, 42) 0.339992197465 (4, 11) 0.202877476983 (4, 21) 0.202877476983 (4, 28) 0.302932576437 (4, 31) 0.302932576437 (4, 37) 0.302932576437 (4, 14) 0.302932576437 (4, 29) 0.302932576437 (4, 32) 0.302932576437 (4, 38) 0.302932576437 (4, 15) 0.302932576437 (4, 30) 0.302932576437 (4, 33) 0.302932576437 </code></pre> <p>What values this matrix is representing. ? can anybody worked on this can help me to understand this ?</p>
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</code> object.</p> <p>The second column contains the TF-IDF value of your given <code>word</code> (the word corresponding to <code>(ind_document, ind_word)</code>.</p> <hr> <p><strong>UPDATE</strong></p> <p>If you look closer to the implementation of <code>TfidfVectorizer</code><a href="http://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.TfidfVectorizer.html" rel="nofollow">here</a>, you can see that there is a parameter called <code>norm</code>. By <strong>default</strong> this parameter is set to <code>l2</code> which is the L2-norm used to normalize the data obtained.</p> <p>If you don't want to normalize your data and compare it to the results obtained manually <strong>change this parameter</strong> to <code>norm = None</code></p>
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 data as well. I want to exclude the rows with the data about the leader and add a column <code>is_leader</code> to indicate whether a member is the leader or not. Something like this:</p> <pre><code>id date event name time is_leader 2 2016-10-01 A AA 12:87 0 3 2016-10-01 A BB 12:45 1 </code></pre> <p>So, I know at <code>id=3</code> is the leader based on the time, which is 12:45 for both here. We can assume that this time won't be the same for any other members. </p> <p>What is an efficient way to accomplish this in pandas. Here I have just one event as an example, but I'll have several of these and I need to do this for each event.</p>
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> of row with text <code>leader</code> in column <code>name</code>:</p> <pre><code>print (df) id date event name time 0 1 2016-10-01 A leader 12:45 1 2 2016-10-01 A AA 12:87 2 3 2016-10-01 A BB 12:45 3 1 2016-10-01 B leader 12:15 4 2 2016-10-01 B AA 12:15 5 3 2016-10-01 B BB 12:45 def f(x): x['is_leader'] = x.time == x.ix[x['name'] == 'leader', 'time'].iloc[0] return x df= df.groupby('event').apply(f) print (df) id date event name time is_leader 0 1 2016-10-01 A leader 12:45 True 1 2 2016-10-01 A AA 12:87 False 2 3 2016-10-01 A BB 12:45 True 3 1 2016-10-01 B leader 12:15 True 4 2 2016-10-01 B AA 12:15 True 5 3 2016-10-01 B BB 12:45 False </code></pre> <hr> <p>One row solution with lambda function:</p> <pre><code>df['is_leader'] = df.groupby('event') .apply(lambda x: x.time == x.ix[x['name'] == 'leader', 'time'].iloc[0]) .reset_index(drop=True, level=0) print (df) id date event name time is_leader 0 1 2016-10-01 A leader 12:45 True 1 2 2016-10-01 A AA 12:87 False 2 3 2016-10-01 A BB 12:45 True 3 1 2016-10-01 B leader 12:15 True 4 2 2016-10-01 B AA 12:15 True 5 3 2016-10-01 B BB 12:45 False </code></pre> <p>Then remove rows with <code>leader</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a> and cast <code>boolean</code> column to <code>int</code>:</p> <pre><code>df = df[df.name != 'leader'] df.is_leader = df.is_leader.astype(int) print (df) id date event name time is_leader 1 2 2016-10-01 A AA 12:87 0 2 3 2016-10-01 A BB 12:45 1 4 2 2016-10-01 B AA 12:15 1 5 3 2016-10-01 B BB 12:45 0 </code></pre>
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 quite some time to figure out how to do that but unfortunately with little success. The function MeasureValues is called in every period of the simulation run.</p> <p>If anybody has an idea how to improve the code, I would be really grateful.</p> <p>Thank you guys.</p> <pre><code>def MeasureValues(self, CurrentPeriod): if CurrentPeriod &gt; self.WarmUp: self.ValueOne[CurrentPeriod] = self.FixedValueOne if self.Futurevalue[CurrentPeriod + self.Reload] &gt; 0 else 0 self.ValueTwo[CurrentPeriod] = self.VarValueTwo * self.AmountValueTwo[CurrentPeriod] self.ValueThree[CurrentPeriod] = self.VarValueThree * self.AmountValueThree[CurrentPeriod] self.SumOfValues[CurrentPeriod] = self.ValueOne[CurrentPeriod] + self.ValueTwo[CurrentPeriod] + self.ValueThree[CurrentPeriod] self.TotalSumOfValues += self.SumOfValues[CurrentPeriod] self.HelperSumValueFour += self.ValueFour[CurrentPeriod] self.HelperSumValueTwo += self.AmountValueTwo[CurrentPeriod] self.HelperSumValueFive += self.ValueFive[CurrentPeriod] self.RatioOne[CurrentPeriod] = (1 - (self.HelperSumValueFour / self.HelperSumValueFive )) if self.HelperSumValueFive &gt; 0 else 1 self.RatioTwo[CurrentPeriod] = (1 - (self.HelperSumValueTwo / self.HelperSumValueFive )) if self.HelperSumValueFive &gt; 0 else 1 </code></pre>
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 with <code>pip install cython</code> - then use it to see if you can speed up your code any.</p>
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 quite some time to figure out how to do that but unfortunately with little success. The function MeasureValues is called in every period of the simulation run.</p> <p>If anybody has an idea how to improve the code, I would be really grateful.</p> <p>Thank you guys.</p> <pre><code>def MeasureValues(self, CurrentPeriod): if CurrentPeriod &gt; self.WarmUp: self.ValueOne[CurrentPeriod] = self.FixedValueOne if self.Futurevalue[CurrentPeriod + self.Reload] &gt; 0 else 0 self.ValueTwo[CurrentPeriod] = self.VarValueTwo * self.AmountValueTwo[CurrentPeriod] self.ValueThree[CurrentPeriod] = self.VarValueThree * self.AmountValueThree[CurrentPeriod] self.SumOfValues[CurrentPeriod] = self.ValueOne[CurrentPeriod] + self.ValueTwo[CurrentPeriod] + self.ValueThree[CurrentPeriod] self.TotalSumOfValues += self.SumOfValues[CurrentPeriod] self.HelperSumValueFour += self.ValueFour[CurrentPeriod] self.HelperSumValueTwo += self.AmountValueTwo[CurrentPeriod] self.HelperSumValueFive += self.ValueFive[CurrentPeriod] self.RatioOne[CurrentPeriod] = (1 - (self.HelperSumValueFour / self.HelperSumValueFive )) if self.HelperSumValueFive &gt; 0 else 1 self.RatioTwo[CurrentPeriod] = (1 - (self.HelperSumValueTwo / self.HelperSumValueFive )) if self.HelperSumValueFive &gt; 0 else 1 </code></pre>
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.</li> <li><a href="http://cython.org/" rel="nofollow">Cython</a> as suggested by <em>holdenweb</em>, but you need to redefine a lot of stuff to be static-typed (using <code>cdef</code>) or nothing will change.</li> <li>rewrite the function in C as a <a href="https://docs.python.org/3/extending/extending.html" rel="nofollow">Python extension</a>, this may take some time, especially if you have no experience in C programming.</li> </ol> <p>The <code>PyPy</code> way seems the most reasonable, if it works you will gain a boost for all the simulations code.</p>
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 1.222 to 3.111 over say 3000 milliseconds, then from 3.111 to 0.456 over the same amount of time, and when it gets to the end of the list I want the 5th element of the list to ramp to the 1st element of the list and continue indefinitely.</p>
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 = given_list[i] second = given_list[(i+1) % len_list] delta = (second - first) / interval_count for j in range(interval_count): new_list.append(first + j * delta) return new_list def endless_play_led(ramp_list,count): endless = count == 0 count = abs(count) while endless or count!=0: for i in range(len(ramp_list)): play_led(ramp_list[i]) #time.sleep(1) if not endless: count -= 1 print '##############',count endless_play_led(calc_ramp(l, 3),2) endless_play_led(calc_ramp(l, 3),-2) endless_play_led(calc_ramp(l, 3),0) </code></pre>
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 1.222 to 3.111 over say 3000 milliseconds, then from 3.111 to 0.456 over the same amount of time, and when it gets to the end of the list I want the 5th element of the list to ramp to the 1st element of the list and continue indefinitely.</p>
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] step = float(abs(_from - _to )/_sensitivy) wise = -1 if _from &gt; _to else +1 _clk =float( (_time/1000.0) /_sensitivy ) count = 1 while time.time() &lt; (init_time + float(_time/1000)) : if time.time() &gt; init_time + (count * _clk) : count += 1 print (step*wise*count) + _from set_pwm(_ramplist, 3000, 40) </code></pre> <p><strong>Missing points :</strong> <code>step</code> is important because time object include infinity elements. This example is a <code>RTC</code>, so never see a <code>time.sleep()</code> function. <em>Check variable names if you want more information !</em></p>
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 1.222 to 3.111 over say 3000 milliseconds, then from 3.111 to 0.456 over the same amount of time, and when it gets to the end of the list I want the 5th element of the list to ramp to the 1st element of the list and continue indefinitely.</p>
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, second, fract): return first + (second - first)*fract def find_borders(list_of_values, total_time, time_per_step): len_list = len(list_of_values) total_steps = total_time // time_per_step fract = (total_time - total_steps * time_per_step) / float(time_per_step) index1 = int(total_steps % len_list) return [list_of_values[index1], list_of_values[(index1 + 1) % len_list], fract] def start_program(list_of_values, time_per_step, relax_time): total_start = time.time() while True: last_time = time.time() while time.time() - last_time &lt; relax_time: pass x = find_borders(list_of_values,time.time(),time_per_step) play_LED(interpol(x[0],x[1],x[2])) start_program(list_of_ramp,time_per_step=5,relax_time=0.5) </code></pre>
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 = db.cursor() cursor.execute("select IMAGE from T where ROWID in ('AAAAAAAAAA')") bf, = cursor.fetchone() bfile_data = bf.read() </code></pre> <p>The exception raised is: <code>AttributeError: 'cx_Oracle.OBJECT' object has no attribute 'read'</code></p>
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: returnValue = [] for value in obj.aslist(): if isinstance(value, cx_Oracle.Object): value = ObjectRepr(value) returnValue.append(value) else: returnValue = {} for attr in obj.type.attributes: value = getattr(obj, attr.name) if value is None: continue elif isinstance(value, cx_Oracle.Object): value = ObjectRepr(value) returnValue[attr.name] = value return returnValue print(ObjectRepr(bf)) </code></pre> <p>If you are using 5.2.1, though, some of the introspective code is not available. Fortunately, you don't need that. You can describe the type in SQL*Plus which will show you the list of attributes at the beginning of its output</p> <pre><code>desc ordsys.ordimage </code></pre> <p>That should allow you to do the following in your Python code:</p> <pre><code>print(bf.HEIGHT) print(bf.WIDTH) print(bf.CONTENTLENGTH) print(bf.FILEFORMAT) </code></pre> <p>Note that the attribute SOURCE is yet another object so you can access its attributes in the same way:</p> <pre><code>print(bf.SOURCE.SRCNAME) print(bf.SOURCE.UPDATETIME) </code></pre> <p>and so forth.</p> <p>The attribute bf.SOURCE.LOCALDATA is of type BLOB which is currently unsupported. You can access its value using an anonymous PL/SQL block instead:</p> <pre><code>var = cursor.var(cx_Oracle.BLOB) cursor.execute(""" declare t_Image ordsys.ordimage; begin select Image into t_Image from T where rownum &lt;= 1; :1 := t_Image.source.localdata; end;""", (var,)) blob = var.getvalue() print("Image data is:", blob.read()) </code></pre>
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]: [&lt;ModuleInfo 1&gt;, &lt;ModuleInfo 5&gt;, &lt;ModuleInfo 14&gt;, &lt;ModuleInfo 16&gt;, &lt;ModuleInfo 20&gt;, &lt;ModuleInfo 17&gt;, &lt;ModuleInfo 28&gt;, &lt;ModuleInfo 27&gt;] </code></pre> <p>retuan values are not max id, I want to <code>ip:127.0.0.1</code>-><code>id:4</code>, I use order_by id, but it just reverse the list.</p> <p>And when I try to use <code>distinct</code>, I found it not work:</p> <pre><code>In [51]: ModuleInfo.query.distinct(ModuleInfo.ip).all() Out[51]: [&lt;ModuleInfo 1&gt;, &lt;ModuleInfo 2&gt;, &lt;ModuleInfo 3&gt;, &lt;ModuleInfo 4&gt;, &lt;ModuleInfo 5&gt;, &lt;ModuleInfo 6&gt;, &lt;ModuleInfo 7&gt;, &lt;ModuleInfo 14&gt;, &lt;ModuleInfo 15&gt;, &lt;ModuleInfo 16&gt;, &lt;ModuleInfo 17&gt;, &lt;ModuleInfo 18&gt;, &lt;ModuleInfo 19&gt;, &lt;ModuleInfo 20&gt;, &lt;ModuleInfo 21&gt;, &lt;ModuleInfo 22&gt;, &lt;ModuleInfo 23&gt;, &lt;ModuleInfo 24&gt;, &lt;ModuleInfo 25&gt;, &lt;ModuleInfo 26&gt;, &lt;ModuleInfo 27&gt;, &lt;ModuleInfo 28&gt;, &lt;ModuleInfo 29&gt;, &lt;ModuleInfo 30&gt;] </code></pre>
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 tuples with (max(id), ip) as a result. </p> <p>Hannu</p>
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 backup count as 20 with each file size of 10MB? Should I convert it to simple file handler? </p> <p>I am using following yaml based log configuration in my python logger. </p> <pre><code> 1 version: 1 2 3 formatters: 4 simple: 5 format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s' 6 7 handlers: 8 console: 9 class: logging.StreamHandler 10 level: DEBUG 11 formatter: simple 12 stream: ext://sys.stdout 13 14 info_handler: 15 class: logging.handlers.RotatingFileHandler 16 level: INFO 17 formatter: simple 18 filename: info.log 19 maxBytes: 10485760 # 10MB 20 backupCount: 20 21 encoding: utf8 22 23 error_handler: 24 class: logging.handlers.RotatingFileHandler 25 level: ERROR 26 formatter: simple 27 filename: errors.log 28 maxBytes: 10485760 # 10MB 29 backupCount: 20 30 encoding: utf8 31 32 loggers: 33 my_module: 34 level: ERROR 35 handlers: [console] 36 propagate: no 37 38 root: 39 level: DEBUG 40 handlers: [info_handler, info_handler] </code></pre> <p>I am using the following python logger initializer code to initialize my logger. </p> <pre><code> 1 import os 2 import logging.config 3 import yaml 4 5 """Setup logging configuration """ 6 default_path='logging.yaml' 7 default_level=logging.INFO 8 env_key='LOG_CFG' 9 10 class MyLogger(): 11 12 def __init__(self): 13 path = default_path 14 value = os.getenv(env_key, None) 15 if value: 16 path = value 17 if os.path.exists(path): 18 with open(path, 'rt') as f: 19 config = yaml.safe_load(f.read()) 20 logging.config.dictConfig(config) 21 else: 22 logging.basicConfig(filemode='w', level=default_level) </code></pre>
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><code>with open(config['handlers']['info_handler']['filename'], 'w') as f: pass </code></pre>
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 -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC myModule.c </code></pre> <p>which returns no error. The problem; comes when i try to launch the C function in python. Let's consider the following simple function in C :</p> <pre><code>int multiplier(int a, int b) { int lol = 0; lol = a*b; return lol; } </code></pre> <p>I launch python3 (3.5.2), and then :</p> <pre><code>import ctypes zelib = ctypes.CDLL("/Users/longeard/Desktop/Codes/DraII/testlib.so",ctypes.RTLD_GLOBAL) </code></pre> <p>The library should be ready to use in python by doing :</p> <pre><code>res = zelib.multiplier(2,3) </code></pre> <p>When doing that, it works and python returns </p> <pre><code>6 </code></pre> <p>Problem is, that the function i want to use ( the multiplier function I use is just for the example ) is supposed to take floats as input and return a float. But if I now consider the same multiplier function as before but with float :</p> <pre><code>float multiplier(float a, float b) { float lol = 0.0; lol = a*b; return lol; } </code></pre> <p>I recompile using gcc, I reimport ctypes and re-do ctypes.CDLL, and I do in python3 :</p> <pre><code>zelib.multiplier(ctypes.c_float(2),ctypes.c_float(3)) </code></pre> <p>(the types.c_float are here to convert the 2 in python into a float in C ), python will return :</p> <pre><code>2 </code></pre> <p>This is weird because if I add a printf within the function to print lol, python will print :</p> <pre><code> 6.0 </code></pre> <p>but still return 2, or 18 sometimes. Even though I printf and return the same variable "lol".</p> <p>I tried a lot of things, and none of it worked. Do somebody have a idea please ? Thank You.</p>
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.python.org/3/library/ctypes.html#specifying-the-required-argument-types-function-prototypes" rel="nofollow">Specifying the required argument types (function prototypes)</a>:</p> <blockquote> <p>It is possible to specify the required argument types of functions exported from DLLs by setting the <code>argtypes</code> attribute.</p> </blockquote> <p>and <a href="https://docs.python.org/3/library/ctypes.html#return-types" rel="nofollow">Return types</a> in <a href="https://docs.python.org/3/library/ctypes.html" rel="nofollow"><code>ctypes</code> module documentation</a>:</p> <blockquote> <p>By default functions are assumed to return the C int type. Other return types can be specified by setting the <code>restype</code> attribute of the function object.</p> </blockquote> <hr> <pre><code># without specifying types &gt;&gt;&gt; import ctypes &gt;&gt;&gt; zelib = ctypes.CDLL('testlib.so') &gt;&gt;&gt; zelib.multiplier(2, 3) 0 # specifying types &gt;&gt;&gt; zelib.multiplier.restype = ctypes.c_float &gt;&gt;&gt; zelib.multiplier.argtypes = [ctypes.c_float, ctypes.c_float] &gt;&gt;&gt; zelib.multiplier(2, 3) 6.0 </code></pre>
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 -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC myModule.c </code></pre> <p>which returns no error. The problem; comes when i try to launch the C function in python. Let's consider the following simple function in C :</p> <pre><code>int multiplier(int a, int b) { int lol = 0; lol = a*b; return lol; } </code></pre> <p>I launch python3 (3.5.2), and then :</p> <pre><code>import ctypes zelib = ctypes.CDLL("/Users/longeard/Desktop/Codes/DraII/testlib.so",ctypes.RTLD_GLOBAL) </code></pre> <p>The library should be ready to use in python by doing :</p> <pre><code>res = zelib.multiplier(2,3) </code></pre> <p>When doing that, it works and python returns </p> <pre><code>6 </code></pre> <p>Problem is, that the function i want to use ( the multiplier function I use is just for the example ) is supposed to take floats as input and return a float. But if I now consider the same multiplier function as before but with float :</p> <pre><code>float multiplier(float a, float b) { float lol = 0.0; lol = a*b; return lol; } </code></pre> <p>I recompile using gcc, I reimport ctypes and re-do ctypes.CDLL, and I do in python3 :</p> <pre><code>zelib.multiplier(ctypes.c_float(2),ctypes.c_float(3)) </code></pre> <p>(the types.c_float are here to convert the 2 in python into a float in C ), python will return :</p> <pre><code>2 </code></pre> <p>This is weird because if I add a printf within the function to print lol, python will print :</p> <pre><code> 6.0 </code></pre> <p>but still return 2, or 18 sometimes. Even though I printf and return the same variable "lol".</p> <p>I tried a lot of things, and none of it worked. Do somebody have a idea please ? Thank You.</p>
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 built-in commands to clear figures and axes do not work properly anymore.</p> <p>Example:</p> <pre><code>import numpy as np import matplotlib.pyplot as mpp class PlotTest: def __init__(self,nx=1,ny=1): # Switch off interactive mode: mpp.ioff() # Create Figure and Axes: self.createFigure(nx, ny) def createFigure(self,nx=1,ny=1): self.fig, self.axes = mpp.subplots(nx,ny) if nx*ny == 1: self.axes = np.array([self.axes]) def linePlot(self): X = np.linspace(0,20,21) Y = np.random.rand(21) self.axes[0].plot(X,Y) P = PlotTest() P.linePlot() P.fig.show() </code></pre> <p>Now I was thinking I could use <code>P.fig.clear()</code> any time to simply clear <code>P.fig</code>, but apparently that's not the case.</p> <p>Writing <code>P.fig.clear()</code> directly into the script and execute it together it works and all I see is an empty figure. However that's rather pointless as I never get to see the actual plot like that.</p> <p>Doing <code>P.fig.clear()</code> manually in the console does not do anything, regardless if the plot window is open or not, all other possible commands fail as well:</p> <pre><code>P.fig.clf() P.axes[0].clear() P.axes[0].cla() mpp.clf() mpp.cla() mpp.close(P.fig) </code></pre> <p>Wrapping the command into a class method doesn't work either:</p> <pre><code>def clearFig(self): self.fig.clear() </code></pre> <p>EDIT ================</p> <p>After a <code>clear()</code> <code>fig.axes</code> is empty, yet <code>show()</code> still shows the old plot with the axes still being plotted.</p> <p>/EDIT ================</p> <p>Is it because I switched off interactive mode?</p>
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 automatically re-drawn. This should be only rarely needed, but there may be ways to modify the state of a figure with out marking it as stale. Please report these cases as bugs.</p> </blockquote> <p>I guess this is not a bug as you have switched off interactive mode so it is now your responsibility to explicitly redraw when you want to.</p> <p>You can also use <code>P.fig.canvas.draw_idle()</code> which could be wrapper in the class as <code>clearFigure</code> method.</p>
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 version is still loaded. Python 2.6 has a Microsoft.VC90.CRT.manifest file that also specifies 9.0.21022.8 but the newer version is always loaded.</p> <p>Using Process monitor I can see all other instances when msvcr90.dll is loaded and they all use 9.0.30729.9247.</p> <p>Somewhere my PC must be telling all these programs to use the newer version but I can't seem to find out where. I have many versions of microsoft.vc90.crt in my WinSxS folder.</p> <p>If I can't change the default version, is there any way that I can 'downgrade' my microsoft.vc90.crt? To a version that seems more standard (9.0.30729.6161)</p> <p>PS. I have no idea where my version 9.0.30729.9247 of microsoft.vc90.crt came from</p>
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 version back to an older version as required</p>
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 types instead of opening them). Upon clicking, one of the following two events may unfold:</p> <ol> <li>A pop-up window appears. A button on the pop-up window needs to be clicked to close it before the document is downloaded.</li> <li>A blank pop-up appears momentarily before it disappears on its own when the document download begins.</li> </ol> <p>Here's an excerpt of the script that is written to handle the events above:</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 for the pop-up window try: print "Step 1" driver.switch_to.window(driver.window_handles[1]) print "Step 2" # SCRIPT STOPS RUNNING HERE agree_button = driver.find_element_by_xpath('//input[@value="Agree and proceed"]') print "Popup found" except: driver.switch_to.window(driver.window_handles[0]) # Clicks the button if the pop-up window is found if agree_button is not None: agree_button.click() print "Button clicked" </code></pre> <p>The trouble surfaces when there's high latency in the network for Event 2. Under normal circumstances, the blank pop-up disappears almost instantaneously and the download begins immediately after. However, if the network is slow, the blank pop-up may persist beyond the allocated 7 seconds and that resulted in the script running into "Step 2" before the pop-up window disappears.</p> <p>Strangely, at this point the script doesn't continue on to look for the <code>agree_button</code>. If it does, then that would have triggered the exception and I would be able to revert back to the original window to resume the steps. The script just stalls and does nothing it seems.</p> <p>Thanks in advance for your time guys!</p>
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 for the pop-up window try: print "Step 1" driver.switch_to.window(driver.window_handles[1]) print "Step 2" # SCRIPT STOPS RUNNING HERE while True: agree_button = driver.find_element_by_xpath('//input[@value="Agree and proceed"]') if agree_button is not None: break else: sleep(7) print "Popup found" except: driver.switch_to.window(driver.window_handles[0]) # Clicks the button if the pop-up window is found if agree_button is not None: agree_button.click() print "Button clicked" </code></pre>
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 , 49</p> <p>C , 1 , 96</p> <p>C , 2 , 287</p> <p>etc.</p> <p>What is the best way to save it?</p> <p>In PERL, I would have used a hash and separators, as follows, and then called by hash key and separated using split over the comma:</p> <p>$data{$ID1} .= $ID2.':'.$value.',';</p> <p>I have to address the following problem in PYTHON as it would be integrated with other code, but I am new to the language. Please suggest what might be the best way to do it.</p> <p>P.S. The input data file is huge (~500Mb) and could be more.</p> <p>Thanks for the help.</p>
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 outfile: pickle.dump(big_list_list, outfile) # Retrieving the data with with open("data.pickle", "rb") as infile: reconstructed_big_list_list = pickle.load(infile) </code></pre> <p>This has two caveats: if part of your workflow includes Non-Python programs, they won't be able to read pickles. And you shouldn't trust pickle files from arbitrary sources, since they could contain malicious code.</p> <p>Instead of using pickles, you can also use JSON files. Simple replace the word <code>pickle</code> with <code>json</code> in the recipy above. JSON has the advantage that many Non-Python programs can deal with it.</p> <p>Even more universal would be the use of CSV files, like this:</p> <pre><code>import csv with open('data.csv', 'w', newline='') as outfile: writer = csv.writer(outfile) writer.writerows(big_list_list) with open('data.csv', newline='') as infile: reader = csv.reader(infile) reconstructed_big_list_list = [row for row in reader] </code></pre> <p>Python's standard library also includes the module <code>sqlite3</code>, which allows you to write your data to a database, which might be useful if your data becomes more complicated than a simple list of lists, or you need concurrent access.</p> <p>PS.: I just saw that you noted that your files could be uge. In this case, you could modify the CSV solution to store and load your data incrementally:</p> <pre><code>import csv with open('data.csv', 'w', newline='') as outfile: writer = csv.writer(outfile) for row in big_list_list: writer.writerow(row) with open('data.csv', newline='') as infile: reader = csv.reader(infile) for row in reader: print(row) </code></pre>
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 example:</p> <p>(12)3((45)6) -> 123(456), remove the parentheses around 12 then around 45</p> <p>((12)3)4(((5)67)8) -> 1234(5678), remove the parentheses around 12, then 123, then 5, then 567. Do not remove the parentheses around 5678 since that is the second element.</p> <p>How do I do this?</p> <p>EDIT: So far what I have is this:</p> <pre><code>def simplify(expression): """ call itself recursively until no consecutive parentheses exist """ result = [] consec_parens = 0 inside_nested = False for char in expression: if char == ')' and inside_nested: inside_nested = False consec_parens = 0 continue if char == '(': consec_parens += 1 else: consec_parens = 0 if consec_parens == 2: inside_nested = True else: result.append(char) result = ''.join(result) if result == expression: return result return simplify(result) </code></pre> <p>It works for all cases where the number of nested parentheses is at least two, but it doesn't work for the head, i.e. for (AB)C, it does not remove the parentheses around AB. However, for ((AB)C) it removes the parentheses around AB resulting in (ABC).</p>
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 <code>(</code>, just push the index to the <code>leftstk</code>.</p> <p>Keep track of the number of <code>(</code> found say <code>leftbrackets</code> and <code>)</code> found say <code>righttbrackets</code> </p> <p>Whenever a <code>)</code> is found , you remove the corresponding <code>(</code> if and only if <code>leftbrackets &gt;= righttbrackets</code>, and the equality holds only for the first time only when the condition get true using equality, meaning the condition <code>leftbrackets == righttbrackets</code> must not be used after first time it is evaluated to be true , and then the condition <code>leftbrackets &gt; righttbrackets</code> must be used.</p> <p>For example if in <code>((12)3)4(((5)67)8)</code> we use the equality condition second time, then we end up removing brackets from <code>5678</code> also, which is not required.</p> <p>You can easily find the position of corresponding <code>(</code>, by using the stack <code>leftstk</code>.</p>
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 example:</p> <p>(12)3((45)6) -> 123(456), remove the parentheses around 12 then around 45</p> <p>((12)3)4(((5)67)8) -> 1234(5678), remove the parentheses around 12, then 123, then 5, then 567. Do not remove the parentheses around 5678 since that is the second element.</p> <p>How do I do this?</p> <p>EDIT: So far what I have is this:</p> <pre><code>def simplify(expression): """ call itself recursively until no consecutive parentheses exist """ result = [] consec_parens = 0 inside_nested = False for char in expression: if char == ')' and inside_nested: inside_nested = False consec_parens = 0 continue if char == '(': consec_parens += 1 else: consec_parens = 0 if consec_parens == 2: inside_nested = True else: result.append(char) result = ''.join(result) if result == expression: return result return simplify(result) </code></pre> <p>It works for all cases where the number of nested parentheses is at least two, but it doesn't work for the head, i.e. for (AB)C, it does not remove the parentheses around AB. However, for ((AB)C) it removes the parentheses around AB resulting in (ABC).</p>
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 (an in-progress state and a done state, neither of which we model explicitly) and three stack symbols, each representing the state of the machine for the current level:</p> <ul> <li><strong>Before</strong> - The state we are in immediately after entering a level. Encountering any characters except <code>)</code> transitions to some other state.</li> <li><strong>Inside</strong> - The state we are in while inside parentheses that need to be removed. Entered by encoutering a <code>(</code> while in <strong>Before</strong>.</li> <li><strong>Done</strong> - The state we are in when the current level has been processed. This means that either we already removed a set of parentheses or we did not need to, since the first element wasn't enclosed in them.</li> </ul> <p>Additionally, encountering a <code>(</code> pushes a new symbol onto the stack, which models entering a new level, and a <code>)</code> pops the one symbol from it, which models leaving from a level. All input characters get appended onto the result <em>except</em> when the <strong>Before</strong> → <strong>Inside</strong> and <strong>Inside</strong> → <strong>Done</strong> transitions occur.</p> <p>The following code is a simple translation of the above into Python:</p> <pre><code>from enum import Enum class State(Enum): Before = 0 Inside = 1 Done = 2 def simplify(expression): levels = [State.Before] result = [] for c in expression: if c == '(': if levels[-1] == State.Before: levels[-1] = State.Inside else: result.append(c) levels.append(State.Before) elif c == ')': levels.pop() if levels[-1] == State.Inside: levels[-1] = State.Done else: result.append(c) else: if levels[-1] == State.Before: levels[-1] = State.Done result.append(c) return ''.join(result) </code></pre> <p>Testing the above out, we get:</p> <pre><code>&gt;&gt;&gt; simplify('(12)3((45)6)') '123(456)' &gt;&gt;&gt; simplify('((12)3)4(((5)67)8)') '1234(5678)' &gt;&gt;&gt; simplify('(AB)C') 'ABC' &gt;&gt;&gt; simplify('((AB)C)') 'ABC' </code></pre>
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 module here because this is the object that is bound to a name by the import statement.</p> <p>On the other hand, the statement from spam.ham import eggs, sausage as saus results in</p> <pre><code>_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0) eggs = _temp.eggs saus = _temp.sausage </code></pre> <p>see: <a href="https://docs.python.org/3/library/functions.html#__import__" rel="nofollow">https://docs.python.org/3/library/functions.html#<strong>import</strong></a></p>
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 appriciated!</p> <pre><code>import seaborn as sns import matplotlib.pyplot as plt import matplotlib import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn import datasets %matplotlib inline iris = datasets.load_iris() x = iris['data'] y = iris['target'] x = iris_x[:, :2] clf_tree = DecisionTreeClassifier(random_state = 1) fit_clf = clf_tree.fit(x, y) y_pred_proba = fit_clf.predict_proba(x) y_pred = fit_clf.predict(x) conf_mat = confusion_matrix(y_true = y, y_pred = y_pred) fig, ax = plt.subplots(figsize = (15, 9)) ax.matshow(conf_mat, cmap = plt.cm.Blues, alpha = 0.3) for i in range(conf_mat.shape[0]): for j in range(conf_mat.shape[1]): ax.text(x = j, y = i, s = conf_mat[i, j], va = 'center', ha = 'center') plt.xlabel('Predicted') plt.ylabel('Actual') plt.show() conf_mat_prc = conf_mat/len(y) fig, ax = plt.subplots(figsize = (15, 9)) ax.matshow(conf_mat_prc, cmap = plt.cm.Blues, alpha = 0.3) for i in range(conf_mat_prc.shape[0]): for j in range(conf_mat_prc.shape[1]): ax.text(x = j, y = i, s = conf_mat_prc[i, j], va = 'center', ha = 'center') plt.xlabel('Predicted % dist') plt.ylabel('Actual % dist') plt.show() </code></pre> <p>Many thanks in advance,</p> <p>--swepab</p>
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> instead of <code>conf_mat_prc = conf_mat/len(y)</code> to get float instead of 0 (int). </p></li> </ul> <p>Finally, for the second graph (line 48) use <code>str(round(conf_mat_prc[i, j]*100,precision)) + "%"</code> in which precision defines the number of floating point digits.</p> <p>Here's the new code: </p> <pre><code>import seaborn as sns import matplotlib.pyplot as plt import matplotlib import numpy as np from sklearn.tree import DecisionTreeClassifier from sklearn import datasets from sklearn.metrics import confusion_matrix # %matplotlib inline iris = datasets.load_iris() x = iris['data'] y = iris['target'] x = x[:, :2] clf_tree = DecisionTreeClassifier(random_state = 1) fit_clf = clf_tree.fit(x, y) y_pred_proba = fit_clf.predict_proba(x) y_pred = fit_clf.predict(x) conf_mat = confusion_matrix(y_true = y, y_pred = y_pred) fig, ax = plt.subplots(figsize = (15, 9)) ax.matshow(conf_mat, cmap = plt.cm.Blues, alpha = 0.3) for i in range(conf_mat.shape[0]): for j in range(conf_mat.shape[1]): ax.text(x = j, y = i, s = conf_mat[i, j], va = 'center', ha = 'center') plt.xlabel('Predicted') plt.ylabel('Actual') plt.show() conf_mat_prc = conf_mat/float(len(y)) fig, ax = plt.subplots(figsize = (15, 9)) ax.matshow(conf_mat_prc, cmap = plt.cm.Blues, alpha = 0.3) precision = 2 for i in range(conf_mat_prc.shape[0]): for j in range(conf_mat_prc.shape[1]): ax.text(x = j, y = i, s = str(round(conf_mat_prc[i, j]*100,precision)) + "%", va = 'center', ha = 'center') plt.xlabel('Predicted % dist') plt.ylabel('Actual % dist') plt.show() </code></pre> <p>Here's the new second graph :</p> <p><a href="https://i.stack.imgur.com/7CPku.png" rel="nofollow"><img src="https://i.stack.imgur.com/7CPku.png" alt="enter image description here"></a></p>
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.ManyToManyField(OtherModel,related_name='confirming') def get_confirming(self): return ','.join([l.pmid for l in self.confirming_stuff.all()]) class SomeForm(ModelForm): def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) self.initial['confirming_field'] = self.instance.get_confirming() </code></pre> <p>Everything works fine with an update. The field is populated with comma separated entries as expected. The problem arises with creation. As the instance does not yet exist the field cannot be filled with data, so I tried to skip this step. But it doesn't work. Instead, I encountered a strange behavior of the python code.</p> <pre><code>class SomeForm(ModelForm): def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) if self.instance: print "Self instance: ",self.instance self.initial['some_field'] = self.instance.get_some_field() </code></pre> <p>produces the same error. Additionally the printout on the debug screen shows:</p> <blockquote> <p>Self instance: None</p> </blockquote> <p>I tried several other logical expressions, </p> <pre><code>if self.instance != None: if not self.instance == None: if self.instance &gt; 0: </code></pre> <p>but the result remains the same.</p> <p>It remains a mystery to me why the instance is printed as 'None' but cannot be tested properly as such. </p>
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/path1/filename.conf"</code></p> <p>in the <code>filename.conf</code>, it has ~35 lines and i wanted to insert one line after matching string <code>"ReWriteEngine On"</code></p> <pre><code>subprocess.call(["sed","-i" ,'/ReWriteEngine On/a', addline1,filename]) </code></pre> <p>and it fails with below exception:</p> <pre><code>**sed: -e expression #1, char 16: expected \ after `a', `c' or `i'** </code></pre> <p>Can any one please advice any correction to be made ?</p> <p><br> Code tried with <code>fileinput</code> instead of <code>sed</code></p> <pre><code>import fileinput processing_foo1s = False for line in fileinput.input('/tmp/filename1/mod_wl_ohs.conf', inplace=1): if line.startswith("RewriteEngine On"): processing_foo1s = True else: if processing_foo1s: print 'foo bar' processing_foo1s = False print line </code></pre>
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> <pre><code>import fileinput for line in fileinput.input(filename1, inplace=1): print line, if line.startswith("ReWriteEngine On"): print 'foo bar' </code></pre> <p>Reference: <a href="http://stackoverflow.com/questions/657186/python-prevent-fileinput-from-adding-newline-characters">Python: Prevent fileinput from adding newline characters</a></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) df = pytrend.trend(trend_payload, return_type='dataframe') df </code></pre> <p>As this query has the disadvantage that Google Trends normalizes all data based on the queried data, I prefer to make each a single call and chain the df next to each other. I thought about a function like this:</p> <pre><code>queries = ['Cats', 'Dogs', 'Catfood','Dogfood'] function(queries) trend_payload = {'q': queries, 'date': '01/2015 12m'} trend = pytrend.trend(trend_payload) df = pytrend.trend(trend_payload, return_type='dataframe') # then put every df of each query next to each other </code></pre> <p>How can I do this?</p>
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([query,]) for query in queries] </code></pre> <p>then you have to <code>concat</code> the data frames in the list. </p> <p>More elegantly you can call: </p> <pre><code>list_of_df = map(function, queries) </code></pre> <p>in this case you should rewrite <code>function</code> so that it accepts a single item. If you don't want to modify <code>function</code> you can write this: </p> <pre><code>list_of_df = map(lambda x: function([x,]), queries) </code></pre>
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) df = pytrend.trend(trend_payload, return_type='dataframe') df </code></pre> <p>As this query has the disadvantage that Google Trends normalizes all data based on the queried data, I prefer to make each a single call and chain the df next to each other. I thought about a function like this:</p> <pre><code>queries = ['Cats', 'Dogs', 'Catfood','Dogfood'] function(queries) trend_payload = {'q': queries, 'date': '01/2015 12m'} trend = pytrend.trend(trend_payload) df = pytrend.trend(trend_payload, return_type='dataframe') # then put every df of each query next to each other </code></pre> <p>How can I do this?</p>
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='dataframe') for x in queries], axis=1) </code></pre> <p>or in function:</p> <pre><code>def get_trends(queries, dt): return pd.concat([pytrend.trend({'q': x, 'date': dt}, return_type='dataframe') for x in queries], axis=1) df = get_trends(queries, '01/2015 12m') </code></pre> <p>Demo:</p> <pre><code>In [24]: df = get_trends(queries, '01/2015 12m') In [25]: df Out[25]: cats dogs catfood dogfood Date 2015-01-04 74.0 85.0 65.0 47.0 2015-01-11 74.0 84.0 60.0 52.0 2015-01-18 72.0 82.0 49.0 57.0 2015-01-25 69.0 78.0 45.0 37.0 2015-02-01 73.0 77.0 51.0 52.0 ... ... ... ... ... 2015-11-29 83.0 80.0 47.0 49.0 2015-12-06 80.0 79.0 70.0 50.0 2015-12-13 83.0 84.0 67.0 49.0 2015-12-20 89.0 91.0 61.0 58.0 2015-12-27 90.0 100.0 58.0 45.0 [52 rows x 4 columns] </code></pre>
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()</strong> will not execute. I know you will say to handle this by catching the exception (try..except) but then i have to catch every exception which is not i am looking for. In a nutshell how do i code where my other functions are not impacted if any of the function is having issue. Ideally it should exclude that problematic function and let the other function to execute.</p> <pre><code>def function1(): some code def function2(): some code def function3(): some code def function4(): some code def function5(): some code if __name__ == '__main__': function1() function2() function3() function4() function5() </code></pre>
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() except: pass </code></pre> <hr> <p>OR, create a <em>decorator</em> and add that decorator to each of your function. Check <a href="http://thecodeship.com/patterns/guide-to-python-function-decorators/" rel="nofollow">A guide to Python's function decorators</a>. For example, your decorator should be like:</p> <pre><code>def wrap_error(func): def func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except: pass return func_wrapper </code></pre> <p>Now add this decorator with your function definition as:</p> <pre><code>@wrap_error def function1(): some code </code></pre> <p>Functions having this decorator added to them won't raise any <code>Exception</code></p>
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()</strong> will not execute. I know you will say to handle this by catching the exception (try..except) but then i have to catch every exception which is not i am looking for. In a nutshell how do i code where my other functions are not impacted if any of the function is having issue. Ideally it should exclude that problematic function and let the other function to execute.</p> <pre><code>def function1(): some code def function2(): some code def function3(): some code def function4(): some code def function5(): some code if __name__ == '__main__': function1() function2() function3() function4() function5() </code></pre>
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: pass </code></pre> <p>for large number of functions you can use</p> <pre><code>func_dict = { func1 : { param1 : val param2 : val }, func1 : { param1 : val param2 : val } } </code></pre> <p>thus you can iterate over the keys of the dictionary for the function and iterate on the parameters </p>
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', 'target', 'data:{...}', 'timestamp'} Failure message format: {'result', 'action', 'error_message', 'path', 'linenumber', 'timestamp', 'data:{}'} """ if result == 'success': # *** I'm getting warning on this one message = {'result': result, 'action': action, 'target': path.strip('\''), 'timestamp': datetime.datetime.strptime(time_stamp, '%Y/%m/%d %H-%M-%S.%f'), 'data': data} else: message = {'result': result, 'action': action, 'error_message': error_message, 'target': path, 'linenum': line, 'timestamp': datetime.datetime.strptime(time_stamp, '%Y/%m/%d %H-%M-%S.%f'), 'data': data} try: return True, json.dumps(message) except (ValueError, TypeError) as json_error: return False, json_error.message </code></pre> <p>Thanks</p>
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, 'action': action, 'target': path.strip('\''), 'timestamp': datetime.datetime.strptime(time_stamp, '%Y/%m/%d %H-%M-%S.%f'), 'data': data} else: message = {'result': result, 'action': action, 'error_message': error_message, 'target': path, 'linenum': line, 'timestamp': datetime.datetime.strptime(time_stamp, '%Y/%m/%d %H-%M-%S.%f'), 'data': data} try: return True, json.dumps(message) except (ValueError, TypeError) as json_error: return False, json_error.message </code></pre> <p>but then you need to get <code>message</code> variable initialized before <code>if-else</code> or you will get errors about using variable before assigning</p> <pre><code>message = "" if ... ... else ... </code></pre>
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 both have the same working directory because I am importing <code>mymodule</code> into <code>myfile</code>, or does <code>mymodule</code> have it's working directory as the directory of where it was installed</p>
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 &#13; 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 via:</p> <pre><code>code = etree.tostring(root) </code></pre> <p>which yielded me the exact HTML code but with </p> <blockquote> <p><code>&amp;#13;</code></p> </blockquote> <p>everywhere in the Code. I think this might cause my parsing issues (I hope so at least).</p> <p>How can I get clean HTML code out of this? Any encoding/decoding needed?</p> <p>I've tried to decode it to UTF-8, but that didn't work appearantly.</p> <pre><code>print code.decode('utf-8') </code></pre>
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>&lt; 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) jobC = Job('C', 2) jobD = Job('D', 10) jobE = Job('E', 3) jobF = Job('F', 11) jobA.add_dependent(jobB) jobA.add_dependent(jobC) jobB.add_dependent(jobD) jobC.add_dependent(jobE) jobD.add_dependent(jobF) jobE.add_dependent(jobF) </code></pre> <p>so we have two possible paths</p> <pre><code>A-&gt;B-&gt;D-&gt;F 0+4+10+11 = 25 A-&gt;C-&gt;E-&gt;F 0+2+3+11 = 16 </code></pre> <p>so the longest paths would be the former</p> <p>Is there an easy way to gather the longest path, <code>A-&gt;B-&gt;D-&gt;F</code>?</p> <pre><code>def longest_path(root): paths = [] # some logic here return paths print longest_path(jobA) # should print A-&gt;B-&gt;D-&gt;F </code></pre>
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=operator.itemgetter(1)) return ([job.name] + path, job.weight + cost) else: return ([job.name], job.weight) return "-&gt;".join(_find_longest(root)[0]) </code></pre>
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) jobC = Job('C', 2) jobD = Job('D', 10) jobE = Job('E', 3) jobF = Job('F', 11) jobA.add_dependent(jobB) jobA.add_dependent(jobC) jobB.add_dependent(jobD) jobC.add_dependent(jobE) jobD.add_dependent(jobF) jobE.add_dependent(jobF) </code></pre> <p>so we have two possible paths</p> <pre><code>A-&gt;B-&gt;D-&gt;F 0+4+10+11 = 25 A-&gt;C-&gt;E-&gt;F 0+2+3+11 = 16 </code></pre> <p>so the longest paths would be the former</p> <p>Is there an easy way to gather the longest path, <code>A-&gt;B-&gt;D-&gt;F</code>?</p> <pre><code>def longest_path(root): paths = [] # some logic here return paths print longest_path(jobA) # should print A-&gt;B-&gt;D-&gt;F </code></pre>
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 ...: self.job = job ...: def _find_heaviest(self, job, path='', weight=0): ...: path += job.name ...: weight += job.weight ...: if not job.depends: ...: if weight &gt; self.weight: ...: self.weight = weight ...: self.path = path ...: else: ...: for job in job.depends: ...: self._find_heaviest(job, path, weight) ...: def __call__(self): ...: self._find_heaviest(self.job) ...: return '-&gt;'.join(list(self.path)), self.weight ...: In [112]: Heaviest(jobA)() Out[112]: ('A-&gt;B-&gt;D-&gt;F', 25) </code></pre> <p>An afterthought:</p> <p>It occurred to me last night that in case of cyclic dependency (see my comment), the solution above will not yield an answer, stopping with exception when maximum recursion depth is reached. Just adding the line below will blow any tree traversing algorithm - not just this one.</p> <pre><code>In [226]: jobF.add_dependent(jobA) In [227]: Heaviest(jobA)() --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) &lt;ipython-input-227-94e994624b4e&gt; in &lt;module&gt;() ----&gt; 1 Heaviest(jobA)() &lt;ipython-input-111-1ff9f69480a9&gt; in __call__(self) 15 self._find_heaviest(job, path, weight) 16 def __call__(self): ---&gt; 17 self._find_heaviest(self.job) 18 return '-&gt;'.join(list(self.path)), self.weight 19 &lt;ipython-input-111-1ff9f69480a9&gt; in _find_heaviest(self, job, path, weight) 13 else: 14 for job in job.depends: ---&gt; 15 self._find_heaviest(job, path, weight) 16 def __call__(self): 17 self._find_heaviest(self.job) ... last 1 frames repeated, from the frame below ... &lt;ipython-input-111-1ff9f69480a9&gt; in _find_heaviest(self, job, path, weight) 13 else: 14 for job in job.depends: ---&gt; 15 self._find_heaviest(job, path, weight) 16 def __call__(self): 17 self._find_heaviest(self.job) RuntimeError: maximum recursion depth exceeded </code></pre> <p>While I leave attempt to mend the implementation to you - if you wish - simple safeguard can fix that</p> <pre><code>def _find_heaviest(self, job, path='', weight=0): if not job.name in path: path += job.name weight += job.weight stop_search = not job.depends else: stop_search = True if stop_search: if weight &gt; self.weight: </code></pre> <p>.....</p> <p>Problem solved</p> <pre><code>In [230]: Heaviest(jobA)() Out[230]: ('A-&gt;B-&gt;D-&gt;F', 25) </code></pre>
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 the variables. This is what i have done so far.</p> <pre><code>class appl: def __init__(self, master): self.master = master self.frame = tk.Frame( self.master, width=800, height=700 ) self.var = tk.IntVar( ) self.func1 = tk.Radiobutton( self.frame, text='fun1', value=1, variable=self.var,command=self.new_window ) self.func1.pack( ) self.frame.pack( ) def new_window(self): self.newWindow = tk.Toplevel(self.master) self.intvar1 = tk.IntVar() self.intvar2 = tk.IntVar() self.intvar3 = tk.IntVar() self.ent = tk.Button( self.newWindow, text='ENTER', state='disabled', command=self.validate_check ).grid(row=3, column=1 ) self.intvar1.trace( 'w', self.validate_check ) self.intvar2.trace( 'w', self.validate_check ) self.intvar3.trace( 'w', self.validate_check ) self.X = tk.Entry( self.newWindow,textvariable=self.intvar1 ) self.Y = tk.Entry( self.newWindow, textvariable=self.intvar2) self.Z = tk.Entry( self.newWindow, textvariable=self.intvar3) self.X.grid( row=0, column=1 ) self.Y.grid( row=1, column=1 ) self.Z.grid( row=2, column=1 ) tk.Label( self.newWindow, text=" X" ).grid( row=0 ) tk.Label( self.newWindow, text=" Y" ).grid( row=1 ) tk.Label( self.newWindow, text=" Z" ).grid( row=2 ) def validate_check(self, *args): x = self.intvar1.get() y = self.intvar2.get() z = self.intvar3.get() if x and y and z: self.ent.config(state=NORMAL) else: self.ent.config(state=DISABLED) def main(): root = tk.Tk() app = appl(root) root.mainloop() if __name__ == '__main__': main() </code></pre>
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 ) self.ent.grid(row=3, column=1 ) </code></pre> <p>Also, when you input something other than <code>0-9</code> in the entry boxes, <code>validate_check(...)</code> will raise exception because the entry text cannot be converted to integer value. Try changing <code>validate_check(...)</code> to:</p> <pre><code>def validate_check(self, *args): try: x = self.intvar1.get() y = self.intvar2.get() z = self.intvar3.get() # all three entries are valid integers, enable the button self.ent.config(state=tk.NORMAL) except: # something wrong on the entries, disable the button self.ent.config(state=tk.DISABLED) </code></pre>
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...') connectionSocket, addr = serverSocket.accept() print("connected from: ", addr) try: message = connectionSocket.recv(1024) filename = message.split()[1] f = open(filename[1:]) outputdata = f.read() connectionSocket.send("HTTP/1.1 200 OK\r\n") for i in range(0, len(outputdata)): connectionSocket.send(outputdata[i].encode()) connectionSocket.send("\r\n".encode()) connectionSocket.close() except IOError: connectionSocket.send("file not found") serverSocket.close() sys.exit() </code></pre> <p>The error comes from the open statement. I dont fully understand how this line of code's return value is organized.</p> <pre><code>message = connectionSocket.recv(1024) </code></pre> <p>I know that the return value is in bytes but when I try to use a fuction to turn it into a string like decode() i get errors as well</p> <p>I have the .py file and the html file sitting in the same directory on my local machine and the way I test this is I just run this and open up a browser and type in</p> <pre><code>http://127.0.0.1:4567/helloworld.html </code></pre> <p>My code then promptly crashes after receiving the HTTP request. Any and all help will be greatly appreciated!</p>
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 character you send back to the client.</p> <p>Also, it doesn't deal with the client disconnecting because you're sending back invalid data.</p> <p>Even if what you were trying to do didn't have these errors in it, you don't appear to be attempting to send back a valid http response. </p> <p><a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html" rel="nofollow">https://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html</a></p>
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 &lt;open file 'MVL_ref.txt', mode 'r' at 0x0267D230&gt; print f.read() # same output of the for-cycle print f.readline() # same output of the for-cycle </code></pre> <p>The for-loop is printing each line that is present in my text file. However, if I print the file object I get something totally different. This puzzles me because I would expect that I had to use something like:</p> <pre><code>for line in f.read(): print line </code></pre> <p>but of course this is not the case. If I use the read or readline methods without a for-loop I get the same output of the for-loop. </p> <p>Is the for-loop doing some magic like calling read() or readline() by default on the file object? I am learning how to code with python but I fell I don't really understand much of what the code is doing "behind my back". </p> <p>Thank you for all the explanations that will come.</p>
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><code>l = ["line1", "line2"] print l </code></pre> <p>but you will see entity description</p> <pre><code>&lt;open file 'path_to_the_file', mode 'r' at 0x0245D020&gt; </code></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 classifier, but it sends a error message call "ValueError: X has 2 features per sample; expecting 908430" for this code "Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])"</p> <pre><code>clf = SGDClassifier().fit(step2, index) X=step2 y=index h = .02 colors = "bry" x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h)) Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) # Put the result into a color plot Z = Z.reshape(xx.shape) plt.contourf(xx, yy, Z, cmap=plt.cm.Paired) plt.axis('off') # Plot also the training points plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired) </code></pre> <p>the 'index' is a label which contain around [98579 X 1] label for the comment which include positive, natural and negative</p> <pre><code>array(['N', 'N', 'P', ..., 'NEU', 'P', 'N'], dtype=object) </code></pre> <p>the 'step2' is the [98579 X 908430] numpy matrix which formed by the Countvectorizer function, which is about the comment data</p> <pre><code>&lt;98579x908430 sparse matrix of type '&lt;type 'numpy.float64'&gt;' with 3168845 stored elements in Compressed Sparse Row format&gt; </code></pre>
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 trained on <strong>2D data</strong> (reduced Iris) and this is <strong>the only reason</strong> why they were able to plot it.</p>
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 in dataset.iterrows(): print(row['Summary']) </code></pre> <p>I tried to add <code>encoding</code> to <code>read_csv()</code>, it didn't work. I tried <code>unicode</code>, <code>decode</code>(UTF-8) ... Nothing worked.</p> <p>Then I tried to concatenate those extracted words with some text, and I got a utf-8 error, I don't know how to deal with that. Thanks</p>
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" ]