title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
Jinja2 include & extends not working as expected
39,555,769
<p>I used <code>include</code> and <code>extends</code> in the <code>base.html</code> file and expect them to be included in order. But the <code>extends</code> template is appended to the end of the file.</p> <p>I expect my template to give me the output of:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Title&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;p&gt;Test String from block !&lt;/p&gt; &lt;footer&gt;text from footer.&lt;/footer&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>but the current result are:</p> <pre class="lang-html prettyprint-override"><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Title&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;footer&gt;text from footer.&lt;/footer&gt; &lt;/body&gt; &lt;/html&gt; &lt;p&gt;Test String from block !&lt;/p&gt; </code></pre> <p>In <code>base.html</code>, first I include <code>header.html</code>, then <code>content.html</code> and then <code>footer.html</code> but the rendered order is <code>header.html</code>, <code>footer.html</code>, <code>content.html</code>.</p> <p><code>index.html</code></p> <pre><code>{% extends "base.html" %} {% block content %} &lt;p&gt;Test String from block !&lt;/p&gt; {% endblock %} </code></pre> <p><code>base.html</code></p> <pre><code>{% include "header.html" %} &lt;body&gt; {% extends "content.html" %} {% include "footer.html" %} </code></pre> <p><code>header.html</code></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Title&lt;/title&gt; &lt;/head&gt; </code></pre> <p><code>content.html</code></p> <pre><code>{% block content %} {% endblock %} </code></pre> <p><code>footer.html</code></p> <pre><code>&lt;footer&gt;text from footer.&lt;/footer&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
2
2016-09-18T08:47:49Z
39,556,662
<p>I would suggest structuring slightly differently. I used a structure like this just recently and got the proper results.</p> <p>index.html:</p> <pre><code>{% extends "base.html" %} {% block head %} &lt;!-- if you want to change the &lt;head&gt; somehow, you can do that here --&gt; {% endblock head %} {% block content %} &lt;body&gt; &lt;p&gt;Test String from block !&lt;/p&gt; {% include 'content.html' %} &lt;/body&gt; {% include 'footer.html' %} {% endblock content %} </code></pre> <p>base.html:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; {% block head %} &lt;meta charset="UTF-8"&gt; &lt;title&gt;Title&lt;/title&gt; {% endblock head %} &lt;/head&gt; {% block content %} {% endblock content %} &lt;/html&gt; </code></pre> <p>content.html:</p> <pre><code>&lt;!-- whatever you want in here --&gt; </code></pre> <p>footer.html:</p> <pre><code>&lt;footer&gt;text from footer.&lt;/footer&gt; </code></pre> <p>Hopefully that helps.</p>
1
2016-09-18T10:30:21Z
[ "python", "flask", "jinja2" ]
How to populate a dropdown in Django?
39,555,782
<p>I want to build a simple view using Django. There will be a dropdown of 'customer site's and then, after one customer site is selected the view will populate a dropdown of competitors of previously selected customer. My trouble is with the second part: when I select the customer from the first dropdown and press 'choose' the page reloads but the competitors dropdown is empty:</p> <p>I debugged the code and there are values returned for the competitors dropdown and they are correct. I have this single view:</p> <pre><code>def index_unify_brands(request): class CustomerSiteDropDown(forms.Form): customer_site_id = forms.ChoiceField(Site.objects.filter(site_type='customer').exclude( crawl_groups='').values_list('id', 'site_name').order_by('site_name'), required=True) class OptionsForm(forms.Form): competitors_site_ids = forms.ChoiceField() def populate_competitors_in_dropdown(self,customer_site_id): competitors_ids = get_competitors_positions(customer_site_id)[ customer_site_id].keys() # todo: if no competitors print competitors_ids competitors_for_dropdown = Site.objects.filter(id__in=competitors_ids).exclude(crawl_groups='') \ .values_list('id', 'site_name').order_by('site_name') print competitors_for_dropdown self.competitors_site_ids = forms.ChoiceField(competitors_for_dropdown, required=True) if request.method == 'POST': # received request for a specific customer site id customer_dropdown_form = CustomerSiteDropDown(request.POST) options_form = OptionsForm(request.POST) options_form.populate_competitors_in_dropdown(int(request.POST['customer_site_id'])) if customer_dropdown_form.is_valid(): return render_to_response('manage/unify_brands/unify_brands.html', {'customer_dropdown_form': customer_dropdown_form, 'options_form': options_form}, context_instance=RequestContext(request) ) else: customer_dropdown_form = CustomerSiteDropDown() return render_to_response('manage/unify_brands/unify_brands.html', {'customer_dropdown_form': customer_dropdown_form}, context_instance=RequestContext(request)) </code></pre> <p>It seems that when I instantiate the <code>OptionsForm</code> object, the <code>options_form.populate_competitors_in_dropdown(....)</code> method doesn't change the dropdown inside this object that is represented by <code>competitors_site_ids</code> variable.</p> <p>Any idea what I do wrong here?</p>
0
2016-09-18T08:49:21Z
39,556,075
<p>In your form, <code>self.competitors_site_ids</code> isn't anything relevant. You need to assign to <code>self.fields['competitors_site_ids']</code>.</p> <p>Also this code should probably be in <code>__init__</code>, not a separate method.</p>
0
2016-09-18T09:25:52Z
[ "python", "django" ]
Return the different child object depending on the condition using the same method
39,555,914
<p>I have a two child classes which are inherited from the base class. I have one method in the different script which will actually return one of the child class object depending on some condition, is it the correct way in python to return the different child object using the same method. I think yes as their type is same and they are inherited from the same base class? Or should type casting be done? Please guide the below example is just for explaining the question in simple terms.</p> <pre><code>class A(): class B(A): Different methods class C(A): Different methods </code></pre> <p>Other Script: </p> <pre><code>def test_func: if &lt;some-condition&gt; new_obj = B() else new_obj = C() return new_obj </code></pre>
-1
2016-09-18T09:07:10Z
39,556,215
<p>Python is a dynamically typed language. One does not declare types. So, from that side, it is perfectly fine to pass arguments and return values of any type.</p> <p>On the other hand, you want your objects to be usable, so some interface has to be adhered to. For example, you can often pass any object with <code>read</code> and <code>readline</code> methods instead of an opened file. That is not only acceptable, but actually one of the strong advantages of Python over some other languages.</p> <p>In this question, the case is even cleaner than what is usually done in Python. This pattern is valid even in e.g. much stricter C++ (see <a href="http://stackoverflow.com/questions/4665117/c-virtual-function-return-type">this question</a>).</p> <p><strong>TL;DR:</strong></p> <p>Yes, it is fine. It would even be fine without inheriting from <code>A</code>, as long as <code>B</code> and <code>C</code> looked and behaved (and <a href="https://en.wikipedia.org/wiki/Duck_test" rel="nofollow">quacked</a>) similarly enough for the code using <code>test_func</code> to work.</p>
0
2016-09-18T09:40:35Z
[ "python" ]
How can I update a Gtk.TextView from events from a different thread?
39,556,006
<p>In a separate thread, I check for information in the pySerial Buffer (Infinite Loop). If new information is available, I'd like to show that Input in a <code>Gtk.TextView</code>. After Googling on the subject it turns out doing Gtk -Stuff inside threads is a killer. Random errors will appear and so on, which was also a problem I ran into.</p> <p>I decided to use a queue to synchronize the thread with the GUI. Putting information into a queue is pretty simple, but how do I suppose to check in the mainloop if there are any entries in the queue? </p> <p>Some kind of event would be nice, which triggers if any new information is available.</p> <p>Is there anything of that kind? Maybe a function exists to implement custom python code into the GTK3+ mainloop?</p>
1
2016-09-18T09:17:26Z
39,558,636
<p>Found a Solution:</p> <blockquote> <p>GObject.timeout_add</p> </blockquote> <p><a href="http://www.pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--timeout-add" rel="nofollow">http://www.pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--timeout-add</a></p> <p>This GObject Function implements a Callback to a own Function every X Milliseconds. Found a pritty simple Explanation here:</p> <p><a href="https://gist.github.com/jampola/473e963cff3d4ae96707" rel="nofollow">https://gist.github.com/jampola/473e963cff3d4ae96707</a></p> <p>So i can work down all Informations gathered from the Queue every X Milliseconds. Nice way for dealing with Threads! </p>
1
2016-09-18T14:19:46Z
[ "python", "user-interface", "queue", "gtk3", "python-multithreading" ]
How can I update a Gtk.TextView from events from a different thread?
39,556,006
<p>In a separate thread, I check for information in the pySerial Buffer (Infinite Loop). If new information is available, I'd like to show that Input in a <code>Gtk.TextView</code>. After Googling on the subject it turns out doing Gtk -Stuff inside threads is a killer. Random errors will appear and so on, which was also a problem I ran into.</p> <p>I decided to use a queue to synchronize the thread with the GUI. Putting information into a queue is pretty simple, but how do I suppose to check in the mainloop if there are any entries in the queue? </p> <p>Some kind of event would be nice, which triggers if any new information is available.</p> <p>Is there anything of that kind? Maybe a function exists to implement custom python code into the GTK3+ mainloop?</p>
1
2016-09-18T09:17:26Z
39,558,651
<p>To successfully periodically update the GUI from events in a thread, we cannot simply use <code>threading</code> to start a second process. Like you mention, it will lead to conflicts.</p> <p>Here is where <code>GObject</code> comes in, to, as it is put in <a href="http://faq.pygtk.org/index.py?req=edit&amp;file=faq20.006.htp" rel="nofollow">this (slightly outdated) link</a> :</p> <blockquote> <p>call gobject.threads_init() at applicaiton initialization. Then you launch your threads normally, but make sure the threads never do any GUI tasks directly. Instead, you use gobject.idle_add to schedule GUI task to executed in the main thread</p> </blockquote> <p>When we replace <code>gobject.threads_init()</code> by <code>GObject.threads_init()</code> and <code>gobject.idle_add</code> by <code>GObject.idle_add()</code>, we pretty much have the updated version of how to run threads in a Gtk application. A simplified example, showing an increasing number of Monkeys in your textfield. See the comments in the code:</p> <h3>Example, counting an updated number of monkeys in your TextView:</h3> <p><a href="http://i.stack.imgur.com/Urg2i.png" rel="nofollow"><img src="http://i.stack.imgur.com/Urg2i.png" alt="enter image description here"></a>...<a href="http://i.stack.imgur.com/9MLbC.png" rel="nofollow"><img src="http://i.stack.imgur.com/9MLbC.png" alt="enter image description here"></a>...<a href="http://i.stack.imgur.com/3oxkx.png" rel="nofollow"><img src="http://i.stack.imgur.com/3oxkx.png" alt="enter image description here"></a></p> <pre><code>#!/usr/bin/env python3 import gi gi.require_version('Gtk', '3.0') from gi.repository import Gtk, GObject import time from threading import Thread class InterFace(Gtk.Window): def __init__(self): Gtk.Window.__init__(self, title="Test 123") maingrid = Gtk.Grid() maingrid.set_border_width(10) self.add(maingrid) scrolledwindow = Gtk.ScrolledWindow() scrolledwindow.set_hexpand(True) scrolledwindow.set_vexpand(True) scrolledwindow.set_min_content_height(50) scrolledwindow.set_min_content_width(150) maingrid.attach(scrolledwindow, 0,0,1,1) self.textfield = Gtk.TextView() self.textbuffer = self.textfield.get_buffer() self.textbuffer.set_text("Let's count monkeys") self.textfield.set_wrap_mode(Gtk.WrapMode.WORD) scrolledwindow.add(self.textfield) # 1. define the tread, updating your text self.update = Thread(target=self.counting_monkeys) # 2. Deamonize the thread to make it stop with the GUI self.update.setDaemon(True) # 3. Start the thread self.update.start() def counting_monkeys(self): # replace this with your thread to update the text n = 1 while True: time.sleep(2) newtext = str(n)+" monkey" if n == 1 else str(n)+" monkeys" GObject.idle_add( self.textbuffer.set_text, newtext, priority=GObject.PRIORITY_DEFAULT ) n += 1 def run_gui(): window = InterFace() # 4. this is where we call GObject.threads_init() GObject.threads_init() window.show_all() Gtk.main() run_gui() </code></pre>
2
2016-09-18T14:22:04Z
[ "python", "user-interface", "queue", "gtk3", "python-multithreading" ]
Django migrations in subfolders
39,556,018
<p>I have the following project structure:</p> <pre><code>bm_app_1 | contents here bm_app_2 | contents here bm_common | __init__.py | deletable | | __init__.py | | behaviors.py | | models.py | timestampable | | __init__.py | | behaviors.py </code></pre> <p>The files in app <code>bm_common</code> define managed models, that I want in migration files. When I run <code>python managepy makemigrations</code> however, the files inside the subfolders of the app <code>bm_common</code> are not taken into account. All apps are in <code>INSTALLED_APPS</code></p> <pre><code>PREREQ_APPS = [ required apps here ] PROJECT_APPS = [ 'bm_common', 'bm_app_1', 'bm_app_2' ] INSTALLED_APPS = PREREQ_APPS + PROJECT_APPS </code></pre> <p>Is there a way to change the behavior of <code>makemigrations</code> to look into subfolders as well? If not, what would be a good suggestion to make this split? I do not want to have all behaviors in one <code>behaviors.py</code>, because it grows too big and was causing circular references for me.</p>
0
2016-09-18T09:18:38Z
39,556,055
<p>The models need to be imported in some way when the app registry is populating all models, otherwise they are not registered and Django doesn't know about them. The easiest solution is to create a <code>bm_common/models.py</code> file and import all models in there:</p> <pre><code>from .deletable.models import ModelA, ModelB from .timestampable.models import ModelC ... </code></pre>
1
2016-09-18T09:24:01Z
[ "python", "django", "django-models", "django-migrations" ]
How to keep variable in for loop and others'conditional statement wouldn't change it
39,556,032
<p>when program executed the second <code>if</code> and change <code>P = 0</code>, it will execute the next <code>if</code>. I know it's wrong, but I curiously wonder how to hold variables(<code>P</code>) constant and don't impact other in the if statement.</p> <pre><code> """ :type a: str :type b: str :rtype: str """ class Solution(object): def addBinary(self, a, b): c = '' P = 0 for i,j in zip(range(len(a)-1, -1, -1),range(len(b)-1, -1, -1)): if a[i] + b[j] == '11': c = c + '0' P = 1 if a[i] + b[j] == '10' or a[i] + b[j] == '01' and P == 1: c = c + '0' P = 0 if a[i] + b[j] == '10' or a[i] + b[j] == '01' and P == 0: c = c + '1' if a[i] + b[j] == '00' and P == 1: c = c + '1' P =0 if a[i] + b[j] == '00' and P == 0: c = c + '0' T = len(a) - len(b) if T &gt; 0: c = c + a[:T] else: c = c + b[:T] return c[::-1] </code></pre>
1
2016-09-18T09:20:45Z
39,556,067
<p>Use <code>elif</code> (else if).</p> <p>Instead of:</p> <pre><code>if something: change_something() if something_else: change_something_else() </code></pre> <p>Do:</p> <pre><code>if something: change_something() elif something_else: change_something_else() </code></pre>
2
2016-09-18T09:25:09Z
[ "python", "if-statement", "condition" ]
How to keep variable in for loop and others'conditional statement wouldn't change it
39,556,032
<p>when program executed the second <code>if</code> and change <code>P = 0</code>, it will execute the next <code>if</code>. I know it's wrong, but I curiously wonder how to hold variables(<code>P</code>) constant and don't impact other in the if statement.</p> <pre><code> """ :type a: str :type b: str :rtype: str """ class Solution(object): def addBinary(self, a, b): c = '' P = 0 for i,j in zip(range(len(a)-1, -1, -1),range(len(b)-1, -1, -1)): if a[i] + b[j] == '11': c = c + '0' P = 1 if a[i] + b[j] == '10' or a[i] + b[j] == '01' and P == 1: c = c + '0' P = 0 if a[i] + b[j] == '10' or a[i] + b[j] == '01' and P == 0: c = c + '1' if a[i] + b[j] == '00' and P == 1: c = c + '1' P =0 if a[i] + b[j] == '00' and P == 0: c = c + '0' T = len(a) - len(b) if T &gt; 0: c = c + a[:T] else: c = c + b[:T] return c[::-1] </code></pre>
1
2016-09-18T09:20:45Z
39,556,079
<p>Don't you want to use <code>elif</code>?</p> <pre><code>if a[i] + b[j] == '10' or a[i] + b[j] == '01' and P == 1: c = c + '0' P = 0 elif a[i] + b[j] == '10' or a[i] + b[j] == '01' and P == 0: c = c + '1' elif a[i] + b[j] == '00' and P == 1: c = c + '1' P =0 elif a[i] + b[j] == '00' and P == 0: </code></pre>
1
2016-09-18T09:26:11Z
[ "python", "if-statement", "condition" ]
Running pdflatex from a python script (3.5.2)
39,556,116
<p>I am trying to run pdflatex from a python script using the subprocess module but for some reason python cannot find the pdflatex module. I can call pdflatex from a command prompt and it works without any issues. I have verified that the path to pdflatex exists under environment variables. I have a MikTex 2.9 installation which works from TexWorks as well as Texstudio. </p> <p>I have installed the latex package for python (which also uses the subprocess module) but that too cannot find pdflatex.</p> <p>I am running Win 10 but I can reproduce the problem on Win 7 and Win 8. I had found a solution for Win 7 based on the env parameter but cannot find it now for some reason. </p> <p>Does anyone have any idea for how to get pdflatex to work properly with Python?</p> <p>Best regards,</p>
0
2016-09-18T09:30:17Z
39,556,191
<p>You should try <a href="https://github.com/aclements/latexrun" rel="nofollow">latexrun</a>. This takes care of running all latex related commands.</p>
0
2016-09-18T09:37:24Z
[ "python", "subprocess", "pdflatex" ]
Bokeh is behaving in mysterious way
39,556,175
<pre><code>import numpy as np from bokeh.plotting import * from bokeh.models import ColumnDataSource </code></pre> <h1>prepare data</h1> <pre><code>N = 300 x = np.linspace(0,4*np.pi, N) y0 = np.sin(x) y1 = np.cos(x) output_notebook() #create a column data source for the plots to share source = ColumnDataSource(data = dict(x = x, y0 = y0, y1 = y1)) Tools = "pan, wheel_zoom, box_zoom, reset, save, box_select, lasso_select" </code></pre> <h1>create a new plot and add a renderer</h1> <pre><code>left = figure(tools = Tools, plot_width = 350, plot_height = 350, title = 'sinx') left.circle(x, y0,source = source ) </code></pre> <h1>create another plot and add a renderer</h1> <pre><code>right = figure(tools = Tools, plot_width = 350, plot_height = 350 , title = 'cosx') right.circle(x, y1, source = source) </code></pre> <h1>put the subplot in gridplot and show the plot</h1> <pre><code>p = gridplot([[left, right]]) show(p) </code></pre> <p><a href="http://i.stack.imgur.com/To6If.png" rel="nofollow"><img src="http://i.stack.imgur.com/To6If.png" alt="enter image description here"></a></p> <p><strong>something is wrong with sin graph. Don't know why 'Bokeh' is behaving like this.But if I write y's into Double or single quotation marks/inverted commas then things work fine</strong> </p> <pre><code>left.circle(x, 'y0',source = source ) right.circle(x, 'y1', source = source) </code></pre> <h1>put the subplot in gridplot and show the plot</h1> <pre><code>p = gridplot([[left, right]]) show(p) </code></pre> <p><a href="http://i.stack.imgur.com/OFNQh.png" rel="nofollow"><img src="http://i.stack.imgur.com/OFNQh.png" alt="enter image description here"></a></p> <p>Things I tried to resolve the problem</p> <p>1) Restarted my notebook . (Easiest way to solve problem)</p> <p>2) Generated the output into new window.</p> <p>3) Generated plot separately instead of grid plot.</p> <p>Please help me out to find out the reason behind the scene. </p> <p>Am I doing something wrong ? Is it a bug ?</p>
0
2016-09-18T09:36:24Z
39,562,869
<p>If you want to configure multiple glyphs to share data from a single <code>ColumnDataSource</code>, then you always need to configure the glyph properties with the <em>names</em> of the columns, and <strong><em>not</em></strong> with the actual data literals, as you have done. In other words:</p> <pre><code>left.circle('x', 'y0',source = source ) right.circle('x', 'y1', source = source) </code></pre> <p>Note that I have quoted <code>'x'</code> as well. This is the correct way to do things when sharing a source. When you pass a literal value (i.e., a real list or array), glyphs functions like <code>.circle</code> automatically synthesize a column for you as a convenience. But they use defined names based on the property, so if you share a source between two renderers, then the second call to <code>.circle</code> will overwrite the column <code>'y'</code> column that the first call to <code>.circle</code> made. Which is exactly what you are seeing. </p> <p>As you can imagine, this behavior is confusing. Accordingly, there is an <a href="https://github.com/bokeh/bokeh/issues/2056" rel="nofollow">open GitHub issue</a> to specifically and completely disallow passing in data literals whenever the <code>source</code> argument is provided explicitly. I can guarantee this will happen in the near future, so if you are sharing a source, you should always and only pass in <em>column names</em> (i.e. strings).</p>
0
2016-09-18T21:29:55Z
[ "python", "python-3.x", "debugging", "data-visualization", "bokeh" ]
Computer guessing game
39,556,504
<pre><code>import random def start(): print "\t\t***-- Please enter Y for Yes and N for No --***" answer = raw_input("\t\t Would you like to play a Guessing Game?: ") if answer == "Y" or answer == "y": game() elif answer == "N" or answer == "n": end() def end(): print("\t\t\t **Goodbye** ") raw_input("\t\t\t**Press ENTER to Exit**") def game(): print "\t\t\t Welcome to Williams Guessing Game" user_name = raw_input("\n\t\t Please enter your name: ") print "\n", user_name, "I am thinking of a number between 1 and 20" print "You have 5 attempts at getting it right" attempt = 0 number = random.randint(1, 20) while attempt &lt; 5: guess = input("\t\nPlease enter a number: ") attempt = attempt + 1 answer = attempt if guess &lt; number: print "\nSorry", user_name, "your guess was too low" print "You have ", 5 - attempt, " attempts left\n" elif guess &gt; number: print "\nSorry ", user_name, " your guess was too high" print "You have ", 5 - attempt, " attempts left\n" elif guess == number: print "\n\t\t Yay, you selected my lucky number. Congratulations" print "\t\t\tYou guessed it in", attempt, "number of attempts!\n" answer = raw_input("\n\t\t\t\tTry again? Y/N?: ") if answer == "Y" or answer == "y": game() elif answer == "N" or answer == "n": end() start() </code></pre>
-2
2016-09-18T10:12:59Z
39,557,100
<p>If you want the computer to guess your number, you could use a function like this:</p> <pre><code>import random my_number = int(raw_input("Please enter a number between 1 and 20: ")) guesses = [] def make_guess(): guess = random.randint(1, 20) while guess in guesses: guess = random.randint(1, 20) guesses.append(guess) return guess while True: guess = make_guess() print(guess) if guess == my_number: print("The computer wins!") break else: print(guesses) </code></pre> <p>It's just a quick-and-dirty example, but I hope it gives you the idea. This way, the computer gets unlimited guesses, but you could easily change the <code>while</code> loop to limit its number of guesses.</p>
0
2016-09-18T11:22:33Z
[ "python" ]
Connecting to MySQL over SSH using Python
39,556,553
<p>I need some help adding tables from a desktop PC to an existing MySQL database (db name DB2639162) on a webserver using a python script. I have written the following script (create_db.py):</p> <pre><code>import MySQLdb from sshtunnel import SSHTunnelForwarder ssh_pwd='' ssh_usr='' mysql_pwd='' mysql_usr='' with SSHTunnelForwarder(('ssh.strato.de', 22), ssh_password=ssh_pwd, ssh_username=ssh_usr, remote_bind_address=('rdbms', 3306)) as server: print 'Server connected via SSH!' db1 = MySQLdb.connect(host='127.0.0.1', port=server.local_bind_port, user=mysql_usr, passwd=mysql_pwd, db='DB2639162') cursor = db1.cursor() sql = 'CREATE TABLE mydata' cursor.execute(sql) db1.close() </code></pre> <p>But unfortunately the script does not work and I get the output below. Obviously, the SSH connection can be established successfully, but the access to the database fails.</p> <pre><code>Server connected via SSH! 2016-09-18 11:02:19,291| ERROR | Secsh channel 0 open FAILED: open failed: Administratively prohibited 2016-09-18 11:02:19,295| ERROR | Could not establish connection from ('127.0.0.1', 44017) to remote side of the tunnel Traceback (most recent call last): File "create_db.py", line 18, in &lt;module&gt; db='DB2639162') File "build/bdist.linux-x86_64/egg/MySQLdb/__init__.py", line 81, in Connect File "build/bdist.linux-x86_64/egg/MySQLdb/connections.py", line 193, in __init__ _mysql_exceptions.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0") </code></pre> <p>Additionally, the usernames, passwords are fine as the terminal commands work well and grant me access to the MySQL database.</p> <pre><code>ssh ssh_usr@ssh.strato.de mysql -h rdbms -u mysql_usr -p DB2639162 </code></pre> <p>Thank you in advance</p>
0
2016-09-18T10:18:56Z
39,558,723
<p>The answer is right there in the error message:</p> <blockquote> <p>2016-09-18 11:02:19,291| ERROR | Secsh channel 0 open FAILED: open failed: Administratively prohibited</p> </blockquote> <p>Running the MySQL command-line client in a shell session on a server and setting up port forwarding/tunneling are completely different things. The fact that you can do one does not imply that you can do the other.</p> <p>This server obviously forbids port forwarding/tunneling ("Administratively prohibited"). You'll need a different approach.</p>
1
2016-09-18T14:28:39Z
[ "python", "mysql", "linux", "ssh" ]
Convert &#xxxx; to normal character?
39,556,554
<p>lxml.etree.parse() have generate string in utf-16 file as &amp;#xxxx; How can I convert it back?</p> <p>Opening output file in web browser is fine. However I still need regular string in output file, too.</p> <p>Example file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-16"?&gt; &lt;?xml-stylesheet type="text/xsl" href="xxx.xsl"?&gt; &lt;TEI.2&gt; &lt;teiHeader&gt;&lt;/teiHeader&gt; &lt;text&gt; &lt;front&gt;&lt;/front&gt; &lt;body&gt; &lt;p rend="chapter"&gt;อธิกรณปจฺจยกถาวณฺณนา&lt;/p&gt; &lt;p rend="bodytext" n="285"&gt;&lt;hi rend="paranum"&gt;๒๘๕&lt;/hi&gt;&lt;hi rend="dot"&gt;.&lt;/hi&gt; &lt;hi rend="bold"&gt;วิวาทาธิกรณมฺหา&lt;/hi&gt;ติ ‘‘อธมฺมํ ‘ธโมฺม’ติ ทีเปตี’’ติอาทินยปฺปวตฺตา อฎฺฐารสเภทกรวตฺถุนิสฺสิตา วิวาทาธิกรณมฺหาฯ&lt;/p&gt; &lt;/body&gt; &lt;back&gt;&lt;/back&gt; &lt;/text&gt; &lt;/TEI.2&gt; </code></pre> <p>Code:</p> <pre><code>#coding:utf8 import lxml.etree as ET xml_filename="example.xml" dom = ET.parse(xml_filename) print ET.tostring(dom, pretty_print=True)) </code></pre> <p>Example output:</p> <pre><code>&lt;?xml-stylesheet type="text/xsl" href="xxx.xsl"?&gt;&lt;TEI.2&gt; &lt;teiHeader/&gt; &lt;text&gt; &lt;front/&gt; &lt;body&gt; &lt;p rend="chapter"&gt;&amp;#3607;&amp;#3640;&amp;#3585;&amp;#3617;&amp;#3634;&amp;#3605;&amp;#3636;&amp;#3585;&amp;#3634;&amp;#3611;&amp;#3607;&amp;#3623;&amp;#3603;&amp;#3642;&amp;#3603;&amp;#3609;&amp;#3634;&lt;/p&gt; &lt;/body&gt; &lt;back/&gt; &lt;/text&gt; &lt;/TEI.2&gt; </code></pre>
0
2016-09-18T10:19:02Z
39,557,045
<p>You need to specify the encoding when you use <em>tostring</em>:</p> <pre><code>dIn [2]: !cat "test.xml" ��&lt;?xml version="1.0" encoding="UTF-16"?&gt; &lt;?xml-stylesheet type="text/xsl" href="xxx.xsl"?&gt; &lt;TEI.2&gt; &lt;teiHeader&gt;&lt;/teiHeader&gt; &lt;text&gt; &lt;front&gt;&lt;/front&gt; &lt;body&gt; &lt;p rend="chapter"&gt;-4#"2':2&lt;/p&gt; &lt;p rend="bodytext" n="285"&gt;&lt;hi rend="paranum"&gt;RXU&lt;/hi&gt;&lt;hi rend="dot"&gt;.&lt;/hi&gt; &lt;hi rend="bold"&gt;'4'224#!:+2&lt;/hi&gt;4 -!:!M B!:! 4 5@5 4-24":':2 -:2#*@ #':84*:*42 '4'224#!:+2/&lt;/p&gt; &lt;/body&gt; &lt;back&gt;&lt;/back&gt; &lt;/text&gt; &lt;/TEI.2&gt; In [3]: import lxml.etree as ET In [4]: xml_filename = "test.xml" In [5]: dom = ET.parse(xml_filename) </code></pre> <p><em>utf-16:</em></p> <pre><code>In [6]: print ET.tostring(dom, pretty_print=True, encoding="utf-16") ��&lt;?xml version='1.0' encoding='utf-16'?&gt; &lt;?xml-stylesheet type="text/xsl" href="xxx.xsl"?&gt; &lt;TEI.2&gt; &lt;teiHeader/&gt; &lt;text&gt; &lt;front/&gt; &lt;body&gt; &lt;p rend="chapter"&gt;-4#"2':2&lt;/p&gt; &lt;p rend="bodytext" n="285"&gt;&lt;hi rend="paranum"&gt;RXU&lt;/hi&gt;&lt;hi rend="dot"&gt;.&lt;/hi&gt; &lt;hi rend="bold"&gt;'4'224#!:+2&lt;/hi&gt;4 -!:!M B!:! 4 5@5 4-24":':2 -:2#*@ #':84*:*42 '4'224#!:+2/&lt;/p&gt; &lt;/body&gt; &lt;back/&gt; &lt;/text&gt; &lt;/TEI.2&gt; </code></pre> <p><em>utf-8:</em></p> <pre><code>In [7]: print ET.tostring(dom, pretty_print=True, encoding="utf-8") &lt;?xml-stylesheet type="text/xsl" href="xxx.xsl"?&gt; &lt;TEI.2&gt; &lt;teiHeader/&gt; &lt;text&gt; &lt;front/&gt; &lt;body&gt; &lt;p rend="chapter"&gt;อธิกรณปจฺจยกถาวณฺณนา&lt;/p&gt; &lt;p rend="bodytext" n="285"&gt;&lt;hi rend="paranum"&gt;๒๘๕&lt;/hi&gt;&lt;hi rend="dot"&gt;.&lt;/hi&gt; &lt;hi rend="bold"&gt;วิวาทาธิกรณมฺหา&lt;/hi&gt;ติ ‘‘อธมฺมํ ‘ธโมฺม’ติ ทีเปตี’’ติอาทินยปฺปวตฺตา อฎฺฐารสเภทกรวตฺถุนิสฺสิตา วิวาทาธิกรณมฺหาฯ&lt;/p&gt; &lt;/body&gt; &lt;back/&gt; &lt;/text&gt; &lt;/TEI.2&gt; </code></pre> <p><em>ascii(default)</em>:</p> <pre><code>In [8]: print ET.tostring(dom, pretty_print=True, encoding="ascii") &lt;?xml-stylesheet type="text/xsl" href="xxx.xsl"?&gt; &lt;TEI.2&gt; &lt;teiHeader/&gt; &lt;text&gt; &lt;front/&gt; &lt;body&gt; &lt;p rend="chapter"&gt;&amp;#3629;&amp;#3608;&amp;#3636;&amp;#3585;&amp;#3619;&amp;#3603;&amp;#3611;&amp;#3592;&amp;#3642;&amp;#3592;&amp;#3618;&amp;#3585;&amp;#3606;&amp;#3634;&amp;#3623;&amp;#3603;&amp;#3642;&amp;#3603;&amp;#3609;&amp;#3634;&lt;/p&gt; &lt;p rend="bodytext" n="285"&gt;&lt;hi rend="paranum"&gt;&amp;#3666;&amp;#3672;&amp;#3669;&lt;/hi&gt;&lt;hi rend="dot"&gt;.&lt;/hi&gt; &lt;hi rend="bold"&gt;&amp;#3623;&amp;#3636;&amp;#3623;&amp;#3634;&amp;#3607;&amp;#3634;&amp;#3608;&amp;#3636;&amp;#3585;&amp;#3619;&amp;#3603;&amp;#3617;&amp;#3642;&amp;#3627;&amp;#3634;&lt;/hi&gt;&amp;#3605;&amp;#3636; &amp;#8216;&amp;#8216;&amp;#3629;&amp;#3608;&amp;#3617;&amp;#3642;&amp;#3617;&amp;#3661; &amp;#8216;&amp;#3608;&amp;#3650;&amp;#3617;&amp;#3642;&amp;#3617;&amp;#8217;&amp;#3605;&amp;#3636; &amp;#3607;&amp;#3637;&amp;#3648;&amp;#3611;&amp;#3605;&amp;#3637;&amp;#8217;&amp;#8217;&amp;#3605;&amp;#3636;&amp;#3629;&amp;#3634;&amp;#3607;&amp;#3636;&amp;#3609;&amp;#3618;&amp;#3611;&amp;#3642;&amp;#3611;&amp;#3623;&amp;#3605;&amp;#3642;&amp;#3605;&amp;#3634; &amp;#3629;&amp;#3598;&amp;#3642;&amp;#3600;&amp;#3634;&amp;#3619;&amp;#3626;&amp;#3648;&amp;#3616;&amp;#3607;&amp;#3585;&amp;#3619;&amp;#3623;&amp;#3605;&amp;#3642;&amp;#3606;&amp;#3640;&amp;#3609;&amp;#3636;&amp;#3626;&amp;#3642;&amp;#3626;&amp;#3636;&amp;#3605;&amp;#3634; &amp;#3623;&amp;#3636;&amp;#3623;&amp;#3634;&amp;#3607;&amp;#3634;&amp;#3608;&amp;#3636;&amp;#3585;&amp;#3619;&amp;#3603;&amp;#3617;&amp;#3642;&amp;#3627;&amp;#3634;&amp;#3631;&lt;/p&gt; &lt;/body&gt; &lt;back/&gt; &lt;/text&gt; &lt;/TEI.2&gt; </code></pre>
1
2016-09-18T11:15:27Z
[ "python", "html", "xml", "character-encoding", "lxml" ]
Generate MATLAB code from python
39,556,602
<p>I have a problem when using the <a href="http://se.mathworks.com/help/matlab/matlab-engine-for-python.html" rel="nofollow">MATLAB python engine</a>.</p> <p>I want to get approximated solutions to ODEs (using something like the <code>ode45</code> function in MATLAB) from Python, but the problem is that ODE approximation requires an ODE function specification that I can't seem to create from the MATLAB Python engine.</p> <p>It works fine calling MATLAB functions, such as <code>isprime</code>, from Python but there seems to be no way of specifying a MATLAB function in Python.</p> <p>My question is therefore; Are there any way of generating MATLAB function code from Python or is a way to specify MATLAB functions from Python? </p>
3
2016-09-18T10:24:05Z
39,559,459
<p><a href="https://www.mathworks.com/help/matlab/ref/ode45.html" rel="nofollow"><code>odefun</code> passed to <code>ode45</code>, according to docs, has to be a function handle</a>.</p> <blockquote> <p>Solve the ODE</p> <p>y' = 2t</p> <p>Use a time interval of [0,5] and the initial condition y0 = 0.</p> </blockquote> <pre><code>tspan = [0 5]; y0 = 0; [t,y] = ode45(@(t,y) 2*t, tspan, y0); </code></pre> <p><code>@(t,y) 2*t</code> returns a function handle to anonymous function.</p> <p>Unfortunately, <a href="http://www.mathworks.com/help/matlab/matlab_external/handle-data-returned-from-matlab-to-python.html" rel="nofollow">function handles are listed as one of datatypes unsupported in MATLAB &lt;-> Python conversion</a>:</p> <blockquote> <p><strong>Unsupported MATLAB Types The following MATLAB data types are not supported by the MATLAB Engine API for Python:</strong></p> <ul> <li>Categorical array</li> <li>char array (M-by-N)</li> <li>Cell array (M-by-N)</li> <li><strong>Function handle</strong></li> <li>Sparse array</li> <li>Structure array</li> <li>Table</li> <li>MATLAB value objects (for a discussion of handle and value classes see Comparison of Handle and Value Classes)</li> <li>Non-MATLAB objects (such as Java® objects)</li> </ul> </blockquote> <p>To sum up, it seems like there is no straightforward way of doing it.</p> <p>Potential workaround may involve some combination of <code>engine.workspace</code> and <code>engine.eval</code>, as shown in <a href="http://www.mathworks.com/help/matlab/matlab_external/use-the-matlab-engine-workspace-in-python.html" rel="nofollow">Use MATLAB Engine Workspace in Python</a> example.</p> <p>Workaround with <code>engine.eval</code> (<a href="https://www.mathworks.com/help/matlab/ref/ode45.html" rel="nofollow">first demo</a>):</p> <pre><code>import matlab.engine import matplotlib.pyplot as plt e = matlab.engine.start_matlab() tr, yr = e.eval('ode45(@(t,y) 2*t, [0 5], 0)', nargout=2) plt.plot(tr, yr) plt.show() </code></pre> <p>By doing so, you avoid passing function handle via MATLAB/Python barrier. You pass string (bytes) and allow MATLAB to evaluate it there. What's returned is pure numeric arrays. After that, you may operate on result vectors, e.g. plot them.</p> <p><a href="http://i.stack.imgur.com/DI2il.png" rel="nofollow"><img src="http://i.stack.imgur.com/DI2il.png" alt="Matplotlib result"></a></p> <p>Since passing arguments as literals would quickly became pain, <code>engine.workspace</code> may be used to avoid it:</p> <pre><code>import matlab.engine import matplotlib.pyplot as plt e = matlab.engine.start_matlab() e.workspace['tspan'] = matlab.double([0.0, 5.0]) e.workspace['y0'] = 0.0 tr, yr = e.eval('ode45(@(t,y) 2*t, tspan, y0)', nargout=2) plt.plot(tr, yr) plt.show() </code></pre>
1
2016-09-18T15:39:40Z
[ "python", "matlab", "python-3.x" ]
Django Test: error creating the test database: permission denied to copy database "template_postgis"
39,556,719
<p>I am am working on setting up Django Project for <code>running tests</code>. But I am getting below error:</p> <pre><code>Got an error creating the test database: permission denied to copy database "template_postgis" </code></pre> <p><strong>Note</strong>: My default application's database is working fine. The <code>issue is happening while running tests</code>.</p> <p>Complete stack trace is as:</p> <pre><code>moin@moin-pc:~/workspace/mozio$ python manage.py test --verbosity=3 nosetests --verbosity=3 nose.config: INFO: Ignoring files matching ['^\\.', '^_', '^setup\\.py$'] Creating test database for alias 'default' ('test_my_db')... Got an error creating the test database: permission denied to copy database "template_postgis" Type 'yes' if you would like to try deleting the test database 'test_mozio_db_test', or 'no' to cancel: yes Destroying old test database 'default'... Got an error recreating the test database: must be owner of database test_mozio_db_test </code></pre> <p>Below is the DATABASE configuration of <code>setting.py</code>:</p> <pre><code>POSTGIS_VERSION = (2, 2, 2) DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'my_db', 'USER': 'my_user', 'PASSWORD': 'my_pass', 'HOST': '&lt;HOST_IP', 'PORT': '', 'TEST': { 'NAME': 'test_my_db', }, } } </code></pre> <p>Any help regarding this? Below are the steps I tried:</p> <ul> <li><p>Grant create DB access to user:</p> <pre><code>ALTER USER my_user CREATEDB; </code></pre></li> <li><p>Grant all privileges to user for <code>test_my_db</code> database:</p> <pre><code>GRANT ALL PRIVILEGES ON DATABASE test_mozio_db_test to mozio; </code></pre></li> </ul> <hr> <p><strong>Edit</strong>: After fixing above issue, I was also getting error as:</p> <pre><code>django.db.utils.ProgrammingError: type "geometry" does not exist LINE 5: "polygon" geometry(POLYGON,4326) NOT NULL, </code></pre> <p>Updated my answer to fix both the issues.</p>
0
2016-09-18T10:36:40Z
39,556,765
<p>I finally found how to fix this issue. The problem is that when I created <code>template_postgis</code>, I didn’t set it to be a <code>template</code>.</p> <p>You can check it doing:</p> <pre><code>SELECT * FROM pg_database; </code></pre> <p>You can fix it doing:</p> <pre><code>update pg_database set datistemplate=true where datname='template_postgis'; </code></pre> <hr> <p>After that in case you are getting error related to <code>geometry</code> like:</p> <pre><code>django.db.utils.ProgrammingError: type "geometry" does not exist LINE 5: "polygon" geometry(POLYGON,4326) NOT NULL, </code></pre> <p>That is because you need to add extension <code>postgix</code> with database. In order to fix this, add <code>postgis</code> to <code>template_postgis</code> like:</p> <pre><code>psql -d psql -d template_postgis -c 'create extension postgis;' </code></pre> <p><em>Note</em>: You must be superuser to create this extension.</p>
0
2016-09-18T10:42:28Z
[ "python", "django", "postgis", "django-testing", "geodjango" ]
Django Test: error creating the test database: permission denied to copy database "template_postgis"
39,556,719
<p>I am am working on setting up Django Project for <code>running tests</code>. But I am getting below error:</p> <pre><code>Got an error creating the test database: permission denied to copy database "template_postgis" </code></pre> <p><strong>Note</strong>: My default application's database is working fine. The <code>issue is happening while running tests</code>.</p> <p>Complete stack trace is as:</p> <pre><code>moin@moin-pc:~/workspace/mozio$ python manage.py test --verbosity=3 nosetests --verbosity=3 nose.config: INFO: Ignoring files matching ['^\\.', '^_', '^setup\\.py$'] Creating test database for alias 'default' ('test_my_db')... Got an error creating the test database: permission denied to copy database "template_postgis" Type 'yes' if you would like to try deleting the test database 'test_mozio_db_test', or 'no' to cancel: yes Destroying old test database 'default'... Got an error recreating the test database: must be owner of database test_mozio_db_test </code></pre> <p>Below is the DATABASE configuration of <code>setting.py</code>:</p> <pre><code>POSTGIS_VERSION = (2, 2, 2) DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'my_db', 'USER': 'my_user', 'PASSWORD': 'my_pass', 'HOST': '&lt;HOST_IP', 'PORT': '', 'TEST': { 'NAME': 'test_my_db', }, } } </code></pre> <p>Any help regarding this? Below are the steps I tried:</p> <ul> <li><p>Grant create DB access to user:</p> <pre><code>ALTER USER my_user CREATEDB; </code></pre></li> <li><p>Grant all privileges to user for <code>test_my_db</code> database:</p> <pre><code>GRANT ALL PRIVILEGES ON DATABASE test_mozio_db_test to mozio; </code></pre></li> </ul> <hr> <p><strong>Edit</strong>: After fixing above issue, I was also getting error as:</p> <pre><code>django.db.utils.ProgrammingError: type "geometry" does not exist LINE 5: "polygon" geometry(POLYGON,4326) NOT NULL, </code></pre> <p>Updated my answer to fix both the issues.</p>
0
2016-09-18T10:36:40Z
39,556,812
<p>Install packages first correctly.</p> <pre><code>sudo apt-get update sudo apt-get install python-pip python-dev libpq-dev postgresql postgresql-contrib </code></pre> <p>During installation postgres user is created automatically. </p> <pre><code> sudo su - postgres </code></pre> <p>You should now be in a shell session for the postgres user. Log into a Postgres session by typing:</p> <pre><code> psql CREATE DATABASE myproject; </code></pre> <p>In your settings.py.</p> <pre><code>DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } </code></pre>
0
2016-09-18T10:48:07Z
[ "python", "django", "postgis", "django-testing", "geodjango" ]
Python: Does 'kron' create sparse matrix when I use ' from scipy.sparse import * '?
39,556,910
<p>For the code below, Mat is a array-type matrix,</p> <pre><code>a = kron(Mat,ones((8,1))) b = a.flatten() </code></pre> <p>If I don't import scipy.sparse package, <code>a</code> is an <strong>array-type matrix</strong>, <code>b</code> can also be executed. If I use 'from scipy.sparse import *', <code>a</code> is a <strong>sparse-type matrix</strong>, <code>b</code> <strong>cannot</strong> be exectued. Can someone tell me why <code>kron</code> gives different results? And, whether flatten() can be applied to sparse-type matrix?</p>
0
2016-09-18T10:59:33Z
39,557,562
<p><code>from module import *</code> is generally considered bad form in application code, for the reason you're seeing - it makes it very hard to tell which modules functions are coming from, especially if you do this for more than one module</p> <p>Right now, you have:</p> <pre><code>from numpy import * # from scipy.sparse import * a = kron(Mat,ones((8,1))) b = a.flatten() </code></pre> <p>Uncommenting the second line might affect where <code>ones</code> and <code>kron</code> comes from. But unless you look up whether sparse redefines these, you won't know. Better to write it like this:</p> <pre><code>import numpy as np from scipy import sparse a = np.kron(Mat, np.ones((8,1))) b = a.flatten() </code></pre> <p>And then you can swap <code>np</code> for <code>sparse</code> where you want to use the sparse version, and the reader will immediately know which one you're using. And you'll get an error if you try to use a sparse version when in fact there isn't one.</p>
2
2016-09-18T12:17:05Z
[ "python", "numpy", "matrix", "scipy", "sparse-matrix" ]
How do I override django admin's default file upload behavior?
39,556,939
<p>I need to change default file upload behavior in django and the documentation on the django site is rather confusing. </p> <p>I have a model with a field as follows:</p> <pre><code>class document (models.Model): name = models.CharField(max_length=200) file = models.FileField(null=True, upload_to='uploads/') </code></pre> <p>I need to create a .json file that will contain meta data when a file is uploaded. For example if I upload a file mydocument.docx I need to create mydocument.json file within the uploads/ folder and add meta information about the document. </p> <p>From what I can decipher from the documentation I need to create a file upload handler as a subclass of django.core.files.uploadhandler.FileUploadHandler. It also goes on to say I can define this anywhere I want. </p> <p>My questions: Where is the best place to define my subclass? Also from the documentation found here <a href="https://docs.djangoproject.com/en/1.8/ref/files/uploads/#writing-custom-upload-handlers" rel="nofollow">https://docs.djangoproject.com/en/1.8/ref/files/uploads/#writing-custom-upload-handlers</a> looks like the subclass would look like the following:</p> <pre><code>class FileUploadHandler(object): def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None): # do the acctual writing to disk def file_complete(self, file_size): # some logic to create json file </code></pre> <p>Does anyone have a working example of a upload handler class that works for django version 1.8?</p>
0
2016-09-18T11:03:04Z
39,560,147
<p>One option could be to do the <code>.json</code> file generation on the (model) form used to initially upload the file. Override the <code>save()</code> method of the <code>ModelForm</code> to generate the file immediately after the model has been saved.</p> <pre><code>class DocumentForm(forms.ModelForm): class Meta(object): model = Document fields = 'name', 'file' def save(self, commit=True): saved_document = super().save(commit) with open(saved_document.file.path + '.json', mode='w') as fh: fh.write(json.dumps({ "size": saved_document.file.size, "uploaded": timezone.now().isoformat() })) return saved_document </code></pre> <p>I've tested this locally but YMMV if you are using custom storages for working with things like S3.</p>
1
2016-09-18T16:42:54Z
[ "python", "django" ]
Export the list of file name from CSV file and copy to another directory with python
39,557,016
<p>i have one csv file that include the list of file: nome Desert Hydrangeas Jellyfish Koala Lighthouse Penguins Tulips I would like to create one script with python for copy this list of file from one directory to another directory, i can do this :</p> <pre><code>import csv import os import shutil source = os.listdir("C:\Test") destination = "C:\Test1" with open('semplice1.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['nome']) </code></pre> <p>in this wway i can print the name of the file. Can you help me to complete the code for copy only the list file? Thanks.<code>enter code here</code></p>
-1
2016-09-18T11:11:59Z
39,561,009
<p>The issue is that <code>os.listdir()</code> returns a <em>list</em> of files contained in the directory that you give it - in this case "C:\test".</p> <p>Later on, when you then try and concatenate <code>source</code> with the individual files, you are therefor attempting to combine a list with a str. This is why you are getting the <code>TypeError</code>.</p> <p>If all of the files are contained directly in "C:\test", then you can drop the <code>os.listdir()</code> and do:</p> <pre><code>import csv import os import shutil source = "C:\Test" destination = "C:\Test1" with open('semplice1.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['nome']) a = row['nome'] shutil.copyfile(os.path.join(source, a), destination) </code></pre> <p>Note the use of <code>os.path.join()</code> also as a better solution for building filepaths up.</p>
0
2016-09-18T18:10:38Z
[ "python", "csv" ]
Export the list of file name from CSV file and copy to another directory with python
39,557,016
<p>i have one csv file that include the list of file: nome Desert Hydrangeas Jellyfish Koala Lighthouse Penguins Tulips I would like to create one script with python for copy this list of file from one directory to another directory, i can do this :</p> <pre><code>import csv import os import shutil source = os.listdir("C:\Test") destination = "C:\Test1" with open('semplice1.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['nome']) </code></pre> <p>in this wway i can print the name of the file. Can you help me to complete the code for copy only the list file? Thanks.<code>enter code here</code></p>
-1
2016-09-18T11:11:59Z
39,562,623
<p>I resolve my problem with this code:</p> <pre><code>import csv import os import shutil source = "C:\Test" destination = "C:\Test1" with open('semplice1.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: print(row['nome']) shutil.copyfile(os.path.join(source, row['nome']), os.path.join(destination, row['nome'])) </code></pre>
0
2016-09-18T20:58:50Z
[ "python", "csv" ]
Creating lmdb file in the right way
39,557,118
<p>I'm trying to create an lmdb file that contains all of my database images (in order to train CNN).</p> <p>This is my 'test code', that I took from <a href="http://deepdish.io/2015/04/28/creating-lmdb-in-python/" rel="nofollow">here</a>:</p> <pre><code>import numpy as np import lmdb import caffe import cv2 import glob N = 18 # Let's pretend this is interesting data X = np.zeros((N, 1, 32, 32), dtype=np.uint8) y = np.zeros(N, dtype=np.int64) # We need to prepare the database for the size. We'll set it 10 times # greater than what we theoretically need. There is little drawback to # setting this too big. If you still run into problem after raising # this, you might want to try saving fewer entries in a single # transaction. map_size = X.nbytes * 10 train_data = [img for img in glob.glob("/home/roishik/Desktop/Thesis/Code/cafe_cnn/third/code/train_images/*png")] for i , img_path in enumerate(train_data): img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) X[i]=img y[i]=i%2 env = lmdb.open('train', map_size=map_size) print X print y with env.begin(write=True) as txn: # txn is a Transaction object for i in range(N): datum = caffe.proto.caffe_pb2.Datum() datum.channels = X.shape[1] datum.height = X.shape[2] datum.width = X.shape[3] datum.data = X[i].tobytes() # or .tostring() if numpy &lt; 1.9 print 'a ' + str(X[i]) datum.label = int(y[i]) print 'b ' + str(datum.label) str_id = '{:08}'.format(i) txn.put(str_id.encode('ascii'), datum.SerializeToString()) </code></pre> <p>As you can see I specified random binary labels (0 or 1, for even or odd, respectively). before I create much larger lmdb file I wanna make sure that I'm doing it the right way.</p> <p>After creating this file I wanted to 'look into the file' and check if it's OK, but I couldn't. the file didn't open properly using python, Access 2016, and .mdb reader (linux ubunto software). my problems are:</p> <ol> <li><p>I don't understand what this code is doing. what is <code>str_id</code>? what is <code>X[i].tobytes</code>? what does the last line do?</p></li> <li><p>After I run the code, I got 2 files: 'data.mdb' and 'key.mdb'. what are those two? maybe those 2 files are the reason why I can't open the database?</p></li> </ol> <p><a href="http://i.stack.imgur.com/WcWCR.png" rel="nofollow"><img src="http://i.stack.imgur.com/WcWCR.png" alt="the two output files"></a></p> <p>Thanks a lot, really appreciate your help!</p>
0
2016-09-18T11:24:25Z
39,582,450
<p>str_id is the internal name of the data set (e.g. one JPG image) used inside the LMDB. It's derived from the path and sequence number <strong>i</strong>.</p> <p><strong>tobytes</strong> ... here, let me <a href="https://docs.python.org/3/library/array.html?highlight=tobytes#array.array.tobytes" rel="nofollow">search</a> that for you. This overall process, through the end of the loop, converts the data set (datum) to the LMDB format, and then copies that binary representation straight to the file. <strong>tobytes</strong> and <strong>SerializeToString</strong> are the critical methods that transfer the bit pattern as-is.</p> <p><strong>data.mdb</strong> is the relatively huge data file, containing all of these bit sequences in a readily recoverable form. In other words, it's not blocking your DB access, because it <em>is</em> the data base.</p> <p><strong>lock.mdb</strong> is the record-level lock file: each datum gets appropriately locked (fully or read-only) during any read or write.</p> <p>That should explain the open questions. <strong>lock</strong> will not block opening the data base; it operates only during access operations. Check your file permissions. Check your user identity as well: did the LMDB creation run as <strong>root</strong>, perhaps, and not give you read permissions? Have you tried opening it read-only with a simple-minded editor, such as <strong>vi</strong> or <strong>wordpad</strong>?</p> <p>I hope this gets you moving toward a solution.</p>
1
2016-09-19T21:31:27Z
[ "python", "database", "neural-network", "caffe", "lmdb" ]
Creating lmdb file in the right way
39,557,118
<p>I'm trying to create an lmdb file that contains all of my database images (in order to train CNN).</p> <p>This is my 'test code', that I took from <a href="http://deepdish.io/2015/04/28/creating-lmdb-in-python/" rel="nofollow">here</a>:</p> <pre><code>import numpy as np import lmdb import caffe import cv2 import glob N = 18 # Let's pretend this is interesting data X = np.zeros((N, 1, 32, 32), dtype=np.uint8) y = np.zeros(N, dtype=np.int64) # We need to prepare the database for the size. We'll set it 10 times # greater than what we theoretically need. There is little drawback to # setting this too big. If you still run into problem after raising # this, you might want to try saving fewer entries in a single # transaction. map_size = X.nbytes * 10 train_data = [img for img in glob.glob("/home/roishik/Desktop/Thesis/Code/cafe_cnn/third/code/train_images/*png")] for i , img_path in enumerate(train_data): img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE) X[i]=img y[i]=i%2 env = lmdb.open('train', map_size=map_size) print X print y with env.begin(write=True) as txn: # txn is a Transaction object for i in range(N): datum = caffe.proto.caffe_pb2.Datum() datum.channels = X.shape[1] datum.height = X.shape[2] datum.width = X.shape[3] datum.data = X[i].tobytes() # or .tostring() if numpy &lt; 1.9 print 'a ' + str(X[i]) datum.label = int(y[i]) print 'b ' + str(datum.label) str_id = '{:08}'.format(i) txn.put(str_id.encode('ascii'), datum.SerializeToString()) </code></pre> <p>As you can see I specified random binary labels (0 or 1, for even or odd, respectively). before I create much larger lmdb file I wanna make sure that I'm doing it the right way.</p> <p>After creating this file I wanted to 'look into the file' and check if it's OK, but I couldn't. the file didn't open properly using python, Access 2016, and .mdb reader (linux ubunto software). my problems are:</p> <ol> <li><p>I don't understand what this code is doing. what is <code>str_id</code>? what is <code>X[i].tobytes</code>? what does the last line do?</p></li> <li><p>After I run the code, I got 2 files: 'data.mdb' and 'key.mdb'. what are those two? maybe those 2 files are the reason why I can't open the database?</p></li> </ol> <p><a href="http://i.stack.imgur.com/WcWCR.png" rel="nofollow"><img src="http://i.stack.imgur.com/WcWCR.png" alt="the two output files"></a></p> <p>Thanks a lot, really appreciate your help!</p>
0
2016-09-18T11:24:25Z
39,627,172
<p>You can use the <a href="https://github.com/LMDB/lmdb/blob/mdb.master/libraries/liblmdb/mdb_dump.c" rel="nofollow">mdb_dump</a> tool to inspect the contents of the database.</p>
1
2016-09-21T21:54:04Z
[ "python", "database", "neural-network", "caffe", "lmdb" ]
save some variables in tensorflow
39,557,122
<p>I am trying to save some variable ( weights and biases) to use them later but i have detected error, i don't know if my steps is right or not :</p> <pre><code>graph = tf.Graph() with graph.as_default(): weights = { 'wc1_0': tf.Variable(tf.random_normal([patch_size_1, patch_size_1, num_channels, depth],stddev=0.1)), 'wc1_1': tf.Variable(tf.random_normal([patch_size_2, patch_size_2, depth, depth], stddev=0.1)), ...... } biases = { 'bc1_0' : tf.Variable(tf.zeros([depth])), 'bc1_1' : tf.Variable(tf.constant(1.0, shape=[depth])), ..... } def model(data): conv_1 = tf.nn.conv2d(data, wc1_0 , [1, 2, 2, 1], padding='SAME') hidden_1 = tf.nn.relu(conv_1 + bc1_0) pool_1 = tf.nn.max_pool(hidden_1,ksize = [1,5,5,1], strides= [1,2,2,1],padding ='SAME' ) ....... ....... weights_saver = tf.train.Saver(var_list=weights) biases_saver = tf.train.Saver(var_list=biases) with tf.Session(graph=graph) as sess: sess.run() for loop.... ...... save_path_weights = weights_saver.save(sess, "my_path") save_path_biases = biases_saver.save(sess, "my_path") </code></pre> <p>when i run the code, i get this erorr:</p> <pre><code> conv_1 = tf.nn.conv2d(data, wc1_0 , [1, 2, 2, 1], padding='SAME') NameError: global name 'wc1_0' is not defined </code></pre> <p>how can i assign the variable in the conv_1 ?</p>
0
2016-09-18T11:24:54Z
39,558,932
<p>You defined two dictionaries: 1 for weights and 1 for biases. You have filled the dictionaries with Tensorflow variables objects.. So, why don't you use them?</p> <pre><code> conv_1 = tf.nn.conv2d(data, weights['wc1_0'] , [1, 2, 2, 1], padding='SAME') hidden_1 = tf.nn.relu(conv_1 + biases['bc1_0']) pool_1 = tf.nn.max_pool(hidden_1,ksize = [1,5,5,1], strides= [1,2,2,1],padding ='SAME' ) </code></pre>
1
2016-09-18T14:48:23Z
[ "python", "tensorflow", "convolution" ]
Python 2.7 conversion to 3
39,557,125
<p>I found a code snippet online, that would be able to display sensor readings from an android phone, but I need this to run on Python 3. And I have no idea how to fix it:</p> <pre><code># ------------------------------------------------------- import socket, traceback, string from sys import stderr host = '' port = 5555 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) s.bind((host, port)) # print one blank line print while 1: try: message, address = s.recvfrom(8192) # print message # split records using comma as delimiter (data are streamed in CSV format) data = message.split( "," ) # convert to flaot for plotting purposes t = data[0] sensorID = int(data[1]) if sensorID==3: # sensor ID for the eccelerometer ax, ay, az = data[2], data[3], data[4] # SAVE TO FILE # print &gt;&gt; open("prova.txt","a"), t, ax, ay, az # print t, ax, ay, az # FLUSH TO STERR stderr.write("\r t = %s s | (ax,ay,az) = (%s,%s,%s) m/s^2" % (t, ax, ay, az) ) stderr.flush() except (KeyboardInterrupt, SystemExit): raise except: traceback.print_exc() # ------------------------------------------------------- </code></pre> <p>I'm getting this error: </p> <pre><code>Traceback (most recent call last): File "D:\Desktop\androidSensor123.py", line 21, in &lt;module&gt; data = message.split( "," ) TypeError: a bytes-like object is required, not 'str' </code></pre>
0
2016-09-18T11:25:21Z
39,557,216
<p>you're trying to split <code>bytes</code> object</p> <p>convert it back to a string like this, by decoding the bytes back to a string</p> <pre><code>data = data.decode() # you can also specify the encoding of the string if it's not unicode data = message.split(",") </code></pre> <p>this is a demonstration of what is going on</p> <pre><code>&gt;&gt;&gt; a = b'hello,world' &gt;&gt;&gt; a.split(',') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: a bytes-like object is required, not 'str' &gt;&gt;&gt; a = a.decode() &gt;&gt;&gt; a.split(',') ['hello', 'world'] </code></pre>
1
2016-09-18T11:35:31Z
[ "python", "python-2.7" ]
Vim huge delay when inserting newline after complex strings
39,557,163
<p>Vim takes an annoyingly noticeable long time to insert a newline (<code>o</code> in normal mode or return key in insert mode) when inserted at the end of a specific code block that could be considered complex.</p> <p>How would I go about identifying the cause and fixing the problem?</p> <h1>Case-specific information:</h1> <p>I my case, a problematic Python code block is the following, which contains multiple single quotes in double-quoted strings:</p> <pre><code> for item in tree.xpath("//li"): a = item.xpath(".//div[contains(concat(' ', normalize-space(@class), ' '), ' alpha ')]/text()")[0] b = item.xpath(".//div[contains(concat(' ', normalize-space(@class), ' '), ' betahaus ')]/text()")[0] c = item.xpath(".//div[contains(concat(' ', normalize-space(@class), ' '), ' capitalism ')]/text()")[0] d = item.xpath(".//div[contains(concat(' ', normalize-space(@class), ' '), ' doughnuts-of-the-realm ')]/a")[0].attrib['href'] g = item.xpath(".//span[contains(concat(' ', normalize-space(@type), ' '), ' dontcare ')]/text()")[0] h = item.xpath(".//span[contains(concat(' ', normalize-space(@type), ' '), ' foo ')]/text()") </code></pre> <p>The delay is less than a second but noticeable.</p> <p>The machine is a AMD Phenom(tm) 9550 2.2GHz, 64bit Quad-Core Processor and this is on Arch Linux with .vimrc moved (so Arch's vim defaults are used). Both vim and gvim are affected.</p> <p>If I copy paste the lines defining variables 5 times, resulting in about 48 lines, the delay is 3 seconds long. Increasing to over 400 lines causes the same delay which makes me assume there's a timeout that is being reached.</p> <p>A video showing the issue: <a href="https://youtu.be/rCSfSASrZjQ" rel="nofollow">https://youtu.be/rCSfSASrZjQ</a></p>
1
2016-09-18T11:29:49Z
39,571,883
<p>It's likely related to syntax highlighting; check whether the delay is gone after <code>:syntax off</code>.</p> <p>If your Vim version (recent ones with "huge" features) supports the <code>:syntime</code> command, you can dive deeper; cp. <code>:help :syntime</code>.</p> <p>This may turn up a pattern that is responsible for the slowness; you'd then contact the syntax plugin author (whose address / link to issue tracker you'll find in the script's header: <code>$VIMRUNTIME/syntax/python.vim</code>.</p>
1
2016-09-19T11:16:34Z
[ "python", "vim", "archlinux" ]
The newest file after unpacking file [python]
39,557,187
<p>When I'm unpack file, it is not the newest. Is there any chance to upack file and change its name so it is the newest file in the directory?</p> <pre><code>print newest() #prints myFile.rar if newest().endswith('.rar') or newest().endswith('.zip') : patoolib.extract_archive(newest(), outdir=".") #myFile.rar extracted to `.'. And it shows up in my directory myFile.pdf time.sleep(20) print newest() #prints myFile.rar </code></pre> <p>My function:</p> <pre><code>def newest(): path = '/home/es/ajo/files' os.chdir(path) files = sorted(os.listdir(os.getcwd()), key=os.path.getmtime) newest = files[-1] return str(newest) </code></pre>
0
2016-09-18T11:32:15Z
39,588,482
<p>It is really easy. After I unpack the file I just use function os.utime so unpacked file is the newest one in a directory :) ts = time.time() os.utime("/home/es/ajo/files/all")), (ts, ts)) It changes modified date. </p>
0
2016-09-20T07:48:29Z
[ "python", "python-2.7", "file" ]
Set limit feature_importances_ in DataFrame Pandas
39,557,194
<p>I want to set a limit for my feature_importances_ output using DataFrame. Below is my code (refer from this <a href="https://statcompute.wordpress.com/2012/12/05/learning-decision-tree-in-scikit-learn-package/" rel="nofollow">blog</a>):</p> <pre><code>train = df_visualization.sample(frac=0.9,random_state=639) test = df_visualization.drop(train.index) train.to_csv('train.csv',encoding='utf-8') test.to_csv('test.csv',encoding='utf-8') train_dis = train.iloc[:,:66] train_val = train_dis.values train_in = train_val[:,:65] train_out = train_val[:,65] test_dis = test.iloc[:,:66] test_val = test_dis.values test_in = test_val[:,:65] test_out = test_val[:,65] dt = tree.DecisionTreeClassifier(random_state=59,criterion='entropy') dt = dt.fit(train_in,train_out) score = dt.score(train_in,train_out) test_predicted = dt.predict(test_in) # Print the feature ranking print("Feature ranking:") print (DataFrame(dt.feature_importances_, columns = ["Imp"], index = train.iloc[:,:65].columns).sort_values(['Imp'], ascending = False)) </code></pre> <p>My problem now is it display all 65 features. Output :</p> <pre><code> Imp wbc 0.227780 age 0.100949 gcs 0.069359 hr 0.069270 rbs 0.053418 sbp 0.052067 Intubation-No 0.050729 ... ... Babinski-Normal 0.000000 ABG-Metabolic Alkolosis 0.000000 ABG-Respiratory Acidosis 0.000000 Reflexes-Unilateral Hyperreflexia 0.000000 NS-No 0.000000 </code></pre> <p>For example I just want top 5 features only. Expected output:</p> <pre><code> Imp wbc 0.227780 age 0.100949 gcs 0.069359 hr 0.069270 rbs 0.053418 </code></pre> <p><strong>Update :</strong> I got the way to display using <a href="http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.DataFrame.itertuples.html" rel="nofollow">itertuples</a>.</p> <pre><code>display = pd.DataFrame(dt.feature_importances_, columns = ["Imp"], index = train.iloc[:,:65].columns).sort_values(['Imp'], ascending = False) x=0 for row,col in display.itertuples(): if x&lt;5: print(row,"=",col) else: break x++ </code></pre> <p>Output :</p> <pre><code>Feature ranking: wbc = 0.227780409582 age = 0.100949241154 gcs = 0.0693593476192 hr = 0.069270425399 rbs = 0.0534175402602 </code></pre> <p>But I want to know whether this is the efficient way to get the output?</p>
1
2016-09-18T11:32:49Z
39,559,040
<p>Try this: </p> <pre><code>indices = np.argsort(dt.feature_importances_)[::-1] for i in range(5): print " %s = %s" % (feature_cols[indices[i]], dt.feature_importances_[indices[i]]) </code></pre>
0
2016-09-18T14:58:53Z
[ "python", "dataframe" ]
remove a contour from image using skimage
39,557,205
<p>I want to remove some contour from an image but I don't know how to achieve it using <code>skimage</code>? I do something like this in <code>OpenCV</code> using <code>drawContour</code> but I can't find the equivalent in <code>skimage</code>.</p> <p>Assume I have a simple image like:</p> <pre><code>0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 </code></pre> <p>that has only one connected component. </p> <p>I need to remove it by masking it. </p> <p>The final result will be a 8 * 5 zero matrix!</p> <pre><code>a = '''0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 1 0 0 1 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0''' np.array([int(i) for i in a.split()], dtype=bool).reshape(5, 8) cc = measure.regionprops(measure.label(a))[0] # here is what I do for removing cc </code></pre> <p>What should I do to remove <code>cc</code> connected component using <code>skimage</code>?</p>
0
2016-09-18T11:34:01Z
39,558,221
<p>skimage have equivalent function: </p> <pre><code>contours=skimage.measure.find_contours(array, level, fully_connected='low', positive_orientation='low') </code></pre> <p>find_countours return value is an array of numpy arrays each of which contain specific contour. Then you can just select specific contour by index from contours and iterate through your image by addresses of pixels which belong to specific contour, setting them to 0. </p> <p>In your case you should have only one contour, so:</p> <pre><code>c=contours[0] n=contours[0].shape[0] for i in range(0,n): for j in range(0,n): image[c[i]][c[j]]=0 </code></pre>
0
2016-09-18T13:36:52Z
[ "python", "image-processing", "skimage" ]
Is there a debugger tool that shows the value of a variable?
39,557,207
<p>I am looking for a debugger tool that helps me find what causes the error in my program?</p> <p>Usually to debug I use the <strong>print(variable) function</strong> to see what the value of a certain variable is at a given time. Hence I can see where and when something goes wrong. However, this takes way too long if the program is a little longer.</p> <p>I wish there was tool which would show the value of a variable when I move the mouse to that variable. Instead, I always have to go into the code and use the print function in multiple place and run the program multiple times.</p> <p>Example:</p> <pre><code>y = "otito" y = list(y) del y[2] ###show me the new value of y when mouse over y = "otto"### </code></pre> <p>Is there something like this out there?</p> <p>IF NOT</p> <p>How do you guys go about to check the value of variables at certain times?</p>
0
2016-09-18T11:34:16Z
39,557,347
<p>Yes, Pycharm has built-in debugging capabilities. First, set the breakpoint at the point (line) you would like to see the variable. In your case that would have to be after the <code>del y[2]</code> line, as this is the point that the <code>del</code> would have effect:</p> <p>y = "otito" y = list(y) del y[2] y # &lt;- set the Breakpoint at this line, by just clicking right of the number line in Pycharm</p> <p>Then, run your program with <code>Run -&gt; Debug</code> and it will stop at the breakpoint and show you all of the variables, including <code>y</code>:</p> <p><a href="http://i.stack.imgur.com/u5wd0.png" rel="nofollow"><img src="http://i.stack.imgur.com/u5wd0.png" alt="enter image description here"></a></p>
0
2016-09-18T11:51:03Z
[ "python", "debugging", "pycharm" ]
Scrapy SgmlLinkExtractor how to define rule with regex
39,557,231
<p>I have a link like <code>http://www.example.com/kaufen/105975478</code></p> <p>I only want to allow links that have "/kaufen/" in the url and which contain a 9 digit integer number at the end of the url. </p> <p>I managed to allow only links containing "/kaufen/" with the following allow statement:</p> <pre><code>allow=('/kaufen/', ) </code></pre> <p>How can I extend the allow statement such that it only follows the links having a 9 digit number at the end?</p>
1
2016-09-18T11:36:46Z
39,557,379
<p>You can use <code>\/kaufen\/[0-9]{9}</code></p> <ul> <li><code>\/kaufen\/</code> means /kaufen/ litteraly</li> <li><code>[0-9]{9}</code> means 9 number chars</li> </ul> <p><a href="https://regex101.com/r/tH5pC7/1" rel="nofollow">https://regex101.com/r/tH5pC7/1</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var re = /\/kaufen\/[0-9]{9}/gi; var str = 'http://www.homegate.ch/kaufen/105975478'; var m; while ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } // View your result using the m-variable. console.log(m[0]); }</code></pre> </div> </div> </p>
2
2016-09-18T11:54:04Z
[ "python", "regex", "scrapy" ]
Scrapy SgmlLinkExtractor how to define rule with regex
39,557,231
<p>I have a link like <code>http://www.example.com/kaufen/105975478</code></p> <p>I only want to allow links that have "/kaufen/" in the url and which contain a 9 digit integer number at the end of the url. </p> <p>I managed to allow only links containing "/kaufen/" with the following allow statement:</p> <pre><code>allow=('/kaufen/', ) </code></pre> <p>How can I extend the allow statement such that it only follows the links having a 9 digit number at the end?</p>
1
2016-09-18T11:36:46Z
39,557,544
<p>You can use:</p> <pre><code>allow=(r'kaufen/\d+$') </code></pre>
1
2016-09-18T12:14:57Z
[ "python", "regex", "scrapy" ]
how can I best translate this java method to python
39,557,242
<p>how can i write less python2 code to achieve the same thing,need encryption results are the same.</p> <p><code>b[i++] = (byte) 172;</code> In what way cast int to byte in python2....</p> <pre><code>public static String encryptPassword(String content) { String resultString = ""; String appkey = "ftjf,ckdfkl"; byte[] a = appkey.getBytes(); byte[] datSource = content.getBytes(); byte[] b = new byte[a.length + 4 + datSource.length]; int i; for (i = 0; i &lt; datSource.length; i++) { b[i] = datSource[i]; } b[i++] = (byte) 172; b[i++] = (byte) 163; b[i++] = (byte) 161; b[i++] = (byte) 163; for (int k = 0; k &lt; a.length; k++) { b[i] = a[k]; i++; } try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(b); resultString = new HexBinaryAdapter().marshal(md5.digest()); } catch (Exception e) { } return resultString.toLowerCase(); } public static void main(String[] args) { System.out.print(encryptPassword("123456")); } </code></pre>
1
2016-09-18T11:37:51Z
39,566,552
<p>Use <code>chr</code> to get the char of a byte in python.</p> <pre><code>from Crypto.Hash import MD5 key = 'ftjf,ckdfkl' src= '123' b = src+chr(172)+chr(163)+chr(161)+chr(163)+key md5 = MD5.new() md5.update(b) text = md5.hexdigest() print text </code></pre> <p>Given the src '123',output is:</p> <pre><code>eedb36cc3204923459dcf891224a0c1d </code></pre>
0
2016-09-19T06:21:10Z
[ "java", "python", "python-2.7", "python-3.x" ]
rolling apply in pandas shows "TypeError: only length-1 arrays can be converted to Python scalars"
39,557,313
<p>Dataframe <code>df_implied_full</code> has several columns, one of them is called <code>'USDZARV1Y Curncy'</code>, and it has only <code>floats</code>.</p> <p>This code works:</p> <pre><code>mad = lambda x: np.median(np.fabs(x - np.median(x))) df_implied_full['madtest'] = df_implied_full['USDZARV1Y Curncy'].rolling(window=60).apply(mad) </code></pre> <p>This code doesn't work:</p> <pre><code>test = lambda x: (x - np.median(x)) df_implied_full['rolltest2'] = df_implied_full['USDZARV1Y Curncy'].rolling(window=60).apply(test) </code></pre> <p>The error shown is:</p> <blockquote> <p>File "pandas\algos.pyx", line 1831, in pandas.algos.roll_generic (pandas\algos.c:51581)</p> <p>TypeError: only length-1 arrays can be converted to Python scalars</p> </blockquote> <p>I'm using Pandas 0.18.1 and python 2.7.12</p> <p>What is wrong with my code?</p>
1
2016-09-18T11:46:45Z
39,557,459
<p>There is problem output of <code>x</code> in <code>lambda x: (x ...</code> is <code>numpy array</code>, so if use only <code>test = lambda x: x</code> numpy array cannot be converted to scalar values per each row. I think you need return scalar value only e.g. use <code>x[0]</code> or <code>np.median(x)</code>. The best is use custom function and test it.</p> <p>Sample with <code>window=2</code>:</p> <pre><code>import pandas as pd import numpy as np df_implied_full = pd.DataFrame({'USDZARV1Y Curncy': [1.2,4.6,7.3,4.9,1.5]}) print (df_implied_full) def test (x): print (x) #[ 1.2 4.6] #[ 4.6 7.3] #[ 7.3 4.9] #[ 4.9 1.5] print (type(x)) #&lt;class 'numpy.ndarray'&gt; #&lt;class 'numpy.ndarray'&gt; #&lt;class 'numpy.ndarray'&gt; #&lt;class 'numpy.ndarray'&gt; #Return only first value of list return x[0] mad = lambda x: np.median(np.fabs(x - np.median(x))) df_implied_full['madtest'] = df_implied_full['USDZARV1Y Curncy'].rolling(window=2).apply(test) print (df_implied_full) USDZARV1Y Curncy madtest 0 1.2 NaN 1 4.6 1.2 2 7.3 4.6 3 4.9 7.3 4 1.5 4.9 </code></pre> <hr> <pre><code>def test (x): def test (x): print (x) #[ 1.2 4.6] #[ 4.6 7.3] #[ 7.3 4.9] #[ 4.9 1.5] #Return median as scalar return np.median(x) mad = lambda x: np.median(np.fabs(x - np.median(x))) df_implied_full['madtest'] = df_implied_full['USDZARV1Y Curncy'].rolling(window=2).apply(test) print (df_implied_full) USDZARV1Y Curncy madtest 0 1.2 NaN 1 4.6 2.90 2 7.3 5.95 3 4.9 6.10 4 1.5 3.20 </code></pre>
1
2016-09-18T12:04:50Z
[ "python", "arrays", "function", "pandas", "median" ]
How can i read the text between xml tags using xml.etree.Elementree ?If the xml is complex
39,557,384
<pre><code>&lt;GeocodeResponse&gt; &lt;status&gt;OK&lt;/status&gt; &lt;result&gt; &lt;type&gt;locality&lt;/type&gt; &lt;type&gt;political&lt;/type&gt; &lt;formatted_address&gt;Chengam, Tamil Nadu 606701, India&lt;/formatted_address&gt; &lt;address_component&gt; &lt;long_name&gt;Chengam&lt;/long_name&gt; &lt;short_name&gt;Chengam&lt;/short_name&gt; &lt;type&gt;locality&lt;/type&gt; &lt;type&gt;political&lt;/type&gt; &lt;/address_component&gt; &lt;address_component&gt; &lt;long_name&gt;Tiruvannamalai&lt;/long_name&gt; &lt;short_name&gt;Tiruvannamalai&lt;/short_name&gt; &lt;type&gt;administrative_area_level_2&lt;/type&gt; &lt;type&gt;political&lt;/type&gt; &lt;/address_component&gt; &lt;address_component&gt; &lt;long_name&gt;Tamil Nadu&lt;/long_name&gt; &lt;short_name&gt;TN&lt;/short_name&gt; &lt;type&gt;administrative_area_level_1&lt;/type&gt; &lt;type&gt;political&lt;/type&gt; &lt;/address_component&gt; &lt;address_component&gt; &lt;long_name&gt;India&lt;/long_name&gt; &lt;short_name&gt;IN&lt;/short_name&gt; &lt;type&gt;country&lt;/type&gt; &lt;type&gt;political&lt;/type&gt; &lt;/address_component&gt; &lt;address_component&gt; &lt;long_name&gt;606701&lt;/long_name&gt; &lt;short_name&gt;606701&lt;/short_name&gt; &lt;type&gt;postal_code&lt;/type&gt; &lt;/address_component&gt; &lt;geometry&gt; &lt;location&gt; &lt;lat&gt;12.3067864&lt;/lat&gt; &lt;lng&gt;78.7957856&lt;/lng&gt; &lt;/location&gt; &lt;location_type&gt;APPROXIMATE&lt;/location_type&gt; &lt;viewport&gt; &lt;southwest&gt; &lt;lat&gt;12.2982423&lt;/lat&gt; &lt;lng&gt;78.7832165&lt;/lng&gt; &lt;/southwest&gt; &lt;northeast&gt; &lt;lat&gt;12.3213030&lt;/lat&gt; &lt;lng&gt;78.8035583&lt;/lng&gt; &lt;/northeast&gt; &lt;/viewport&gt; &lt;bounds&gt; &lt;southwest&gt; &lt;lat&gt;12.2982423&lt;/lat&gt; &lt;lng&gt;78.7832165&lt;/lng&gt; &lt;/southwest&gt; &lt;northeast&gt; &lt;lat&gt;12.3213030&lt;/lat&gt; &lt;lng&gt;78.8035583&lt;/lng&gt; &lt;/northeast&gt; &lt;/bounds&gt; &lt;/geometry&gt; &lt;place_id&gt;ChIJu8JCb3jxrDsRAOfhACQczWo&lt;/place_id&gt; &lt;/result&gt; &lt;/GeocodeResponse&gt; </code></pre> <p>I am new to xml thing and i don't know how to handle it with python xml.etree ? Basic stuffs i read from <a href="https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml" rel="nofollow">https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml</a> is useful,but still struggling to printout the latitude and longitude values under geometry-->location.i have tried something like this</p> <pre><code> with open('data.xml', 'w') as f: f.write(xmlURL.text) tree = ET.parse('data.xml') root = tree.getroot() lat = root.find(".//geometry/location") print(lat.text) </code></pre>
0
2016-09-18T11:54:51Z
39,557,421
<p>You almost got it. Change <code>root.find(".//geometry/location")</code> to <code>root.find(".//geometry/location/lat")</code>:</p> <pre><code>lat = root.find(".//geometry/location/lat") print(lat.text) &gt;&gt; 12.3067864 </code></pre> <p>Same goes for <code>lng</code> of course:</p> <pre><code>lng = root.find(".//geometry/location/lng") print(lng.text) &gt;&gt; 78.7957856 </code></pre>
1
2016-09-18T12:00:21Z
[ "python", "xml.etree" ]
Output not showing entirely in Python
39,557,405
<p>The output when running a simple code breaks and is not entirely shown. What are the options to avoid the breaks?</p> <pre><code>22 December 23, 1989, Saturday, Late Edition - Final 23 December 22, 1989, Friday, Late Edition - Final 24 December 21, 1989, Thursday, Late Edition - Final 25 December 21, 1989, Thursday, Late Edition - Final 26 December 20, 1989, Wednesday, Late Edition - F... 27 December 20, 1989, Wednesday, Late Edition - F... 28 December 19, 1989, Tuesday, Late Edition - Final 29 December 18, 1989, Monday, Late Edition - Final ... 605 January 12, 2016 Tuesday 606 January 12, 2016 Tuesday 10:58 PM EST 607 January 12, 2016 Tuesday 8:28 PM EST 608 January 12, 2016 Tuesday 9:43 AM EST </code></pre> <p>Thanks!</p> <p>PD: this is the code used to produce the file:</p> <pre><code>import json import nltk import re import pandas appended_data = [] for i in range(1989,2017): df0 = pandas.DataFrame([json.loads(l) for l in open('NYT_%d.json' % i)]) df1 = pandas.DataFrame([json.loads(l) for l in open('USAT_%d.json' % i)]) df2 = pandas.DataFrame([json.loads(l) for l in open('WP_%d.json' % i)]) appended_data.append(df0) appended_data.append(df1) appended_data.append(df2) appended_data = pandas.concat(appended_data) print(appended_data.date) </code></pre>
1
2016-09-18T11:57:13Z
39,557,507
<p>You need to change the display width for pandas. The option you are looking for is <code>pd.set_option('display.width', 2000)</code>, but you may also find some other pandas options helpful which I use regularily:</p> <pre><code>pd.set_option('display.max_rows', None) pd.set_option('display.max_columns', None) pd.set_option('display.width', 2000) </code></pre> <p>Detailed description can be found <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html" rel="nofollow">here</a>.</p>
2
2016-09-18T12:10:55Z
[ "python" ]
How to shorten year into two-number integer in Python?
39,557,438
<p>I have a basic block of code, and a portion of it asks the user their year of birth. In order to complete the program, I need their year (e.g. 1997) to be shortened into a two-number integer (e.g. 97). At the moment, the only way I can work out is to subtract 2000, but obviously that barely works.</p> <pre><code>year=input("And finally, what's the year of your birthday? ") shortyear=int(year)-2000 </code></pre> <p>I have researched online into slicing strings and integers but none of them seem to work for me. I'm still extremely basic at Python but I'm guessing that there should be a way to select only the last two characters in an integer?:</p> <pre><code>intyear=int(year) shortyear=year[-2:] </code></pre> <p>That doesn't seem to work for me, though. Hopefully, someone will have an answer that works!</p> <p>Thank you very much! 😀👍🏽</p>
0
2016-09-18T12:02:15Z
39,557,451
<p>For slicing to work (<code>year[-2:]</code>) you should not convert <code>year</code> to <code>int</code> (ie <code>year</code> needs to be a string):</p> <pre><code>year = '2016' year[-2:] &gt;&gt; '16' </code></pre>
1
2016-09-18T12:04:08Z
[ "python" ]
How to shorten year into two-number integer in Python?
39,557,438
<p>I have a basic block of code, and a portion of it asks the user their year of birth. In order to complete the program, I need their year (e.g. 1997) to be shortened into a two-number integer (e.g. 97). At the moment, the only way I can work out is to subtract 2000, but obviously that barely works.</p> <pre><code>year=input("And finally, what's the year of your birthday? ") shortyear=int(year)-2000 </code></pre> <p>I have researched online into slicing strings and integers but none of them seem to work for me. I'm still extremely basic at Python but I'm guessing that there should be a way to select only the last two characters in an integer?:</p> <pre><code>intyear=int(year) shortyear=year[-2:] </code></pre> <p>That doesn't seem to work for me, though. Hopefully, someone will have an answer that works!</p> <p>Thank you very much! 😀👍🏽</p>
0
2016-09-18T12:02:15Z
39,557,481
<p>you can use <code>year%100</code> to only get the digits within a century:</p> <pre><code>&gt;&gt;&gt; 2000%100 0 &gt;&gt;&gt; 2013%100 13 &gt;&gt;&gt; 1985%100 85 &gt;&gt;&gt; 1997%100 97 </code></pre>
2
2016-09-18T12:07:20Z
[ "python" ]
How to shorten year into two-number integer in Python?
39,557,438
<p>I have a basic block of code, and a portion of it asks the user their year of birth. In order to complete the program, I need their year (e.g. 1997) to be shortened into a two-number integer (e.g. 97). At the moment, the only way I can work out is to subtract 2000, but obviously that barely works.</p> <pre><code>year=input("And finally, what's the year of your birthday? ") shortyear=int(year)-2000 </code></pre> <p>I have researched online into slicing strings and integers but none of them seem to work for me. I'm still extremely basic at Python but I'm guessing that there should be a way to select only the last two characters in an integer?:</p> <pre><code>intyear=int(year) shortyear=year[-2:] </code></pre> <p>That doesn't seem to work for me, though. Hopefully, someone will have an answer that works!</p> <p>Thank you very much! 😀👍🏽</p>
0
2016-09-18T12:02:15Z
39,557,656
<p>You want a function which takes the year as input and returns the last two digits as output.</p> <p>Since the last two digits may start with a <code>0</code>, you need to return the output as a string.</p> <hr> <p>Assuming that the input is an integer, here is one way for implementing it:</p> <pre><code>def TruncateYear(year): return '%.2d'%(year%100) </code></pre> <hr> <p>Assuming that the input is a string, here is one way for implementing it:</p> <pre><code>def TruncateYear(year): return year[-2:] </code></pre>
0
2016-09-18T12:30:22Z
[ "python" ]
How to shorten year into two-number integer in Python?
39,557,438
<p>I have a basic block of code, and a portion of it asks the user their year of birth. In order to complete the program, I need their year (e.g. 1997) to be shortened into a two-number integer (e.g. 97). At the moment, the only way I can work out is to subtract 2000, but obviously that barely works.</p> <pre><code>year=input("And finally, what's the year of your birthday? ") shortyear=int(year)-2000 </code></pre> <p>I have researched online into slicing strings and integers but none of them seem to work for me. I'm still extremely basic at Python but I'm guessing that there should be a way to select only the last two characters in an integer?:</p> <pre><code>intyear=int(year) shortyear=year[-2:] </code></pre> <p>That doesn't seem to work for me, though. Hopefully, someone will have an answer that works!</p> <p>Thank you very much! 😀👍🏽</p>
0
2016-09-18T12:02:15Z
39,557,818
<p>You don't validate the input so using slicing or modulo could give you nonsensical output, you should use a while loop and verify the user enters a year in some realistic range which if you go by the <a href="https://en.wikipedia.org/wiki/List_of_the_verified_oldest_people" rel="nofollow">verified oldest person in the world</a> is 1875-now:</p> <pre><code>import datetime this_year = str(datetime.datetime.now().year) while True: year = input("And finally, what's the year of your birthday? ") if "1875" &lt;= year &lt;= this_year: short_year = year[-2:] break print("{} is not a valid year\n" "Please enter a year between 1875 and {}".format(year, this_year)) print(short_year) </code></pre>
0
2016-09-18T12:50:40Z
[ "python" ]
How to have a conversation with a bot?
39,557,488
<p>I want to send a <a href="https://python-telegram-bot.org" rel="nofollow">python telegram bot</a> a specific command that causes the bot to respond with a request for more information and listen for another message containing that extra information.</p> <p>For instance:</p> <ul> <li>I send <code>/add</code> the bot responds: <code>ok, tell me your torrent link</code>. </li> <li>I send the bot another message with the torrent link and the bot saves it into a Python variable for further use.</li> </ul>
-3
2016-09-18T12:07:49Z
39,566,732
<p>You can make a list of those things. So, when you say your torrent link he adds it to the list using yourlistname.append(yourtorrentlinkinput)</p>
-1
2016-09-19T06:34:18Z
[ "python", "bots", "python-telegram-bot" ]
How to have a conversation with a bot?
39,557,488
<p>I want to send a <a href="https://python-telegram-bot.org" rel="nofollow">python telegram bot</a> a specific command that causes the bot to respond with a request for more information and listen for another message containing that extra information.</p> <p>For instance:</p> <ul> <li>I send <code>/add</code> the bot responds: <code>ok, tell me your torrent link</code>. </li> <li>I send the bot another message with the torrent link and the bot saves it into a Python variable for further use.</li> </ul>
-3
2016-09-18T12:07:49Z
39,567,979
<p>In this case I would look into <a href="https://pythonhosted.org/python-telegram-bot/telegram.ext.conversationhandler.html?module-telegram.ext.conversationhandler" rel="nofollow">ConversationHandler</a></p>
0
2016-09-19T07:53:08Z
[ "python", "bots", "python-telegram-bot" ]
Extract data from multiple bracket string in Pandas and create new table
39,557,680
<p>I am trying to build a 2 x 24 table in pandas with the following data below: </p> <pre><code>d.iloc[0:2] = [[0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 0L], [0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 2L, 2L, 0L, 0L, 0L]] </code></pre> <p>Basically, the first sub-bracket represents 24 hour data for one day in January, and the second sub-bracket for Febuary. I am looking to structure the 2x24 table (without 'L') in the following fashion:</p> <pre><code> 1 2 3 4 5 6 7 8 9 10 11 12 ... 24 Jan 0 0 0 0 0 0 0 0 0 1 1 1 ... 0 Feb 0 0 0 0 0 0 0 0 0 1 1 1 ... 0 </code></pre> <p>What I find challenging is stripping (.strip), splitting, and copying the data to a new dataframe structure. I often find the original structure on online dataframes with 12 sub-brackets (one for each month). I included <code>d.iloc[0,2]</code> because I am going to apply the function to all elements in column 2 with a <code>for</code> loop. Thank you for your precious help. </p>
0
2016-09-18T12:34:05Z
39,557,783
<p>I think you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.from_records.html" rel="nofollow"><code>DataFrame.from_records</code></a> with apply <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.strip.html" rel="nofollow"><code>str.strip</code></a>:</p> <pre><code>import pandas as pd import numpy as np a = [['0L', '0L', '0L', '0L', '0L', '0L', '0L', '0L', '0L', '1L', '1L', '1L', '1L', '1L', '0L', '0L', '0L', '1L', '1L', '1L', '1L', '0L', '0L', '0L'], ['0L', '0L', '0L', '0L', '0L', '0L', '0L', '0L', '0L', '1L', '1L', '1L', '1L', '1L', '0L', '0L', '0L', '1L', '1L', '2L', '2L', '0L', '0L', '0L']] idx = ['Jan','Feb'] df = pd.DataFrame.from_records(a, index=idx).apply(lambda x: x.str.strip('L').astype(int)) print (df) 0 1 2 3 4 5 6 7 8 9 ... 14 15 16 17 18 19 20 \ Jan 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 1 1 Feb 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 2 2 21 22 23 Jan 0 0 0 Feb 0 0 0 [2 rows x 24 columns] </code></pre> <p>More general solution with generating months names by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.strftime.html" rel="nofollow"><code>dt.strftime</code></a>:</p> <pre><code>print (pd.Series(range(1,len(a) + 1))) 0 1 1 2 dtype: int32 idx = pd.to_datetime(pd.Series(range(1,len(a) + 1)), format='%m').dt.strftime('%b') 0 Jan 1 Feb dtype: object df = pd.DataFrame.from_records(a, index=idx).apply(lambda x: x.str.strip('L').astype(int)) print (df) 0 1 2 3 4 5 6 7 8 9 ... 14 15 16 17 18 19 20 \ Jan 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 1 1 Feb 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 2 2 21 22 23 Jan 0 0 0 Feb 0 0 0 </code></pre> <p>If need <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow"><code>split</code></a> values first:</p> <pre><code>b = [['0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 0L'], ['0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 1L, 1L, 2L, 2L, 0L, 0L, 0L']] idx = pd.to_datetime(pd.Series(range(1,len(a) + 1)), format='%m').dt.strftime('%b') df1 = pd.DataFrame.from_records(b, index=idx) .iloc[:,0] .str.split(', ', expand=True) .replace({'L':''}, regex=True) .astype(int) print (df1) 0 1 2 3 4 5 6 7 8 9 ... 14 15 16 17 18 19 20 \ Jan 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 1 1 Feb 0 0 0 0 0 0 0 0 0 1 ... 0 0 0 1 1 2 2 21 22 23 Jan 0 0 0 Feb 0 0 0 [2 rows x 24 columns] </code></pre>
1
2016-09-18T12:47:28Z
[ "python", "pandas", "data-structures", "extract", "reshape" ]
Using findall and clickall without getting an error if image doesn't exit
39,557,746
<p>I can't figure out what I'm doing wrong. The code works great as long as there is an image displayed for the <code>findall</code>, but if <code>x</code> doesn't appear, then I get an error: </p> <p><code>[error] FindFailed ( can not find P(1474201252795.png) S: 0.99 in R[0,0 1920x1080]@S(0) )</code></p> <p>Not quite sure how to fix this.</p> <pre><code>running = True def runHotkey(event): global running running = False Env.addHotkey(Key.F1, KeyModifier.CTRL, runHotkey) while exists("1474199877323.png")and running: click("1474138615993.png") click("1474138629993.png") wait(5) if exists("1474201633804.png"): for x in findAll(Pattern("1474201252795.png").exact()): click(x) click("1474201809505.png") else: click("1474201689791.png") wait(5) </code></pre>
1
2016-09-18T12:43:31Z
39,558,830
<p>As per documentation <code>findAll</code> throws an Exception on failed search. (<a href="https://github.com/sikuli/sikuli/blob/develop/sikuli-script/src/main/java/org/sikuli/script/Region.java#L434" rel="nofollow">docs</a>). Try to use <code>hasNext()</code> method along with context manager, e.g.</p> <pre><code>with findAll(Pattern(...)) as mm: while mm.hasNext(): x = mm.next() // process x </code></pre>
0
2016-09-18T14:37:48Z
[ "python", "jython", "sikuli" ]
Using findall and clickall without getting an error if image doesn't exit
39,557,746
<p>I can't figure out what I'm doing wrong. The code works great as long as there is an image displayed for the <code>findall</code>, but if <code>x</code> doesn't appear, then I get an error: </p> <p><code>[error] FindFailed ( can not find P(1474201252795.png) S: 0.99 in R[0,0 1920x1080]@S(0) )</code></p> <p>Not quite sure how to fix this.</p> <pre><code>running = True def runHotkey(event): global running running = False Env.addHotkey(Key.F1, KeyModifier.CTRL, runHotkey) while exists("1474199877323.png")and running: click("1474138615993.png") click("1474138629993.png") wait(5) if exists("1474201633804.png"): for x in findAll(Pattern("1474201252795.png").exact()): click(x) click("1474201809505.png") else: click("1474201689791.png") wait(5) </code></pre>
1
2016-09-18T12:43:31Z
39,568,944
<p>Use try/catch</p> <pre><code>private boolean exists(Pattern img, int sec) { try { window.wait(img, sec); return true; } catch (FindFailed exception) { return false; } } </code></pre>
0
2016-09-19T08:48:32Z
[ "python", "jython", "sikuli" ]
Using findall and clickall without getting an error if image doesn't exit
39,557,746
<p>I can't figure out what I'm doing wrong. The code works great as long as there is an image displayed for the <code>findall</code>, but if <code>x</code> doesn't appear, then I get an error: </p> <p><code>[error] FindFailed ( can not find P(1474201252795.png) S: 0.99 in R[0,0 1920x1080]@S(0) )</code></p> <p>Not quite sure how to fix this.</p> <pre><code>running = True def runHotkey(event): global running running = False Env.addHotkey(Key.F1, KeyModifier.CTRL, runHotkey) while exists("1474199877323.png")and running: click("1474138615993.png") click("1474138629993.png") wait(5) if exists("1474201633804.png"): for x in findAll(Pattern("1474201252795.png").exact()): click(x) click("1474201809505.png") else: click("1474201689791.png") wait(5) </code></pre>
1
2016-09-18T12:43:31Z
39,800,821
<p>Another way to avoid the error is to check if the image exist before using findAll:</p> <pre><code>if exists("image_in_findAll.png"): for x in findAll("image.png"): ... </code></pre>
0
2016-09-30T22:14:45Z
[ "python", "jython", "sikuli" ]
Transforming visualization from Seaborn to Bokeh
39,557,758
<p>I want the similar visualization as shown below using <strong>Bokeh</strong>. As I am new to <strong>Bokeh</strong> , I might be wondering is there any code that is as concise as the below one using <strong>Seaborn</strong> ?</p> <p><strong><em>My main focus is how to write code for same visualization in Bokeh</em></strong></p> <h1>dataset</h1> <pre><code>data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv',index_col = 0) </code></pre> <h1>Plotting the dataset</h1> <pre><code>import seaborn as sns sns.pairplot(data, x_vars = ['TV', 'Radio','Newspaper'], y_vars = ['Sales'], size =7, aspect =.7, kind = 'reg') </code></pre> <p><strong>Also the code in Seaborn doesn't require to enter the best fitted line</strong> . It automatically generates the best fitted line in the graph with a shadow of <strong>confidence interval</strong> . <strong>Is this kind of plotting possible in Bokeh ?</strong></p> <p><a href="http://i.stack.imgur.com/dmCHs.png" rel="nofollow"><img src="http://i.stack.imgur.com/dmCHs.png" alt="enter image description here"></a></p>
3
2016-09-18T12:45:05Z
39,562,767
<p>The above charts are certainly <em>possible</em> with Bokeh, in the sense that Bokeh could draw them, without any question. But it would take some work, and require more code, than with Seaborn. Basically you'd have to compute all the coordinates and set up all the glyphs "by hand". As of Bokeh <code>0.12.2</code>, there is not currently any comparable "single line" high level function or chart in <code>bokeh.charts</code>. </p> <p>Adding more high level chart types lie this to <code>bokeh.charts</code> is definitely something that we'd like, but it will probably require motivated new contributors to make that happen. Fortunately, this area of Bokeh is pure-python and probably the most approachable for new contributors. If you are possibly interested in contributing to Bokeh, I encourage you to reach out on the <a href="https://groups.google.com/a/continuum.io/forum/?pli=1#!forum/bokeh" rel="nofollow">public mailing list</a> or <a href="https://gitter.im/bokeh/bokeh" rel="nofollow">gitter chat channel</a>. We are always happy to answer questions and help people get started. </p>
2
2016-09-18T21:17:34Z
[ "python", "data-visualization", "linear-regression", "seaborn", "bokeh" ]
How to write a binary file filled with zeros as binary digits?
39,557,788
<p>How can I write a binary file filled with zeros as binary digits? </p> <p>For example I have 8 bits of zeros like 00000000 which will be saved as one byte.</p>
-1
2016-09-18T12:47:43Z
39,557,807
<p>Files are sequences of bytes, and Python trivially lets you write bytes. Just write <code>\x00</code> characters to produce byes that consist of nothing but <code>0</code> bits.</p> <p>Open the file as binary and just write as many such bytes as you need:</p> <pre><code>with open(filename, 'wb') as binfile: binfile.write(b'\x00' * desired_length) </code></pre>
0
2016-09-18T12:49:38Z
[ "python", "binary" ]
NameError:my function has not be defined
39,557,798
<p>This is my python code in ipython notebook</p> <pre><code>import sys sys.path.append('C:/Users/dell/.ipynb_checkpoints/bsm_functions.py') tol=0.5 for option in options_data.index: forward=futures_data[futures_data['MATURITY']==\ options_data.loc[option]['MATURITY']]['PRICE'].values[0] if(forward*(1-tol)&lt;options_data.loc[option]['STRIKE'] &lt;forward*(1+tol)): imp_vol=bsm_call_imp_vol(v0, options_data.loc[option]['STRIKE'], options_data.loc[option]['TTM'],r, options_data.loc[option]['PRICE'], sigma_est=2,it=100) options_data['IMP_VOL'].loc[option]=imp_vol </code></pre> <p>this the module I wrote:</p> <pre><code>def bsm_call_value(S0,K,T,r,sigma): from math import log,sqrt,exp from scipy import stats S0=float(S0) d1=(log(S0/K)+(r+0.5*sigma**2)*T)/(sigma*sqrt(T)) d2=(log(S0/K)+(r-0.5*sigma**2)*T)/(sigma*sqrt(T)) value=(S0*stats.norm.cdf(d1,0.0,1.0)-K*exp(-r- T)*stats.norm.cdf(d2,0.0,1.0)) return value def bsm_vega(S0,K,T,r,sigma): from math import log,sqrt from scipy import stats S0=float(S0) d1 = (log(S0 / K) + (r + 0.5 * sigma ** 2) * T) / (sigma * sqrt(T)) vega=S0*stats.norm.cdf(d1,0.0,1.0)*sqrt(T) return vega def bsm_call_imp_vol(S0,K,T,r,C0,sigma_est,it=100): for i in range(it): sigma_est-=((bsm_call_value(S0,K,T,r,sigma_est)-C0)/bsm_vega(S0,K,T,r,sigma_est)) return sigma_est </code></pre> <p>my error is:</p> <pre><code>name 'bsm_call_imp_vol' is not defined </code></pre> <p>I do not know the reason of this error</p>
-1
2016-09-18T12:48:42Z
39,557,825
<p>You need to <strong>import</strong> your module. You add the <em>parent directory</em> of a module to your <code>sys.path</code>, then import names from the module:</p> <pre><code>sys.path.append('C:/Users/dell/.ipynb_checkpoints') from bsm_functions import bsm_call_imp_vol </code></pre> <p>Adding the path to a <code>.py</code> file itself to <code>sys.path</code> does not import the module.</p>
2
2016-09-18T12:51:21Z
[ "python" ]
Python recursion variable state
39,557,886
<p>I'm trying to write a Python function to take a string and a number and return a list containing repetitions of the string. For example</p> <pre><code>print func(3, 'aaa') </code></pre> <p>returns</p> <pre><code>['aaa', 'aaa', 'aaa'] </code></pre> <p>This is what I've done so far:</p> <pre><code>def func(times, data): if times &gt; 0: return data.split() + func(times-1, data) </code></pre> <p>However, it's giving me a TypeError:</p> <pre><code>can only concatenate list (not "NoneType") to list. </code></pre> <p>I'm still a novice and I just read about recursion. </p> <p>I would also like to know how to "carry over" the state of a variable from successive function calls, without having to define a global variable. Help please!</p>
2
2016-09-18T12:59:39Z
39,557,917
<p>You need a base case where times is 0, there you can just return an empty list:</p> <pre><code>def func(times, data): if times == 0: return [] # no need for split, just wrap data in a list. return [data] + func(times-1, data) </code></pre> <p>In your code when times == 0, your function implicitly returns None so you are trying to add the result of the recursive calls to None. We should also probably use &lt;= in the base case to catch negative input for times:</p> <pre><code>def func(times, data): if times &lt;= 0: return [] return [data] + func(times-1, data) </code></pre> <p>If we don't we would recurse infinitely and hit a <code>RuntimeError: maximum recursion depth exceeded</code> as we would never hit the base case.</p> <p>There is a nice online tool <a href="http://www.pythontutor.com/visualize.html#" rel="nofollow">python tutor</a> that can visualise the steps so you can see exactly what is happening which would highlight why and where your code erros. </p> <p>When you have a working solution you could use <a href="https://github.com/carlsborg/rcviz" rel="nofollow">rcviz</a> which will create a nice png of the execution steps:</p> <p><a href="http://i.stack.imgur.com/CNJaM.png" rel="nofollow"><img src="http://i.stack.imgur.com/CNJaM.png" alt="enter image description here"></a></p> <p><em>Note: 1. The edges are numbered by the order in which they were traversed by the execution. 2. The edges are colored from black to grey to indicate order of traversal : black edges first, grey edge</em>s last.</p>
5
2016-09-18T13:02:52Z
[ "python" ]
Python recursion variable state
39,557,886
<p>I'm trying to write a Python function to take a string and a number and return a list containing repetitions of the string. For example</p> <pre><code>print func(3, 'aaa') </code></pre> <p>returns</p> <pre><code>['aaa', 'aaa', 'aaa'] </code></pre> <p>This is what I've done so far:</p> <pre><code>def func(times, data): if times &gt; 0: return data.split() + func(times-1, data) </code></pre> <p>However, it's giving me a TypeError:</p> <pre><code>can only concatenate list (not "NoneType") to list. </code></pre> <p>I'm still a novice and I just read about recursion. </p> <p>I would also like to know how to "carry over" the state of a variable from successive function calls, without having to define a global variable. Help please!</p>
2
2016-09-18T12:59:39Z
39,558,373
<p>While @Padraic Cunningham has a good answer, here is a simple way to do it:</p> <pre><code>def func(number, content): return [content] * number </code></pre> <p>Or list comprehension:</p> <pre><code>def func(number, content): return [content for _ in range(number)] </code></pre>
0
2016-09-18T13:54:12Z
[ "python" ]
Is it possible to run just through the item pipeline without crawling with Scrapy?
39,557,896
<p>I have a <code>.jl</code> file with items I've scraped. I have another pipeline now which was not present when I was doing the scraping. Is it possible to run just the pipeline, and have it apply the new pipeline without doing the crawl/scrape again?</p>
0
2016-09-18T13:00:35Z
39,558,345
<p>Quick answer: Yes.</p> <p>To bypass the downloader while having other components of scrapy working, you could use a customized downloader middleware which returns <code>Response</code> objects in its <code>process_request</code> method. Check the details: <a href="http://doc.scrapy.org/en/latest/topics/downloader-middleware.html" rel="nofollow">http://doc.scrapy.org/en/latest/topics/downloader-middleware.html</a></p> <p>But in your case I personally think you could use some simple code to download the <code>.jl</code> file from your local file system. A quick (and full) example:</p> <pre><code># coding: utf8 import json import scrapy class SampleSpider(scrapy.Spider): name = 'sample_spider' start_urls = [ 'file:///tmp/some_file.jl', ] custom_settings = { 'ITEM_PIPELINES': { 'your_pipeline_here': 100, }, } def parse(self, response): for line in response.body.splitlines(): jdata = json.loads(line) yield jdata </code></pre> <p>Just replace <code>'/tmp/some_file.jl'</code> with your actual path to the file.</p>
2
2016-09-18T13:50:12Z
[ "python", "scrapy" ]
Print in getter of a property not working?
39,558,027
<p>I am new to python, currently trying to learn properties. </p> <pre><code>class Car(object): def set_speed(self, speed): self._speed = speed print("set speed to {}".format(self.speed)) def get_speed(self): return self._speed print("the speed is {}".format(self.speed)) speed = property(fget = get_speed, fset=set_speed) car1 = Car() car1.speed = 170 x = car1.speed </code></pre> <p>The output I get is <code>set speed to 170</code> </p> <p>That is all well and fine, and there is no surprise here since <code>car1.speed</code> was called. However, why was there never a <code>"The speed is 170"</code> printline? <code>car1.speed</code> was called in the same manner? Is there something I have not understood?</p>
0
2016-09-18T13:15:08Z
39,558,038
<p>You used a <code>return</code> statement <em>before</em> the <code>print()</code> call. The function execution <em>ends</em> at that point, the <code>print()</code> is never reached:</p> <pre><code>def get_speed(self): # return ends a function return self._speed # anything beyond this point is ignored print("the speed is {}".format(self.speed)) </code></pre> <p>Put the <code>print()</code> call <em>before</em> the return statement:</p> <pre><code>def get_speed(self): print("the speed is {}".format(self._speed)) return self._speed </code></pre> <p>I corrected the <code>print()</code> function to show <code>self._speed</code> (<em>with</em> an underscore in the attribute name), otherwise you'd get into an infinite recursion (since <code>self.speed</code> would trigger the property again getter). You probably want to do the same in the <code>set_speed()</code> function, as that'll trigger the <code>get_speed()</code> getter too and you'll see <code>the speed is &lt;newspeed&gt;</code> printed before <code>set speed to &lt;newspeed&gt;</code> is printed each time you change the speed:</p> <pre><code>class Car(object): def set_speed(self, speed): self._speed = speed print("set speed to {}".format(speed)) def get_speed(self): print("the speed is {}".format(self._speed)) return self._speed speed = property(fget = get_speed, fset=set_speed) </code></pre> <p>Next, you can use the <code>property</code> object as a <em>decorator</em>; the resulting <code>property</code> instance has a <code>setter()</code> method that can then be re-used to decorate the setter too:</p> <pre><code>class Car(object): @property def speed(self): print("the speed is {}".format(self._speed)) return self._speed @speed.setter def speed(self, speed): self._speed = speed print("set speed to {}".format(speed)) </code></pre> <p>See <a href="https://stackoverflow.com/questions/17330160/how-does-the-property-decorator-work">How does the @property decorator work?</a> as to how that works.</p>
7
2016-09-18T13:16:20Z
[ "python", "properties" ]
How to add each element in two vectors with Theano?
39,558,303
<p>I would like to know how to add each element in two vectors with Theano?</p> <p>Assume that we have two vector <em>vector_1</em> and <em>vecotr_2</em>, and we would like to construct a matrix <em>A</em>, where</p> <blockquote> <p><em>A[i][j]</em> = <em>vector_1[i]</em> + <em>vecotr_2[j]</em></p> </blockquote> <p>I know that in numpy we can use list comprehension. But i would like to use Theano obtain the result with less time. It seems that Theano.scan() can do this job, but i really don't know how to deal with it.</p>
1
2016-09-18T13:46:21Z
39,559,410
<p>You can make use of broadcasting. Here is an example in NumPy, you can do the same in Theano:</p> <pre><code>&gt;&gt;&gt; import numpy as np &gt;&gt;&gt; x1 = np.array([1,1,9]).reshape((3,1)) &gt;&gt;&gt; x2 = np.array([0,3,4]).reshape((1,3)) &gt;&gt;&gt; np.add(x1, x2) array([[ 1, 4, 5], [ 1, 4, 5], [ 9, 12, 13]]) </code></pre>
0
2016-09-18T15:34:08Z
[ "python", "theano", "theano.scan" ]
How can I remove a URL channel from Anaconda?
39,558,316
<p>Recently I needed to install PyPdf2 to one of my programs using Anaconda. Unfortunately, I failed, but the URLs that was added to Anaconda environment prohibit the updates of all the Conda libraries. Every time I tried to update anaconda it gives the following </p> <pre><code>conda update conda Using Anaconda Cloud api site https://api.anaconda.org Fetching package metadata ..........Error: Invalid index file: https://pypi.python.org/pypi/PyPDF2/1.26.0/win-64/repodata.json: No JSON object could be decoded </code></pre> <p>I typed the command <strong>conda info</strong> to see what causes the error, I found lots of URLs that points to PyPdf2!</p> <p>Simply, I want to remove all these URLS from anaconda's channel URLs, How can I do it? No matter manually or automatic.</p> <p>Note: I have uninstalled Anaconda, and reinstall, but no luck!</p> <pre><code>C:\WINDOWS\system32&gt;conda info Using Anaconda Cloud api site https://api.anaconda.org Current conda install: platform : win-64 conda version : 4.1.6 conda-env version : 2.5.1 conda-build version : 1.21.3 python version : 2.7.12.final.0 requests version : 2.10.0 root environment : C:\Anaconda2 (writable) default environment : C:\Anaconda2 envs directories : C:\Anaconda2\envs package cache : C:\Anaconda2\pkgs channel URLs : https://pypi.python.org/pypi/PyPDF2/1.26.0/win-64/ https://pypi.python.org/pypi/PyPDF2/1.26.0/noarch/ https://conda.anaconda.org/C:\Python27\Lib\site-packages\PyPDF2/win-64/ https://conda.anaconda.org/C:\Python27\Lib\site-packages\PyPDF2/noarch/ https://conda.anaconda.org/X:\Downloads\Compressed\PyPDF2-master\/win-64/ https://conda.anaconda.org/X:\Downloads\Compressed\PyPDF2-master\/noarch/ https://github.com/mstamy2/PyPDF2/zipball/master/win-64/ https://github.com/mstamy2/PyPDF2/zipball/master/noarch/ https://pypi.python.org/pypi/PyPDF2/win-64/ https://pypi.python.org/pypi/PyPDF2/noarch/ https://pythonhosted.org/PyPDF2/win-64/ https://pythonhosted.org/PyPDF2/noarch/ https://github.com/mstamy2/PyPDF2/win-64/ https://github.com/mstamy2/PyPDF2/noarch/ https://repo.continuum.io/pkgs/free/win-64/ https://repo.continuum.io/pkgs/free/noarch/ https://repo.continuum.io/pkgs/pro/win-64/ https://repo.continuum.io/pkgs/pro/noarch/ config file : C:\Users\Dr. Mohammad Elnesr\.condarc offline mode : False is foreign system : False </code></pre>
2
2016-09-18T13:47:26Z
39,566,207
<p>Fortunately, I found the answer (Thanks to @cel as well).</p> <p>I navigated to <code>C:\Users\{MyUserName}\</code> Then I found a file with no name but has a strange extension (<code>.condarc</code>) I opened it with Notepad++, I found the files as below></p> <p><a href="http://i.stack.imgur.com/dPbWh.png" rel="nofollow"><img src="http://i.stack.imgur.com/dPbWh.png" alt="enter image description here"></a></p> <p>Then I deleted all lines except the last one, saved the file, then I ran the command <code>conda update conda</code>, and it works without errors.</p>
1
2016-09-19T05:55:30Z
[ "python", "anaconda", "channel", "pypdf2" ]
How can I remove a URL channel from Anaconda?
39,558,316
<p>Recently I needed to install PyPdf2 to one of my programs using Anaconda. Unfortunately, I failed, but the URLs that was added to Anaconda environment prohibit the updates of all the Conda libraries. Every time I tried to update anaconda it gives the following </p> <pre><code>conda update conda Using Anaconda Cloud api site https://api.anaconda.org Fetching package metadata ..........Error: Invalid index file: https://pypi.python.org/pypi/PyPDF2/1.26.0/win-64/repodata.json: No JSON object could be decoded </code></pre> <p>I typed the command <strong>conda info</strong> to see what causes the error, I found lots of URLs that points to PyPdf2!</p> <p>Simply, I want to remove all these URLS from anaconda's channel URLs, How can I do it? No matter manually or automatic.</p> <p>Note: I have uninstalled Anaconda, and reinstall, but no luck!</p> <pre><code>C:\WINDOWS\system32&gt;conda info Using Anaconda Cloud api site https://api.anaconda.org Current conda install: platform : win-64 conda version : 4.1.6 conda-env version : 2.5.1 conda-build version : 1.21.3 python version : 2.7.12.final.0 requests version : 2.10.0 root environment : C:\Anaconda2 (writable) default environment : C:\Anaconda2 envs directories : C:\Anaconda2\envs package cache : C:\Anaconda2\pkgs channel URLs : https://pypi.python.org/pypi/PyPDF2/1.26.0/win-64/ https://pypi.python.org/pypi/PyPDF2/1.26.0/noarch/ https://conda.anaconda.org/C:\Python27\Lib\site-packages\PyPDF2/win-64/ https://conda.anaconda.org/C:\Python27\Lib\site-packages\PyPDF2/noarch/ https://conda.anaconda.org/X:\Downloads\Compressed\PyPDF2-master\/win-64/ https://conda.anaconda.org/X:\Downloads\Compressed\PyPDF2-master\/noarch/ https://github.com/mstamy2/PyPDF2/zipball/master/win-64/ https://github.com/mstamy2/PyPDF2/zipball/master/noarch/ https://pypi.python.org/pypi/PyPDF2/win-64/ https://pypi.python.org/pypi/PyPDF2/noarch/ https://pythonhosted.org/PyPDF2/win-64/ https://pythonhosted.org/PyPDF2/noarch/ https://github.com/mstamy2/PyPDF2/win-64/ https://github.com/mstamy2/PyPDF2/noarch/ https://repo.continuum.io/pkgs/free/win-64/ https://repo.continuum.io/pkgs/free/noarch/ https://repo.continuum.io/pkgs/pro/win-64/ https://repo.continuum.io/pkgs/pro/noarch/ config file : C:\Users\Dr. Mohammad Elnesr\.condarc offline mode : False is foreign system : False </code></pre>
2
2016-09-18T13:47:26Z
39,596,897
<p>Expanding upon Mohammed's <a href="http://stackoverflow.com/a/39566207/1193874">answer</a>.</p> <p>All those URLs that you see in your <code>conda info</code> are your channel URLs. These are where conda will look for packages. As noted by @cel, these channels can be found in the <code>.condarc</code> file in your home directory. </p> <p>You can interact with the channels, and other data, in your <code>.condarc</code> file with the <code>conda config</code> command. For example, let's say your <code>.condarc</code> file lists the following channels:</p> <pre><code>channels: - https://github.com/mstamy2/PyPDF2/ - defaults </code></pre> <p>Then if we do <code>conda config --get channels</code> we will see returned:</p> <pre><code>--add channels 'defaults' # lowest priority --add channels 'https://github.com/mstamy2/PyPDF2/' # highest priority </code></pre> <p>If we then want to remove the github channel we would do <code>conda config --remove channels 'https://github.com/mstamy2/PyPDF2/'</code>. You can also add channels through the <code>--add</code> command so, for example, we could add back that channel with <code>conda config --add channels 'https://github.com/mstamy2/PyPDF2/'</code>.</p> <p>In this case, since there were several channels to remove, it was probably faster to simply edit the <code>.condarc</code> directly but it's useful to know how to do it through <code>conda config</code>.</p>
0
2016-09-20T14:33:26Z
[ "python", "anaconda", "channel", "pypdf2" ]
How to pass error without try catch in Python-Selenium?
39,558,340
<p>In my python-Selenium code, i should use many <strong>try-catch</strong> to pass the errors, and if i don't use it, my script doesn't continue. for example if i don't use try catch, if my script doesn't find <code>desc span</code> i will have an error and i can't continue, </p> <pre><code> try : libelle1produit = prod.find_element_by_css_selector(('.desc span')).text # libelle1produit OK except: pass </code></pre> <p>is there an alternative method for passing error? </p>
1
2016-09-18T13:49:57Z
39,558,743
<blockquote> <p>is there an alternative method for passing error?</p> </blockquote> <p>Yes, To avoid <code>try-catch</code> and avoid error as well try using <code>find_elements</code> instead which would return either a list of all elements with matching locator or empty list if nothing is found, you need to just check the list length to determine that element exists or not as below :-</p> <pre><code>libelle1produit = prod.find_elements_by_css_selector('.desc span') if len(libelle1produit) &gt; 0 : libelle1produit[0].text </code></pre>
1
2016-09-18T14:29:59Z
[ "python", "selenium", "exception", "web-scraping", "try-catch" ]
How to enter the offset for a Caesar cipher in Python
39,558,372
<p>I have this code which is a basic Caesar cipher, the offset is set to one but I want it so that the user can enter the offset. The user should be able to say by how much the alphabet is moved across by, but it won't work if offset = input</p> <pre><code>#Caesar cipher sentance = input('Enter sentance: ') alphabet = ('abcdefghijklmnopqrstuvwxyz') offset = 1 cipher = '' for c in sentance: if c in alphabet: cipher += alphabet[(alphabet.index(c)+offset)%(len(alphabet))] print('Your encrypted message is: ' + cipher) </code></pre>
0
2016-09-18T13:54:03Z
39,558,753
<p>That is probably because you did not convert the input into an integer, and practically filled <code>offset</code> with a string.</p> <p>Use <code>int(input())</code> to convert the inputted string as an integer (optional- also remember to add the original character in case they are not in the alphabet):</p> <pre><code>sentance = input('Enter sentance: ') offset = int(input('Enter offset: ')) alphabet = ('abcdefghijklmnopqrstuvwxyz') cipher = '' for c in sentance: if c in alphabet: cipher += alphabet[(alphabet.index(c) + offset) % (len(alphabet))] else: cipher += c print('Your encrypted message is: ' + cipher) </code></pre> <p>Will produce:</p> <pre><code>Enter sentance: hello world! Enter offset: 13 Your encrypted message is: uryyb jbeyq! </code></pre>
1
2016-09-18T14:31:26Z
[ "python", "encryption", "caesar-cipher" ]
remove parentheses created by csv.DictWriter in python
39,558,413
<p>when i'm saving a dictionary representing a graph with the format:</p> <pre><code>graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []} </code></pre> <p>and save it with the csv.DictWriter and load it i get:</p> <pre><code>loaded_graph ={'b': "['a', 'c']", 'c': "['a']", 'a': '[]', 'd': '[]'} </code></pre> <p>How can i avoid the added quotation marks for the value lists or what code do i have to use to remove them when reading the file? Help would be appreciated!</p> <pre><code>print(graph_dict) with open('graph.csv', 'w') as csvfile: graph = ['vertices', 'edges'] writer = csv.DictWriter(csvfile, fieldnames=graph) writer.writeheader() for vertex in graph_dict: edges = graph_dict[vertex] writer.writerow({'vertices': vertex, 'edges': edges}) print("reading") loaded_graph = {} with open('graph.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: loaded_graph[row['vertices']] = row['edges'] print(loaded_graph) </code></pre> <p>the csv file opened in editor looks like this:</p> <pre><code>vertices,edges b,"['a', 'c']" a,[] c,['a'] d,[] </code></pre>
0
2016-09-18T13:58:22Z
39,558,518
<p>You have</p> <pre><code>graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []} </code></pre> <p>Then</p> <pre><code> edges = graph_dict[vertex] writer.writerow({'vertices': vertex, 'edges': edges}) </code></pre> <p>This writes a list to the file -- it is converted to str.</p> <p>Do, for example</p> <pre><code>writer.writerow({'vertices': vertex, 'edges': ','.join(edges)}) </code></pre>
0
2016-09-18T14:09:11Z
[ "python", "python-3.x" ]
remove parentheses created by csv.DictWriter in python
39,558,413
<p>when i'm saving a dictionary representing a graph with the format:</p> <pre><code>graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []} </code></pre> <p>and save it with the csv.DictWriter and load it i get:</p> <pre><code>loaded_graph ={'b': "['a', 'c']", 'c': "['a']", 'a': '[]', 'd': '[]'} </code></pre> <p>How can i avoid the added quotation marks for the value lists or what code do i have to use to remove them when reading the file? Help would be appreciated!</p> <pre><code>print(graph_dict) with open('graph.csv', 'w') as csvfile: graph = ['vertices', 'edges'] writer = csv.DictWriter(csvfile, fieldnames=graph) writer.writeheader() for vertex in graph_dict: edges = graph_dict[vertex] writer.writerow({'vertices': vertex, 'edges': edges}) print("reading") loaded_graph = {} with open('graph.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: loaded_graph[row['vertices']] = row['edges'] print(loaded_graph) </code></pre> <p>the csv file opened in editor looks like this:</p> <pre><code>vertices,edges b,"['a', 'c']" a,[] c,['a'] d,[] </code></pre>
0
2016-09-18T13:58:22Z
39,558,545
<p>CSV is not intended for nested data structures; it has no meaningful way of dealing with them (it's converting your <code>list</code> values to <code>str</code> for output).</p> <p>You either need to use a more appropriate format (e.g. JSON or <code>pickle</code>), or use horrible hacks to convert the <code>repr</code> of the values back to their original values, e.g. <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval</code></a> (except that won't work properly if some of the original values were supposed to be strings).</p>
0
2016-09-18T14:11:38Z
[ "python", "python-3.x" ]
remove parentheses created by csv.DictWriter in python
39,558,413
<p>when i'm saving a dictionary representing a graph with the format:</p> <pre><code>graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []} </code></pre> <p>and save it with the csv.DictWriter and load it i get:</p> <pre><code>loaded_graph ={'b': "['a', 'c']", 'c': "['a']", 'a': '[]', 'd': '[]'} </code></pre> <p>How can i avoid the added quotation marks for the value lists or what code do i have to use to remove them when reading the file? Help would be appreciated!</p> <pre><code>print(graph_dict) with open('graph.csv', 'w') as csvfile: graph = ['vertices', 'edges'] writer = csv.DictWriter(csvfile, fieldnames=graph) writer.writeheader() for vertex in graph_dict: edges = graph_dict[vertex] writer.writerow({'vertices': vertex, 'edges': edges}) print("reading") loaded_graph = {} with open('graph.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: loaded_graph[row['vertices']] = row['edges'] print(loaded_graph) </code></pre> <p>the csv file opened in editor looks like this:</p> <pre><code>vertices,edges b,"['a', 'c']" a,[] c,['a'] d,[] </code></pre>
0
2016-09-18T13:58:22Z
39,558,575
<p>You're trying to "serialize" this data using CSV, which might be appropriate if you want to analyze the file outside of Python. If not, your problem will be solved more easily with the <a href="https://docs.python.org/3/library/pickle.html" rel="nofollow">pickle</a> module.</p> <p>If you must use CSV, make sure the values you save as "edges" to the file are all strings. Then when you read them back from the file, turn them back to a list.</p> <pre><code>import csv graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []} file_path = 'graph.csv' with open(file_path, 'w', newline='') as outfile: fieldnames = ['vertices', 'edges'] writer = csv.DictWriter(outfile, fieldnames=fieldnames) writer.writeheader() for vertex, edges in graph_dict.items(): # Save multiples as "x,y,z" edges = ','.join(edges) row = {'vertices': vertex, 'edges': edges} writer.writerow(row) loaded_graph = {} with open(file_path, 'r', newline='') as infile: reader = csv.DictReader(infile) for row in reader: edges = row['edges'] # Read empty as [], full as ['x', 'y', 'z'] edges = edges.split(',') if edges else [] loaded_graph[row['vertices']] = edges </code></pre> <p>That gives <code>{'a': [], 'b': ['a', 'c'], 'c': ['a'], 'd': []}</code> as requested.</p>
0
2016-09-18T14:14:42Z
[ "python", "python-3.x" ]
How can I load my Aurelia app from an index.html which is not located in the same folder as the rest of the application?
39,558,580
<p>How can I load my app from an <code>index.html</code> which is not located in the same folder as the rest of the application?</p> <p>I’m currently using <code>jspm</code> (which I’m new to). I’m trying to integrate <code>Aurelia</code> with <code>web2py</code> (Python web framework). </p> <p>My <code>index.html</code> in accessible via</p> <pre><code>http://websiteaddress.com/myapp/default/index.html </code></pre> <p>and may later be accessible via</p> <pre><code>http://websiteaddress.com/myapp/index.html </code></pre> <p>but the code of my <code>Aurelia</code> app is accessible from</p> <pre><code>http://websiteaddress.com/myapp/static/aurelia_app/ </code></pre> <p>On the disk the <code>index.html</code> file is at </p> <pre><code>/web2py/applications/myapp/views/default/index.html </code></pre> <p>and the <code>Aurelia</code> app folder is at</p> <pre><code>/web2py/applications/myapp/static/aurelia_app </code></pre>
0
2016-09-18T14:14:58Z
39,644,621
<p>You need to use the <a href="http://web2py.com/books/default/chapter/29/04/the-core?search=router#Pattern-based-system" rel="nofollow">web2py pattern router</a>, something like this in the router definition should work:</p> <pre><code>routes_in = ( ('/appname/default/index', '/appname/static/aurelia_app/index.html'), ('/appname/default/jspm_packages/$anything', '/appname/static/aurelia_app/jspm_packages/$anything'), ) </code></pre>
0
2016-09-22T16:45:03Z
[ "javascript", "python", "web2py", "aurelia", "jspm" ]
Using set_index within a custom function
39,558,659
<p>I would like to convert the date observations from a column into the index for my dataframe. I am able to do this with the code below:</p> <p>Sample data:</p> <pre><code>test = pd.DataFrame({'Values':[1,2,3], 'Date':["1/1/2016 17:49","1/2/2016 7:10","1/3/2016 15:19"]}) </code></pre> <p>Indexing code:</p> <pre><code>test['Date Index'] = pd.to_datetime(test['Date']) test = test.set_index('Date Index') test['Index'] = test.index.date </code></pre> <p>However when I try to include this code in a function, I am able to create the 'Date Index' column but <code>set_index</code> does not seem to work as expected.</p> <pre><code>def date_index(df): df['Date Index'] = pd.to_datetime(df['Date']) df = df.set_index('Date Index') df['Index'] = df.index.date </code></pre> <p>If I inspect the output of not using a function <code>info()</code> returns:</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; DatetimeIndex: 3 entries, 2016-01-01 17:49:00 to 2016-01-03 15:19:00 Data columns (total 3 columns): Date 3 non-null object Values 3 non-null int64 Index 3 non-null object dtypes: int64(1), object(2) memory usage: 96.0+ bytes </code></pre> <p>If I inspect the output of the function <code>info()</code> returns:</p> <pre><code>&lt;class 'pandas.core.frame.DataFrame'&gt; RangeIndex: 3 entries, 0 to 2 Data columns (total 2 columns): Date 3 non-null object Values 3 non-null int64 dtypes: int64(1), object(1) memory usage: 120.0+ bytes </code></pre> <p>I would like the <code>DatetimeIndex</code>.</p> <p>How can <code>set_index</code> be used within a function? Am I using it incorrectly? </p>
0
2016-09-18T14:22:35Z
39,558,726
<p>IIUC <code>return df</code> is missing:</p> <pre><code>df1 = pd.DataFrame({'Values':[1,2,3], 'Exam Completed Date':["1/1/2016 17:49","1/2/2016 7:10","1/3/2016 15:19"]}) def date_index(df): df['Exam Completed Date Index'] = pd.to_datetime(df['Exam Completed Date']) df = df.set_index('Exam Completed Date Index') df['Index'] = df.index.date return df print (date_index(df1)) Exam Completed Date Values Index Exam Completed Date Index 2016-01-01 17:49:00 1/1/2016 17:49 1 2016-01-01 2016-01-02 07:10:00 1/2/2016 7:10 2 2016-01-02 2016-01-03 15:19:00 1/3/2016 15:19 3 2016-01-03 </code></pre> <hr> <pre><code>print (date_index(df1).info()) &lt;class 'pandas.core.frame.DataFrame'&gt; DatetimeIndex: 3 entries, 2016-01-01 17:49:00 to 2016-01-03 15:19:00 Data columns (total 3 columns): Exam Completed Date 3 non-null object Values 3 non-null int64 Index 3 non-null object dtypes: int64(1), object(2) memory usage: 96.0+ bytes None </code></pre>
0
2016-09-18T14:28:53Z
[ "python", "pandas" ]
Regex find whole substring between parenthesis containing exact substring
39,558,667
<p>For example I have string:</p> <pre><code>"one two (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)" </code></pre> <p>and I need only whole substring with parenthesis, containing word <code>"back"</code>, for this string it will be:</p> <pre><code>"(87 back sack)" </code></pre> <p>I've tried:</p> <pre><code>(\(.*?back.*?\)) </code></pre> <p>but it's return <code>"(78-45ack sack); now (87 back sack)"</code></p> <p>How should my regex look like? As I understood it's happening cause search going from begin of the string, in common - <strong>how to perform regex to <code>"search"</code> from the middle of string, from the word <code>"back"</code>?</strong></p>
1
2016-09-18T14:23:31Z
39,558,763
<p>You can use this regex based on negated character class:</p> <pre><code>\([^()]*?back[^()]*\) </code></pre> <ul> <li><code>[^()]*</code> matches 0 or more of any character that is not <code>(</code> and <code>)</code>, thus making sure we don't match across the pair of <code>(...)</code>.</li> </ul> <p><a href="https://regex101.com/r/hX7yW2/3" rel="nofollow">RegEx Demo 1</a></p> <hr> <p>Alternatively, you can also use this regex based on negative regex:</p> <pre><code>\((?:(?!back|[()]).)*?back[^)]*\) </code></pre> <p><a href="https://regex101.com/r/hX7yW2/4" rel="nofollow">RegEx Demo 2</a></p> <ul> <li><code>(?!back|[()])</code> is negative lookahead that asserts that current position doesn't have <code>back</code> or <code>(</code> or <code>)</code> ahead in the text.</li> <li><code>(?:(?!back|\)).)*?</code> matches 0 or more of any character that doesn't have <code>back</code> or <code>(</code> or <code>)</code> ahead.</li> <li><code>[^)]*</code> matches anything but <code>)</code>.</li> </ul>
3
2016-09-18T14:32:27Z
[ "python", "regex", "string", "substring", "parentheses" ]
Regex find whole substring between parenthesis containing exact substring
39,558,667
<p>For example I have string:</p> <pre><code>"one two (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)" </code></pre> <p>and I need only whole substring with parenthesis, containing word <code>"back"</code>, for this string it will be:</p> <pre><code>"(87 back sack)" </code></pre> <p>I've tried:</p> <pre><code>(\(.*?back.*?\)) </code></pre> <p>but it's return <code>"(78-45ack sack); now (87 back sack)"</code></p> <p>How should my regex look like? As I understood it's happening cause search going from begin of the string, in common - <strong>how to perform regex to <code>"search"</code> from the middle of string, from the word <code>"back"</code>?</strong></p>
1
2016-09-18T14:23:31Z
39,559,021
<pre><code>h="one two (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)" l=h.split("(") [x.split(")")[0] for x in l if ")" in x and "back" in x] </code></pre>
0
2016-09-18T14:56:12Z
[ "python", "regex", "string", "substring", "parentheses" ]
Regex find whole substring between parenthesis containing exact substring
39,558,667
<p>For example I have string:</p> <pre><code>"one two (78-45ack sack); now (87 back sack) follow dollow (59 uhhaaa)" </code></pre> <p>and I need only whole substring with parenthesis, containing word <code>"back"</code>, for this string it will be:</p> <pre><code>"(87 back sack)" </code></pre> <p>I've tried:</p> <pre><code>(\(.*?back.*?\)) </code></pre> <p>but it's return <code>"(78-45ack sack); now (87 back sack)"</code></p> <p>How should my regex look like? As I understood it's happening cause search going from begin of the string, in common - <strong>how to perform regex to <code>"search"</code> from the middle of string, from the word <code>"back"</code>?</strong></p>
1
2016-09-18T14:23:31Z
39,614,422
<p>Try the below pattern for reluctant matching</p> <p>pattern="\(.*?\)"</p>
0
2016-09-21T10:47:58Z
[ "python", "regex", "string", "substring", "parentheses" ]
Pivot Table with All the Index
39,558,733
<p>I am using python pandas to create a pivot table from df. The df looks like:</p> <p><a href="http://i.stack.imgur.com/uId4U.png" rel="nofollow"><img src="http://i.stack.imgur.com/uId4U.png" alt="enter image description here"></a></p> <p>The fields that have missing values are: Origin City, Shipment Date, Volume and Landing Date. Note that Landing Date is the sum of Shipment date and TAT.</p> <p>What I want to get the Output is This:</p> <p><a href="http://i.stack.imgur.com/ntdxH.png" rel="nofollow"><img src="http://i.stack.imgur.com/ntdxH.png" alt="enter image description here"></a></p> <p>I have the following code for the output above:</p> <pre><code>pd.pivot_table(df, values='Volume', index=['DC'], columns=['Landing date'], aggfunc=np.sum, fill_value = 0) </code></pre> <p>The actual output I am getting is</p> <p><a href="http://i.stack.imgur.com/DcXGM.png" rel="nofollow"><img src="http://i.stack.imgur.com/DcXGM.png" alt="enter image description here"></a></p> <p>The problem here is my code removes the <code>DC = DLT</code> as it has missing value while pivoting. Any ideas?</p>
1
2016-09-18T14:29:27Z
39,558,860
<p>You can use <code>ffill</code>, what is same as <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>Series.fillna</code></a> with <code>method='ffill'</code>:</p> <pre><code>print (df) DC Landing date Volume 0 MAR 02-09-16 50.0 1 MAR 03-09-16 98.0 2 MAR NaN NaN 3 BOY 05-09-16 60.0 4 BOY 06-09-16 14.0 5 DLT NaN NaN 6 DLT NaN NaN df['Landing date'] = df['Landing date'].ffill() print (df) DC Landing date Volume 0 MAR 02-09-16 50.0 1 MAR 03-09-16 98.0 2 MAR 03-09-16 NaN 3 BOY 05-09-16 60.0 4 BOY 06-09-16 14.0 5 DLT 06-09-16 NaN 6 DLT 06-09-16 NaN df1 = pd.pivot_table(df, values='Volume', index=['DC'], columns=['Landing date'], aggfunc=np.sum, fill_value = 0) df1.index.name = None df1.columns.name = None print (df1) 02-09-16 03-09-16 05-09-16 06-09-16 BOY 0 0 60 14 DLT 0 0 0 0 MAR 50 98 0 0 </code></pre> <hr> <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html" rel="nofollow"><code>fillna</code></a> by first non NaN value from column <code>Landing date</code>:</p> <pre><code>val = df['Landing date'].dropna().iloc[0] print (val) 02-09-16 df['Landing date'] = df['Landing date'].fillna(val) print (df) DC Landing date Volume 0 MAR 02-09-16 50.0 1 MAR 03-09-16 98.0 2 MAR 02-09-16 NaN 3 BOY 05-09-16 60.0 4 BOY 06-09-16 14.0 5 DLT 02-09-16 NaN 6 DLT 02-09-16 NaN </code></pre>
0
2016-09-18T14:40:39Z
[ "python", "python-2.7", "pandas", "pivot", "pivot-table" ]
If statement not firing
39,558,770
<p>This code does a recursive bisection search for a character in a string. </p> <p>When the <code>print</code> statements are not commented out, it seems to work well with the recursion and bisection, but the <code>if</code> statement that returns <code>True</code> does not seem to fire.</p> <pre><code>def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' b = sorted(aStr) c = len(aStr) # print("string b " + str(b)) # print("c " + str(c)) # print("element middle: " + str(b[round(c/2)])) #print("char: " + str(char)) #print(str(char) == str(b[round(c/2)])) if ((str(char) == str(b[round(c/2)]))): # this if statement does not seem to fire return True elif (c == 1 and char != str(b[round(c/2)])) or (c == 0 and char != "") : return False #print("false") else: #if str(char) == str(b[round(c/2)]): # return True # print("true") if char &gt; b[round(c/2)]: isIn(char, b[round(c/2):c]) elif char &lt; b[round(c/2)]: isIn(char, b[0:round(c/2)]) else: return False #print('fales') </code></pre>
0
2016-09-18T14:32:40Z
39,558,843
<p>You need to return the result of each recursive call.</p> <p>This is a very common mistake, for some reason.</p>
1
2016-09-18T14:39:08Z
[ "python" ]
If statement not firing
39,558,770
<p>This code does a recursive bisection search for a character in a string. </p> <p>When the <code>print</code> statements are not commented out, it seems to work well with the recursion and bisection, but the <code>if</code> statement that returns <code>True</code> does not seem to fire.</p> <pre><code>def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' b = sorted(aStr) c = len(aStr) # print("string b " + str(b)) # print("c " + str(c)) # print("element middle: " + str(b[round(c/2)])) #print("char: " + str(char)) #print(str(char) == str(b[round(c/2)])) if ((str(char) == str(b[round(c/2)]))): # this if statement does not seem to fire return True elif (c == 1 and char != str(b[round(c/2)])) or (c == 0 and char != "") : return False #print("false") else: #if str(char) == str(b[round(c/2)]): # return True # print("true") if char &gt; b[round(c/2)]: isIn(char, b[round(c/2):c]) elif char &lt; b[round(c/2)]: isIn(char, b[0:round(c/2)]) else: return False #print('fales') </code></pre>
0
2016-09-18T14:32:40Z
39,559,031
<p>You shouldn't be using <code>round</code> in whatever that calculation is, as then you are using a <code>float</code> instead of an <code>int</code> as the index to the string.<br> use <code>int</code> instead:</p> <pre><code>str(b[int(c/2)])) </code></pre>
0
2016-09-18T14:57:41Z
[ "python" ]
If statement not firing
39,558,770
<p>This code does a recursive bisection search for a character in a string. </p> <p>When the <code>print</code> statements are not commented out, it seems to work well with the recursion and bisection, but the <code>if</code> statement that returns <code>True</code> does not seem to fire.</p> <pre><code>def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' b = sorted(aStr) c = len(aStr) # print("string b " + str(b)) # print("c " + str(c)) # print("element middle: " + str(b[round(c/2)])) #print("char: " + str(char)) #print(str(char) == str(b[round(c/2)])) if ((str(char) == str(b[round(c/2)]))): # this if statement does not seem to fire return True elif (c == 1 and char != str(b[round(c/2)])) or (c == 0 and char != "") : return False #print("false") else: #if str(char) == str(b[round(c/2)]): # return True # print("true") if char &gt; b[round(c/2)]: isIn(char, b[round(c/2):c]) elif char &lt; b[round(c/2)]: isIn(char, b[0:round(c/2)]) else: return False #print('fales') </code></pre>
0
2016-09-18T14:32:40Z
39,559,140
<p>This code works, has return before the recursive function calls:</p> <pre><code>def isIn(char, aStr): ''' char: a single character aStr: an alphabetized string returns: True if char is in aStr; False otherwise ''' b = sorted(aStr) c = len(aStr) # print("string b " + str(b)) # print("c " + str(c)) # print("element middle: " + str(b[round(c/2)])) #print("char: " + str(char)) #print(str(char) == str(b[round(c/2)])) if ((str(char) == str(b[int(c/2)]))): # this if statement does not seem to fire return True elif (c == 1 and char != str(b[round(c/2)])) or (c == 0 and char != "") : return False #print("false") else: #if str(char) == str(b[round(c/2)]): # return True # print("true") if char &gt; b[round(c/2)]: return isIn(char, b[round(c/2):c]) elif char &lt; b[round(c/2)]: return isIn(char, b[0:round(c/2)]) else: return False #print('fales') </code></pre>
0
2016-09-18T15:07:27Z
[ "python" ]
Check if multiple lists contain multiple items
39,558,820
<p>I have a list of lists in my python code, and I want to check if <em>any</em> of those lists contains a certain two items.</p> <pre><code>f1=['a','b'] f2=['c','d'] f3=['e','f'] f4=['g','h'] f5=['i','j'] f6=['k','l'] flist=[f1,f2,f3,f4,f5,f6] </code></pre> <p>I want something like:</p> <pre><code>if 'a' in flist[0:5] and 'b' in flist[flist.index('a')]: print (true) </code></pre> <p>What's the easiest way to do this?</p>
-1
2016-09-18T14:37:10Z
39,558,962
<pre><code>for f in flist: if 'a' not in f: continue if 'b' not in f: continue return True return False </code></pre>
1
2016-09-18T14:50:17Z
[ "python", "list" ]
Check if multiple lists contain multiple items
39,558,820
<p>I have a list of lists in my python code, and I want to check if <em>any</em> of those lists contains a certain two items.</p> <pre><code>f1=['a','b'] f2=['c','d'] f3=['e','f'] f4=['g','h'] f5=['i','j'] f6=['k','l'] flist=[f1,f2,f3,f4,f5,f6] </code></pre> <p>I want something like:</p> <pre><code>if 'a' in flist[0:5] and 'b' in flist[flist.index('a')]: print (true) </code></pre> <p>What's the easiest way to do this?</p>
-1
2016-09-18T14:37:10Z
39,558,967
<p>You can use <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>any</code></a> with <code>issubset</code>:</p> <pre><code>if any({'a', 'b'}.issubset(sublist) for sublist in flist): print "a and b were found" </code></pre> <p>By using <code>any</code>, the search is called off as soon as a <em>superset</em> of the search items is found.</p> <p>This handles the general case where the sublists may contain more than two items.</p> <hr> <p>But if the <em>sublists</em> will always contain two items, it is sufficient to check for equality:</p> <pre><code>if any({'a', 'b'} == set(sublist) for sublist in flist): print "a and b were found" </code></pre>
3
2016-09-18T14:50:50Z
[ "python", "list" ]
Check if multiple lists contain multiple items
39,558,820
<p>I have a list of lists in my python code, and I want to check if <em>any</em> of those lists contains a certain two items.</p> <pre><code>f1=['a','b'] f2=['c','d'] f3=['e','f'] f4=['g','h'] f5=['i','j'] f6=['k','l'] flist=[f1,f2,f3,f4,f5,f6] </code></pre> <p>I want something like:</p> <pre><code>if 'a' in flist[0:5] and 'b' in flist[flist.index('a')]: print (true) </code></pre> <p>What's the easiest way to do this?</p>
-1
2016-09-18T14:37:10Z
39,558,982
<p>How about you just iterate over it.</p> <pre><code>for i in range(len(flist)): if ['a', 'b'] == sorted(flist[i]): print (i) </code></pre> <p>or you can simply do one-liner, just to know if it exists.</p> <pre><code>print (["a", "b"] in [sorted(x) for x in flist]) </code></pre>
1
2016-09-18T14:51:56Z
[ "python", "list" ]
Removing values from dataframe based on groupby condition
39,558,888
<p>I'm a bit stuck here trying to determine how to slice my dataframe.</p> <pre><code>data = {'Date' : ['08/20/10','08/20/10','08/20/10','08/21/10','08/22/10','08/24/10','08/25/10','08/26/10'] , 'Receipt' : [10001,10001,10002,10002,10003,10004,10004,10004], 'Product' : ['xx1','xx2','yy1','fff4','gggg4','fsf4','gggh5','hhhg6']} dfTest = pd.DataFrame(data) dfTest </code></pre> <p>This will produce:</p> <pre><code> Date Product Receipt 0 08/20/10 xx1 10001 1 08/20/10 xx2 10001 2 08/20/10 yy1 10002 3 08/21/10 fff4 10002 4 08/22/10 gggg4 10003 5 08/24/10 fsf4 10004 6 08/25/10 gggh5 10004 7 08/26/10 hhhg6 10004 </code></pre> <p>I want to create a new dataframe that only contains unique receipts, meaning the receipt should only be used on 1 day only (but it can be shown multiple times in 1 day). If the receipt shows up in multiple days, it needs to be removed. The above data set should look like this:</p> <pre><code> Date Product Receipt 0 08/20/10 xx1 10001 1 08/20/10 xx2 10001 2 08/22/10 gggg4 10003 </code></pre> <p>What I have done so far is:</p> <pre><code>dfTest.groupby(['Receipt','Date']).count() Product Receipt Date 10001 08/20/10 2 10002 08/20/10 1 08/21/10 1 10003 08/22/10 1 10004 08/24/10 1 08/25/10 1 08/26/10 1 </code></pre> <p>I didn't know how to do a query for that date in that kind of structure, so I reset the index.</p> <pre><code>df1 = dfTest.groupby(['Receipt','Date']).count().reset_index() Receipt Date Product 0 10001 08/20/10 2 1 10002 08/20/10 1 2 10002 08/21/10 1 3 10003 08/22/10 1 4 10004 08/24/10 1 5 10004 08/25/10 1 6 10004 08/26/10 1 </code></pre> <p>Now I'm not sure how to proceed. I hope someone out there can lend a helping hand. This might be easy, I'm just a bit confused or lacking in experience. </p>
1
2016-09-18T14:43:50Z
39,559,062
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.SeriesGroupBy.nunique.html" rel="nofollow"><code>SeriesGroupBy.nunique</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow">boolean indexing</a> where condition use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.isin.html" rel="nofollow"><code>Series.isin</code></a>:</p> <pre><code>df1 = dfTest.groupby(['Receipt'])['Date'].nunique() print (df1) Receipt 10001 1 10002 2 10003 1 10004 3 Name: Date, dtype: int64 #get indexes of all rows where length is 1 print (df1[df1 == 1].index) Int64Index([10001, 10003], dtype='int64', name='Receipt') #get all rows where in column Receipt are indexes with length 1 print (dfTest[dfTest['Receipt'].isin(df1[df1 == 1].index)]) Date Product Receipt 0 08/20/10 xx1 10001 1 08/20/10 xx2 10001 4 08/22/10 gggg4 10003 </code></pre> <hr> <p>Another solution where find indexes by condition and then select <code>DataFrame</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a>:</p> <pre><code>print (dfTest.groupby(['Receipt']).filter(lambda x: x.Date.nunique()==1).index) Int64Index([0, 1, 4], dtype='int64') df1 = dfTest.loc[dfTest.groupby(['Receipt']).filter(lambda x: x.Date.nunique()==1).index] print (df1) Date Product Receipt 0 08/20/10 xx1 10001 1 08/20/10 xx2 10001 4 08/22/10 gggg4 10003 </code></pre>
0
2016-09-18T15:00:50Z
[ "python", "pandas" ]
Removing values from dataframe based on groupby condition
39,558,888
<p>I'm a bit stuck here trying to determine how to slice my dataframe.</p> <pre><code>data = {'Date' : ['08/20/10','08/20/10','08/20/10','08/21/10','08/22/10','08/24/10','08/25/10','08/26/10'] , 'Receipt' : [10001,10001,10002,10002,10003,10004,10004,10004], 'Product' : ['xx1','xx2','yy1','fff4','gggg4','fsf4','gggh5','hhhg6']} dfTest = pd.DataFrame(data) dfTest </code></pre> <p>This will produce:</p> <pre><code> Date Product Receipt 0 08/20/10 xx1 10001 1 08/20/10 xx2 10001 2 08/20/10 yy1 10002 3 08/21/10 fff4 10002 4 08/22/10 gggg4 10003 5 08/24/10 fsf4 10004 6 08/25/10 gggh5 10004 7 08/26/10 hhhg6 10004 </code></pre> <p>I want to create a new dataframe that only contains unique receipts, meaning the receipt should only be used on 1 day only (but it can be shown multiple times in 1 day). If the receipt shows up in multiple days, it needs to be removed. The above data set should look like this:</p> <pre><code> Date Product Receipt 0 08/20/10 xx1 10001 1 08/20/10 xx2 10001 2 08/22/10 gggg4 10003 </code></pre> <p>What I have done so far is:</p> <pre><code>dfTest.groupby(['Receipt','Date']).count() Product Receipt Date 10001 08/20/10 2 10002 08/20/10 1 08/21/10 1 10003 08/22/10 1 10004 08/24/10 1 08/25/10 1 08/26/10 1 </code></pre> <p>I didn't know how to do a query for that date in that kind of structure, so I reset the index.</p> <pre><code>df1 = dfTest.groupby(['Receipt','Date']).count().reset_index() Receipt Date Product 0 10001 08/20/10 2 1 10002 08/20/10 1 2 10002 08/21/10 1 3 10003 08/22/10 1 4 10004 08/24/10 1 5 10004 08/25/10 1 6 10004 08/26/10 1 </code></pre> <p>Now I'm not sure how to proceed. I hope someone out there can lend a helping hand. This might be easy, I'm just a bit confused or lacking in experience. </p>
1
2016-09-18T14:43:50Z
39,559,319
<p>Another solution using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reindex.html" rel="nofollow"><code>reindex</code></a> in combination with <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#filtration" rel="nofollow"><code>groupby.filter</code></a> and filtering based on the number of unique lengths:</p> <pre><code>df.reindex(df.groupby(['Receipt'])['Date'].filter(lambda x: len(x.unique()) == 1).index) </code></pre> <p><a href="http://i.stack.imgur.com/UKqMr.png" rel="nofollow"><img src="http://i.stack.imgur.com/UKqMr.png" alt="Image"></a></p>
0
2016-09-18T15:25:05Z
[ "python", "pandas" ]
Python scraping splash javascript click
39,558,904
<p>I'm trying to use Splash to renderer a webpage with javascript content. I'm using lxml to parse the result. I need to expand hidden menus. I've found the method to click on element but I don't know how I can click on each result from an xpath search.</p> <p>Below my xpath filter. </p> <p>//div[contains(@class,'clickable_area')]</p> <p>So, I need to perform a "find all" search on this xpath expression and for each of them, click on the object to display hidden informations.</p> <p>If someone can help me... </p> <p>Thanks</p>
1
2016-09-18T14:45:47Z
39,610,148
<p>Here I will explain you how to get all submenu.</p> <p><a href="https://angel.co/new_tags/list_children?tag_id=data-tag_id" rel="nofollow">https://angel.co/new_tags/list_children?tag_id=data-tag_id</a> eg. <a href="https://angel.co/new_tags/list_children?tag_id=9217" rel="nofollow">https://angel.co/new_tags/list_children?tag_id=9217</a> It will return all submenu of "All Markets"</p> <p>Then you can collect all "data-tag_id" and pass one by one to URL.</p> <p>If there is no data-tag_id then it will return error.</p>
0
2016-09-21T07:31:15Z
[ "javascript", "python", "xpath", "splash" ]
ComboBox not present in TK
39,558,908
<p>According to the docs there should be a <code>ComboBox</code> operation in TK, but I can't find it. <code>dir(tk)</code> shows</p> <blockquote> <p>['ACTIVE', 'ALL', 'ANCHOR', 'ARC', 'At', 'AtEnd', 'AtInsert', 'AtSelFirst', 'AtSelLast', 'BASELINE', 'BEVEL', 'BOTH', 'BOTTOM', 'BROWSE', 'BUTT', 'BaseWidget', 'BitmapImage', 'BooleanType', 'BooleanVar', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'Button', 'CASCADE', 'CENTER', 'CHAR', 'CHECKBUTTON', 'CHORD', 'COMMAND', 'CURRENT', 'CallWrapper', 'Canvas', 'Checkbutton', 'ClassType', 'CodeType', 'ComplexType', 'DISABLED', ...</p> </blockquote> <p>The version is</p> <pre><code>import Tkinter as tk tk.__version__ </code></pre> <blockquote> <p>'$Revision: 81008 $'</p> </blockquote> <p>on my Mac (latest OS X 10.11.6). No brewery for python whatsoever. </p>
0
2016-09-18T14:46:17Z
39,558,955
<p>There is no <code>ComboBox</code> widget in <code>tkinter</code>, what you are looking for is <code>tkinter.ttk</code> (in Python 3, in Python 2 it's just called <code>ttk</code>), which provides themed tk widgets. <a href="https://docs.python.org/3.1/library/tkinter.ttk.html" rel="nofollow">Docs for <code>tkinter.ttk</code></a>, and <a href="https://docs.python.org/3.1/library/tkinter.ttk.html#tkinter.ttk.Combobox" rel="nofollow">subsection for ComboBox</a>.</p> <p>You can use this code to import ttk and use its widgets rather than standard <code>tkinter</code> ones:</p> <p>Python 2</p> <pre><code>from Tkinter import * from ttk import * </code></pre> <p>Python 3:</p> <pre><code>from tkinter import * from tkinter.ttk import * </code></pre>
2
2016-09-18T14:49:38Z
[ "python", "tkinter", "combobox" ]
Skip part of superclass __init__?
39,558,956
<p>I have a class which subclass another. I would like to skip a part of the initialization process, for example:</p> <pre><code>class Parent: __init__(self, a, b, c, ...): # part I want to keep: self.a = a self.b = b self.c = c ... # part I want to skip, which is memory and time consuming # but unnecessary for the subclass: self.Q = AnotherClass() class Child(Parent): __init__(self): #a part of the parent initialization process, then other stuff </code></pre> <p>The two solutions I've come up with are:</p> <ul> <li>Make an abstract class parent of the <code>Parent</code> class which wouldn't include the unwanted part of the initialization for the <code>Child</code>, or</li> <li>Duplicate just the part of the initialization of the parent that I want in the child</li> </ul> <p>Which is best, or are there better methods?</p>
1
2016-09-18T14:49:43Z
39,559,015
<p>What about wrapping creation of <code>Q</code> into private method, and overriding that method in subclass?</p> <pre><code>class Parent: def __init__(self, a, b, c, ...): # part I want to keep: self.a = a self.b = b self.c = c self._init_q() def _init_q(): self.Q = AnotherClass() class Child(Parent): def _init_q(self): pass # do not init q when creating subclass </code></pre> <p>It's not a cleanest approach, since if <code>Child</code> does not need <code>Q</code> either it shouldn't be a child of Parent, or maybe <code>AnotherClass</code> is misplaced (maybe it should be injected to methods which needs it) but it solves your issue without changing any of class interfaces.</p>
4
2016-09-18T14:55:51Z
[ "python", "inheritance" ]
Determine why WTForms form didn't validate
39,558,984
<p>I called <code>form.validate_on_submit()</code>, but it returned <code>False</code>. How can I find out why the form didn't validate?</p>
0
2016-09-18T14:52:14Z
39,559,508
<p>For the whole form, <code>form.errors</code> contains a map of fields to lists of errors. If it is not empty, then the form did not validate. For an individual field, <code>field.errors</code> contains a list of errors for that field. The list is the same as the one in <code>form.errors</code>.</p> <p><code>form.validate()</code> performs validation and populates <code>errors</code>. When using Flask-WTF, <code>form.validate_on_submit()</code> performs an additional check that <code>request.method</code> is a "submit" method, which mostly means it is not a <code>GET</code> request.</p>
1
2016-09-18T15:45:21Z
[ "python", "flask", "wtforms", "flask-wtforms" ]
How to find 4 byte number that was absent in input?
39,558,996
<p>I have such task, and actually have no idea how to start. On the input I have a huge array of 4-byte positive numbers. Numbers can be repeated. I know that one of the number is not included in the input array. How can I find this number, using minimum resources?</p>
0
2016-09-18T14:53:29Z
39,559,322
<p>The simplest code to do so, would probably be (in pseudo code):</p> <pre><code>function find_missing(input) sort!(input) # in-place sort, should take most of the time val = 0 for d in input # go over sorted input if d == val val += 1 end if d &gt; val break end end return val end </code></pre> <p>The above function should return the missing value or zero (in case there are no missing values because of wrap around of integers). If the missing value is zero, there is a bit of a confusion but the fix is simple and left to the reader.</p> <p>Note: this is not the fastest method. Faster methods would use multiple passes to split up the input to subsets and analyze these subsets using the maximum available memory.</p>
3
2016-09-18T15:25:18Z
[ "python", "algorithm" ]
How to find 4 byte number that was absent in input?
39,558,996
<p>I have such task, and actually have no idea how to start. On the input I have a huge array of 4-byte positive numbers. Numbers can be repeated. I know that one of the number is not included in the input array. How can I find this number, using minimum resources?</p>
0
2016-09-18T14:53:29Z
39,560,512
<p>I am not really sure whether I understand your question fully. However, from what I understand, you have an array of integers and an input (which is also integers).</p> <pre><code>set_of_integers = set(array_of_integers) for input_item in input: if input_item not in set_of_integers: print(input_item) </code></pre> <p>In this approach, the input is not sorted, which has O(n log n) time complexity, and also, you don't store the entire input (assuming the input is coming from an external file). The only memory requirement is to hold the set of integers. If there are many redundancies in the original list of numbers, the size of the set will be significantly smaller. A set look up is O(1). Therefore, the provided solution has O(n) time complexity, where n is the number of input items. </p>
0
2016-09-18T17:19:18Z
[ "python", "algorithm" ]
How to find 4 byte number that was absent in input?
39,558,996
<p>I have such task, and actually have no idea how to start. On the input I have a huge array of 4-byte positive numbers. Numbers can be repeated. I know that one of the number is not included in the input array. How can I find this number, using minimum resources?</p>
0
2016-09-18T14:53:29Z
39,563,838
<p>You haven't specified how you know what the original set of values is, so I'm going to go ahead and just assume that you have two lists of values, <code>set1</code> and <code>set2</code>, which may or may not contain duplicates, may or may not be in the same order, and differ by a single element which you wish to identify. I'm not going to worry about how the sets originated.</p> <p>With that setup, you can XOR all of the data. The result will be your missing value. To illustrate this, I have a small demo that creates two identical lists, randomly deletes an element from the second one (and retains the value for checking), shuffles the lists, and does the XOR.</p> <pre><code>import random as r from functools import reduce def xor_all(lst): return reduce(lambda x,y: x ^ y, lst) set1 = [1,2,3,3,4,5,6,7,8,8,9] r.shuffle(set1) set2 = [1,2,3,3,4,5,6,7,8,8,9] rv = set2.pop(r.randrange(len(set2))) r.shuffle(set2) print("deleted value was: ", rv) print("xor_all identified: ", xor_all(set1) ^ xor_all(set2)) </code></pre>
0
2016-09-19T00:21:08Z
[ "python", "algorithm" ]
How to find 4 byte number that was absent in input?
39,558,996
<p>I have such task, and actually have no idea how to start. On the input I have a huge array of 4-byte positive numbers. Numbers can be repeated. I know that one of the number is not included in the input array. How can I find this number, using minimum resources?</p>
0
2016-09-18T14:53:29Z
39,567,381
<p>I go with Dan Getz assumption of the problem. Dan's solution gives you in the worst case O(n log n) runtime. </p> <p>Now the crazy idea: How about skipping the sorting part that is the "heaviest" overhead O(n log n)? Instead of starting with the sorting, just maintain a <code>Hashmap</code> of ALL 4 byte positive integers with integer itself as a key and <code>false</code> as the default value. Some pseudo code:</p> <p><strong>start</strong></p> <pre><code>foreach number in the input: if the number is in the valid range: if the corresponding hashmap entry has the value set to `false`, toggle it to `true` otherwise, do nothing and skip to the next input foreach Hashmap entry if the value is `false` return the key of that entry </code></pre> <p><strong>end</strong></p> <p>The size of the Hashmap is smaller or equal to the size of the input (n). The runtime complexity in the worst case O(n) Memory-wise you will need an additional O(n) of memory. Most likely it will be worse than for Dan Gretz solution (depends what sorting algorithm he uses, if I assume the normal Merge sort, then probably my solution will waste more memory most of the time and will waste the same or less amount of memory only during the last step of merge sort)</p>
0
2016-09-19T07:15:52Z
[ "python", "algorithm" ]
Append row with counts in PANDAS
39,559,054
<p>I have a data frame with categorical data structured in the following way:</p> <pre><code>index A B C D ind1 0 0 1 2 ind2 1 0 2 0 ind3 2 1 0 0 </code></pre> <p>I would like to append a row which sums only the instances of <code>"1"</code>. The desired result would look like:</p> <pre><code>index A B C D ind1 0 0 1 2 ind2 1 0 2 0 ind3 2 1 0 0 count1 1 1 1 0 </code></pre> <p>I have imported the table such that all characters are strings and have tried the following:</p> <pre><code>dataframe = dataframe.append(dataframe.applymap(lambda x: str.count(x, "1")) </code></pre> <p>However this results in numerous additional rows without meaning. Any help is much appreciated!!</p>
1
2016-09-18T15:00:04Z
39,559,101
<p>You can sum boolean mask <code>df == 1</code>:</p> <pre><code>print (df == 1) A B C D index ind1 False False True False ind2 True False False False ind3 False True False False df.loc['count1'] = (df == 1).sum() print (df) A B C D index ind1 0 0 1 2 ind2 1 0 2 0 ind3 2 1 0 0 count1 1 1 1 0 </code></pre>
2
2016-09-18T15:03:59Z
[ "python", "pandas", "sum", "append", "condition" ]
Append row with counts in PANDAS
39,559,054
<p>I have a data frame with categorical data structured in the following way:</p> <pre><code>index A B C D ind1 0 0 1 2 ind2 1 0 2 0 ind3 2 1 0 0 </code></pre> <p>I would like to append a row which sums only the instances of <code>"1"</code>. The desired result would look like:</p> <pre><code>index A B C D ind1 0 0 1 2 ind2 1 0 2 0 ind3 2 1 0 0 count1 1 1 1 0 </code></pre> <p>I have imported the table such that all characters are strings and have tried the following:</p> <pre><code>dataframe = dataframe.append(dataframe.applymap(lambda x: str.count(x, "1")) </code></pre> <p>However this results in numerous additional rows without meaning. Any help is much appreciated!!</p>
1
2016-09-18T15:00:04Z
39,559,110
<p>Not sure if you want to sum over the <code>1s</code> or if you want to count the 1s. This assumes that the <code>dtype</code> is not <code>object</code>. If it is only @jezrael's solution will work if you check against <code>'1'</code> rather than <code>1</code>.</p> <p>To sum over the 1s:</p> <pre><code>sr = df.where(df == 1, 0).sum() sr.name = 'count1' df.append(sr) </code></pre> <p>to count over the 1s you can use the approach highlighted <a href="http://stackoverflow.com/a/39559101/1764089">here</a> by @jezrael</p> <p>In that case the result is the same since you are summing 1s, but if you wanted to do it over 2 then they will give different results.</p>
0
2016-09-18T15:04:40Z
[ "python", "pandas", "sum", "append", "condition" ]
SQLite3 query ORDER BY parameter with ? notation
39,559,072
<p>I am trying to make a query with sqlite3 in python, to be ordered by a parameter column "overall_risk" or "latest_risk" (which is double number)</p> <pre><code>param = ('overall_risk',) cur = db.execute("SELECT * FROM users ORDER BY ? DESC", param) </code></pre> <p>However, I doesn't return the data ordered by <code>"overall_risk"</code> (or <code>"latest_risk"</code>), moreover, when I write the query like: </p> <pre><code>"SELECT * FROM users ORDER BY " + 'overall_risk' + " DESC" </code></pre> <p>it does work. </p>
0
2016-09-18T15:01:36Z
39,559,103
<p>SQL parameters can't be used for anything other than <em>values</em>. The whole point in using a placeholder is to have the value properly quoted to avoid it from being interpreted as part of a SQL statement or as an object.</p> <p>You are trying to insert an object name, not a value, so you can't use <code>?</code> for this. You'll have to use string formatting and be extremely careful as to what names you allow:</p> <pre><code>cur = db.execute("SELECT * FROM users ORDER BY {} DESC".format(column_name)) </code></pre> <p>If <code>column_name</code> is taken from user input, you'll need to validate this against existing column names.</p> <p>The alternative is to use a library like <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> to generate your SQL for you. See the <a href="http://docs.sqlalchemy.org/en/rel_1_0/core/tutorial.html" rel="nofollow">SQL Expression Language tutorial</a>.</p>
3
2016-09-18T15:04:07Z
[ "python", "sqlite3" ]
PySide:QWebView's Mouse move and Mouse press events Freezing html document
39,559,334
<p>I am trying to make a QwebView window move whenever I drag the mouse within the window (not the title bar) while at the same time events in the html documents can trigger.</p> <p>Here is my implementation of it</p> <pre><code>import sys import json import threading from time import sleep from PySide.QtCore import * from PySide.QtGui import * from PySide.QtWebKit import QWebView, QWebSettings from PySide.QtNetwork import QNetworkRequest from PySide.QtCore import QObject, Slot, Signal #html_str="".join((open("/root/adstar_gui_generate.html","r").readlines())) html_str=""" &lt;!doctype&gt; &lt;body&gt; &lt;html&gt; &lt;div class="btns"&gt;Books&lt;/div&gt; &lt;div class="btns"&gt;Enteraintment&lt;/div&gt; &lt;div class="btns"&gt;Sport&lt;/div&gt; &lt;/html&gt; &lt;style&gt; .btns{ display:inline-block; color:white; background:black; } .btns:hover{ background:green; cursor:pointer; } &lt;/style&gt; &lt;/body&gt; &lt;/doctype&gt; """ class move_win(QObject): def __init__(self): super(move_win,self).__init__() @Slot(str) def move(self,pos): print pos pos=json.loads(pos) #x_w = event.pos().X #y_w = event.pos().X dial.webview.move(pos["x"],pos["y"]) class web_view(QWebView): def __init__(self): super(web_view,self).__init__() self.mousedown=None self.mouseup=None def mouseReleaseEvent(self,event): self.mouseup=True self.mousedown=False def mousePressEvent(self, event): #self.offset = event.pos() self.offset = event.pos() self.mouseup=False self.mousedown=True def mouseMoveEvent(self, event): if self.mousedown is True: x=event.globalX() y=event.globalY() x_w = self.offset.x() y_w = self.offset.y() self.move(x-x_w, y-y_w) if __name__=="__main__": Qapp=QApplication(sys.argv) t=web_view() t.settings().setAttribute(QWebSettings.WebAttribute.DeveloperExtrasEnabled, True) t.setHtml(html_str) t.show() QCoreApplication.processEvents() Qapp.exec_() </code></pre> <p>Running the above codes, One can see that hovering over the html buttons does not work most of the time (the color of the button does not change neither the cursor). <hr> <strong>My thoughts</strong></p> <p>I am assuming that this is due to mousePressEvent and mouseMoveEvents of QWebview Itself (well my implementation of it) preventing or causing the html document to freeze.</p> <p><hr> <strong>Note</strong></p> <p>If I commented out the mousePressEvent and mouseMoveEvent from the class web_view. hovering over the html buttons works (the buttons change color and the cursor changes)</p> <p>I tried creating a QThread to determine if an asynchronous approach can be the solution (same bad luck)...</p> <p><strong>Question:</strong></p> <p>How can drag the QWebView Window without causing the html document in the window to freeze ( A simple approach will be welcomed since I am new to PySide)</p>
3
2016-09-18T15:26:15Z
39,616,062
<p>You forgot to call super methods of mouse*Event.</p> <p>Reason: Those methods are called event handler. Since you overridden it and didn't call default implementation, QWebView have no chance to know mouse states (But it was not "freezed").</p> <p><a href="https://doc.qt.io/qt-4.8/eventsandfilters.html" rel="nofollow">Qt events overview</a></p> <pre><code>class web_view(QWebView): def __init__(self): super(web_view,self).__init__() self.mousedown=None self.mouseup=None def mouseReleaseEvent(self,event): self.mouseup=True self.mousedown=False super(web_view, self).mouseReleaseEvent(event) # here def mousePressEvent(self, event): #self.offset = event.pos() self.offset = event.pos() self.mouseup=False self.mousedown=True super(web_view, self).mousePressEvent(event) # here def mouseMoveEvent(self, event): if self.mousedown is True: x=event.globalX() y=event.globalY() x_w = self.offset.x() y_w = self.offset.y() self.move(x-x_w, y-y_w) super(web_view, self).mouseMoveEvent(event) # here </code></pre>
5
2016-09-21T12:03:04Z
[ "python", "pyqt", "pyside" ]
Append multiple values for a key from a file
39,559,372
<p>I've got a file similar to below:</p> <pre><code>t_air_sens1 laten t_air_sens1 periodic t_air_air laten t_air_air periodic ... ... </code></pre> <p>I want to make a dictionary in order to assign those values of <em>laten</em> and <em>periodic</em> to each key of <em>t_air_sens1</em> and etc. The final result must be something like below:</p> <pre><code>{ "t_air_sens1": [laten,periodic] "t_air_air": [laten,periodic] ... ... } </code></pre> <p>I did write the code below:</p> <pre><code>prop_dict = {} with open('file.pl') as f, open('result.pl', 'w') as procode: for line in f: if line[0] in prop_dict: prop_dict[line[0]].append(line[1]) else: prop_dict[line[0]] = [line[1]] #will write the values in "result.pl" </code></pre> <p>But the result I get when I try to print the dictionary is something like below:</p> <pre><code>{'p': ['e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e', 'e'], 't': ['_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_', '_'], 'l': ['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']} </code></pre> <p>What can I do to fix it? How do I need to make queries in order to get the proper result?</p>
1
2016-09-18T15:30:27Z
39,559,399
<p><code>line[0]</code> and <code>line[1]</code> are single characters in the string, not the current line and the next.</p> <p>File objects are iterators; the <code>for</code> loop will get new lines from it each iteration, but you can also use the <a href="https://docs.python.org/3/library/functions.html#next" rel="nofollow"><code>next()</code> function</a> to pull another line in. Use this to read two lines at a time:</p> <pre><code>prop_dict = {} with open('file.pl') as f: for key in f: key = key.rstrip('\n') # get the next line as the value value = next(f).rstrip('\n') prop_dict.setdefault(key, []).append(value) </code></pre> <p>I also used <a href="https://docs.python.org/3/library/stdtypes.html#dict.setdefault" rel="nofollow"><code>dict.setdefault()</code></a> to insert an empty list for any key that is missing from the dictionary. Like <code>prop_dict[key]</code>, it'll return the current value in the dictionary, but if there is no such key, <code>prop_dict[key] = []</code> is executed first before returning that empty list.</p> <p>How the above works is that the <code>for</code> loop reads lines one by one as the loop iterates, basically by using <code>next()</code> internally. Calling <code>next(f)</code> in the loop simply draws in an extra line, and the <code>for</code> loop continues from there again, so you are alternating between reading a property name (<code>key</code>), and a property value (<code>value</code>).</p> <p>Note that <code>next()</code> can raise a <code>StopIteration</code> exception if the end of the file was reached by reading the last line in the <code>for</code> loop; this would indicate your file did not have an even number of lines. If this is not an error, you could specify a default instead: <code>next(f, '')</code> would return the empty string <code>''</code> if the file has been exhausted.</p>
3
2016-09-18T15:33:21Z
[ "python", "dictionary", "key-value" ]
Django is failing to save data related to User table. It says it doesn't have `mymodel_set` attribute
39,559,374
<p>I have a model linked to Django <code>User</code> model but when I try saving to that model using <code>User</code> instance, it says <strong>'User' object has no attribute 'mymodel_set'</strong></p> <p><strong>My models.py:</strong></p> <pre><code>from django.contrib.auth.models import User from django.db import models class MyModel(models.Model): user = models.OneToOneField(User, blank=True, null=True, related_name='mymodel') name = models.CharField(max_length=14, blank=True, null=True) </code></pre> <p><strong>My views.py:</strong></p> <pre><code>from django.contrib.auth.models import User from myapp.models import mymodel def register(request): #gets data here from template user = User(username=reg_username, password=reg_password) user.save() user.mymodel_set.create(name= display_name) return HttpResponse('Success') </code></pre>
0
2016-09-18T15:30:39Z
39,559,421
<p>If the related object existed, you would use <code>mymodel</code>, but it does not exist and the relationship is void, so it cannot be accessed via the <code>user</code>. Create it first and set the relationship to that user:</p> <pre><code>mymodel = MyModel.objects.create(name=display_name, user=user) # ^^^^ set related user </code></pre> <p>The <code>_set</code> suffix is usually used for reverse <code>ForeignKey</code> relationships and not for <code>OneToOne</code> relationships.</p> <p>Also note that the <code>related_name</code> on the user field was already specified as <code>mymodel</code>, and the related field can now be accessed from the <code>User</code> model via <code>user.mymodel</code></p>
0
2016-09-18T15:35:19Z
[ "python", "django" ]
Xfce Python Dbus
39,559,383
<p>I run Xfce (Arch Linux) and I'm trying to control the power manager. I already declared the power manager but what are the methods to hibernate it and control it? Here's my code so far:</p> <pre><code>from pydbus import SessionBus bus = SessionBus power = bus.get('org.xfce.PowerManager', '/org/xfce/PowerManager') power.hibernate </code></pre> <p>And it's not working. I've tried googling it, looking at docs, and guessing every method I could think of.</p>
0
2016-09-18T15:31:54Z
39,626,965
<p>As Dartmouth mentioned, you need to find xfce4-power-manager's exposed methods. For that <a href="https://wiki.gnome.org/Apps/DFeet" rel="nofollow">DFeet</a> (a D-Bus debugger) will help you:</p> <p><a href="http://i.stack.imgur.com/UIOz6.png" rel="nofollow"><img src="http://i.stack.imgur.com/UIOz6.png" alt="enter image description here"></a></p> <p>Then you can call the method (via terminal):</p> <pre><code>dbus-send --session --print-reply \ --dest=org.freedesktop.PowerManagement \ /org/freedesktop/PowerManagement \ org.freedesktop.PowerManagement.Hibernate </code></pre>
0
2016-09-21T21:37:05Z
[ "python", "dbus" ]
Can't "import urllib.request, urllib.parse, urllib.error"
39,559,384
<p>I trying to convert my project to python3.</p> <p>My server script is server.py:</p> <pre><code>#!/usr/bin/env python #-*-coding:utf8-*- import http.server import os, sys server = http.server.HTTPServer handler = http.server.CGIHTTPRequestHandler server_address = ("", 8080) #handler.cgi_directories = [""] httpd = server(server_address, handler) httpd.serve_forever() </code></pre> <p>But when I try:</p> <pre><code>import urllib.request, urllib.parse, urllib.error </code></pre> <p>I get this in terminal of python3 ./server.py:</p> <pre class="lang-none prettyprint-override"><code> import urllib.request, urllib.parse, urllib.error ImportError: No module named request 127.0.0.1 - - [18/Sep/2016 22:47:18] CGI script exit status 0x100 </code></pre> <p>How can I do this?</p>
0
2016-09-18T15:31:55Z
39,559,790
<p>Your shebang suggests that code should be run by <code>python</code> binary, which is historically associated with Python 2.x releases.</p> <p>Simply change first line to:</p> <pre><code>#!/usr/bin/env python3 </code></pre>
1
2016-09-18T16:11:09Z
[ "python", "python-3.x", "urllib", "2to3" ]
pyspark: expand a DenseVector to tuple in a RDD
39,559,401
<p>I have the following RDD, each record is a tuple of (bigint, vector):</p> <pre><code>myRDD.take(5) [(1, DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432])), (1, DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432])), (0, DenseVector([5.0, 20.0, 0.3444, 0.3295, 54.3122, 4.0])), (1, DenseVector([9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432])), (1, DenseVector([9.2463, 2.0, 0.392, 0.3381, 162.6437, 7.9432]))] </code></pre> <p>How do I expand the Dense vector and make it part of a tuple? i.e. I want the above to become:</p> <pre><code>[(1, 9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432), (1, 9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432), (0, 5.0, 20.0, 0.3444, 0.3295, 54.3122, 4.0), (1, 9.2463, 1.0, 0.392, 0.3381, 162.6437, 7.9432), (1, 9.2463, 2.0, 0.392, 0.3381, 162.6437, 7.9432)] </code></pre> <p>Thanks!</p>
0
2016-09-18T15:33:32Z
39,559,884
<p>Well, since <code>pyspark.ml.linalg.DenseVector</code> (or <code>mllib</code>) is iterbale (provide <code>__len__</code> and <code>__getitem__</code> methods) you can treat it like any other python collections, for example:</p> <pre><code>def as_tuple(kv): """ &gt;&gt;&gt; as_tuple((1, DenseVector([9.25, 1.0, 0.31, 0.31, 162.37]))) (1, 9.25, 1.0, 0.31, 0.31, 162.37) """ k, v = kv # Use *v.toArray() if you want to support Sparse one as well. return (k, *v) </code></pre> <p>For Python 2 replace:</p> <pre><code>(k, *v) </code></pre> <p>with:</p> <pre><code>from itertools import chain tuple(chain([k], v)) </code></pre> <p>or:</p> <pre><code>(k, ) + tuple(v) </code></pre> <p>If you want to convert values to Python (not NumPy) scalars use:</p> <pre><code>v.toArray().tolist() </code></pre> <p>in place of <code>v</code>.</p>
1
2016-09-18T16:19:12Z
[ "python", "apache-spark", "pyspark", "rdd" ]
Way to transfer OpenCV Mat to iPhone
39,559,521
<p>I'm doing a computer vision project on my RaspberryPi 2. The computer vision is done through the well known OpenCV library with Python bindings. I want to show a live stream of what the Raspberry Pi is doing with an iOS app.</p> <p>The images being elaborated by the Raspberry Pi are OpenCV Mats that in Python are no less then Numpy Arrays. The iPhone app on the other end doesn't have OpenCV elaboration capabilities and it can only work with images in my logic.</p> <p>Now, while i'm designing this thing, I can't figure out the best way to do so.</p> <p>I would separate the problem this way:</p> <ol> <li>Best way to transfer information: TCP Server Socket connection or Web APIs to download somehow the new images?</li> <li>Format of the information I'm sending: Multidimentional array of values (taken directly from the Mat), and in this case how to decode the information on the iPhone, or convert the mat to an image with OpenCV on the Raspberry Pi and then store it somewhere and send it (It seems messy and slow to me)?</li> </ol> <p>What are your opinions on this?</p> <p>Thanks in advance.</p>
1
2016-09-18T15:45:46Z
40,052,651
<p>I solved the problem this way:</p> <ol> <li>Encoded the image Mat with <code>cv2.imencode(extension, mat)</code> function which returns a byte array with the encoded image.</li> <li>Use TCP Socket to send the generated byte array.</li> </ol> <p>Specifically:</p> <p>The function used for conversion is</p> <pre><code>def mat_to_byte_array(mat, ext): success, img = cv2.imencode(ext, mat) bytedata = img.tostring() # numpy function used for casting to bytearray return success, bytedata </code></pre> <p>On iOS I used <a href="https://github.com/swiftsocket/SwiftSocket" rel="nofollow">SwiftSocket</a> Library to implement the TCP Client.</p> <p>It all works fine and smoothly now.</p> <p>Thanks anyway.</p>
0
2016-10-14T22:04:52Z
[ "python", "ios", "swift", "opencv", "raspberry-pi" ]
How do I programmatically implement super user privileges in a script?
39,559,568
<p>I've written a python script. One of the functions opens a port to listen on. To open a port to listen on I need to do it as super user. I don't want to run the script with <code>sudo</code> or with root permissions, etc. I saw an answer here regarding sub-process using <code>sudo</code>. It's not a sub-process I want as far as I know. It's just a function within the application.</p> <p>Question: How do I programmatically open a port with super user permissions?</p>
2
2016-09-18T15:50:59Z
39,559,644
<p>You can't do that. If you could then malicious code would have free access to any system as root at any time! </p> <p>If you want super user privileges you need to run the script from the root account or use sudo and type in the password - this is the whole point of having user accounts.</p> <p>EDIT</p> <p>It is worth noting that you can run bash commands from within a python script - for example using the subprocess module.</p> <pre><code>import subprocess subprocess.run(['sudo', 'blah']) </code></pre> <p>This essentially creates a new bash process to run the given command.</p> <p>If you do this your user will be prompted to enter their password in the same way as you would expect, and the privileges will only apply to the subprocess that is being created - not to the script that you are calling it from (which may have been the original question).</p>
0
2016-09-18T15:57:09Z
[ "python", "permissions" ]
How do I programmatically implement super user privileges in a script?
39,559,568
<p>I've written a python script. One of the functions opens a port to listen on. To open a port to listen on I need to do it as super user. I don't want to run the script with <code>sudo</code> or with root permissions, etc. I saw an answer here regarding sub-process using <code>sudo</code>. It's not a sub-process I want as far as I know. It's just a function within the application.</p> <p>Question: How do I programmatically open a port with super user permissions?</p>
2
2016-09-18T15:50:59Z
39,559,666
<p>You could use sudo inside your python script like this, so you don't have to run the script with sudo or as root.</p> <pre><code>import subprocess subprocess.call(["sudo", "cat", "/etc/shadow"]) </code></pre>
0
2016-09-18T15:59:22Z
[ "python", "permissions" ]
Reduction the Pandas dataframe to other dataframe
39,559,603
<p>I have two data frames and their shapes are (<code>707</code>,<code>140</code>) and (<code>34</code>,<code>98</code>).</p> <p>I want to minimize the bigger data frame to the small one based on the same index name and column names. </p> <p>So after the removing additional rows and columns from bigger data frame, in the final its shape should be (<code>34</code>,<code>98</code>) with the same index and columns with the small data frame.</p> <p>How can I do this in python ? </p>
1
2016-09-18T15:53:41Z
39,559,624
<p>I think you can select by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html" rel="nofollow"><code>loc</code></a> <code>index</code> and <code>columns</code> of small <code>DataFrame</code>:</p> <pre><code>dfbig.loc[dfsmall.index, dfsmall.columns] </code></pre> <p>Sample:</p> <pre><code>dfbig = pd.DataFrame({'a':[1,2,3,4,5], 'b':[4,7,8,9,4], 'c':[5,0,1,2,4]}) print (dfbig) a b c 0 1 4 5 1 2 7 0 2 3 8 1 3 4 9 2 4 5 4 4 dfsmall = pd.DataFrame({'a':[4,8], 'c':[0,1]}) print (dfsmall) a c 0 4 0 1 8 1 print (dfbig.loc[dfsmall.index, dfsmall.columns]) a c 0 1 5 1 2 0 </code></pre>
3
2016-09-18T15:55:15Z
[ "python", "pandas", "dataframe", "multiple-columns" ]
Django: ImportError: cannot import name 'User'
39,559,635
<p>I'm new to django and I'm facing some difficulties in creating a user from the AbstractBaseUser model. Now I'm starting wondering if my user model is not being build in the right way. This is my User model</p> <pre><code>from django.db import models from django.contrib.auth.models import AbstractBaseUser class User(AbstractBaseUser): ''' Custom user class. ''' username = models.CharField('username', max_length=10, unique=True, db_index=True) email = models.EmailField('email address', unique=True) joined = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) </code></pre> <p>and user is only referenced in this other model</p> <pre><code>from django.db import models from user_profile import User class Tweet(models.Model): ''' Tweet model ''' user = models.ForeignKey(User) text = models.CharField(max_length=160) created_date = models.DateTimeField(auto_now_add=True) country = models.CharField(max_length=30) is_active = models.BooleanField(default=True) </code></pre> <p>then when I try to migrate my new model into db</p> <pre><code>Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/myuser/django-book/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/home/myuser/django-book/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/home/myuser/django-book/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/home/myuser/django-book/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/myuser/django-book/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "/home/myuser/django-book/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 986, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 673, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 665, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 222, in _call_with_frames_removed File "/home/myuser/django-book/mytweets/tweets/models.py", line 2, in &lt;module&gt; from user_profile import User ImportError: cannot import name 'User' </code></pre> <p>I'm using django 1.10.1 on ubuntu 16.04 with python3.5 and mysql as database.</p>
0
2016-09-18T15:56:18Z
39,559,879
<p>You didn't import from right package.</p> <p>Use:</p> <pre><code>from user_profile.models import User </code></pre>
1
2016-09-18T16:18:45Z
[ "python", "django", "django-models", "model", "django-users" ]
Subtract two lists of tuples from each other
39,559,649
<p>I have the these two lists and I need to subtract one from the other but the regular "-" won't work, neither will .intersection or XOR (^). </p> <pre><code>A = [(0, 1)] B = [(0, 0), (0,1), (0, 2)] </code></pre> <p>Essentially what I want is:</p> <pre><code>B - A = [(0, 0), (0, 2)] </code></pre>
1
2016-09-18T15:57:29Z
39,559,657
<p>You can use list comprehension to solve this problem: </p> <pre><code>[item for item in B if item not in A] </code></pre> <p>More discussion can be found <a href="http://stackoverflow.com/questions/3428536/python-list-subtraction-operation">here</a></p>
2
2016-09-18T15:58:39Z
[ "python", "list", "tuples", "subtraction" ]
Subtract two lists of tuples from each other
39,559,649
<p>I have the these two lists and I need to subtract one from the other but the regular "-" won't work, neither will .intersection or XOR (^). </p> <pre><code>A = [(0, 1)] B = [(0, 0), (0,1), (0, 2)] </code></pre> <p>Essentially what I want is:</p> <pre><code>B - A = [(0, 0), (0, 2)] </code></pre>
1
2016-09-18T15:57:29Z
39,559,676
<p>If there are no duplicate tuples in <code>B</code> and <code>A</code>, might be better to keep them as sets, and use the <a href="https://docs.python.org/2/library/stdtypes.html#set.difference" rel="nofollow"><code>difference</code></a> of sets:</p> <pre><code>A = [(0, 1)] B = [(0, 0), (0,1), (0, 2)] diff = set(B) - set(A) # or set(B).difference(A) print(diff) # {(0, 0), (0, 2)} </code></pre> <p>You could perform other operations like find the <a href="https://docs.python.org/2/library/stdtypes.html#set.intersection" rel="nofollow"><code>intersection</code></a> between both sets:</p> <pre><code>&gt;&gt;&gt; set(B) &amp; set(A) {(0, 1)} </code></pre> <p>Or even take their <a href="https://docs.python.org/2/library/stdtypes.html#set.symmetric_difference" rel="nofollow"><code>symmetric_difference</code></a>:</p> <pre><code>&gt;&gt;&gt; set(B) ^ set(A) {(0, 0), (0, 2)} </code></pre>
1
2016-09-18T16:00:17Z
[ "python", "list", "tuples", "subtraction" ]
Subtract two lists of tuples from each other
39,559,649
<p>I have the these two lists and I need to subtract one from the other but the regular "-" won't work, neither will .intersection or XOR (^). </p> <pre><code>A = [(0, 1)] B = [(0, 0), (0,1), (0, 2)] </code></pre> <p>Essentially what I want is:</p> <pre><code>B - A = [(0, 0), (0, 2)] </code></pre>
1
2016-09-18T15:57:29Z
39,559,774
<p>You can do such operations by converting the lists to sets. Set difference:</p> <pre><code>r = set(B)-set(A) </code></pre> <p>Convert to list if necessary: list(r)</p> <p>Working on sets is efficient compared to running "in" operations on lists: <a href="http://stackoverflow.com/questions/25294897/why-is-converting-a-list-to-a-set-faster-than-using-just-list-to-compute-a-list">using lists vs sets for list differences</a></p>
0
2016-09-18T16:09:36Z
[ "python", "list", "tuples", "subtraction" ]
Project Euler #4 repeat of numbers generated
39,559,671
<p>I was trying to solve Project Euler Problem #4 and while I have solved it I am not satisfied with my code because it generates repeats.</p> <p>Below is the code:</p> <pre><code>pal = [] for i in range(100 ** 2, 1000 ** 2): if str(i) == str(i)[::-1]: pal.append(i) for n in pal: for x in range(100, 1000): if 99 &lt; n / x &lt; 1000 and n % x == 0: print(x, n//x, n) # largest palindrome product of two 3-digit numbers </code></pre> <p>When I run this code, I get repeats ie. multiples of the same palindrome product. For example, it will return 840048 twice, which is a product of 888 and 946. Is there a way to not generate repeats with this code?</p> <p>EDIT 1: part of my build output</p> <pre><code>946 888 840048 869 982 853358 982 869 853358 894 957 855558 957 894 855558 924 932 861168 </code></pre>
0
2016-09-18T15:59:42Z
39,559,817
<p>You could you <code>set</code> or to store values just once:</p> <pre><code>pal = set() for i in range(100 ** 2, 1000 ** 2): if str(i) == str(i)[::-1]: pal.add(i) for n in pal: for x in range(100, 1000): if 99 &lt; n / x &lt; 1000 and n % x == 0: print(x, n//x, n) </code></pre>
1
2016-09-18T16:13:46Z
[ "python", "python-3.x" ]